diff
stringlengths 262
553k
| is_single_chunk
bool 2
classes | is_single_function
bool 1
class | buggy_function
stringlengths 20
391k
| fixed_function
stringlengths 0
392k
|
---|---|---|---|---|
diff --git a/src/contributions/resources/data-repo-sitetree/src/java/org/wyona/yanel/impl/resources/DataRepoSitetreeResource.java b/src/contributions/resources/data-repo-sitetree/src/java/org/wyona/yanel/impl/resources/DataRepoSitetreeResource.java
index 6fa20c853..0c0e4ca8a 100644
--- a/src/contributions/resources/data-repo-sitetree/src/java/org/wyona/yanel/impl/resources/DataRepoSitetreeResource.java
+++ b/src/contributions/resources/data-repo-sitetree/src/java/org/wyona/yanel/impl/resources/DataRepoSitetreeResource.java
@@ -1,125 +1,125 @@
/*
* Copyright 2006 Wyona
*/
package org.wyona.yanel.impl.resources;
import org.wyona.yanel.core.Resource;
import org.wyona.yanel.core.api.attributes.ViewableV2;
import org.wyona.yanel.core.attributes.viewable.View;
import org.wyona.yanel.core.attributes.viewable.ViewDescriptor;
import org.wyona.yanel.core.navigation.Node;
import org.wyona.yanel.core.navigation.Sitetree;
import org.apache.log4j.Category;
/**
*
*/
public class DataRepoSitetreeResource extends Resource implements ViewableV2 {
private static Category log = Category.getInstance(DataRepoSitetreeResource.class);
/**
*
*/
public DataRepoSitetreeResource() {
}
/**
*
*/
public String getMimeType(String viewId) throws Exception {
if (viewId != null && viewId.equals("xml")) return "application/xml";
return "application/xhtml+xml";
}
/**
*
*/
public long getSize() throws Exception {
return -1;
}
/**
*
*/
public boolean exists() throws Exception {
return true;
}
/**
*
*/
public View getView(String viewId) throws Exception {
StringBuffer sb = new StringBuffer("<?xml version=\"1.0\"?>");
if (viewId != null && viewId.equals("xml")) {
sb.append(getSitetreeAsXML());
//sb.append(getSitetreeAsXML(getPath().toString()));
} else {
sb.append("<html xmlns=\"http://www.w3.org/1999/xhtml\" xmlns:xhtml=\"http://www.w3.org/1999/xhtml\"><head><title>Browse Data Repository Sitetree</title></head><body><a href=\"?yanel.resource.viewid=xml\">Show XML</a><br/><br/>This content is being generated by the resource <![CDATA[" + getResourceTypeUniversalName() + "]]></body></html>");
}
View view = new View();
view.setMimeType(getMimeType(viewId));
view.setInputStream(new java.io.StringBufferInputStream(sb.toString()));
return view;
}
/**
*
*/
public ViewDescriptor[] getViewDescriptors() {
try {
ViewDescriptor[] vd = new ViewDescriptor[2];
vd[0] = new ViewDescriptor("default");
vd[0].setMimeType(getMimeType(null));
vd[1] = new ViewDescriptor("xml");
vd[1].setMimeType(getMimeType("xml"));
return vd;
} catch (Exception e) {
log.error(e.getMessage(), e);
return null;
}
}
/**
*
*/
private String getSitetreeAsXML() {
//private String getSitetreeAsXML(String path) {
String path = "/";
StringBuffer sb = new StringBuffer("<sitetree>");
sb.append(getNodeAsXML(path));
sb.append("</sitetree>");
return sb.toString();
}
/**
*
*/
private String getNodeAsXML(String path) {
- log.error("DEBUG: Path: " + path);
+ //log.error("DEBUG: Path: " + path);
Sitetree sitetree = (Sitetree) getYanel().getBeanFactory().getBean("repo-navigation");
Node node = sitetree.getNode(getRealm(), path);
StringBuffer sb = new StringBuffer("");
if (node.isCollection()) {
- sb.append("<collection path=\"" + path + "\">");
+ sb.append("<collection path=\"" + path + "\" name=\" " + node.getName() + "\">");
Node[] children = node.getChildren();
for (int i = 0; i < children.length; i++) {
if (children[i].isCollection()) {
sb.append(getNodeAsXML(children[i].getPath()));
} else if (children[i].isResource()) {
- sb.append("<resource path=\"" + children[i].getPath() + "\"/>");
+ sb.append("<resource path=\"" + children[i].getPath() + "\" name=\"" + children[i].getName() + "\"/>");
} else {
- sb.append("<neither-resource-nor-collection path=\"" + children[i].getPath() + "\"/>");
+ sb.append("<neither-resource-nor-collection path=\"" + children[i].getPath() + "\" name=\"" + children[i].getName() + "\"/>");
}
}
sb.append("</collection>");
} else {
- sb.append("<resource path=\"" + path + "\"/>");
+ sb.append("<resource path=\"" + path + "\" name=\"" + node.getName() + "\"/>");
}
return sb.toString();
}
}
| false | true | private String getNodeAsXML(String path) {
log.error("DEBUG: Path: " + path);
Sitetree sitetree = (Sitetree) getYanel().getBeanFactory().getBean("repo-navigation");
Node node = sitetree.getNode(getRealm(), path);
StringBuffer sb = new StringBuffer("");
if (node.isCollection()) {
sb.append("<collection path=\"" + path + "\">");
Node[] children = node.getChildren();
for (int i = 0; i < children.length; i++) {
if (children[i].isCollection()) {
sb.append(getNodeAsXML(children[i].getPath()));
} else if (children[i].isResource()) {
sb.append("<resource path=\"" + children[i].getPath() + "\"/>");
} else {
sb.append("<neither-resource-nor-collection path=\"" + children[i].getPath() + "\"/>");
}
}
sb.append("</collection>");
} else {
sb.append("<resource path=\"" + path + "\"/>");
}
return sb.toString();
}
| private String getNodeAsXML(String path) {
//log.error("DEBUG: Path: " + path);
Sitetree sitetree = (Sitetree) getYanel().getBeanFactory().getBean("repo-navigation");
Node node = sitetree.getNode(getRealm(), path);
StringBuffer sb = new StringBuffer("");
if (node.isCollection()) {
sb.append("<collection path=\"" + path + "\" name=\" " + node.getName() + "\">");
Node[] children = node.getChildren();
for (int i = 0; i < children.length; i++) {
if (children[i].isCollection()) {
sb.append(getNodeAsXML(children[i].getPath()));
} else if (children[i].isResource()) {
sb.append("<resource path=\"" + children[i].getPath() + "\" name=\"" + children[i].getName() + "\"/>");
} else {
sb.append("<neither-resource-nor-collection path=\"" + children[i].getPath() + "\" name=\"" + children[i].getName() + "\"/>");
}
}
sb.append("</collection>");
} else {
sb.append("<resource path=\"" + path + "\" name=\"" + node.getName() + "\"/>");
}
return sb.toString();
}
|
diff --git a/src/appmonk/tricks/ImageTricks.java b/src/appmonk/tricks/ImageTricks.java
index b5678e8..9950075 100644
--- a/src/appmonk/tricks/ImageTricks.java
+++ b/src/appmonk/tricks/ImageTricks.java
@@ -1,221 +1,221 @@
package appmonk.tricks;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.HashMap;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.ImageView;
import appmonk.image.ImageRequest;
@SuppressWarnings("unused")
public class ImageTricks {
protected static Handler uiThreadHandler = null;
public static class AsyncImageRequest extends AsyncTricks.AsyncRequest {
protected ImageRequest imageRequest;
protected ImageView imageView;
protected int defaultImageResource;
protected Bitmap bitmap = null;
protected static HashMap<String, String> assignedRequests = new HashMap<String, String>();
public AsyncImageRequest(ImageRequest request, ImageView view, int defaultResource) {
super(AsyncTricks.INTERACTIVE);
imageRequest = request;
imageView = view;
defaultImageResource = defaultResource;
if (uiThreadHandler == null)
uiThreadHandler = new Handler();
synchronized (assignedRequests) {
String viewName = Integer.toString(view.hashCode());
String requestName = imageRequest.name();
assignedRequests.put(viewName, requestName);
}
}
public AsyncImageRequest(ImageRequest request, ImageView view) {
this(request, view, 0);
}
public AsyncImageRequest(String url, ImageView view, int defaultResource) {
this(new ImageRequest().load(url), view, defaultResource);
}
public AsyncImageRequest(String url, ImageView view) {
this(new ImageRequest().load(url), view, 0);
}
public String label() {
return "loading image " + imageRequest.name() + " for view " + imageView.hashCode();
}
Handler handler() {
return uiThreadHandler;
}
@Override
public boolean before() {
if (imageRequest.isInMemory()) {
bitmap = imageRequest.getBitmap();
if (bitmap != null)
imageView.setImageBitmap(bitmap);
else if (defaultImageResource != 0)
imageView.setImageResource(defaultImageResource);
else
imageView.setImageBitmap(null);
return false;
}
else {
if (defaultImageResource != 0)
imageView.setImageResource(defaultImageResource);
else
imageView.setImageBitmap(null);
return true;
}
}
@Override
public void request() {
bitmap = imageRequest.getBitmap();
}
@Override
public void interrupted() {
boolean stillMatchesRequest = false;
synchronized (assignedRequests) {
String viewName = Integer.toString(imageView.hashCode());
String requestName = imageRequest.name();
String assignedName = assignedRequests.remove(viewName);
if (assignedName != null && assignedName.equals(requestName)) {
stillMatchesRequest = true;
}
}
if (stillMatchesRequest) {
if (defaultImageResource != 0)
imageView.setImageResource(defaultImageResource);
else
imageView.setImageBitmap(null);
}
}
@Override
public void after() {
boolean stillMatchesRequest = false;
synchronized (assignedRequests) {
String viewName = Integer.toString(imageView.hashCode());
String requestName = imageRequest.name();
String assignedName = assignedRequests.remove(viewName);
if (assignedName != null && assignedName.equals(requestName)) {
stillMatchesRequest = true;
}
}
if (stillMatchesRequest) {
if (bitmap != null) {
// Log.d("XXX", "Image " + imageRequest.name() + " loaded onto " + imageView);
imageView.setImageBitmap(bitmap);
}
else {
if (defaultImageResource != 0)
imageView.setImageResource(defaultImageResource);
else
imageView.setImageBitmap(null);
}
}
}
public void queue() {
AsyncTricks.queueRequest(AsyncTricks.INTERACTIVE, this);
}
}
public static Bitmap scaleDownBitmap(Bitmap original, int minDimension, boolean recycleOriginal) {
int origWidth = original.getWidth();
int origHeight = original.getHeight();
if (origWidth <= minDimension && origHeight <= minDimension) {
Bitmap b = Bitmap.createBitmap(original);
- if (recycleOriginal)
+ if (recycleOriginal && (original != b))
original.recycle();
return b;
}
int newWidth = 0;
int newHeight = 0;
float ratio = (float)origHeight / (float)origWidth;
if (origWidth > origHeight) {
newWidth = minDimension;
newHeight = (int)((float)newWidth * ratio);
} else {
newHeight = minDimension;
newWidth = (int)((float)newHeight / ratio);
}
Bitmap rtr = Bitmap.createScaledBitmap(original, newWidth, newHeight, false);
- if (recycleOriginal)
+ if (recycleOriginal && original != rtr)
original.recycle();
return rtr;
}
public static void scaleDownImageFile(File originalImageFile, int minDimension, CompressFormat format, int quality) {
Bitmap b = BitmapFactory.decodeFile(originalImageFile.getAbsolutePath());
if (b == null)
throw new RuntimeException("Original image could not be decoded.");
try {
b = scaleDownBitmap(b, minDimension, true);
originalImageFile.delete();
originalImageFile.createNewFile();
BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(originalImageFile));
b.compress(format, quality, outputStream);
outputStream.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static Uri scaleDownImageUri(Uri imageUri, int minDimension, CompressFormat format, int quality) {
try {
InputStream mediaStream = AppMonk.getContentResolver().openInputStream(imageUri);
Bitmap b = BitmapFactory.decodeStream(mediaStream);
mediaStream.close();
b = scaleDownBitmap(b, minDimension, true);
File tmpFile = new File(Environment.getExternalStorageDirectory(), "scaledImage." + (format == CompressFormat.JPEG ? "jpg" : "png"));
tmpFile.createNewFile();
BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(tmpFile));
b.compress(format, quality, outputStream);
outputStream.close();
b.recycle();
Uri rtr = Uri.parse(MediaStore.Images.Media.insertImage(AppMonk.getContentResolver(), tmpFile.getAbsolutePath(), null, null));
tmpFile.delete();
return rtr;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
| false | true | public static Bitmap scaleDownBitmap(Bitmap original, int minDimension, boolean recycleOriginal) {
int origWidth = original.getWidth();
int origHeight = original.getHeight();
if (origWidth <= minDimension && origHeight <= minDimension) {
Bitmap b = Bitmap.createBitmap(original);
if (recycleOriginal)
original.recycle();
return b;
}
int newWidth = 0;
int newHeight = 0;
float ratio = (float)origHeight / (float)origWidth;
if (origWidth > origHeight) {
newWidth = minDimension;
newHeight = (int)((float)newWidth * ratio);
} else {
newHeight = minDimension;
newWidth = (int)((float)newHeight / ratio);
}
Bitmap rtr = Bitmap.createScaledBitmap(original, newWidth, newHeight, false);
if (recycleOriginal)
original.recycle();
return rtr;
}
| public static Bitmap scaleDownBitmap(Bitmap original, int minDimension, boolean recycleOriginal) {
int origWidth = original.getWidth();
int origHeight = original.getHeight();
if (origWidth <= minDimension && origHeight <= minDimension) {
Bitmap b = Bitmap.createBitmap(original);
if (recycleOriginal && (original != b))
original.recycle();
return b;
}
int newWidth = 0;
int newHeight = 0;
float ratio = (float)origHeight / (float)origWidth;
if (origWidth > origHeight) {
newWidth = minDimension;
newHeight = (int)((float)newWidth * ratio);
} else {
newHeight = minDimension;
newWidth = (int)((float)newHeight / ratio);
}
Bitmap rtr = Bitmap.createScaledBitmap(original, newWidth, newHeight, false);
if (recycleOriginal && original != rtr)
original.recycle();
return rtr;
}
|
diff --git a/src/minecraft/co/uk/flansmods/client/GuiDriveableController.java b/src/minecraft/co/uk/flansmods/client/GuiDriveableController.java
index 06279f66..3d522f67 100644
--- a/src/minecraft/co/uk/flansmods/client/GuiDriveableController.java
+++ b/src/minecraft/co/uk/flansmods/client/GuiDriveableController.java
@@ -1,229 +1,216 @@
package co.uk.flansmods.client;
import java.util.ArrayList;
import org.lwjgl.LWJGLException;
import org.lwjgl.input.Controller;
import org.lwjgl.input.Controllers;
import org.lwjgl.input.Keyboard;
import org.lwjgl.input.Mouse;
import co.uk.flansmods.api.IControllable;
import net.minecraft.client.gui.GuiChat;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.gui.inventory.GuiInventory;
import net.minecraft.entity.player.EntityPlayer;
public class GuiDriveableController extends GuiScreen
{
private IControllable plane;
/*private static ArrayList<Controller> joySticks = new ArrayList<Controller>();
static
{
try
{
Controllers.create();
for(int i = 0; i < Controllers.getControllerCount(); i++)
{
if(Controllers.getController(i).getAxisCount() >= 2)
joySticks.add(Controllers.getController(i));
}
}
catch(LWJGLException e)
{
e.printStackTrace();
}
}*/
public GuiDriveableController(IControllable thePlane)
{
super();
plane = thePlane;
}
@Override
public void onGuiClosed()
{
mc.mouseHelper.ungrabMouseCursor();
}
@Override
public void handleMouseInput()
{
EntityPlayer player = (EntityPlayer)plane.getControllingEntity();
if(player != mc.thePlayer)
{
mc.displayGuiScreen(null);
return;
}
if(Mouse.isButtonDown(0)) //Left mouse
{
plane.pressKey(9, player); //Shoot
}
if(Mouse.isButtonDown(1)) //Right mouse
{
plane.pressKey(8, player); //Bomb
}
}
protected void keyTyped(char c, int i)
{
if(i == 1)
{
mc.displayGuiScreen(null);
mc.displayInGameMenu();
}
if(i == 59)
{
mc.gameSettings.hideGUI = !mc.gameSettings.hideGUI;
}
if(i == 61)
{
mc.gameSettings.showDebugInfo = !mc.gameSettings.showDebugInfo;
}
if(i == 63)
{
mc.gameSettings.thirdPersonView = (mc.gameSettings.thirdPersonView + 1) % 3;
}
if(i == 66)
{
mc.gameSettings.smoothCamera = !mc.gameSettings.smoothCamera;
}
if(i == mc.gameSettings.keyBindInventory.keyCode)
{
mc.displayGuiScreen(new GuiInventory(mc.thePlayer));
}
if(i == mc.gameSettings.keyBindDrop.keyCode)
{
//mc.thePlayer.dropCurrentItem();
}
if(i == mc.gameSettings.keyBindChat.keyCode)
{
mc.displayGuiScreen(new GuiChat());
}
}
public void handleInput()
{
EntityPlayer player = (EntityPlayer)plane.getControllingEntity();
if(player != mc.thePlayer)
{
mc.displayGuiScreen(null);
return;
}
if(!Mouse.isGrabbed())
{
mc.mouseHelper.grabMouseCursor();
}
- for(; Mouse.next(); handleMouseInput()) { }
+ handleMouseInput();
for(; Keyboard.next(); handleKeyboardInput()) { }
int l = Mouse.getDX();
int m = Mouse.getDY();
plane.onMouseMoved(l, m);
- /*
- for(Controller joyStick : joySticks)
- {
- int dy = (int)(800F * joyStick.getAxisValue(0));
- int dx = (int)(800F * joyStick.getAxisValue(1));
- if(dx != 0 || dy != 0)
- {
- plane.onMouseMoved(dx, dy);
- System.out.println(joyStick.getAxisValue(0) + " " + joyStick.getAxisValue(1));
- break;
- }
- }
- */
if(plane != null && !plane.isDead() && plane.getControllingEntity() != null && plane.getControllingEntity() instanceof EntityPlayer)
{
if(Keyboard.isKeyDown(KeyInputHandler.accelerateKey.keyCode))
{
plane.pressKey(0, player);
}
if(Keyboard.isKeyDown(KeyInputHandler.decelerateKey.keyCode))
{
plane.pressKey(1, player);
}
if(Keyboard.isKeyDown(KeyInputHandler.leftKey.keyCode))
{
plane.pressKey(2, player);
}
if(Keyboard.isKeyDown(KeyInputHandler.rightKey.keyCode))
{
plane.pressKey(3, player);
}
if(Keyboard.isKeyDown(KeyInputHandler.upKey.keyCode))
{
plane.pressKey(4, player);
}
if(Keyboard.isKeyDown(KeyInputHandler.downKey.keyCode))
{
plane.pressKey(5, player);
}
if(Keyboard.isKeyDown(KeyInputHandler.exitKey.keyCode))
{
plane.pressKey(6, player);
}
if(Keyboard.isKeyDown(KeyInputHandler.inventoryKey.keyCode))
{
plane.pressKey(7, player);
}
if(Keyboard.isKeyDown(KeyInputHandler.bombKey.keyCode))
{
plane.pressKey(8, player);
}
if(Keyboard.isKeyDown(KeyInputHandler.gunKey.keyCode))
{
plane.pressKey(9, player);
}
if(Keyboard.isKeyDown(KeyInputHandler.controlSwitchKey.keyCode))
{
plane.pressKey(10, player);
}
if(Keyboard.isKeyDown(KeyInputHandler.leftRollKey.keyCode))
{
plane.pressKey(11, player);
}
if(Keyboard.isKeyDown(KeyInputHandler.rightRollKey.keyCode))
{
plane.pressKey(12, player);
}
if(Keyboard.isKeyDown(KeyInputHandler.gearKey.keyCode))
{
plane.pressKey(13, player);
}
if(Keyboard.isKeyDown(KeyInputHandler.doorKey.keyCode))
{
plane.pressKey(14, player);
}
if(Keyboard.isKeyDown(KeyInputHandler.wingKey.keyCode))
{
plane.pressKey(15, player);
}
if(Keyboard.isKeyDown(KeyInputHandler.trimKey.keyCode))
{
plane.pressKey(16, player);
}
}
else
{
mc.displayGuiScreen(null);
return;
}
}
public void drawBackground(int i)
{
//Plane gauges overlay
}
public boolean doesGuiPauseGame()
{
return false;
}
}
| false | true | public void handleInput()
{
EntityPlayer player = (EntityPlayer)plane.getControllingEntity();
if(player != mc.thePlayer)
{
mc.displayGuiScreen(null);
return;
}
if(!Mouse.isGrabbed())
{
mc.mouseHelper.grabMouseCursor();
}
for(; Mouse.next(); handleMouseInput()) { }
for(; Keyboard.next(); handleKeyboardInput()) { }
int l = Mouse.getDX();
int m = Mouse.getDY();
plane.onMouseMoved(l, m);
/*
for(Controller joyStick : joySticks)
{
int dy = (int)(800F * joyStick.getAxisValue(0));
int dx = (int)(800F * joyStick.getAxisValue(1));
if(dx != 0 || dy != 0)
{
plane.onMouseMoved(dx, dy);
System.out.println(joyStick.getAxisValue(0) + " " + joyStick.getAxisValue(1));
break;
}
}
*/
if(plane != null && !plane.isDead() && plane.getControllingEntity() != null && plane.getControllingEntity() instanceof EntityPlayer)
{
if(Keyboard.isKeyDown(KeyInputHandler.accelerateKey.keyCode))
{
plane.pressKey(0, player);
}
if(Keyboard.isKeyDown(KeyInputHandler.decelerateKey.keyCode))
{
plane.pressKey(1, player);
}
if(Keyboard.isKeyDown(KeyInputHandler.leftKey.keyCode))
{
plane.pressKey(2, player);
}
if(Keyboard.isKeyDown(KeyInputHandler.rightKey.keyCode))
{
plane.pressKey(3, player);
}
if(Keyboard.isKeyDown(KeyInputHandler.upKey.keyCode))
{
plane.pressKey(4, player);
}
if(Keyboard.isKeyDown(KeyInputHandler.downKey.keyCode))
{
plane.pressKey(5, player);
}
if(Keyboard.isKeyDown(KeyInputHandler.exitKey.keyCode))
{
plane.pressKey(6, player);
}
if(Keyboard.isKeyDown(KeyInputHandler.inventoryKey.keyCode))
{
plane.pressKey(7, player);
}
if(Keyboard.isKeyDown(KeyInputHandler.bombKey.keyCode))
{
plane.pressKey(8, player);
}
if(Keyboard.isKeyDown(KeyInputHandler.gunKey.keyCode))
{
plane.pressKey(9, player);
}
if(Keyboard.isKeyDown(KeyInputHandler.controlSwitchKey.keyCode))
{
plane.pressKey(10, player);
}
if(Keyboard.isKeyDown(KeyInputHandler.leftRollKey.keyCode))
{
plane.pressKey(11, player);
}
if(Keyboard.isKeyDown(KeyInputHandler.rightRollKey.keyCode))
{
plane.pressKey(12, player);
}
if(Keyboard.isKeyDown(KeyInputHandler.gearKey.keyCode))
{
plane.pressKey(13, player);
}
if(Keyboard.isKeyDown(KeyInputHandler.doorKey.keyCode))
{
plane.pressKey(14, player);
}
if(Keyboard.isKeyDown(KeyInputHandler.wingKey.keyCode))
{
plane.pressKey(15, player);
}
if(Keyboard.isKeyDown(KeyInputHandler.trimKey.keyCode))
{
plane.pressKey(16, player);
}
}
else
{
mc.displayGuiScreen(null);
return;
}
}
| public void handleInput()
{
EntityPlayer player = (EntityPlayer)plane.getControllingEntity();
if(player != mc.thePlayer)
{
mc.displayGuiScreen(null);
return;
}
if(!Mouse.isGrabbed())
{
mc.mouseHelper.grabMouseCursor();
}
handleMouseInput();
for(; Keyboard.next(); handleKeyboardInput()) { }
int l = Mouse.getDX();
int m = Mouse.getDY();
plane.onMouseMoved(l, m);
if(plane != null && !plane.isDead() && plane.getControllingEntity() != null && plane.getControllingEntity() instanceof EntityPlayer)
{
if(Keyboard.isKeyDown(KeyInputHandler.accelerateKey.keyCode))
{
plane.pressKey(0, player);
}
if(Keyboard.isKeyDown(KeyInputHandler.decelerateKey.keyCode))
{
plane.pressKey(1, player);
}
if(Keyboard.isKeyDown(KeyInputHandler.leftKey.keyCode))
{
plane.pressKey(2, player);
}
if(Keyboard.isKeyDown(KeyInputHandler.rightKey.keyCode))
{
plane.pressKey(3, player);
}
if(Keyboard.isKeyDown(KeyInputHandler.upKey.keyCode))
{
plane.pressKey(4, player);
}
if(Keyboard.isKeyDown(KeyInputHandler.downKey.keyCode))
{
plane.pressKey(5, player);
}
if(Keyboard.isKeyDown(KeyInputHandler.exitKey.keyCode))
{
plane.pressKey(6, player);
}
if(Keyboard.isKeyDown(KeyInputHandler.inventoryKey.keyCode))
{
plane.pressKey(7, player);
}
if(Keyboard.isKeyDown(KeyInputHandler.bombKey.keyCode))
{
plane.pressKey(8, player);
}
if(Keyboard.isKeyDown(KeyInputHandler.gunKey.keyCode))
{
plane.pressKey(9, player);
}
if(Keyboard.isKeyDown(KeyInputHandler.controlSwitchKey.keyCode))
{
plane.pressKey(10, player);
}
if(Keyboard.isKeyDown(KeyInputHandler.leftRollKey.keyCode))
{
plane.pressKey(11, player);
}
if(Keyboard.isKeyDown(KeyInputHandler.rightRollKey.keyCode))
{
plane.pressKey(12, player);
}
if(Keyboard.isKeyDown(KeyInputHandler.gearKey.keyCode))
{
plane.pressKey(13, player);
}
if(Keyboard.isKeyDown(KeyInputHandler.doorKey.keyCode))
{
plane.pressKey(14, player);
}
if(Keyboard.isKeyDown(KeyInputHandler.wingKey.keyCode))
{
plane.pressKey(15, player);
}
if(Keyboard.isKeyDown(KeyInputHandler.trimKey.keyCode))
{
plane.pressKey(16, player);
}
}
else
{
mc.displayGuiScreen(null);
return;
}
}
|
diff --git a/src/java/com/facebook/LinkBench/generators/MotifDataGenerator.java b/src/java/com/facebook/LinkBench/generators/MotifDataGenerator.java
index 317275c..6f463b8 100644
--- a/src/java/com/facebook/LinkBench/generators/MotifDataGenerator.java
+++ b/src/java/com/facebook/LinkBench/generators/MotifDataGenerator.java
@@ -1,157 +1,155 @@
package com.facebook.LinkBench.generators;
import java.util.Properties;
import java.util.Random;
import com.facebook.LinkBench.Config;
import com.facebook.LinkBench.ConfigUtil;
import com.facebook.LinkBench.LinkBenchConfigError;
/**
* A simple data generator where the same sequences of bytes, or "motifs" occur
* multiple times. This is designed to emulate one particular property of real
* data that is exploited by compression algorithms. Typically a short sequence
* of data generated by this generator will not be very compressible on its own,
* as no motifs will recur, but if multiple output strings are concatenated
* together then the same motifs will recur repeatedly and the data will be compressible.
*
* The motif data generator has a buffer of "shared" motifs, which reoccur
* frequently in the output of the generator
*
* The data generator generates bytes from within the range of values [min, max).
* There is an additional parameter, which is called uniqueness for lack of a
* better name. The generator fills a buffer with data in chunks. A chunk
* is either generated as random new bytes, or is drawn from the "motifs",
*
* The uniqueness parameter controls the proportion of new chunks versus duplicated
* motifs. It is a probability between 0.0 and 1.0. It can also be seen as the expected
* percentage of bytes are generated from scratch.
*
* Control how often motifs appear in data
* uniqueness = 0.0: all data drawn from motifs
* uniqueness 1.0: completely independent bytes
*/
public class MotifDataGenerator implements DataGenerator {
private static final int MAX_CHUNK_SIZE = 128;
public static final int DEFAULT_MOTIF_BUFFER_SIZE = 512;
/** Lowest byte to appear in output */
private int start;
/** Number of distinct bytes to appear in output */
private int range;
/** percentage of data drawn from motifs */
private double uniqueness;
/**
* Buffer with a sequence of random bytes that are
* pasted into output. Starts off null, initialized
* on demand.
*/
private byte motifs[];
/** Size of motif buffer */
private int motifBytes;
public MotifDataGenerator() {
start = '\0';
range = 1;
uniqueness = 0.0;
}
/**
* Generate characters from start to end (inclusive both ends)
* @param start
* @param end
*/
public void init(int start, int end, double uniqueness) {
init(start, end, uniqueness, DEFAULT_MOTIF_BUFFER_SIZE);
}
public void init(int start, int end, double uniqueness, int motifBytes) {
if (start < 0 || start >= 256) {
throw new LinkBenchConfigError("start " + start +
" out of range [0,255]");
}
if (end < 0 || end >= 256) {
throw new LinkBenchConfigError("endbyte " + end +
" out of range [0,255]");
}
if (start >= end) {
throw new LinkBenchConfigError("startByte " + start
+ " >= endByte " + end);
}
this.start = (byte)start;
this.range = end - start + 1;
this.uniqueness = uniqueness;
this.motifBytes = motifBytes;
this.motifs = null;
}
@Override
public void init(Properties props, String keyPrefix) {
int startByte = ConfigUtil.getInt(props, keyPrefix +
Config.UNIFORM_GEN_STARTBYTE);
int endByte = ConfigUtil.getInt(props, keyPrefix +
Config.UNIFORM_GEN_ENDBYTE);
double uniqueness = ConfigUtil.getDouble(props, keyPrefix +
Config.MOTIF_GEN_UNIQUENESS);
if (props.contains(keyPrefix + Config.MOTIF_GEN_LENGTH)) {
int motifBytes = ConfigUtil.getInt(props, keyPrefix
+ Config.MOTIF_GEN_LENGTH);
init(startByte, endByte, uniqueness, motifBytes);
} else {
init(startByte, endByte, uniqueness);
}
}
/**
* Give an upper bound for the compression ratio for the algorithm
* @return number between 0.0 and 1.0 - 0.0 is perfectly compressible,
* 1.0 is incompressible
*/
public double estMaxCompression() {
// Avg bytes required to represent each character (uniformly distributed)
double charCompression = range / (double) 255;
// random data shouldn't have any inter-character correlations that can
// be compressed. Upper bound derived by assuming motif is completely
// compressible
return charCompression * uniqueness;
}
@Override
public byte[] fill(Random rng, byte[] data) {
// Fill motifs now so that we can use rng
if (motifs == null) {
motifs = new byte[motifBytes];
for (int i = 0; i < motifs.length; i++) {
motifs[i] = (byte) (start + rng.nextInt(range));
}
}
int n = data.length;
int chunk = Math.min(MAX_CHUNK_SIZE, motifBytes);
for (int i = 0; i < n; i += chunk) {
- if (i == 0 || rng.nextDouble() < uniqueness) {
+ if (rng.nextDouble() < uniqueness) {
int chunkEnd = Math.min(n, i + chunk);
// New sequence of unique bytes
for (int j = i; j < chunkEnd; j++) {
data[j] = (byte) (start + rng.nextInt(range));
}
} else {
int thisChunk = Math.min(chunk, n - i);
int k = rng.nextInt(motifBytes - thisChunk + 1);
- //System.err.println("Copying " + thisChunk + " bytes starting at "
- // + k + " to " + i);
// Copy previous sequence of bytes
System.arraycopy(motifs, k, data, i, thisChunk);
}
}
return data;
}
}
| false | true | public byte[] fill(Random rng, byte[] data) {
// Fill motifs now so that we can use rng
if (motifs == null) {
motifs = new byte[motifBytes];
for (int i = 0; i < motifs.length; i++) {
motifs[i] = (byte) (start + rng.nextInt(range));
}
}
int n = data.length;
int chunk = Math.min(MAX_CHUNK_SIZE, motifBytes);
for (int i = 0; i < n; i += chunk) {
if (i == 0 || rng.nextDouble() < uniqueness) {
int chunkEnd = Math.min(n, i + chunk);
// New sequence of unique bytes
for (int j = i; j < chunkEnd; j++) {
data[j] = (byte) (start + rng.nextInt(range));
}
} else {
int thisChunk = Math.min(chunk, n - i);
int k = rng.nextInt(motifBytes - thisChunk + 1);
//System.err.println("Copying " + thisChunk + " bytes starting at "
// + k + " to " + i);
// Copy previous sequence of bytes
System.arraycopy(motifs, k, data, i, thisChunk);
}
}
return data;
}
| public byte[] fill(Random rng, byte[] data) {
// Fill motifs now so that we can use rng
if (motifs == null) {
motifs = new byte[motifBytes];
for (int i = 0; i < motifs.length; i++) {
motifs[i] = (byte) (start + rng.nextInt(range));
}
}
int n = data.length;
int chunk = Math.min(MAX_CHUNK_SIZE, motifBytes);
for (int i = 0; i < n; i += chunk) {
if (rng.nextDouble() < uniqueness) {
int chunkEnd = Math.min(n, i + chunk);
// New sequence of unique bytes
for (int j = i; j < chunkEnd; j++) {
data[j] = (byte) (start + rng.nextInt(range));
}
} else {
int thisChunk = Math.min(chunk, n - i);
int k = rng.nextInt(motifBytes - thisChunk + 1);
// Copy previous sequence of bytes
System.arraycopy(motifs, k, data, i, thisChunk);
}
}
return data;
}
|
diff --git a/core/src/main/java/hudson/model/WorkspaceCleanupThread.java b/core/src/main/java/hudson/model/WorkspaceCleanupThread.java
index a839ad061..c1a859aa4 100644
--- a/core/src/main/java/hudson/model/WorkspaceCleanupThread.java
+++ b/core/src/main/java/hudson/model/WorkspaceCleanupThread.java
@@ -1,128 +1,128 @@
package hudson.model;
import hudson.FilePath;
import hudson.util.StreamTaskListener;
import java.io.File;
import java.io.FileFilter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
/**
* Clean up old left-over workspaces from slaves.
*
* @author Kohsuke Kawaguchi
*/
public class WorkspaceCleanupThread extends PeriodicWork {
private static WorkspaceCleanupThread theInstance;
public WorkspaceCleanupThread() {
super("Workspace clean-up");
theInstance = this;
}
public static void invoke() {
theInstance.run();
}
private TaskListener listener;
protected void execute() {
Hudson h = Hudson.getInstance();
try {
// don't buffer this, so that the log shows what the worker thread is up to in real time
OutputStream os = new FileOutputStream(
new File(h.getRootDir(),"workspace-cleanup.log"));
try {
listener = new StreamTaskListener(os);
for (Slave s : h.getSlaves())
process(s);
process(h);
} catch (InterruptedException e) {
e.printStackTrace(listener.fatalError("aborted"));
} finally {
os.close();
}
} catch (IOException e) {
logger.log(Level.SEVERE, "Failed to access log file",e);
}
}
private void process(Hudson h) throws IOException, InterruptedException {
File jobs = new File(h.getRootDir(), "jobs");
File[] dirs = jobs.listFiles(DIR_FILTER);
if(dirs==null) return;
for (File dir : dirs) {
FilePath ws = new FilePath(new File(dir, "workspace"));
if(shouldBeDeleted(dir.getName(),ws,h)) {
delete(ws);
}
}
}
private boolean shouldBeDeleted(String jobName, FilePath dir, Node n) throws IOException, InterruptedException {
// TODO: the use of remoting is not optimal.
// One remoting can execute "exists", "lastModified", and "delete" all at once.
TopLevelItem item = Hudson.getInstance().getItem(jobName);
if(item==null)
// no such project anymore
return true;
if(!dir.exists())
return false;
- if (item instanceof Project) {
- Project p = (Project) item;
+ if (item instanceof AbstractProject) {
+ AbstractProject p = (AbstractProject) item;
Node lb = p.getLastBuiltOn();
if(lb!=null && lb.equals(n))
// this is the active workspace. keep it.
return false;
}
// if older than a month, delete
return dir.lastModified() + 30 * DAY < new Date().getTime();
}
private void process(Slave s) throws InterruptedException {
listener.getLogger().println("Scanning "+s.getNodeName());
try {
List<FilePath> dirs = s.getWorkspaceRoot().list(DIR_FILTER);
if(dirs ==null) return;
for (FilePath dir : dirs) {
if(shouldBeDeleted(dir.getName(),dir,s))
delete(dir);
}
} catch (IOException e) {
e.printStackTrace(listener.error("Failed on "+s.getNodeName()));
}
}
private void delete(FilePath dir) throws InterruptedException {
try {
listener.getLogger().println("Deleting "+dir);
dir.deleteRecursive();
} catch (IOException e) {
e.printStackTrace(listener.error("Failed to delete "+dir));
}
}
private static class DirectoryFilter implements FileFilter, Serializable {
public boolean accept(File f) {
return f.isDirectory();
}
private static final long serialVersionUID = 1L;
}
private static final FileFilter DIR_FILTER = new DirectoryFilter();
private static final long DAY = 1000*60*60*24;
}
| true | true | private boolean shouldBeDeleted(String jobName, FilePath dir, Node n) throws IOException, InterruptedException {
// TODO: the use of remoting is not optimal.
// One remoting can execute "exists", "lastModified", and "delete" all at once.
TopLevelItem item = Hudson.getInstance().getItem(jobName);
if(item==null)
// no such project anymore
return true;
if(!dir.exists())
return false;
if (item instanceof Project) {
Project p = (Project) item;
Node lb = p.getLastBuiltOn();
if(lb!=null && lb.equals(n))
// this is the active workspace. keep it.
return false;
}
// if older than a month, delete
return dir.lastModified() + 30 * DAY < new Date().getTime();
}
| private boolean shouldBeDeleted(String jobName, FilePath dir, Node n) throws IOException, InterruptedException {
// TODO: the use of remoting is not optimal.
// One remoting can execute "exists", "lastModified", and "delete" all at once.
TopLevelItem item = Hudson.getInstance().getItem(jobName);
if(item==null)
// no such project anymore
return true;
if(!dir.exists())
return false;
if (item instanceof AbstractProject) {
AbstractProject p = (AbstractProject) item;
Node lb = p.getLastBuiltOn();
if(lb!=null && lb.equals(n))
// this is the active workspace. keep it.
return false;
}
// if older than a month, delete
return dir.lastModified() + 30 * DAY < new Date().getTime();
}
|
diff --git a/core/src/visad/trunk/data/gif/GIFAdapter.java b/core/src/visad/trunk/data/gif/GIFAdapter.java
index 662c09395..a65753143 100644
--- a/core/src/visad/trunk/data/gif/GIFAdapter.java
+++ b/core/src/visad/trunk/data/gif/GIFAdapter.java
@@ -1,224 +1,224 @@
//
// GIFAdapter.java
//
/*
VisAD system for interactive analysis and visualization of numerical
data. Copyright (C) 1996 - 1998 Bill Hibbard, Curtis Rueden, Tom
Rink and Dave Glowacki.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 1, or (at your option)
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License in file NOTICE for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package visad.data.gif;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.ColorModel;
import java.awt.image.ImageObserver;
import java.awt.image.ImageProducer;
import java.awt.image.PixelGrabber;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.rmi.RemoteException;
import visad.FlatField;
import visad.FunctionType;
import visad.Linear2DSet;
import visad.RealTupleType;
import visad.RealType;
import visad.TypeException;
import visad.VisADException;
/** this is an adapter for GIF and other images */
public class GIFAdapter
implements ImageObserver
{
private boolean badImage = false;
private FlatField field = null;
/** Create a VisAD FlatField from a local GIF or JPEG file
* @param filename name of local file.
* @exception IOException if there was a problem reading the file.
* @exception VisADException if an unexpected problem occurs.
*/
public GIFAdapter(String filename)
throws IOException, VisADException
{
loadImage(Toolkit.getDefaultToolkit().getImage(filename).getSource());
}
/** Create a VisAD FlatField from a GIF or JPEG on the Web.
* @param filename name of local file.
* @exception IOException if there was a problem reading the file.
* @exception VisADException if an unexpected problem occurs.
*/
public GIFAdapter(URL url)
throws IOException, VisADException
{
Object object = url.getContent();
if (object == null || !(object instanceof ImageProducer)) {
throw new MalformedURLException("URL does not point to an image");
}
loadImage((ImageProducer )object);
}
/** Helper function which keeps track of the image load.
*/
public boolean imageUpdate(Image i, int f, int x, int y, int w, int h)
{
boolean rtnval = true;
if ((f & ABORT) != 0) {
badImage = true;
rtnval = false;
}
if ((f & ALLBITS) != 0) {
rtnval = false;
}
if ((f & ERROR) != 0) {
badImage = true;
rtnval = false;
}
return rtnval;
}
/** Build a FlatField from the image pixels
* @param pixels image pixels.
* @param width image width.
* @param height image height.
* @exception VisADException if an unexpected problem occurs.
*/
private void buildFlatField(float[] red_pix, float[] green_pix, float[] blue_pix,
int width, int height) throws VisADException {
RealType line;
try {
line = new RealType("ImageLine");
} catch (TypeException e) {
line = RealType.getRealTypeByName("ImageLine");
}
RealType element;
try {
element = new RealType("ImageElement");
} catch (TypeException e) {
element = RealType.getRealTypeByName("ImageElement");
}
RealType c_red, c_green, c_blue;
try {
c_red = new RealType("Red");
} catch (TypeException e) {
c_red = RealType.getRealTypeByName("Red");
}
try {
c_green = new RealType("Green");
} catch (TypeException e) {
c_green = RealType.getRealTypeByName("Green");
}
try {
c_blue = new RealType("Blue");
} catch (TypeException e) {
c_blue = RealType.getRealTypeByName("Blue");
}
RealType[] c_all = {c_red, c_green, c_blue};
RealTupleType radiance = new RealTupleType(c_all);
- RealType[] domain_components = {line, element};
+ RealType[] domain_components = {element, line};
RealTupleType image_domain =
new RealTupleType(domain_components);
Linear2DSet domain_set =
new Linear2DSet(image_domain,
- (float) (width - 1.0), 0.0, width,
+ 0.0, (float) (width - 1.0), width,
(float) (height - 1.0), 0.0, height);
FunctionType image_type =
new FunctionType(image_domain, radiance);
field = new FlatField(image_type, domain_set);
float[][] samples = new float[3][];
samples[0] = red_pix;
samples[1] = green_pix;
samples[2] = blue_pix;
try {
field.setSamples(samples, false);
} catch (RemoteException e) {
throw new VisADException("Couldn't finish image initialization");
}
}
/** Load an image from an ImageProducer.
* @exception IOException if there is a problem reading the file.
* @exception VisADException if an unexpected problem occurs.
*/
private void loadImage(ImageProducer producer)
throws IOException, VisADException
{
Image image = Toolkit.getDefaultToolkit().createImage(producer);
badImage = false;
int width = -1;
int height = -1;
do {
try { Thread.sleep(100); } catch (InterruptedException e) { }
if (width < 0) {
width = image.getWidth(this);
}
if (height < 0) {
height = image.getHeight(this);
}
} while (!badImage && (width < 0 || height < 0));
if (badImage) {
throw new IOException("Not an image");
}
int numPixels = width * height;
int[] words = new int[numPixels];
float[] red_pix = new float[numPixels];
float[] green_pix = new float[numPixels];
float[] blue_pix = new float[numPixels];
PixelGrabber grabber;
grabber = new PixelGrabber(producer, 0, 0, width, height, words, 0, width);
try {
grabber.grabPixels();
} catch (InterruptedException e) {
}
ColorModel cm = grabber.getColorModel();
for (int i=0; i<numPixels; i++) {
red_pix[i] = cm.getRed(words[i]);
green_pix[i] = cm.getGreen(words[i]);
blue_pix[i] = cm.getBlue(words[i]);
}
buildFlatField(red_pix, green_pix, blue_pix, width, height);
}
public FlatField getData()
{
return field;
}
}
| false | true | private void buildFlatField(float[] red_pix, float[] green_pix, float[] blue_pix,
int width, int height) throws VisADException {
RealType line;
try {
line = new RealType("ImageLine");
} catch (TypeException e) {
line = RealType.getRealTypeByName("ImageLine");
}
RealType element;
try {
element = new RealType("ImageElement");
} catch (TypeException e) {
element = RealType.getRealTypeByName("ImageElement");
}
RealType c_red, c_green, c_blue;
try {
c_red = new RealType("Red");
} catch (TypeException e) {
c_red = RealType.getRealTypeByName("Red");
}
try {
c_green = new RealType("Green");
} catch (TypeException e) {
c_green = RealType.getRealTypeByName("Green");
}
try {
c_blue = new RealType("Blue");
} catch (TypeException e) {
c_blue = RealType.getRealTypeByName("Blue");
}
RealType[] c_all = {c_red, c_green, c_blue};
RealTupleType radiance = new RealTupleType(c_all);
RealType[] domain_components = {line, element};
RealTupleType image_domain =
new RealTupleType(domain_components);
Linear2DSet domain_set =
new Linear2DSet(image_domain,
(float) (width - 1.0), 0.0, width,
(float) (height - 1.0), 0.0, height);
FunctionType image_type =
new FunctionType(image_domain, radiance);
field = new FlatField(image_type, domain_set);
float[][] samples = new float[3][];
samples[0] = red_pix;
samples[1] = green_pix;
samples[2] = blue_pix;
try {
field.setSamples(samples, false);
} catch (RemoteException e) {
throw new VisADException("Couldn't finish image initialization");
}
}
| private void buildFlatField(float[] red_pix, float[] green_pix, float[] blue_pix,
int width, int height) throws VisADException {
RealType line;
try {
line = new RealType("ImageLine");
} catch (TypeException e) {
line = RealType.getRealTypeByName("ImageLine");
}
RealType element;
try {
element = new RealType("ImageElement");
} catch (TypeException e) {
element = RealType.getRealTypeByName("ImageElement");
}
RealType c_red, c_green, c_blue;
try {
c_red = new RealType("Red");
} catch (TypeException e) {
c_red = RealType.getRealTypeByName("Red");
}
try {
c_green = new RealType("Green");
} catch (TypeException e) {
c_green = RealType.getRealTypeByName("Green");
}
try {
c_blue = new RealType("Blue");
} catch (TypeException e) {
c_blue = RealType.getRealTypeByName("Blue");
}
RealType[] c_all = {c_red, c_green, c_blue};
RealTupleType radiance = new RealTupleType(c_all);
RealType[] domain_components = {element, line};
RealTupleType image_domain =
new RealTupleType(domain_components);
Linear2DSet domain_set =
new Linear2DSet(image_domain,
0.0, (float) (width - 1.0), width,
(float) (height - 1.0), 0.0, height);
FunctionType image_type =
new FunctionType(image_domain, radiance);
field = new FlatField(image_type, domain_set);
float[][] samples = new float[3][];
samples[0] = red_pix;
samples[1] = green_pix;
samples[2] = blue_pix;
try {
field.setSamples(samples, false);
} catch (RemoteException e) {
throw new VisADException("Couldn't finish image initialization");
}
}
|
diff --git a/src/webapp/src/java/org/wyona/yanel/servlet/security/impl/DefaultWebAuthenticatorImpl.java b/src/webapp/src/java/org/wyona/yanel/servlet/security/impl/DefaultWebAuthenticatorImpl.java
index 43b5691ae..c2710aa96 100644
--- a/src/webapp/src/java/org/wyona/yanel/servlet/security/impl/DefaultWebAuthenticatorImpl.java
+++ b/src/webapp/src/java/org/wyona/yanel/servlet/security/impl/DefaultWebAuthenticatorImpl.java
@@ -1,554 +1,555 @@
package org.wyona.yanel.servlet.security.impl;
import org.wyona.yanel.core.map.Map;
import org.wyona.yanel.core.map.Realm;
import org.wyona.yanel.servlet.IdentityMap;
import org.wyona.yanel.servlet.YanelServlet;
import org.wyona.yanel.core.api.security.WebAuthenticator;
import org.wyona.security.core.api.AccessManagementException;
import org.wyona.security.core.ExpiredIdentityException;
import org.wyona.security.core.api.Identity;
import org.wyona.security.core.api.User;
import org.wyona.security.core.api.UserManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamSource;
import java.net.URL;
import org.w3c.dom.Element;
import org.apache.log4j.Category;
import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.configuration.DefaultConfigurationBuilder;
import org.verisign.joid.consumer.OpenIdFilter;
import org.verisign.joid.util.UrlUtils;
import org.openid4java.consumer.ConsumerManager;
import org.openid4java.consumer.VerificationResult;
import org.openid4java.discovery.Discovery;
import org.openid4java.discovery.DiscoveryInformation;
import org.openid4java.discovery.Identifier;
import org.openid4java.message.AuthRequest;
import org.openid4java.message.ParameterList;
/**
*
*/
public class DefaultWebAuthenticatorImpl implements WebAuthenticator {
private static Category log = Category.getInstance(DefaultWebAuthenticatorImpl.class);
private static String OPENID_DISCOVERED_KEY = "openid-discovered";
// NOTE: The OpenID consumer manager needs to be the same instance for redirect to provider and provider verification
private ConsumerManager manager;
/**
*
*/
public void init(org.w3c.dom.Document configuration, javax.xml.transform.URIResolver resolver) throws Exception {
manager = new ConsumerManager();
}
/**
*
*/
public HttpServletResponse doAuthenticate(HttpServletRequest request, HttpServletResponse response, Map map, String reservedPrefix, String xsltLoginScreenDefault, String servletContextRealPath, String sslPort) throws ServletException, IOException {
try {
Realm realm = map.getRealm(request.getServletPath());
String path = map.getPath(realm, request.getServletPath());
//Realm realm = map.getRealm(new Path(request.getServletPath()));
if (log.isDebugEnabled()) log.debug("Generic WebAuthenticator called for realm path " + path);
// HTML Form based authentication
String loginUsername = request.getParameter("yanel.login.username");
String openID = request.getParameter("yanel.login.openid");
String openIDSignature = request.getParameter("openid.sig");
if(loginUsername != null) {
HttpSession session = request.getSession(true);
try {
User user = realm.getIdentityManager().getUserManager().getUser(loginUsername, true);
if (user != null && user.authenticate(request.getParameter("yanel.login.password"))) {
log.debug("Realm: " + realm);
IdentityMap identityMap = (IdentityMap)session.getAttribute(YanelServlet.IDENTITY_MAP_KEY);
if (identityMap == null) {
identityMap = new IdentityMap();
session.setAttribute(YanelServlet.IDENTITY_MAP_KEY, identityMap);
}
identityMap.put(realm.getID(), new Identity(user));
return null;
} else {
log.warn("Login failed: " + loginUsername);
getXHTMLAuthenticationForm(request, response, realm, "Login failed!", reservedPrefix, xsltLoginScreenDefault, servletContextRealPath, sslPort, map);
return response;
}
} catch (ExpiredIdentityException e) {
log.warn("Login failed: [" + loginUsername + "] " + e);
getXHTMLAuthenticationForm(request, response, realm, "The account has expired!", reservedPrefix, xsltLoginScreenDefault, servletContextRealPath, sslPort, map);
return response;
} catch (AccessManagementException e) {
log.warn("Login failed: [" + loginUsername + "] " + e);
getXHTMLAuthenticationForm(request, response, realm, "Login failed!", reservedPrefix, xsltLoginScreenDefault, servletContextRealPath, sslPort, map);
return response;
}
} else if (openID != null) {
// Append http scheme if missing
if (!openID.startsWith("http://")) {
openID = "http://" + openID;
}
String redirectUrlString = null;
try {
redirectUrlString = getOpenIDRedirectURL(openID, request, map);
response.sendRedirect(redirectUrlString);
} catch (Exception e) {
log.error(e, e);
getXHTMLAuthenticationForm(request, response, realm, "Login failed: " + e.getMessage() + "!", reservedPrefix, xsltLoginScreenDefault, servletContextRealPath, sslPort, map);
}
log.debug("Redirect URL: " + redirectUrlString);
return response;
} else if (openIDSignature != null) {
log.debug("Verify OpenID provider response ...");
if (verifyOpenIDProviderResponse(request)) {
UserManager uManager = realm.getIdentityManager().getUserManager();
String openIdentity = request.getParameter("openid.identity");
if (openIdentity != null) {
if (!uManager.existsUser(openIdentity)) {
uManager.createUser(openIdentity, null, null, null);
log.warn("An OpenID user has been created: " + openIdentity);
}
User user = uManager.getUser(openIdentity);
IdentityMap identityMap = (IdentityMap)request.getSession(true).getAttribute(YanelServlet.IDENTITY_MAP_KEY);
if (identityMap == null) {
identityMap = new IdentityMap();
request.getSession().setAttribute(YanelServlet.IDENTITY_MAP_KEY, identityMap);
}
identityMap.put(realm.getID(), new Identity(user));
// OpenID authentication successful, hence return null instead an "exceptional" response
// TODO: Do not return null (although successful), but rather strip-off all the openid query string stuff and then do a redirect
- return null;
+ response.sendRedirect(request.getParameter("openid.return_to"));
+ return response;
} else {
log.error("No openid.identity!");
getXHTMLAuthenticationForm(request, response, realm, "OpenID verification successful, but no openid.identity!", reservedPrefix, xsltLoginScreenDefault, servletContextRealPath, sslPort, map);
}
} else {
getXHTMLAuthenticationForm(request, response, realm, "Login failed: OpenID response from provider could not be verified!", reservedPrefix, xsltLoginScreenDefault, servletContextRealPath, sslPort, map);
}
return response;
} else {
if (log.isDebugEnabled()) log.debug("No form based authentication request.");
}
// Check for Neutron-Auth based authentication
String yanelUsecase = request.getParameter("yanel.usecase");
if(yanelUsecase != null && yanelUsecase.equals("neutron-auth")) {
log.debug("Neutron Authentication ...");
String username = null;
String password = null;
String originalRequest = null;
DefaultConfigurationBuilder builder = new DefaultConfigurationBuilder();
try {
Configuration config = builder.build(request.getInputStream());
Configuration originalRequestConfig = config.getChild("original-request");
originalRequest = originalRequestConfig.getAttribute("url", null);
Configuration[] paramConfig = config.getChildren("param");
for (int i = 0; i < paramConfig.length; i++) {
String paramName = paramConfig[i].getAttribute("name", null);
if (paramName != null) {
if (paramName.equals("username")) {
username = paramConfig[i].getValue();
} else if (paramName.equals("password")) {
password = paramConfig[i].getValue();
}
}
}
} catch(Exception e) {
log.warn(e);
}
log.debug("Username: " + username);
if (username != null) {
HttpSession session = request.getSession(true);
log.debug("Realm ID: " + realm.getID());
User user = realm.getIdentityManager().getUserManager().getUser(username, true);
if (user != null && user.authenticate(password)) {
log.info("Authentication successful: " + username);
IdentityMap identityMap = (IdentityMap)session.getAttribute(YanelServlet.IDENTITY_MAP_KEY);
if (identityMap == null) {
identityMap = new IdentityMap();
session.setAttribute(YanelServlet.IDENTITY_MAP_KEY, identityMap);
}
identityMap.put(realm.getID(), new Identity(user));
// TODO: send some XML content, e.g. <authentication-successful/>
response.setContentType("text/plain; charset=" + YanelServlet.DEFAULT_ENCODING);
response.setStatus(response.SC_OK);
if (log.isDebugEnabled()) log.debug("Neutron Authentication successful.");
PrintWriter writer = response.getWriter();
writer.print("Neutron Authentication Successful!");
return response;
} else {
log.warn("Neutron Authentication failed: " + username);
// TODO: Refactor this code with the one from doAuthenticate ...
log.debug("Original Request: " + originalRequest);
StringBuffer sb = new StringBuffer("");
sb.append("<?xml version=\"1.0\"?>");
sb.append("<exception xmlns=\"http://www.wyona.org/neutron/1.0\" type=\"authentication\">");
sb.append("<message>Authentication failed!</message>");
sb.append("<authentication>");
// TODO: ...
sb.append("<original-request url=\"" + YanelServlet.encodeXML(originalRequest) + "\"/>");
//sb.append("<original-request url=\"" + getRequestURLQS(request, null, true) + "\"/>");
//TODO: Also support https ...
// TODO: ...
sb.append("<login url=\"" + YanelServlet.encodeXML(originalRequest) + "&yanel.usecase=neutron-auth" + "\" method=\"POST\">");
//sb.append("<login url=\"" + getRequestURLQS(request, "yanel.usecase=neutron-auth", true) + "\" method=\"POST\">");
sb.append("<form>");
sb.append("<message>Enter username and password for \"" + realm.getName() + "\" at \"" + realm.getMountPoint() + "\"</message>");
sb.append("<param description=\"Username\" name=\"username\"/>");
sb.append("<param description=\"Password\" name=\"password\"/>");
sb.append("</form>");
sb.append("</login>");
// NOTE: Needs to be a full URL, because user might switch the server ...
// TODO: ...
sb.append("<logout url=\"" + YanelServlet.encodeXML(originalRequest) + "&yanel.usecase=logout" + "\" realm=\"" + realm.getName() + "\"/>");
sb.append("</authentication>");
sb.append("</exception>");
log.debug("Neutron-Auth response: " + sb);
response.setContentType("application/xml; charset=" + YanelServlet.DEFAULT_ENCODING);
response.setStatus(javax.servlet.http.HttpServletResponse.SC_UNAUTHORIZED);
response.setHeader("WWW-Authenticate", "NEUTRON-AUTH");
PrintWriter w = response.getWriter();
w.print(sb);
return response;
}
} else {
// TODO: Refactor resp. reuse response from above ...
log.warn("Neutron Authentication failed because username is NULL!");
StringBuffer sb = new StringBuffer("");
sb.append("<?xml version=\"1.0\"?>");
sb.append("<exception xmlns=\"http://www.wyona.org/neutron/1.0\" type=\"authentication\">");
sb.append("<message>Authentication failed because no username was sent!</message>");
sb.append("<authentication>");
// TODO: ...
sb.append("<original-request url=\"" + YanelServlet.encodeXML(originalRequest) + "\"/>");
//sb.append("<original-request url=\"" + getRequestURLQS(request, null, true) + "\"/>");
//TODO: Also support https ...
// TODO: ...
sb.append("<login url=\"" + YanelServlet.encodeXML(originalRequest) + "&yanel.usecase=neutron-auth" + "\" method=\"POST\">");
//sb.append("<login url=\"" + getRequestURLQS(request, "yanel.usecase=neutron-auth", true) + "\" method=\"POST\">");
sb.append("<form>");
sb.append("<message>Enter username and password for \"" + realm.getName() + "\" at \"" + realm.getMountPoint() + "\"</message>");
sb.append("<param description=\"Username\" name=\"username\"/>");
sb.append("<param description=\"Password\" name=\"password\"/>");
sb.append("</form>");
sb.append("</login>");
// NOTE: Needs to be a full URL, because user might switch the server ...
// TODO: ...
sb.append("<logout url=\"" + YanelServlet.encodeXML(originalRequest) + "&yanel.usecase=logout" + "\" realm=\"" + realm.getName() + "\"/>");
sb.append("</authentication>");
sb.append("</exception>");
response.setContentType("application/xml; charset=" + YanelServlet.DEFAULT_ENCODING);
response.setStatus(javax.servlet.http.HttpServletResponse.SC_UNAUTHORIZED);
response.setHeader("WWW-Authenticate", "NEUTRON-AUTH");
PrintWriter writer = response.getWriter();
writer.print(sb);
return response;
}
} else {
if (log.isDebugEnabled()) log.debug("No Neutron based authentication request.");
}
log.warn("No credentials specified yet!");
// Check if this is a neutron request, a Sunbird/Calendar request or just a common GET request
// Also see e-mail about recognizing a WebDAV request: http://lists.w3.org/Archives/Public/w3c-dist-auth/2006AprJun/0064.html
StringBuffer sb = new StringBuffer("");
String neutronVersions = request.getHeader("Neutron");
String clientSupportedAuthScheme = request.getHeader("WWW-Authenticate");
if (clientSupportedAuthScheme != null && clientSupportedAuthScheme.equals("Neutron-Auth")) {
log.debug("Neutron Versions supported by client: " + neutronVersions);
log.debug("Authentication Scheme supported by client: " + clientSupportedAuthScheme);
sb.append("<?xml version=\"1.0\"?>");
sb.append("<exception xmlns=\"http://www.wyona.org/neutron/1.0\" type=\"authorization\">");
sb.append("<message>Authorization denied: " + getRequestURLQS(request, null, true, map) + "</message>");
sb.append("<authentication>");
sb.append("<original-request url=\"" + getRequestURLQS(request, null, true, map) + "\"/>");
//TODO: Also support https ...
sb.append("<login url=\"" + getRequestURLQS(request, "yanel.usecase=neutron-auth", true, map) + "\" method=\"POST\">");
sb.append("<form>");
sb.append("<message>Enter username and password for \"" + realm.getName() + "\" at \"" + realm.getMountPoint() + "\"</message>");
sb.append("<param description=\"Username\" name=\"username\"/>");
sb.append("<param description=\"Password\" name=\"password\"/>");
sb.append("</form>");
sb.append("</login>");
// NOTE: Needs to be a full URL, because user might switch the server ...
sb.append("<logout url=\"" + getRequestURLQS(request, "yanel.usecase=logout", true, map) + "\" realm=\"" + realm.getName() + "\"/>");
sb.append("</authentication>");
sb.append("</exception>");
log.debug("Neutron-Auth response: " + sb);
response.setContentType("application/xml; charset=" + YanelServlet.DEFAULT_ENCODING);
response.setStatus(javax.servlet.http.HttpServletResponse.SC_UNAUTHORIZED);
response.setHeader("WWW-Authenticate", "NEUTRON-AUTH");
PrintWriter w = response.getWriter();
w.print(sb);
} else if (request.getRequestURI().endsWith(".ics")) {
log.warn("Somebody seems to ask for a Calendar (ICS) ...");
response.setHeader("WWW-Authenticate", "BASIC realm=\"" + realm.getName() + "\"");
response.sendError(response.SC_UNAUTHORIZED);
} else {
getXHTMLAuthenticationForm(request, response, realm, null, reservedPrefix, xsltLoginScreenDefault, servletContextRealPath, sslPort, map);
}
return response;
/*
if (log.isDebugEnabled()) log.debug("TODO: Was this authentication request really necessary!");
return null;
*/
} catch (Exception e) {
log.error(e.getMessage(), e);
throw new ServletException(e.getMessage(), e);
}
}
/**
* Custom XHTML Form for authentication
*/
public void getXHTMLAuthenticationForm(HttpServletRequest request, HttpServletResponse response, Realm realm, String message, String reservedPrefix, String xsltLoginScreenDefault, String servletContextRealPath, String sslPort, Map map) throws ServletException, IOException {
if(log.isDebugEnabled()) log.debug("Default authentication form implementation!");
String pathRelativeToRealm = request.getServletPath().replaceFirst(realm.getMountPoint(),"/");
String backToRealm = org.wyona.yanel.core.util.PathUtil.backToRealm(pathRelativeToRealm);
try {
org.w3c.dom.Document adoc = YanelServlet.getDocument(YanelServlet.NAMESPACE, "yanel-auth-screen");
Element rootElement = adoc.getDocumentElement();
if (message != null) {
Element messageElement = (Element) rootElement.appendChild(adoc.createElementNS(YanelServlet.NAMESPACE, "message"));
messageElement.appendChild(adoc.createTextNode(message));
}
Element requestElement = (Element) rootElement.appendChild(adoc.createElementNS(YanelServlet.NAMESPACE, "request"));
requestElement.setAttributeNS(YanelServlet.NAMESPACE, "urlqs", getRequestURLQS(request, null, true, map));
if (request.getQueryString() != null) {
requestElement.setAttributeNS(YanelServlet.NAMESPACE, "qs", request.getQueryString().replaceAll("&", "&"));
}
Element realmElement = (Element) rootElement.appendChild(adoc.createElementNS(YanelServlet.NAMESPACE, "realm"));
realmElement.setAttributeNS(YanelServlet.NAMESPACE, "name", realm.getName());
realmElement.setAttributeNS(YanelServlet.NAMESPACE, "mount-point", realm.getMountPoint().toString());
String currentUserId = getCurrentUserId(request, realm);
if (currentUserId != null) {
Element userElement = (Element) rootElement.appendChild(adoc.createElementNS(YanelServlet.NAMESPACE, "user"));
userElement.setAttributeNS(YanelServlet.NAMESPACE, "id", currentUserId);
}
Element sslElement = (Element) rootElement.appendChild(adoc.createElementNS(YanelServlet.NAMESPACE, "ssl"));
if(sslPort != null) {
sslElement.setAttributeNS(YanelServlet.NAMESPACE, "status", "ON");
} else {
sslElement.setAttributeNS(YanelServlet.NAMESPACE, "status", "OFF");
}
String yanelFormat = request.getParameter("yanel.format");
if(yanelFormat != null && yanelFormat.equals("xml")) {
response.setContentType("application/xml; charset=" + YanelServlet.DEFAULT_ENCODING);
//OutputStream out = response.getOutputStream();
javax.xml.transform.TransformerFactory.newInstance().newTransformer().transform(new javax.xml.transform.dom.DOMSource(adoc), new javax.xml.transform.stream.StreamResult(response.getOutputStream()));
//out.close();
} else {
String mimeType = YanelServlet.patchMimeType("application/xhtml+xml", request);
response.setContentType(mimeType + "; charset=" + YanelServlet.DEFAULT_ENCODING);
response.setStatus(javax.servlet.http.HttpServletResponse.SC_UNAUTHORIZED);
File realmDir = realm.getRootDir();
if (realmDir == null) realmDir = new File(realm.getConfigFile().getParent());
File xsltLoginScreen = org.wyona.commons.io.FileUtil.file(realmDir.getAbsolutePath(), "src" + File.separator + "webapp" + File.separator + xsltLoginScreenDefault);
if (!xsltLoginScreen.isFile()) xsltLoginScreen = org.wyona.commons.io.FileUtil.file(servletContextRealPath, xsltLoginScreenDefault);
Transformer transformer = TransformerFactory.newInstance().newTransformer(new StreamSource(xsltLoginScreen));
transformer.setParameter("yanel.back2realm", backToRealm);
transformer.setParameter("yanel.reservedPrefix", reservedPrefix);
transformer.transform(new javax.xml.transform.dom.DOMSource(adoc), new javax.xml.transform.stream.StreamResult(response.getWriter()));
}
} catch (Exception e) {
log.error(e.getMessage(), e);
throw new ServletException(e.getMessage());
}
}
/**
* Patch request with proxy settings re realm configuration
*/
private String getRequestURLQS(HttpServletRequest request, String addQS, boolean xml, Map map) {
try {
Realm realm = map.getRealm(request.getServletPath());
// TODO: Handle this exception more gracefully!
if (realm == null) log.error("No realm found for path " +request.getServletPath());
String proxyHostName = realm.getProxyHostName();
int proxyPort = realm.getProxyPort();
String proxyPrefix = realm.getProxyPrefix();
URL url = null;
url = new URL(request.getRequestURL().toString());
//if(proxyHostName != null || proxyPort >= null || proxyPrefix != null) {
if(realm.isProxySet()) {
if (proxyHostName != null) {
url = new URL(url.getProtocol(), proxyHostName, url.getPort(), url.getFile());
}
if (proxyPort >= 0) {
url = new URL(url.getProtocol(), url.getHost(), proxyPort, url.getFile());
} else {
url = new URL(url.getProtocol(), url.getHost(), url.getDefaultPort(), url.getFile());
}
if (proxyPrefix != null) {
url = new URL(url.getProtocol(), url.getHost(), url.getPort(), url.getFile().substring(proxyPrefix.length()));
}
//log.debug("Proxy enabled for this realm resp. request: " + realm + ", " + url);
} else {
//log.debug("No proxy set for this realm resp. request: " + realm + ", " + url);
}
String urlQS = url.toString();
if (request.getQueryString() != null) {
urlQS = urlQS + "?" + request.getQueryString();
if (addQS != null) urlQS = urlQS + "&" + addQS;
} else {
if (addQS != null) urlQS = urlQS + "?" + addQS;
}
if (xml) urlQS = urlQS.replaceAll("&", "&");
if(log.isDebugEnabled()) log.debug("Request: " + urlQS);
return urlQS;
} catch (Exception e) {
log.error(e);
return null;
}
}
// Using openid4java library
/**
* Get OpenID redirect URL (to the OpenID provider). Also see http://code.google.com/p/openid4java/wiki/Documentation and particularly http://code.google.com/p/openid4java/wiki/SampleConsumer
*/
private String getOpenIDRedirectURL(String openID, HttpServletRequest request, Map map) throws Exception {
String returnToUrlString = getRequestURLQS(request, null, false, map);
Identifier identifier = Discovery.parseIdentifier(openID);
java.util.List discoveries = new Discovery().discover(identifier);
DiscoveryInformation discovered = null;
try {
discovered = manager.associate(discoveries);
} catch(Exception e) {
log.warn(e, e);
}
if (discovered == null) {
throw new Exception("OpenID DiscoverInfo is null");
}
request.getSession(true).setAttribute(OPENID_DISCOVERED_KEY, discovered);
AuthRequest authReq = manager.authenticate(discovered, returnToUrlString);
return authReq.getDestinationUrl(true);
}
// Using JOID library
/*
private String getOpenIDRedirectURL(String openID, HttpServletRequest request, Map map) throws Exception {
String returnToUrlString = UrlUtils.getFullUrl(request);
log.debug("After successful authentication return to: " + returnToUrlString);
String redirectUrlString = OpenIdFilter.joid().getAuthUrl(openID, returnToUrlString, returnToUrlString);
log.debug("OpenID Provider URL: " + redirectUrlString);
return redirectUrlString;
}
*/
/**
* Verify OpenID provider response
*/
private boolean verifyOpenIDProviderResponse (HttpServletRequest request) throws Exception {
ParameterList responseParas = new ParameterList(request.getParameterMap());
DiscoveryInformation discovered = (DiscoveryInformation) request.getSession().getAttribute(OPENID_DISCOVERED_KEY);
StringBuffer receivingURL = request.getRequestURL();
String queryString = request.getQueryString();
if (queryString != null && queryString.length() > 0) {
receivingURL.append("?").append(request.getQueryString());
VerificationResult verification = manager.verify(receivingURL.toString(), responseParas, discovered);
Identifier verified = verification.getVerifiedId();
if (verified != null) {
/*
AuthSuccess authSuccess = (AuthSuccess) verification.getAuthResponse();
if (authSuccess.hasExtension(AxMessage.OPENID_NS_AX)) {
FetchResponse fetchResp = (FetchResponse) authSuccess.getExtension(AxMessage.OPENID_NS_AX);
List emails = fetchResp.getAttributeValues("email");
String email = (String) emails.get(0);
}
*/
return true;
}
}
return false;
}
/*
// TODO: src/org/verisign/joid/consumer/JoidConsumer.java
// see AuthenticationResult result = joid.authenticate(convertToStringValueMap(servletRequest.getParameterMap())); (src/org/verisign/joid/consumer/OpenIdFilter.java)
// https://127.0.0.1:8443/yanel/foaf/login.html?openid.sig=2%2FjpOdpJpEMfibrb9v9OHuzm0kg%3D&openid.mode=id_res&openid.return_to=https%3A%2F%2F127.0.0.1%3A8443%2Fyanel%2Ffoaf%2Flogin.html&openid.identity=http%3A%2F%2Fopenid.claimid.com%2Fmichi&openid.signed=identity%2Creturn_to%2Cmode&openid.assoc_handle=%7BHMAC-SHA1%7D%7B47967654%7D%7BB8gYrw%3D%3D%7D
*/
/**
* Get current user id. Return null if not signed in yet.
*/
String getCurrentUserId(HttpServletRequest request, Realm realm) {
IdentityMap identityMap = (IdentityMap)request.getSession(true).getAttribute(YanelServlet.IDENTITY_MAP_KEY);
if (identityMap != null) {
Identity identity = (Identity) identityMap.get(realm.getID());
if (identity != null && !identity.isWorld()) return identity.getUsername();
}
return null;
}
}
| true | true | public HttpServletResponse doAuthenticate(HttpServletRequest request, HttpServletResponse response, Map map, String reservedPrefix, String xsltLoginScreenDefault, String servletContextRealPath, String sslPort) throws ServletException, IOException {
try {
Realm realm = map.getRealm(request.getServletPath());
String path = map.getPath(realm, request.getServletPath());
//Realm realm = map.getRealm(new Path(request.getServletPath()));
if (log.isDebugEnabled()) log.debug("Generic WebAuthenticator called for realm path " + path);
// HTML Form based authentication
String loginUsername = request.getParameter("yanel.login.username");
String openID = request.getParameter("yanel.login.openid");
String openIDSignature = request.getParameter("openid.sig");
if(loginUsername != null) {
HttpSession session = request.getSession(true);
try {
User user = realm.getIdentityManager().getUserManager().getUser(loginUsername, true);
if (user != null && user.authenticate(request.getParameter("yanel.login.password"))) {
log.debug("Realm: " + realm);
IdentityMap identityMap = (IdentityMap)session.getAttribute(YanelServlet.IDENTITY_MAP_KEY);
if (identityMap == null) {
identityMap = new IdentityMap();
session.setAttribute(YanelServlet.IDENTITY_MAP_KEY, identityMap);
}
identityMap.put(realm.getID(), new Identity(user));
return null;
} else {
log.warn("Login failed: " + loginUsername);
getXHTMLAuthenticationForm(request, response, realm, "Login failed!", reservedPrefix, xsltLoginScreenDefault, servletContextRealPath, sslPort, map);
return response;
}
} catch (ExpiredIdentityException e) {
log.warn("Login failed: [" + loginUsername + "] " + e);
getXHTMLAuthenticationForm(request, response, realm, "The account has expired!", reservedPrefix, xsltLoginScreenDefault, servletContextRealPath, sslPort, map);
return response;
} catch (AccessManagementException e) {
log.warn("Login failed: [" + loginUsername + "] " + e);
getXHTMLAuthenticationForm(request, response, realm, "Login failed!", reservedPrefix, xsltLoginScreenDefault, servletContextRealPath, sslPort, map);
return response;
}
} else if (openID != null) {
// Append http scheme if missing
if (!openID.startsWith("http://")) {
openID = "http://" + openID;
}
String redirectUrlString = null;
try {
redirectUrlString = getOpenIDRedirectURL(openID, request, map);
response.sendRedirect(redirectUrlString);
} catch (Exception e) {
log.error(e, e);
getXHTMLAuthenticationForm(request, response, realm, "Login failed: " + e.getMessage() + "!", reservedPrefix, xsltLoginScreenDefault, servletContextRealPath, sslPort, map);
}
log.debug("Redirect URL: " + redirectUrlString);
return response;
} else if (openIDSignature != null) {
log.debug("Verify OpenID provider response ...");
if (verifyOpenIDProviderResponse(request)) {
UserManager uManager = realm.getIdentityManager().getUserManager();
String openIdentity = request.getParameter("openid.identity");
if (openIdentity != null) {
if (!uManager.existsUser(openIdentity)) {
uManager.createUser(openIdentity, null, null, null);
log.warn("An OpenID user has been created: " + openIdentity);
}
User user = uManager.getUser(openIdentity);
IdentityMap identityMap = (IdentityMap)request.getSession(true).getAttribute(YanelServlet.IDENTITY_MAP_KEY);
if (identityMap == null) {
identityMap = new IdentityMap();
request.getSession().setAttribute(YanelServlet.IDENTITY_MAP_KEY, identityMap);
}
identityMap.put(realm.getID(), new Identity(user));
// OpenID authentication successful, hence return null instead an "exceptional" response
// TODO: Do not return null (although successful), but rather strip-off all the openid query string stuff and then do a redirect
return null;
} else {
log.error("No openid.identity!");
getXHTMLAuthenticationForm(request, response, realm, "OpenID verification successful, but no openid.identity!", reservedPrefix, xsltLoginScreenDefault, servletContextRealPath, sslPort, map);
}
} else {
getXHTMLAuthenticationForm(request, response, realm, "Login failed: OpenID response from provider could not be verified!", reservedPrefix, xsltLoginScreenDefault, servletContextRealPath, sslPort, map);
}
return response;
} else {
if (log.isDebugEnabled()) log.debug("No form based authentication request.");
}
// Check for Neutron-Auth based authentication
String yanelUsecase = request.getParameter("yanel.usecase");
if(yanelUsecase != null && yanelUsecase.equals("neutron-auth")) {
log.debug("Neutron Authentication ...");
String username = null;
String password = null;
String originalRequest = null;
DefaultConfigurationBuilder builder = new DefaultConfigurationBuilder();
try {
Configuration config = builder.build(request.getInputStream());
Configuration originalRequestConfig = config.getChild("original-request");
originalRequest = originalRequestConfig.getAttribute("url", null);
Configuration[] paramConfig = config.getChildren("param");
for (int i = 0; i < paramConfig.length; i++) {
String paramName = paramConfig[i].getAttribute("name", null);
if (paramName != null) {
if (paramName.equals("username")) {
username = paramConfig[i].getValue();
} else if (paramName.equals("password")) {
password = paramConfig[i].getValue();
}
}
}
} catch(Exception e) {
log.warn(e);
}
log.debug("Username: " + username);
if (username != null) {
HttpSession session = request.getSession(true);
log.debug("Realm ID: " + realm.getID());
User user = realm.getIdentityManager().getUserManager().getUser(username, true);
if (user != null && user.authenticate(password)) {
log.info("Authentication successful: " + username);
IdentityMap identityMap = (IdentityMap)session.getAttribute(YanelServlet.IDENTITY_MAP_KEY);
if (identityMap == null) {
identityMap = new IdentityMap();
session.setAttribute(YanelServlet.IDENTITY_MAP_KEY, identityMap);
}
identityMap.put(realm.getID(), new Identity(user));
// TODO: send some XML content, e.g. <authentication-successful/>
response.setContentType("text/plain; charset=" + YanelServlet.DEFAULT_ENCODING);
response.setStatus(response.SC_OK);
if (log.isDebugEnabled()) log.debug("Neutron Authentication successful.");
PrintWriter writer = response.getWriter();
writer.print("Neutron Authentication Successful!");
return response;
} else {
log.warn("Neutron Authentication failed: " + username);
// TODO: Refactor this code with the one from doAuthenticate ...
log.debug("Original Request: " + originalRequest);
StringBuffer sb = new StringBuffer("");
sb.append("<?xml version=\"1.0\"?>");
sb.append("<exception xmlns=\"http://www.wyona.org/neutron/1.0\" type=\"authentication\">");
sb.append("<message>Authentication failed!</message>");
sb.append("<authentication>");
// TODO: ...
sb.append("<original-request url=\"" + YanelServlet.encodeXML(originalRequest) + "\"/>");
//sb.append("<original-request url=\"" + getRequestURLQS(request, null, true) + "\"/>");
//TODO: Also support https ...
// TODO: ...
sb.append("<login url=\"" + YanelServlet.encodeXML(originalRequest) + "&yanel.usecase=neutron-auth" + "\" method=\"POST\">");
//sb.append("<login url=\"" + getRequestURLQS(request, "yanel.usecase=neutron-auth", true) + "\" method=\"POST\">");
sb.append("<form>");
sb.append("<message>Enter username and password for \"" + realm.getName() + "\" at \"" + realm.getMountPoint() + "\"</message>");
sb.append("<param description=\"Username\" name=\"username\"/>");
sb.append("<param description=\"Password\" name=\"password\"/>");
sb.append("</form>");
sb.append("</login>");
// NOTE: Needs to be a full URL, because user might switch the server ...
// TODO: ...
sb.append("<logout url=\"" + YanelServlet.encodeXML(originalRequest) + "&yanel.usecase=logout" + "\" realm=\"" + realm.getName() + "\"/>");
sb.append("</authentication>");
sb.append("</exception>");
log.debug("Neutron-Auth response: " + sb);
response.setContentType("application/xml; charset=" + YanelServlet.DEFAULT_ENCODING);
response.setStatus(javax.servlet.http.HttpServletResponse.SC_UNAUTHORIZED);
response.setHeader("WWW-Authenticate", "NEUTRON-AUTH");
PrintWriter w = response.getWriter();
w.print(sb);
return response;
}
} else {
// TODO: Refactor resp. reuse response from above ...
log.warn("Neutron Authentication failed because username is NULL!");
StringBuffer sb = new StringBuffer("");
sb.append("<?xml version=\"1.0\"?>");
sb.append("<exception xmlns=\"http://www.wyona.org/neutron/1.0\" type=\"authentication\">");
sb.append("<message>Authentication failed because no username was sent!</message>");
sb.append("<authentication>");
// TODO: ...
sb.append("<original-request url=\"" + YanelServlet.encodeXML(originalRequest) + "\"/>");
//sb.append("<original-request url=\"" + getRequestURLQS(request, null, true) + "\"/>");
//TODO: Also support https ...
// TODO: ...
sb.append("<login url=\"" + YanelServlet.encodeXML(originalRequest) + "&yanel.usecase=neutron-auth" + "\" method=\"POST\">");
//sb.append("<login url=\"" + getRequestURLQS(request, "yanel.usecase=neutron-auth", true) + "\" method=\"POST\">");
sb.append("<form>");
sb.append("<message>Enter username and password for \"" + realm.getName() + "\" at \"" + realm.getMountPoint() + "\"</message>");
sb.append("<param description=\"Username\" name=\"username\"/>");
sb.append("<param description=\"Password\" name=\"password\"/>");
sb.append("</form>");
sb.append("</login>");
// NOTE: Needs to be a full URL, because user might switch the server ...
// TODO: ...
sb.append("<logout url=\"" + YanelServlet.encodeXML(originalRequest) + "&yanel.usecase=logout" + "\" realm=\"" + realm.getName() + "\"/>");
sb.append("</authentication>");
sb.append("</exception>");
response.setContentType("application/xml; charset=" + YanelServlet.DEFAULT_ENCODING);
response.setStatus(javax.servlet.http.HttpServletResponse.SC_UNAUTHORIZED);
response.setHeader("WWW-Authenticate", "NEUTRON-AUTH");
PrintWriter writer = response.getWriter();
writer.print(sb);
return response;
}
} else {
if (log.isDebugEnabled()) log.debug("No Neutron based authentication request.");
}
log.warn("No credentials specified yet!");
// Check if this is a neutron request, a Sunbird/Calendar request or just a common GET request
// Also see e-mail about recognizing a WebDAV request: http://lists.w3.org/Archives/Public/w3c-dist-auth/2006AprJun/0064.html
StringBuffer sb = new StringBuffer("");
String neutronVersions = request.getHeader("Neutron");
String clientSupportedAuthScheme = request.getHeader("WWW-Authenticate");
if (clientSupportedAuthScheme != null && clientSupportedAuthScheme.equals("Neutron-Auth")) {
log.debug("Neutron Versions supported by client: " + neutronVersions);
log.debug("Authentication Scheme supported by client: " + clientSupportedAuthScheme);
sb.append("<?xml version=\"1.0\"?>");
sb.append("<exception xmlns=\"http://www.wyona.org/neutron/1.0\" type=\"authorization\">");
sb.append("<message>Authorization denied: " + getRequestURLQS(request, null, true, map) + "</message>");
sb.append("<authentication>");
sb.append("<original-request url=\"" + getRequestURLQS(request, null, true, map) + "\"/>");
//TODO: Also support https ...
sb.append("<login url=\"" + getRequestURLQS(request, "yanel.usecase=neutron-auth", true, map) + "\" method=\"POST\">");
sb.append("<form>");
sb.append("<message>Enter username and password for \"" + realm.getName() + "\" at \"" + realm.getMountPoint() + "\"</message>");
sb.append("<param description=\"Username\" name=\"username\"/>");
sb.append("<param description=\"Password\" name=\"password\"/>");
sb.append("</form>");
sb.append("</login>");
// NOTE: Needs to be a full URL, because user might switch the server ...
sb.append("<logout url=\"" + getRequestURLQS(request, "yanel.usecase=logout", true, map) + "\" realm=\"" + realm.getName() + "\"/>");
sb.append("</authentication>");
sb.append("</exception>");
log.debug("Neutron-Auth response: " + sb);
response.setContentType("application/xml; charset=" + YanelServlet.DEFAULT_ENCODING);
response.setStatus(javax.servlet.http.HttpServletResponse.SC_UNAUTHORIZED);
response.setHeader("WWW-Authenticate", "NEUTRON-AUTH");
PrintWriter w = response.getWriter();
w.print(sb);
} else if (request.getRequestURI().endsWith(".ics")) {
log.warn("Somebody seems to ask for a Calendar (ICS) ...");
response.setHeader("WWW-Authenticate", "BASIC realm=\"" + realm.getName() + "\"");
response.sendError(response.SC_UNAUTHORIZED);
} else {
getXHTMLAuthenticationForm(request, response, realm, null, reservedPrefix, xsltLoginScreenDefault, servletContextRealPath, sslPort, map);
}
return response;
/*
if (log.isDebugEnabled()) log.debug("TODO: Was this authentication request really necessary!");
return null;
*/
} catch (Exception e) {
log.error(e.getMessage(), e);
throw new ServletException(e.getMessage(), e);
}
}
| public HttpServletResponse doAuthenticate(HttpServletRequest request, HttpServletResponse response, Map map, String reservedPrefix, String xsltLoginScreenDefault, String servletContextRealPath, String sslPort) throws ServletException, IOException {
try {
Realm realm = map.getRealm(request.getServletPath());
String path = map.getPath(realm, request.getServletPath());
//Realm realm = map.getRealm(new Path(request.getServletPath()));
if (log.isDebugEnabled()) log.debug("Generic WebAuthenticator called for realm path " + path);
// HTML Form based authentication
String loginUsername = request.getParameter("yanel.login.username");
String openID = request.getParameter("yanel.login.openid");
String openIDSignature = request.getParameter("openid.sig");
if(loginUsername != null) {
HttpSession session = request.getSession(true);
try {
User user = realm.getIdentityManager().getUserManager().getUser(loginUsername, true);
if (user != null && user.authenticate(request.getParameter("yanel.login.password"))) {
log.debug("Realm: " + realm);
IdentityMap identityMap = (IdentityMap)session.getAttribute(YanelServlet.IDENTITY_MAP_KEY);
if (identityMap == null) {
identityMap = new IdentityMap();
session.setAttribute(YanelServlet.IDENTITY_MAP_KEY, identityMap);
}
identityMap.put(realm.getID(), new Identity(user));
return null;
} else {
log.warn("Login failed: " + loginUsername);
getXHTMLAuthenticationForm(request, response, realm, "Login failed!", reservedPrefix, xsltLoginScreenDefault, servletContextRealPath, sslPort, map);
return response;
}
} catch (ExpiredIdentityException e) {
log.warn("Login failed: [" + loginUsername + "] " + e);
getXHTMLAuthenticationForm(request, response, realm, "The account has expired!", reservedPrefix, xsltLoginScreenDefault, servletContextRealPath, sslPort, map);
return response;
} catch (AccessManagementException e) {
log.warn("Login failed: [" + loginUsername + "] " + e);
getXHTMLAuthenticationForm(request, response, realm, "Login failed!", reservedPrefix, xsltLoginScreenDefault, servletContextRealPath, sslPort, map);
return response;
}
} else if (openID != null) {
// Append http scheme if missing
if (!openID.startsWith("http://")) {
openID = "http://" + openID;
}
String redirectUrlString = null;
try {
redirectUrlString = getOpenIDRedirectURL(openID, request, map);
response.sendRedirect(redirectUrlString);
} catch (Exception e) {
log.error(e, e);
getXHTMLAuthenticationForm(request, response, realm, "Login failed: " + e.getMessage() + "!", reservedPrefix, xsltLoginScreenDefault, servletContextRealPath, sslPort, map);
}
log.debug("Redirect URL: " + redirectUrlString);
return response;
} else if (openIDSignature != null) {
log.debug("Verify OpenID provider response ...");
if (verifyOpenIDProviderResponse(request)) {
UserManager uManager = realm.getIdentityManager().getUserManager();
String openIdentity = request.getParameter("openid.identity");
if (openIdentity != null) {
if (!uManager.existsUser(openIdentity)) {
uManager.createUser(openIdentity, null, null, null);
log.warn("An OpenID user has been created: " + openIdentity);
}
User user = uManager.getUser(openIdentity);
IdentityMap identityMap = (IdentityMap)request.getSession(true).getAttribute(YanelServlet.IDENTITY_MAP_KEY);
if (identityMap == null) {
identityMap = new IdentityMap();
request.getSession().setAttribute(YanelServlet.IDENTITY_MAP_KEY, identityMap);
}
identityMap.put(realm.getID(), new Identity(user));
// OpenID authentication successful, hence return null instead an "exceptional" response
// TODO: Do not return null (although successful), but rather strip-off all the openid query string stuff and then do a redirect
response.sendRedirect(request.getParameter("openid.return_to"));
return response;
} else {
log.error("No openid.identity!");
getXHTMLAuthenticationForm(request, response, realm, "OpenID verification successful, but no openid.identity!", reservedPrefix, xsltLoginScreenDefault, servletContextRealPath, sslPort, map);
}
} else {
getXHTMLAuthenticationForm(request, response, realm, "Login failed: OpenID response from provider could not be verified!", reservedPrefix, xsltLoginScreenDefault, servletContextRealPath, sslPort, map);
}
return response;
} else {
if (log.isDebugEnabled()) log.debug("No form based authentication request.");
}
// Check for Neutron-Auth based authentication
String yanelUsecase = request.getParameter("yanel.usecase");
if(yanelUsecase != null && yanelUsecase.equals("neutron-auth")) {
log.debug("Neutron Authentication ...");
String username = null;
String password = null;
String originalRequest = null;
DefaultConfigurationBuilder builder = new DefaultConfigurationBuilder();
try {
Configuration config = builder.build(request.getInputStream());
Configuration originalRequestConfig = config.getChild("original-request");
originalRequest = originalRequestConfig.getAttribute("url", null);
Configuration[] paramConfig = config.getChildren("param");
for (int i = 0; i < paramConfig.length; i++) {
String paramName = paramConfig[i].getAttribute("name", null);
if (paramName != null) {
if (paramName.equals("username")) {
username = paramConfig[i].getValue();
} else if (paramName.equals("password")) {
password = paramConfig[i].getValue();
}
}
}
} catch(Exception e) {
log.warn(e);
}
log.debug("Username: " + username);
if (username != null) {
HttpSession session = request.getSession(true);
log.debug("Realm ID: " + realm.getID());
User user = realm.getIdentityManager().getUserManager().getUser(username, true);
if (user != null && user.authenticate(password)) {
log.info("Authentication successful: " + username);
IdentityMap identityMap = (IdentityMap)session.getAttribute(YanelServlet.IDENTITY_MAP_KEY);
if (identityMap == null) {
identityMap = new IdentityMap();
session.setAttribute(YanelServlet.IDENTITY_MAP_KEY, identityMap);
}
identityMap.put(realm.getID(), new Identity(user));
// TODO: send some XML content, e.g. <authentication-successful/>
response.setContentType("text/plain; charset=" + YanelServlet.DEFAULT_ENCODING);
response.setStatus(response.SC_OK);
if (log.isDebugEnabled()) log.debug("Neutron Authentication successful.");
PrintWriter writer = response.getWriter();
writer.print("Neutron Authentication Successful!");
return response;
} else {
log.warn("Neutron Authentication failed: " + username);
// TODO: Refactor this code with the one from doAuthenticate ...
log.debug("Original Request: " + originalRequest);
StringBuffer sb = new StringBuffer("");
sb.append("<?xml version=\"1.0\"?>");
sb.append("<exception xmlns=\"http://www.wyona.org/neutron/1.0\" type=\"authentication\">");
sb.append("<message>Authentication failed!</message>");
sb.append("<authentication>");
// TODO: ...
sb.append("<original-request url=\"" + YanelServlet.encodeXML(originalRequest) + "\"/>");
//sb.append("<original-request url=\"" + getRequestURLQS(request, null, true) + "\"/>");
//TODO: Also support https ...
// TODO: ...
sb.append("<login url=\"" + YanelServlet.encodeXML(originalRequest) + "&yanel.usecase=neutron-auth" + "\" method=\"POST\">");
//sb.append("<login url=\"" + getRequestURLQS(request, "yanel.usecase=neutron-auth", true) + "\" method=\"POST\">");
sb.append("<form>");
sb.append("<message>Enter username and password for \"" + realm.getName() + "\" at \"" + realm.getMountPoint() + "\"</message>");
sb.append("<param description=\"Username\" name=\"username\"/>");
sb.append("<param description=\"Password\" name=\"password\"/>");
sb.append("</form>");
sb.append("</login>");
// NOTE: Needs to be a full URL, because user might switch the server ...
// TODO: ...
sb.append("<logout url=\"" + YanelServlet.encodeXML(originalRequest) + "&yanel.usecase=logout" + "\" realm=\"" + realm.getName() + "\"/>");
sb.append("</authentication>");
sb.append("</exception>");
log.debug("Neutron-Auth response: " + sb);
response.setContentType("application/xml; charset=" + YanelServlet.DEFAULT_ENCODING);
response.setStatus(javax.servlet.http.HttpServletResponse.SC_UNAUTHORIZED);
response.setHeader("WWW-Authenticate", "NEUTRON-AUTH");
PrintWriter w = response.getWriter();
w.print(sb);
return response;
}
} else {
// TODO: Refactor resp. reuse response from above ...
log.warn("Neutron Authentication failed because username is NULL!");
StringBuffer sb = new StringBuffer("");
sb.append("<?xml version=\"1.0\"?>");
sb.append("<exception xmlns=\"http://www.wyona.org/neutron/1.0\" type=\"authentication\">");
sb.append("<message>Authentication failed because no username was sent!</message>");
sb.append("<authentication>");
// TODO: ...
sb.append("<original-request url=\"" + YanelServlet.encodeXML(originalRequest) + "\"/>");
//sb.append("<original-request url=\"" + getRequestURLQS(request, null, true) + "\"/>");
//TODO: Also support https ...
// TODO: ...
sb.append("<login url=\"" + YanelServlet.encodeXML(originalRequest) + "&yanel.usecase=neutron-auth" + "\" method=\"POST\">");
//sb.append("<login url=\"" + getRequestURLQS(request, "yanel.usecase=neutron-auth", true) + "\" method=\"POST\">");
sb.append("<form>");
sb.append("<message>Enter username and password for \"" + realm.getName() + "\" at \"" + realm.getMountPoint() + "\"</message>");
sb.append("<param description=\"Username\" name=\"username\"/>");
sb.append("<param description=\"Password\" name=\"password\"/>");
sb.append("</form>");
sb.append("</login>");
// NOTE: Needs to be a full URL, because user might switch the server ...
// TODO: ...
sb.append("<logout url=\"" + YanelServlet.encodeXML(originalRequest) + "&yanel.usecase=logout" + "\" realm=\"" + realm.getName() + "\"/>");
sb.append("</authentication>");
sb.append("</exception>");
response.setContentType("application/xml; charset=" + YanelServlet.DEFAULT_ENCODING);
response.setStatus(javax.servlet.http.HttpServletResponse.SC_UNAUTHORIZED);
response.setHeader("WWW-Authenticate", "NEUTRON-AUTH");
PrintWriter writer = response.getWriter();
writer.print(sb);
return response;
}
} else {
if (log.isDebugEnabled()) log.debug("No Neutron based authentication request.");
}
log.warn("No credentials specified yet!");
// Check if this is a neutron request, a Sunbird/Calendar request or just a common GET request
// Also see e-mail about recognizing a WebDAV request: http://lists.w3.org/Archives/Public/w3c-dist-auth/2006AprJun/0064.html
StringBuffer sb = new StringBuffer("");
String neutronVersions = request.getHeader("Neutron");
String clientSupportedAuthScheme = request.getHeader("WWW-Authenticate");
if (clientSupportedAuthScheme != null && clientSupportedAuthScheme.equals("Neutron-Auth")) {
log.debug("Neutron Versions supported by client: " + neutronVersions);
log.debug("Authentication Scheme supported by client: " + clientSupportedAuthScheme);
sb.append("<?xml version=\"1.0\"?>");
sb.append("<exception xmlns=\"http://www.wyona.org/neutron/1.0\" type=\"authorization\">");
sb.append("<message>Authorization denied: " + getRequestURLQS(request, null, true, map) + "</message>");
sb.append("<authentication>");
sb.append("<original-request url=\"" + getRequestURLQS(request, null, true, map) + "\"/>");
//TODO: Also support https ...
sb.append("<login url=\"" + getRequestURLQS(request, "yanel.usecase=neutron-auth", true, map) + "\" method=\"POST\">");
sb.append("<form>");
sb.append("<message>Enter username and password for \"" + realm.getName() + "\" at \"" + realm.getMountPoint() + "\"</message>");
sb.append("<param description=\"Username\" name=\"username\"/>");
sb.append("<param description=\"Password\" name=\"password\"/>");
sb.append("</form>");
sb.append("</login>");
// NOTE: Needs to be a full URL, because user might switch the server ...
sb.append("<logout url=\"" + getRequestURLQS(request, "yanel.usecase=logout", true, map) + "\" realm=\"" + realm.getName() + "\"/>");
sb.append("</authentication>");
sb.append("</exception>");
log.debug("Neutron-Auth response: " + sb);
response.setContentType("application/xml; charset=" + YanelServlet.DEFAULT_ENCODING);
response.setStatus(javax.servlet.http.HttpServletResponse.SC_UNAUTHORIZED);
response.setHeader("WWW-Authenticate", "NEUTRON-AUTH");
PrintWriter w = response.getWriter();
w.print(sb);
} else if (request.getRequestURI().endsWith(".ics")) {
log.warn("Somebody seems to ask for a Calendar (ICS) ...");
response.setHeader("WWW-Authenticate", "BASIC realm=\"" + realm.getName() + "\"");
response.sendError(response.SC_UNAUTHORIZED);
} else {
getXHTMLAuthenticationForm(request, response, realm, null, reservedPrefix, xsltLoginScreenDefault, servletContextRealPath, sslPort, map);
}
return response;
/*
if (log.isDebugEnabled()) log.debug("TODO: Was this authentication request really necessary!");
return null;
*/
} catch (Exception e) {
log.error(e.getMessage(), e);
throw new ServletException(e.getMessage(), e);
}
}
|
diff --git a/java/server/src/org/openqa/selenium/remote/server/handler/CookieHandler.java b/java/server/src/org/openqa/selenium/remote/server/handler/CookieHandler.java
index b9b253046..33571c9a0 100644
--- a/java/server/src/org/openqa/selenium/remote/server/handler/CookieHandler.java
+++ b/java/server/src/org/openqa/selenium/remote/server/handler/CookieHandler.java
@@ -1,69 +1,72 @@
/*
Copyright 2007-2009 Selenium committers
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.openqa.selenium.remote.server.handler;
import com.google.common.collect.Maps;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.remote.server.JsonParametersAware;
import org.openqa.selenium.remote.server.Session;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.TimeUnit;
public abstract class CookieHandler extends WebDriverHandler implements JsonParametersAware {
private volatile Map<String, Object> rawCookie;
protected CookieHandler(Session session) {
super(session);
}
@SuppressWarnings({"unchecked"})
public void setJsonParameters(Map<String, Object> allParameters) throws Exception {
if (allParameters == null) {
return;
}
rawCookie = Maps.newHashMap((Map<String, Object>) allParameters.get("cookie"));
}
protected Cookie createCookie() {
if (rawCookie == null) {
return null;
}
String name = (String) rawCookie.get("name");
String value = (String) rawCookie.get("value");
String path = (String) rawCookie.get("path");
String domain = (String) rawCookie.get("domain");
Boolean secure = (Boolean) rawCookie.get("secure");
+ if (secure == null) {
+ secure = false;
+ }
Number expiryNum = (Number) rawCookie.get("expiry");
Date expiry = expiryNum == null ? null : new Date(
TimeUnit.SECONDS.toMillis(expiryNum.longValue()));
return new Cookie.Builder(name, value)
.path(path)
.domain(domain)
.isSecure(secure)
.expiresOn(expiry)
.build();
}
}
| true | true | protected Cookie createCookie() {
if (rawCookie == null) {
return null;
}
String name = (String) rawCookie.get("name");
String value = (String) rawCookie.get("value");
String path = (String) rawCookie.get("path");
String domain = (String) rawCookie.get("domain");
Boolean secure = (Boolean) rawCookie.get("secure");
Number expiryNum = (Number) rawCookie.get("expiry");
Date expiry = expiryNum == null ? null : new Date(
TimeUnit.SECONDS.toMillis(expiryNum.longValue()));
return new Cookie.Builder(name, value)
.path(path)
.domain(domain)
.isSecure(secure)
.expiresOn(expiry)
.build();
}
| protected Cookie createCookie() {
if (rawCookie == null) {
return null;
}
String name = (String) rawCookie.get("name");
String value = (String) rawCookie.get("value");
String path = (String) rawCookie.get("path");
String domain = (String) rawCookie.get("domain");
Boolean secure = (Boolean) rawCookie.get("secure");
if (secure == null) {
secure = false;
}
Number expiryNum = (Number) rawCookie.get("expiry");
Date expiry = expiryNum == null ? null : new Date(
TimeUnit.SECONDS.toMillis(expiryNum.longValue()));
return new Cookie.Builder(name, value)
.path(path)
.domain(domain)
.isSecure(secure)
.expiresOn(expiry)
.build();
}
|
diff --git a/ServerThread.java b/ServerThread.java
index 0a30760..c8febd0 100644
--- a/ServerThread.java
+++ b/ServerThread.java
@@ -1,177 +1,177 @@
import java.util.*;
import java.net.*;
import java.io.*;
public class ServerThread extends Thread {
Socket s = null;
String loggedInUser = null;
// hack for testing
List<String> users;
// ----------------
public ServerThread(Socket socket) {
super("ServerThread");
s = socket;
// hack for testing
users = new ArrayList<String>();
users.add("kai");
users.add("bill");
users.add("bob");
users.add("tyler");
// ----------------
}
public void run() {
try {
String line;
PrintWriter out = new PrintWriter(s.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
System.out.println("New client connected");
out.println("220 Service ready");
boolean inMessage = false;
String messageRecipient = null;
while ((line = in.readLine()) != null) {
String[] command = line.split(" ");
System.out.println("Received \"" + line + "\" from client.");
if (command[0].equals("USER")) {
if (command.length != 2) {
out.println("500 Wrong number of arguments");
System.out.println("Wrong number of arguments");
continue;
} else if (this.loggedInUser != null) {
out.println("500 Already logged in");
System.out.println("Already logged in");
continue;
}
// hack for testing
for (int i = 0; i < users.size(); i++) {
if (users.get(i).equals(command[1])) {
this.loggedInUser = command[1];
break;
}
}
if (this.loggedInUser != null) {
out.println("230 Logged in");
System.out.println("Logged in");
} else {
out.println("500 Unknown user");
System.out.println("Unknown user");
continue;
}
// ----------------
} else if (line.startsWith("MESG")) {
if (command.length != 2) {
out.println("500 Wrong number of arguments");
System.out.println("Wrong number of arguments");
continue;
} else if (!command[1].startsWith("To:")) {
out.println("500 Incorrect argument");
System.out.println("Incorrect argument");
continue;
} else if (this.loggedInUser == null) {
out.println("500 No user logged in");
System.out.println("No user logged in");
continue;
} else if (inMessage) {
out.println("500 Message already started");
System.out.println("Message already started");
continue;
}
String recipient = command[1].substring(3);
if (!users.contains(recipient)) {
out.println("500 Unknown recipient");
System.out.println("Unknown recipient");
continue;
}
inMessage = true;
messageRecipient = recipient;
out.println("250 Ok");
System.out.println("Ok");
} else if (line.startsWith("DATA")) {
if (command.length != 1) {
out.println("500 Wrong number of arguments");
continue;
} else if (this.loggedInUser == null) {
out.println("500 No user logged in");
continue;
} else if (!inMessage) {
out.println("500 Must start a message before sending data");
continue;
}
out.println("354 Enter message, ending with a \".\" on a line by itself.");
System.out.println("Enter message, ending with a \".\" on a line by itself.");
Message m = new Message(this.loggedInUser, messageRecipient);
String dataLine;
while (!(dataLine = in.readLine()).equals(".")) {
m.writeln(dataLine);
}
int max_attempts = 2;
for (int i = 0; i < max_attempts; i++) {
if (!m.store()) {
System.out.println("Failed to store message, on attempt " + (i + 1) + "/" + max_attempts);
} else {
System.out.println("Message saved!");
break;
}
}
/*
System.out.println("Sending message to: " + messageRecipient);
System.out.println(messageData);
*/
inMessage = false;
messageRecipient = null;
out.println("250 Ok");
System.out.println("Ok");
} else if (line.startsWith("QUIT")) {
if (command.length != 1) {
out.println("500 Wrong number of arguments");
System.out.println("Wrong number of arguments");
continue;
} else if (this.loggedInUser == null) {
out.println("500 No user logged in");
System.out.println("No user logged in");
continue;
}
this.loggedInUser = null;
inMessage = false;
messageRecipient = null;
out.println("221 Logged out");
System.out.println("Logged out");
} else if (line.startsWith("RETR")) {
if (command.length != 1) {
out.println("500 Wrong number of arguments");
System.out.println("Wrong number of arguments");
continue;
} else if (this.loggedInUser == null) {
out.println("500 No user logged in");
System.out.println("No user logged in");
continue;
}
List<Message> messages = Message.load(this.loggedInUser);
if (messages.size() == 0) {
out.println("250 No messages");
System.out.println("No messages");
} else {
for (Message m : messages) {
out.println(m);
System.out.println(m);
out.println("|||");
System.out.println("|||");
}
+ out.println("250 No more messages");
+ System.out.println("No more messages");
}
- out.println("250 No more messages");
- System.out.println("No more messages");
} else {
out.println("500 Command \"" + command[0] + "\" was not recognized");
}
}
if (line == null) {
System.out.println("Connection was closed by the client");
// perform cleanup
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Done!");
}
}
| false | true | public void run() {
try {
String line;
PrintWriter out = new PrintWriter(s.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
System.out.println("New client connected");
out.println("220 Service ready");
boolean inMessage = false;
String messageRecipient = null;
while ((line = in.readLine()) != null) {
String[] command = line.split(" ");
System.out.println("Received \"" + line + "\" from client.");
if (command[0].equals("USER")) {
if (command.length != 2) {
out.println("500 Wrong number of arguments");
System.out.println("Wrong number of arguments");
continue;
} else if (this.loggedInUser != null) {
out.println("500 Already logged in");
System.out.println("Already logged in");
continue;
}
// hack for testing
for (int i = 0; i < users.size(); i++) {
if (users.get(i).equals(command[1])) {
this.loggedInUser = command[1];
break;
}
}
if (this.loggedInUser != null) {
out.println("230 Logged in");
System.out.println("Logged in");
} else {
out.println("500 Unknown user");
System.out.println("Unknown user");
continue;
}
// ----------------
} else if (line.startsWith("MESG")) {
if (command.length != 2) {
out.println("500 Wrong number of arguments");
System.out.println("Wrong number of arguments");
continue;
} else if (!command[1].startsWith("To:")) {
out.println("500 Incorrect argument");
System.out.println("Incorrect argument");
continue;
} else if (this.loggedInUser == null) {
out.println("500 No user logged in");
System.out.println("No user logged in");
continue;
} else if (inMessage) {
out.println("500 Message already started");
System.out.println("Message already started");
continue;
}
String recipient = command[1].substring(3);
if (!users.contains(recipient)) {
out.println("500 Unknown recipient");
System.out.println("Unknown recipient");
continue;
}
inMessage = true;
messageRecipient = recipient;
out.println("250 Ok");
System.out.println("Ok");
} else if (line.startsWith("DATA")) {
if (command.length != 1) {
out.println("500 Wrong number of arguments");
continue;
} else if (this.loggedInUser == null) {
out.println("500 No user logged in");
continue;
} else if (!inMessage) {
out.println("500 Must start a message before sending data");
continue;
}
out.println("354 Enter message, ending with a \".\" on a line by itself.");
System.out.println("Enter message, ending with a \".\" on a line by itself.");
Message m = new Message(this.loggedInUser, messageRecipient);
String dataLine;
while (!(dataLine = in.readLine()).equals(".")) {
m.writeln(dataLine);
}
int max_attempts = 2;
for (int i = 0; i < max_attempts; i++) {
if (!m.store()) {
System.out.println("Failed to store message, on attempt " + (i + 1) + "/" + max_attempts);
} else {
System.out.println("Message saved!");
break;
}
}
/*
System.out.println("Sending message to: " + messageRecipient);
System.out.println(messageData);
*/
inMessage = false;
messageRecipient = null;
out.println("250 Ok");
System.out.println("Ok");
} else if (line.startsWith("QUIT")) {
if (command.length != 1) {
out.println("500 Wrong number of arguments");
System.out.println("Wrong number of arguments");
continue;
} else if (this.loggedInUser == null) {
out.println("500 No user logged in");
System.out.println("No user logged in");
continue;
}
this.loggedInUser = null;
inMessage = false;
messageRecipient = null;
out.println("221 Logged out");
System.out.println("Logged out");
} else if (line.startsWith("RETR")) {
if (command.length != 1) {
out.println("500 Wrong number of arguments");
System.out.println("Wrong number of arguments");
continue;
} else if (this.loggedInUser == null) {
out.println("500 No user logged in");
System.out.println("No user logged in");
continue;
}
List<Message> messages = Message.load(this.loggedInUser);
if (messages.size() == 0) {
out.println("250 No messages");
System.out.println("No messages");
} else {
for (Message m : messages) {
out.println(m);
System.out.println(m);
out.println("|||");
System.out.println("|||");
}
}
out.println("250 No more messages");
System.out.println("No more messages");
} else {
out.println("500 Command \"" + command[0] + "\" was not recognized");
}
}
if (line == null) {
System.out.println("Connection was closed by the client");
// perform cleanup
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Done!");
}
| public void run() {
try {
String line;
PrintWriter out = new PrintWriter(s.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
System.out.println("New client connected");
out.println("220 Service ready");
boolean inMessage = false;
String messageRecipient = null;
while ((line = in.readLine()) != null) {
String[] command = line.split(" ");
System.out.println("Received \"" + line + "\" from client.");
if (command[0].equals("USER")) {
if (command.length != 2) {
out.println("500 Wrong number of arguments");
System.out.println("Wrong number of arguments");
continue;
} else if (this.loggedInUser != null) {
out.println("500 Already logged in");
System.out.println("Already logged in");
continue;
}
// hack for testing
for (int i = 0; i < users.size(); i++) {
if (users.get(i).equals(command[1])) {
this.loggedInUser = command[1];
break;
}
}
if (this.loggedInUser != null) {
out.println("230 Logged in");
System.out.println("Logged in");
} else {
out.println("500 Unknown user");
System.out.println("Unknown user");
continue;
}
// ----------------
} else if (line.startsWith("MESG")) {
if (command.length != 2) {
out.println("500 Wrong number of arguments");
System.out.println("Wrong number of arguments");
continue;
} else if (!command[1].startsWith("To:")) {
out.println("500 Incorrect argument");
System.out.println("Incorrect argument");
continue;
} else if (this.loggedInUser == null) {
out.println("500 No user logged in");
System.out.println("No user logged in");
continue;
} else if (inMessage) {
out.println("500 Message already started");
System.out.println("Message already started");
continue;
}
String recipient = command[1].substring(3);
if (!users.contains(recipient)) {
out.println("500 Unknown recipient");
System.out.println("Unknown recipient");
continue;
}
inMessage = true;
messageRecipient = recipient;
out.println("250 Ok");
System.out.println("Ok");
} else if (line.startsWith("DATA")) {
if (command.length != 1) {
out.println("500 Wrong number of arguments");
continue;
} else if (this.loggedInUser == null) {
out.println("500 No user logged in");
continue;
} else if (!inMessage) {
out.println("500 Must start a message before sending data");
continue;
}
out.println("354 Enter message, ending with a \".\" on a line by itself.");
System.out.println("Enter message, ending with a \".\" on a line by itself.");
Message m = new Message(this.loggedInUser, messageRecipient);
String dataLine;
while (!(dataLine = in.readLine()).equals(".")) {
m.writeln(dataLine);
}
int max_attempts = 2;
for (int i = 0; i < max_attempts; i++) {
if (!m.store()) {
System.out.println("Failed to store message, on attempt " + (i + 1) + "/" + max_attempts);
} else {
System.out.println("Message saved!");
break;
}
}
/*
System.out.println("Sending message to: " + messageRecipient);
System.out.println(messageData);
*/
inMessage = false;
messageRecipient = null;
out.println("250 Ok");
System.out.println("Ok");
} else if (line.startsWith("QUIT")) {
if (command.length != 1) {
out.println("500 Wrong number of arguments");
System.out.println("Wrong number of arguments");
continue;
} else if (this.loggedInUser == null) {
out.println("500 No user logged in");
System.out.println("No user logged in");
continue;
}
this.loggedInUser = null;
inMessage = false;
messageRecipient = null;
out.println("221 Logged out");
System.out.println("Logged out");
} else if (line.startsWith("RETR")) {
if (command.length != 1) {
out.println("500 Wrong number of arguments");
System.out.println("Wrong number of arguments");
continue;
} else if (this.loggedInUser == null) {
out.println("500 No user logged in");
System.out.println("No user logged in");
continue;
}
List<Message> messages = Message.load(this.loggedInUser);
if (messages.size() == 0) {
out.println("250 No messages");
System.out.println("No messages");
} else {
for (Message m : messages) {
out.println(m);
System.out.println(m);
out.println("|||");
System.out.println("|||");
}
out.println("250 No more messages");
System.out.println("No more messages");
}
} else {
out.println("500 Command \"" + command[0] + "\" was not recognized");
}
}
if (line == null) {
System.out.println("Connection was closed by the client");
// perform cleanup
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Done!");
}
|
diff --git a/plugins/org.eclipse.tm.tcf.core/src/org/eclipse/tm/tcf/protocol/JSON.java b/plugins/org.eclipse.tm.tcf.core/src/org/eclipse/tm/tcf/protocol/JSON.java
index 41f873a33..a156c340f 100644
--- a/plugins/org.eclipse.tm.tcf.core/src/org/eclipse/tm/tcf/protocol/JSON.java
+++ b/plugins/org.eclipse.tm.tcf.core/src/org/eclipse/tm/tcf/protocol/JSON.java
@@ -1,766 +1,766 @@
/*******************************************************************************
* Copyright (c) 2007, 2010 Wind River Systems, Inc. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Wind River Systems - initial API and implementation
*******************************************************************************/
package org.eclipse.tm.tcf.protocol;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.eclipse.tm.tcf.core.Base64;
/**
* JSON is TCF preferred marshaling. This class implements generation and parsing of JSON strings.
* The code is optimized for speed since it is a time-critical part of the framework.
*
* Reading of JSON produces data structure that consists of objects of these classes:
* Boolean, Number, String, Collection, Map.
*
* Writing of JSON is supported for:
* Boolean, Number, String, char[], byte[], Object[], Collection, Map
*
* Clients can enable writing support for objects of a other classes by
* registering ObjectWriter interface implementation.
*
* @noextend This class is not intended to be subclassed by clients.
* @noinstantiate This class is not intended to be instantiated by clients.
*/
public final class JSON {
/**
* Clients implement ObjectWriter interface when they want to enable marshaling of
* object classes that are not directly supported by JSON library.
*/
public interface ObjectWriter<V> {
void write(V o) throws IOException;
}
private static final Map<Class<?>,ObjectWriter<?>> object_writers =
new HashMap<Class<?>,ObjectWriter<?>>();
/** Wrapper class for binary byte blocs */
public final static class Binary {
public final byte[] bytes;
public final int offs;
public final int size;
public Binary(byte[] bytes, int offs, int size) {
this.bytes = bytes;
this.offs = offs;
this.size = size;
}
}
private static char[] tmp_buf = new char[0x1000];
private static byte[] tmp_bbf = new byte[0x1000];
private static int tmp_buf_pos;
private static boolean zero_copy;
private static Binary[] bin_buf = new Binary[0x10];
private static int bin_buf_pos;
private static byte[] inp;
private static int inp_pos;
private static int cur_ch;
// This buffer is used to create nice error reports
private static final char[] err_buf = new char[100];
private static int err_buf_pos;
private static int err_buf_cnt;
/**
* Add a handler for converting objects of a particular class into JSON.
* @param cls - a class
* @param writer - ObjectWriter implementation that provides generation of JSON for a given class.
*/
public static <X> void addObjectWriter(Class<X> cls, ObjectWriter<X> writer) {
object_writers.put(cls, writer);
}
/**
* Write a character into JSON output buffer.
* Clients should not call this method directly, except from ObjectWriter implementation.
* @param ch
*/
public static void write(char ch) {
if (tmp_buf_pos >= tmp_buf.length) {
char[] tmp = new char[tmp_buf.length * 2];
System.arraycopy(tmp_buf, 0, tmp, 0, tmp_buf_pos);
tmp_buf = tmp;
}
tmp_buf[tmp_buf_pos++] = ch;
}
/**
* Write a string into JSON output buffer.
* The string is written "as-is". Call writeObject() to convert a String into JSON string.
* Clients should not call this method directly, except from ObjectWriter implementation.
* @param s - a string
*/
public static void write(String s) {
int l = s.length();
for (int i = 0; i < l; i++) {
char ch = s.charAt(i);
if (tmp_buf_pos >= tmp_buf.length) write(ch);
else tmp_buf[tmp_buf_pos++] = ch;
}
}
/**
* Write a non-negative integer number into JSON output buffer.
* Clients should not call this method directly, except from ObjectWriter implementation.
* @param n - a number
*/
public static void writeUInt(int n) {
assert n >= 0;
if (n >= 10) writeUInt(n / 10);
write((char)('0' + n % 10));
}
private static int readUTF8Char() {
if (inp_pos >= inp.length) return -1;
int ch = inp[inp_pos++];
if (ch < 0) {
if ((ch & 0xe0) == 0xc0) {
ch = (ch & 0x1f) << 6;
ch |= inp[inp_pos++] & 0x3f;
}
else if ((ch & 0xf0) == 0xe0) {
ch = (ch & 0x0f) << 12;
ch |= (inp[inp_pos++] & 0x3f) << 6;
ch |= inp[inp_pos++] & 0x3f;
}
else if ((ch & 0xf0) == 0xf0) {
ch = (ch & 0x0f) << 18;
ch |= (inp[inp_pos++] & 0x3f) << 12;
ch |= (inp[inp_pos++] & 0x3f) << 6;
ch |= inp[inp_pos++] & 0x3f;
}
else {
assert false : "invalid UTF-8 encoding";
ch &= 0xff;
}
}
return ch;
}
private static void read() throws IOException {
cur_ch = readUTF8Char();
err_buf[err_buf_pos++] = (char)cur_ch;
if (err_buf_pos >= err_buf.length) {
err_buf_pos = 0;
err_buf_cnt++;
}
}
private static void error() throws IOException {
error("syntax error");
}
private static void error(String msg) throws IOException {
StringBuffer bf = new StringBuffer();
bf.append("JSON " + msg + ":");
int cnt = 0;
boolean nl = true;
for (int i = 0;; i++) {
char ch = 0;
if (err_buf_cnt == 0 && i < err_buf_pos) {
ch = err_buf[i];
}
else if (err_buf_cnt > 0 && i < err_buf.length) {
ch = err_buf[(err_buf_pos + i) % err_buf.length];
}
else {
int n = readUTF8Char();
if (n < 0) break;
ch = (char)n;
}
if (nl) {
bf.append("\n ");
if (err_buf_cnt == 0) bf.append(cnt);
else bf.append('*');
bf.append(": ");
if (cnt == 0 && err_buf_cnt > 0) bf.append("...");
nl = false;
}
if (ch == 0) {
cnt++;
nl = true;
continue;
}
bf.append(ch);
}
throw new IOException(bf.toString());
}
private static int readHexDigit() throws IOException {
int n = 0;
if (cur_ch >= '0' && cur_ch <= '9') n = cur_ch - '0';
else if (cur_ch >= 'A' && cur_ch <= 'F') n = cur_ch - 'A' + 10;
else if (cur_ch >= 'a' && cur_ch <= 'f') n = cur_ch - 'a' + 10;
else error();
read();
return n;
}
private static Object readFloat(boolean sign, BigInteger val) throws IOException {
int scale = 0;
int fraction = 0;
if (cur_ch == '.') {
read();
while (cur_ch >= '0' && cur_ch <= '9') {
val = val.multiply(BigInteger.valueOf(10));
val = val.add(BigInteger.valueOf(cur_ch - '0'));
fraction++;
read();
}
}
if (cur_ch == 'E' || cur_ch == 'e') {
read();
boolean neg = cur_ch == '-';
if (neg || cur_ch == '+') read();
while (cur_ch >= '0' && cur_ch <= '9') {
scale = scale * 10 + cur_ch - '0';
read();
}
if (neg) scale = -scale;
}
if (sign) val = val.negate();
return new BigDecimal(val, fraction - scale);
}
private static Object readNestedObject() throws IOException {
switch (cur_ch) {
case '(':
read();
int len = 0;
while (cur_ch >= '0' && cur_ch <= '9') {
len = len * 10 + (cur_ch - '0');
read();
}
if (cur_ch != ')') error();
byte[] res = new byte[len];
System.arraycopy(inp, inp_pos, res, 0, len);
inp_pos += len;
read();
return res;
case '"':
read();
tmp_buf_pos = 0;
for (;;) {
if (cur_ch <= 0) error();
if (cur_ch == '"') break;
if (cur_ch == '\\') {
read();
if (cur_ch <= 0) error();
switch (cur_ch) {
case '"':
case '\\':
case '/':
break;
case 'b':
cur_ch = '\b';
break;
case 'f':
cur_ch = '\f';
break;
case 'n':
cur_ch = '\n';
break;
case 'r':
cur_ch = '\r';
break;
case 't':
cur_ch = '\t';
break;
case 'u':
read();
int n = 0;
n |= readHexDigit() << 12;
n |= readHexDigit() << 8;
n |= readHexDigit() << 4;
n |= readHexDigit();
write((char)n);
continue;
default:
error();
break;
}
}
if (tmp_buf_pos >= tmp_buf.length) {
write((char)cur_ch);
}
else {
tmp_buf[tmp_buf_pos++] = (char)cur_ch;
}
read();
}
read();
return new String(tmp_buf, 0, tmp_buf_pos);
case '[':
List<Object> l = new ArrayList<Object>();
read();
if (cur_ch <= 0) error();
if (cur_ch != ']') {
for (;;) {
l.add(readNestedObject());
if (cur_ch == ']') break;
if (cur_ch != ',') error();
read();
}
}
read();
return Collections.unmodifiableList(l);
case '{':
Map<String,Object> m = new HashMap<String,Object>();
read();
if (cur_ch <= 0) error();
if (cur_ch != '}') {
for (;;) {
String key = (String)readNestedObject();
if (cur_ch != ':') error();
read();
Object val = readNestedObject();
m.put(key, val);
if (cur_ch == '}') break;
if (cur_ch != ',') error();
read();
}
}
read();
return Collections.unmodifiableMap(m);
case 'n':
read();
if (cur_ch != 'u') error();
read();
if (cur_ch != 'l') error();
read();
if (cur_ch != 'l') error();
read();
return null;
case 'f':
read();
if (cur_ch != 'a') error();
read();
if (cur_ch != 'l') error();
read();
if (cur_ch != 's') error();
read();
if (cur_ch != 'e') error();
read();
return Boolean.FALSE;
case 't':
read();
if (cur_ch != 'r') error();
read();
if (cur_ch != 'u') error();
read();
if (cur_ch != 'e') error();
read();
return Boolean.TRUE;
case 'N':
read();
if (cur_ch != 'a') error();
read();
if (cur_ch != 'N') error();
read();
return Float.NaN;
default:
boolean neg = cur_ch == '-';
if (neg) read();
if (cur_ch >= '0' && cur_ch <= '9') {
int v = 0;
while (v <= 0x7fffffff / 10 - 1) {
v = v * 10 + (cur_ch - '0');
read();
if (cur_ch < '0' || cur_ch > '9') {
if (cur_ch == '.' || cur_ch == 'E' || cur_ch == 'e') {
return readFloat(neg, BigInteger.valueOf(v));
}
if (neg) v = -v;
return Integer.valueOf(v);
}
}
long vl = v;
while (vl < 0x7fffffffffffffffl / 10 - 1) {
vl = vl * 10 + (cur_ch - '0');
read();
if (cur_ch < '0' || cur_ch > '9') {
if (cur_ch == '.' || cur_ch == 'E' || cur_ch == 'e') {
return readFloat(neg, BigInteger.valueOf(vl));
}
if (neg) vl = -vl;
return Long.valueOf(vl);
}
}
StringBuffer sb = new StringBuffer();
sb.append(vl);
while (true) {
- sb.append(cur_ch);
+ sb.append((char)cur_ch);
read();
if (cur_ch < '0' || cur_ch > '9') {
BigInteger n = new BigInteger(sb.toString());
if (cur_ch == '.' || cur_ch == 'E' || cur_ch == 'e') {
return readFloat(neg, n);
}
if (neg) n = n.negate();
return n;
}
}
}
error();
return null;
}
}
private static Object readObject() throws IOException {
Object o = readNestedObject();
if (cur_ch >= 0) error();
return o;
}
private static Object[] readSequence() throws IOException {
List<Object> l = new ArrayList<Object>();
while (cur_ch >= 0) {
if (cur_ch == 0) l.add(null);
else l.add(readNestedObject());
if (cur_ch != 0) error("missing \\0 terminator");
read();
}
return l.toArray();
}
/**
* Write an object into JSON output buffer.
* Clients should not call this method directly, except from ObjectWriter implementation.
* @param o - an object to write
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public static void writeObject(Object o) throws IOException {
if (o == null) {
write("null");
}
else if (o instanceof Boolean) {
write(o.toString());
}
else if (o instanceof Number) {
write(o.toString());
}
else if (o instanceof String) {
String s = (String)o;
char[] arr = new char[s.length()];
s.getChars(0, arr.length, arr, 0);
writeObject(arr);
}
else if (o instanceof char[]) {
char[] s = (char[])o;
write('"');
int l = s.length;
for (int i = 0; i < l; i++) {
char ch = s[i];
switch (ch) {
case 0:
write("\\u0000");
break;
case 1:
write("\\u0001");
break;
case '\r':
write("\\r");
break;
case '\n':
write("\\n");
break;
case '\t':
write("\\t");
break;
case '\b':
write("\\b");
break;
case '\f':
write("\\f");
break;
case '"':
case '\\':
write('\\');
default:
if (tmp_buf_pos >= tmp_buf.length) write(ch);
else tmp_buf[tmp_buf_pos++] = ch;
}
}
write('"');
}
else if (o instanceof Binary) {
Binary b = (Binary)o;
if (zero_copy) {
write('(');
write(Integer.toString(b.size));
write(')');
write((char)1);
bin_buf[bin_buf_pos++] = b;
}
else {
writeObject(Base64.toBase64(b.bytes, b.offs, b.size));
}
}
else if (o instanceof byte[]) {
write('[');
byte[] arr = (byte[])o;
boolean comma = false;
for (int i = 0; i < arr.length; i++) {
if (comma) write(',');
writeUInt(arr[i] & 0xff);
comma = true;
}
write(']');
}
else if (o instanceof Object[]) {
write('[');
Object[] arr = (Object[])o;
boolean comma = false;
for (int i = 0; i < arr.length; i++) {
if (comma) write(',');
writeObject(arr[i]);
comma = true;
}
write(']');
}
else if (o instanceof Collection) {
write('[');
boolean comma = false;
for (Iterator<Object> i = ((Collection<Object>)o).iterator(); i.hasNext();) {
if (comma) write(',');
writeObject(i.next());
comma = true;
}
write(']');
}
else if (o instanceof Map) {
Map<String,Object> map = (Map<String,Object>)o;
write('{');
boolean comma = false;
for (Iterator<Map.Entry<String,Object>> i = map.entrySet().iterator(); i.hasNext();) {
if (comma) write(',');
Map.Entry<String,Object> e = i.next();
writeObject(e.getKey());
write(':');
writeObject(e.getValue());
comma = true;
}
write('}');
}
else {
ObjectWriter writer = object_writers.get(o.getClass());
if (writer == null) {
for (Class<?> c : object_writers.keySet()) {
if (c.isInstance(o)) {
writer = object_writers.get(c);
break;
}
}
}
if (writer != null) {
writer.write(o);
}
else {
throw new IOException("JSON: unsupported object type:" + o.getClass());
}
}
}
private static byte[] toBytes() {
int inp_pos = 0;
int out_pos = 0;
int blc_pos = 0;
while (inp_pos < tmp_buf_pos) {
if (out_pos > tmp_bbf.length - 4) {
byte[] tmp = new byte[tmp_bbf.length * 2];
System.arraycopy(tmp_bbf, 0, tmp, 0, out_pos);
tmp_bbf = tmp;
}
int ch = tmp_buf[inp_pos++];
if (ch == 1) {
Binary b = bin_buf[blc_pos++];
while (out_pos > tmp_bbf.length - b.size) {
byte[] tmp = new byte[tmp_bbf.length * 2];
System.arraycopy(tmp_bbf, 0, tmp, 0, out_pos);
tmp_bbf = tmp;
}
System.arraycopy(b.bytes, b.offs, tmp_bbf, out_pos, b.size);
out_pos += b.size;
}
else if (ch < 0x80) {
tmp_bbf[out_pos++] = (byte)ch;
}
else if (ch < 0x800) {
tmp_bbf[out_pos++] = (byte)((ch >> 6) | 0xc0);
tmp_bbf[out_pos++] = (byte)(ch & 0x3f | 0x80);
}
else if (ch < 0x10000) {
tmp_bbf[out_pos++] = (byte)((ch >> 12) | 0xe0);
tmp_bbf[out_pos++] = (byte)((ch >> 6) & 0x3f | 0x80);
tmp_bbf[out_pos++] = (byte)(ch & 0x3f | 0x80);
}
else {
tmp_bbf[out_pos++] = (byte)((ch >> 18) | 0xf0);
tmp_bbf[out_pos++] = (byte)((ch >> 12) & 0x3f | 0x80);
tmp_bbf[out_pos++] = (byte)((ch >> 6) & 0x3f | 0x80);
tmp_bbf[out_pos++] = (byte)(ch & 0x3f | 0x80);
}
}
byte[] res = new byte[out_pos];
System.arraycopy(tmp_bbf, 0, res, 0, out_pos);
return res;
}
/**
* Convert Java object to JSON string.
* @param o - a Java object
* @return JASON string
* @throws IOException
*/
public static String toJSON(Object o) throws IOException {
assert Protocol.isDispatchThread();
tmp_buf_pos = 0;
bin_buf_pos = 0;
zero_copy = false;
writeObject(o);
return new String(tmp_buf, 0, tmp_buf_pos);
}
/**
* Convert Java object to array of bytes that contains UTF-8 encoded JSON string.
* @param o - a Java object
* @return array of bytes
* @throws IOException
*/
public static byte[] toJASONBytes(Object o) throws IOException {
assert Protocol.isDispatchThread();
tmp_buf_pos = 0;
bin_buf_pos = 0;
zero_copy = false;
writeObject(o);
return toBytes();
}
/**
* Convert multiple Java object to array of bytes that contains
* a sequence of zero terminate UTF-8 encoded JSON strings.
* @param o - array of Java objects
* @return array of bytes
* @throws IOException
*/
public static byte[] toJSONSequence(Object[] o) throws IOException {
assert Protocol.isDispatchThread();
if (o == null || o.length == 0) return null;
tmp_buf_pos = 0;
bin_buf_pos = 0;
zero_copy = false;
for (int i = 0; i < o.length; i++) {
writeObject(o[i]);
write((char)0);
}
return toBytes();
}
/**
* Convert multiple Java object to array of bytes that contains
* a sequence of zero terminate UTF-8 encoded JSON strings.
* @param o - array of Java objects
* @param zero_copy - true to enable "zero copy" JSON extension.
* "zero copy" extension allows insertion of binary data arrays into JSON string.
* The extension allows more efficient transfer of large binary blocs.
* @return array of bytes
* @throws IOException
*/
public static byte[] toJSONSequence(Object[] o, boolean zero_copy) throws IOException {
assert Protocol.isDispatchThread();
if (o == null || o.length == 0) return null;
tmp_buf_pos = 0;
bin_buf_pos = 0;
JSON.zero_copy = zero_copy;
for (int i = 0; i < o.length; i++) {
writeObject(o[i]);
write((char)0);
}
return toBytes();
}
/**
* Convert byte array that contains UTF-8 encoded JSON string to Java object.
* @param b - array of bytes with UTF-8 encoded JSON string
* @return Java object that represents data in the JSON string
* @throws IOException
*/
public static Object parseOne(byte[] b) throws IOException {
assert Protocol.isDispatchThread();
if (b.length == 0) return null;
inp = b;
inp_pos = 0;
err_buf_pos = 0;
err_buf_cnt = 0;
read();
return readObject();
}
/**
* Convert byte array that contains sequence of zero terminated UTF-8 encoded JSON string
* to array of Java objects.
* @param b - array of bytes with sequence of zero terminated UTF-8 encoded JSON string
* @return array of Java objects that represents data in the sequence of JSON strings
* @throws IOException
*/
public static Object[] parseSequence(byte[] b) throws IOException {
assert Protocol.isDispatchThread();
inp = b;
inp_pos = 0;
err_buf_pos = 0;
err_buf_cnt = 0;
read();
return readSequence();
}
/**
* Converts a Java object to array of bytes.
* The object is expected to be created from a JSON string by using one of methods in this class.
* If the object is not one of supported representations of binary data, the method throws Error.
* @param o - a Java object representing JSON binary data
* @return array of bytes
*/
public static byte[] toByteArray(Object o) {
if (o == null) return null;
if (o instanceof byte[]) return (byte[])o;
if (o instanceof char[]) return Base64.toByteArray((char[])o);
if (o instanceof String) return Base64.toByteArray(((String)o).toCharArray());
throw new Error();
}
/**
* Converts a Java object to bytes in a given array of bytes.
* The object is expected to be created from a JSON string by using one of methods in this class.
* If the object is not one of supported representations of binary data, the method throws Error.
* @param buf - destination array of bytes
* @param offs - starting position in the destination array
* @param size - the number of bytes to be copied into the destination array
* @param o - a Java object representing JSON binary data
*/
public static void toByteArray(byte[] buf, int offs, int size, Object o) {
if (o instanceof char[]) Base64.toByteArray(buf, offs, size, (char[])o);
else if (o instanceof String) Base64.toByteArray(buf, offs, size, ((String)o).toCharArray());
else if (o != null) System.arraycopy(toByteArray(o), 0, buf, offs, size);
}
}
| true | true | private static Object readNestedObject() throws IOException {
switch (cur_ch) {
case '(':
read();
int len = 0;
while (cur_ch >= '0' && cur_ch <= '9') {
len = len * 10 + (cur_ch - '0');
read();
}
if (cur_ch != ')') error();
byte[] res = new byte[len];
System.arraycopy(inp, inp_pos, res, 0, len);
inp_pos += len;
read();
return res;
case '"':
read();
tmp_buf_pos = 0;
for (;;) {
if (cur_ch <= 0) error();
if (cur_ch == '"') break;
if (cur_ch == '\\') {
read();
if (cur_ch <= 0) error();
switch (cur_ch) {
case '"':
case '\\':
case '/':
break;
case 'b':
cur_ch = '\b';
break;
case 'f':
cur_ch = '\f';
break;
case 'n':
cur_ch = '\n';
break;
case 'r':
cur_ch = '\r';
break;
case 't':
cur_ch = '\t';
break;
case 'u':
read();
int n = 0;
n |= readHexDigit() << 12;
n |= readHexDigit() << 8;
n |= readHexDigit() << 4;
n |= readHexDigit();
write((char)n);
continue;
default:
error();
break;
}
}
if (tmp_buf_pos >= tmp_buf.length) {
write((char)cur_ch);
}
else {
tmp_buf[tmp_buf_pos++] = (char)cur_ch;
}
read();
}
read();
return new String(tmp_buf, 0, tmp_buf_pos);
case '[':
List<Object> l = new ArrayList<Object>();
read();
if (cur_ch <= 0) error();
if (cur_ch != ']') {
for (;;) {
l.add(readNestedObject());
if (cur_ch == ']') break;
if (cur_ch != ',') error();
read();
}
}
read();
return Collections.unmodifiableList(l);
case '{':
Map<String,Object> m = new HashMap<String,Object>();
read();
if (cur_ch <= 0) error();
if (cur_ch != '}') {
for (;;) {
String key = (String)readNestedObject();
if (cur_ch != ':') error();
read();
Object val = readNestedObject();
m.put(key, val);
if (cur_ch == '}') break;
if (cur_ch != ',') error();
read();
}
}
read();
return Collections.unmodifiableMap(m);
case 'n':
read();
if (cur_ch != 'u') error();
read();
if (cur_ch != 'l') error();
read();
if (cur_ch != 'l') error();
read();
return null;
case 'f':
read();
if (cur_ch != 'a') error();
read();
if (cur_ch != 'l') error();
read();
if (cur_ch != 's') error();
read();
if (cur_ch != 'e') error();
read();
return Boolean.FALSE;
case 't':
read();
if (cur_ch != 'r') error();
read();
if (cur_ch != 'u') error();
read();
if (cur_ch != 'e') error();
read();
return Boolean.TRUE;
case 'N':
read();
if (cur_ch != 'a') error();
read();
if (cur_ch != 'N') error();
read();
return Float.NaN;
default:
boolean neg = cur_ch == '-';
if (neg) read();
if (cur_ch >= '0' && cur_ch <= '9') {
int v = 0;
while (v <= 0x7fffffff / 10 - 1) {
v = v * 10 + (cur_ch - '0');
read();
if (cur_ch < '0' || cur_ch > '9') {
if (cur_ch == '.' || cur_ch == 'E' || cur_ch == 'e') {
return readFloat(neg, BigInteger.valueOf(v));
}
if (neg) v = -v;
return Integer.valueOf(v);
}
}
long vl = v;
while (vl < 0x7fffffffffffffffl / 10 - 1) {
vl = vl * 10 + (cur_ch - '0');
read();
if (cur_ch < '0' || cur_ch > '9') {
if (cur_ch == '.' || cur_ch == 'E' || cur_ch == 'e') {
return readFloat(neg, BigInteger.valueOf(vl));
}
if (neg) vl = -vl;
return Long.valueOf(vl);
}
}
StringBuffer sb = new StringBuffer();
sb.append(vl);
while (true) {
sb.append(cur_ch);
read();
if (cur_ch < '0' || cur_ch > '9') {
BigInteger n = new BigInteger(sb.toString());
if (cur_ch == '.' || cur_ch == 'E' || cur_ch == 'e') {
return readFloat(neg, n);
}
if (neg) n = n.negate();
return n;
}
}
}
error();
return null;
}
}
| private static Object readNestedObject() throws IOException {
switch (cur_ch) {
case '(':
read();
int len = 0;
while (cur_ch >= '0' && cur_ch <= '9') {
len = len * 10 + (cur_ch - '0');
read();
}
if (cur_ch != ')') error();
byte[] res = new byte[len];
System.arraycopy(inp, inp_pos, res, 0, len);
inp_pos += len;
read();
return res;
case '"':
read();
tmp_buf_pos = 0;
for (;;) {
if (cur_ch <= 0) error();
if (cur_ch == '"') break;
if (cur_ch == '\\') {
read();
if (cur_ch <= 0) error();
switch (cur_ch) {
case '"':
case '\\':
case '/':
break;
case 'b':
cur_ch = '\b';
break;
case 'f':
cur_ch = '\f';
break;
case 'n':
cur_ch = '\n';
break;
case 'r':
cur_ch = '\r';
break;
case 't':
cur_ch = '\t';
break;
case 'u':
read();
int n = 0;
n |= readHexDigit() << 12;
n |= readHexDigit() << 8;
n |= readHexDigit() << 4;
n |= readHexDigit();
write((char)n);
continue;
default:
error();
break;
}
}
if (tmp_buf_pos >= tmp_buf.length) {
write((char)cur_ch);
}
else {
tmp_buf[tmp_buf_pos++] = (char)cur_ch;
}
read();
}
read();
return new String(tmp_buf, 0, tmp_buf_pos);
case '[':
List<Object> l = new ArrayList<Object>();
read();
if (cur_ch <= 0) error();
if (cur_ch != ']') {
for (;;) {
l.add(readNestedObject());
if (cur_ch == ']') break;
if (cur_ch != ',') error();
read();
}
}
read();
return Collections.unmodifiableList(l);
case '{':
Map<String,Object> m = new HashMap<String,Object>();
read();
if (cur_ch <= 0) error();
if (cur_ch != '}') {
for (;;) {
String key = (String)readNestedObject();
if (cur_ch != ':') error();
read();
Object val = readNestedObject();
m.put(key, val);
if (cur_ch == '}') break;
if (cur_ch != ',') error();
read();
}
}
read();
return Collections.unmodifiableMap(m);
case 'n':
read();
if (cur_ch != 'u') error();
read();
if (cur_ch != 'l') error();
read();
if (cur_ch != 'l') error();
read();
return null;
case 'f':
read();
if (cur_ch != 'a') error();
read();
if (cur_ch != 'l') error();
read();
if (cur_ch != 's') error();
read();
if (cur_ch != 'e') error();
read();
return Boolean.FALSE;
case 't':
read();
if (cur_ch != 'r') error();
read();
if (cur_ch != 'u') error();
read();
if (cur_ch != 'e') error();
read();
return Boolean.TRUE;
case 'N':
read();
if (cur_ch != 'a') error();
read();
if (cur_ch != 'N') error();
read();
return Float.NaN;
default:
boolean neg = cur_ch == '-';
if (neg) read();
if (cur_ch >= '0' && cur_ch <= '9') {
int v = 0;
while (v <= 0x7fffffff / 10 - 1) {
v = v * 10 + (cur_ch - '0');
read();
if (cur_ch < '0' || cur_ch > '9') {
if (cur_ch == '.' || cur_ch == 'E' || cur_ch == 'e') {
return readFloat(neg, BigInteger.valueOf(v));
}
if (neg) v = -v;
return Integer.valueOf(v);
}
}
long vl = v;
while (vl < 0x7fffffffffffffffl / 10 - 1) {
vl = vl * 10 + (cur_ch - '0');
read();
if (cur_ch < '0' || cur_ch > '9') {
if (cur_ch == '.' || cur_ch == 'E' || cur_ch == 'e') {
return readFloat(neg, BigInteger.valueOf(vl));
}
if (neg) vl = -vl;
return Long.valueOf(vl);
}
}
StringBuffer sb = new StringBuffer();
sb.append(vl);
while (true) {
sb.append((char)cur_ch);
read();
if (cur_ch < '0' || cur_ch > '9') {
BigInteger n = new BigInteger(sb.toString());
if (cur_ch == '.' || cur_ch == 'E' || cur_ch == 'e') {
return readFloat(neg, n);
}
if (neg) n = n.negate();
return n;
}
}
}
error();
return null;
}
}
|
diff --git a/BetterBatteryStats/src/com/asksven/betterbatterystats/adapters/StatsAdapter.java b/BetterBatteryStats/src/com/asksven/betterbatterystats/adapters/StatsAdapter.java
index d4ca2222..7e27a6cf 100644
--- a/BetterBatteryStats/src/com/asksven/betterbatterystats/adapters/StatsAdapter.java
+++ b/BetterBatteryStats/src/com/asksven/betterbatterystats/adapters/StatsAdapter.java
@@ -1,476 +1,476 @@
/*
* Copyright (C) 2011-2012 asksven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.asksven.betterbatterystats.adapters;
import java.util.ArrayList;
import java.util.List;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.provider.Settings;
import com.asksven.android.common.kernelutils.NativeKernelWakelock;
import com.asksven.android.common.kernelutils.State;
import com.asksven.android.common.privateapiproxies.Alarm;
import com.asksven.android.common.privateapiproxies.Alarm.AlarmItem;
import com.asksven.android.common.privateapiproxies.Misc;
import com.asksven.android.common.privateapiproxies.NetworkUsage;
import com.asksven.android.common.privateapiproxies.Process;
import com.asksven.android.common.privateapiproxies.StatElement;
import com.asksven.betterbatterystats.data.GoogleAnalytics;
import com.asksven.betterbatterystats.data.KbData;
import com.asksven.betterbatterystats.data.KbEntry;
import com.asksven.betterbatterystats.data.KbReader;
import com.asksven.betterbatterystats.widgets.GraphableBars;
import com.asksven.betterbatterystats.HelpActivity;
import com.asksven.betterbatterystats.PackageInfoTabsPager;
import com.asksven.betterbatterystats.R;
public class StatsAdapter extends BaseAdapter
{
private Context m_context;
private List<StatElement> m_listData;
private static final String TAG = "StatsAdapter";
private double m_maxValue = 0;
/** The Knowlegde base */
private KbData m_kb;
public StatsAdapter(Context context, List<StatElement> listData)
{
this.m_context = context;
this.m_listData = listData;
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this.m_context);
boolean bKbEnabled = sharedPrefs.getBoolean("enable_kb", true);
if (bKbEnabled)
{
// async read KB
new ReadKb().execute("");
}
if (m_listData != null)
{
for (int i = 0; i < m_listData.size(); i++)
{
StatElement g = m_listData.get(i);
double[] values = g.getValues();
m_maxValue = Math.max(m_maxValue, values[values.length - 1]);
m_maxValue = Math.max(m_maxValue, g.getMaxValue());
}
}
}
public int getCount()
{
if (m_listData != null)
{
return m_listData.size();
}
else
{
return 0;
}
}
public Object getItem(int position)
{
return m_listData.get(position);
}
public long getItemId(int position)
{
return position;
}
public View getView(int position, View convertView, ViewGroup viewGroup)
{
StatElement entry = m_listData.get(position);
if (convertView == null)
{
LayoutInflater inflater = (LayoutInflater) m_context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.stat_row, null);
}
TextView tvName = (TextView) convertView.findViewById(R.id.TextViewName);
tvName.setText(entry.getName());
KbEntry kbentry = null;
if (m_kb != null)
{
kbentry = m_kb.findByStatElement(entry.getName(), entry.getFqn(m_context));
}
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this.m_context);
boolean bShowKb = sharedPrefs.getBoolean("enable_kb", true);
ImageView iconKb = (ImageView) convertView.findViewById(R.id.imageKB);
if ( (bShowKb) && (kbentry != null))
{
iconKb.setVisibility(View.VISIBLE);
}
else
{
iconKb.setVisibility(View.INVISIBLE);
}
TextView tvFqn = (TextView) convertView.findViewById(R.id.TextViewFqn);
tvFqn.setText(entry.getFqn(m_context));
TextView tvData = (TextView) convertView.findViewById(R.id.TextViewData);
tvData.setText(entry.getData());
LinearLayout myLayout = (LinearLayout) convertView.findViewById(R.id.LinearLayoutBar);
LinearLayout myFqnLayout = (LinearLayout) convertView.findViewById(R.id.LinearLayoutFqn);
LinearLayout myRow = (LinearLayout) convertView.findViewById(R.id.LinearLayoutEntry);
// long press for "copy to clipboard"
myRow.setOnLongClickListener(new OnItemLongClickListener(position));
GraphableBars buttonBar = (GraphableBars) convertView.findViewById(R.id.ButtonBar);
ImageView iconView = (ImageView) convertView.findViewById(R.id.icon);
if (sharedPrefs.getBoolean("hide_bars", false))
{
myLayout.setVisibility(View.GONE);
}
else
{
myLayout.setVisibility(View.VISIBLE);
int iHeight = 10;
try
{
iHeight = Integer.valueOf(sharedPrefs.getString("graph_bar_height", "10"));
}
catch (Exception e)
{
iHeight = 10;
}
if (iHeight == 0)
{
iHeight = 10;
}
buttonBar.setMinimumHeight(iHeight);
buttonBar.setName(entry.getName());
buttonBar.setValues(entry.getValues(), m_maxValue);
}
// add on click listener for the icon only if KB is enabled
if (bShowKb)
{
// set a click listener for the list
iconKb.setOnClickListener(new OnIconClickListener(position));
}
// show / hide fqn text
if ((entry instanceof Process) || (entry instanceof Alarm) || (entry instanceof NativeKernelWakelock) || (entry instanceof State) || (entry instanceof Misc))
{
myFqnLayout.setVisibility(View.GONE);
}
else
{
myFqnLayout.setVisibility(View.VISIBLE);
}
// show / hide package icons
- if ((entry instanceof Process) || (entry instanceof NativeKernelWakelock) || (entry instanceof State) || (entry instanceof Misc))
+ if ((entry instanceof NativeKernelWakelock) || (entry instanceof State) || (entry instanceof Misc))
{
iconView.setVisibility(View.GONE);
}
else
{
iconView.setVisibility(View.VISIBLE);
iconView.setImageDrawable(entry.getIcon(m_context));
// set a click listener for the list
iconView.setOnClickListener(new OnPackageClickListener(position));
}
// add on click listener for the list entry if details are availble
if ( (entry instanceof Alarm) || (entry instanceof NativeKernelWakelock) )
{
convertView.setOnClickListener(new OnItemClickListener(position));
}
// // show / hide set dividers
// ListView myList = (ListView) convertView.getListView(); //findViewById(R.id.id.list);
// myList.setDivider(new ColorDrawable(0x99F10529));
// myList.setDividerHeight(1);
return convertView;
}
/**
* Handler for on click of the KB icon
* @author sven
*
*/
private class OnIconClickListener implements OnClickListener
{
private int m_iPosition;
OnIconClickListener(int position)
{
m_iPosition = position;
}
@Override
public void onClick(View arg0)
{
StatElement entry = (StatElement) getItem(m_iPosition);
// the timing may lead to m_kb not being initialized yet, it must be checked
if (m_kb == null)
{
return;
}
KbEntry kbentry = m_kb.findByStatElement(entry.getName(), entry.getFqn(StatsAdapter.this.m_context));
if (kbentry != null)
{
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(StatsAdapter.this.m_context);
String url = kbentry.getUrl();
if (sharedPrefs.getBoolean("kb_ext_browser", true))
{
Intent intent = new Intent("android.intent.action.VIEW",
Uri.parse(url));
StatsAdapter.this.m_context.startActivity(intent);
}
else
{
Intent intentKB = new Intent(StatsAdapter.this.m_context,
HelpActivity.class);
intentKB.putExtra("url", url);
StatsAdapter.this.m_context.startActivity(intentKB);
}
}
}
}
/**
* Handler for on click of the KB icon
* @author sven
*
*/
private class OnPackageClickListener implements OnClickListener
{
private int m_iPosition;
OnPackageClickListener(int position)
{
m_iPosition = position;
}
@Override
public void onClick(View arg0)
{
StatElement entry = (StatElement) getItem(m_iPosition);
Context ctx = arg0.getContext();
if (entry.getIcon(ctx) == null)
{
return;
}
// ctx.startActivity(new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS));
String packageName = entry.getPackageName();
showInstalledPackageDetails(ctx, packageName);
}
}
/**
* Handler for the on click of the list item
* @author sven
*
*/
private class OnItemClickListener implements OnClickListener
{
private int m_iPosition;
OnItemClickListener(int position)
{
m_iPosition = position;
}
@Override
public void onClick(View arg0)
{
StatElement entry = (StatElement) getItem(m_iPosition);
if (entry instanceof Alarm)
{
Alarm alarmEntry = (Alarm) getItem(m_iPosition);
Dialog dialog = new Dialog(m_context);
dialog.setContentView(R.layout.alarms_dialog);
dialog.setTitle("Details");
TextView title = (TextView) dialog.findViewById(R.id.title);
TextView subtitle = (TextView) dialog.findViewById(R.id.subtitle);
TextView text = (TextView) dialog.findViewById(R.id.text);
title.setText(entry.getName());
subtitle.setText(entry.getData());
String strText = "";
ArrayList<AlarmItem> myItems = alarmEntry.getItems();
if (myItems != null)
{
for (int i=0; i<myItems.size(); i++)
{
if (myItems.get(i).getCount() > 0)
{
strText = strText + myItems.get(i).getData() + "\n";
}
}
}
text.setText(strText);
dialog.show();
}
if (entry instanceof NativeKernelWakelock)
{
NativeKernelWakelock kernelWakelockEntry = (NativeKernelWakelock) getItem(m_iPosition);
Dialog dialog = new Dialog(m_context);
dialog.setContentView(R.layout.alarms_dialog);
dialog.setTitle("Details");
TextView title = (TextView) dialog.findViewById(R.id.title);
TextView subtitle = (TextView) dialog.findViewById(R.id.subtitle);
TextView text = (TextView) dialog.findViewById(R.id.text);
title.setText(kernelWakelockEntry.getName());
subtitle.setText(kernelWakelockEntry.getData());
String strText = "";
strText += "Count: " + kernelWakelockEntry.getCount() + "\n";
strText += "Expire Count: " + kernelWakelockEntry.getExpireCount() + "\n";
strText += "Wake Count: " + kernelWakelockEntry.getWakeCount() + "\n";
strText += "Total Time: "+ kernelWakelockEntry.getTtlTime() + "\n";
strText += "Sleep Time: " + kernelWakelockEntry.getSleepTime() + "\n";
strText += "Max Time: " + kernelWakelockEntry.getMaxTime() + "\n";
text.setText(strText);
dialog.show();
}
}
}
/**
* Handler for the on click of the list item
* @author sven
*
*/
private class OnItemLongClickListener implements OnLongClickListener
{
private int m_iPosition;
OnItemLongClickListener(int position)
{
m_iPosition = position;
}
@SuppressLint("NewApi")
@Override
public boolean onLongClick(View arg0)
{
StatElement entry = (StatElement) getItem(m_iPosition);
if(android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB)
{
android.text.ClipboardManager clipboard = (android.text.ClipboardManager) m_context.getSystemService(Context.CLIPBOARD_SERVICE);
clipboard.setText(entry.getName());
}
else
{
android.content.ClipboardManager clipboard = (android.content.ClipboardManager) m_context.getSystemService(Context.CLIPBOARD_SERVICE);
android.content.ClipData clip = android.content.ClipData.newPlainText("Copied Text", entry.getName());
clipboard.setPrimaryClip(clip);
}
Toast.makeText(m_context, entry.getName() + " was copied to the clipboard", Toast.LENGTH_LONG).show();
// if (entry instanceof Alarm)
// {
// Alarm alarmEntry = (Alarm) getItem(m_iPosition);
//
// }
// if (entry instanceof NativeKernelWakelock)
// {
// NativeKernelWakelock kernelWakelockEntry = (NativeKernelWakelock) getItem(m_iPosition);
//
// }
return true;
}
}
private class ReadKb extends AsyncTask
{
@Override
protected Object doInBackground(Object... params)
{
// retrieve KB
StatsAdapter.this.m_kb = KbReader.read(StatsAdapter.this.m_context);
return true;
}
@Override
protected void onPostExecute(Object o)
{
super.onPostExecute(o);
// update hourglass
}
}
public static void showInstalledPackageDetails(Context context, String packageName)
{
Intent intentPerms = new Intent(context, PackageInfoTabsPager.class); //Activity.class);
intentPerms.putExtra("package", packageName);
GoogleAnalytics.getInstance(context).trackPage(GoogleAnalytics.ACTIVITY_PERMS);
context.startActivity(intentPerms);
}
}
| true | true | public View getView(int position, View convertView, ViewGroup viewGroup)
{
StatElement entry = m_listData.get(position);
if (convertView == null)
{
LayoutInflater inflater = (LayoutInflater) m_context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.stat_row, null);
}
TextView tvName = (TextView) convertView.findViewById(R.id.TextViewName);
tvName.setText(entry.getName());
KbEntry kbentry = null;
if (m_kb != null)
{
kbentry = m_kb.findByStatElement(entry.getName(), entry.getFqn(m_context));
}
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this.m_context);
boolean bShowKb = sharedPrefs.getBoolean("enable_kb", true);
ImageView iconKb = (ImageView) convertView.findViewById(R.id.imageKB);
if ( (bShowKb) && (kbentry != null))
{
iconKb.setVisibility(View.VISIBLE);
}
else
{
iconKb.setVisibility(View.INVISIBLE);
}
TextView tvFqn = (TextView) convertView.findViewById(R.id.TextViewFqn);
tvFqn.setText(entry.getFqn(m_context));
TextView tvData = (TextView) convertView.findViewById(R.id.TextViewData);
tvData.setText(entry.getData());
LinearLayout myLayout = (LinearLayout) convertView.findViewById(R.id.LinearLayoutBar);
LinearLayout myFqnLayout = (LinearLayout) convertView.findViewById(R.id.LinearLayoutFqn);
LinearLayout myRow = (LinearLayout) convertView.findViewById(R.id.LinearLayoutEntry);
// long press for "copy to clipboard"
myRow.setOnLongClickListener(new OnItemLongClickListener(position));
GraphableBars buttonBar = (GraphableBars) convertView.findViewById(R.id.ButtonBar);
ImageView iconView = (ImageView) convertView.findViewById(R.id.icon);
if (sharedPrefs.getBoolean("hide_bars", false))
{
myLayout.setVisibility(View.GONE);
}
else
{
myLayout.setVisibility(View.VISIBLE);
int iHeight = 10;
try
{
iHeight = Integer.valueOf(sharedPrefs.getString("graph_bar_height", "10"));
}
catch (Exception e)
{
iHeight = 10;
}
if (iHeight == 0)
{
iHeight = 10;
}
buttonBar.setMinimumHeight(iHeight);
buttonBar.setName(entry.getName());
buttonBar.setValues(entry.getValues(), m_maxValue);
}
// add on click listener for the icon only if KB is enabled
if (bShowKb)
{
// set a click listener for the list
iconKb.setOnClickListener(new OnIconClickListener(position));
}
// show / hide fqn text
if ((entry instanceof Process) || (entry instanceof Alarm) || (entry instanceof NativeKernelWakelock) || (entry instanceof State) || (entry instanceof Misc))
{
myFqnLayout.setVisibility(View.GONE);
}
else
{
myFqnLayout.setVisibility(View.VISIBLE);
}
// show / hide package icons
if ((entry instanceof Process) || (entry instanceof NativeKernelWakelock) || (entry instanceof State) || (entry instanceof Misc))
{
iconView.setVisibility(View.GONE);
}
else
{
iconView.setVisibility(View.VISIBLE);
iconView.setImageDrawable(entry.getIcon(m_context));
// set a click listener for the list
iconView.setOnClickListener(new OnPackageClickListener(position));
}
// add on click listener for the list entry if details are availble
if ( (entry instanceof Alarm) || (entry instanceof NativeKernelWakelock) )
{
convertView.setOnClickListener(new OnItemClickListener(position));
}
// // show / hide set dividers
// ListView myList = (ListView) convertView.getListView(); //findViewById(R.id.id.list);
// myList.setDivider(new ColorDrawable(0x99F10529));
// myList.setDividerHeight(1);
return convertView;
}
| public View getView(int position, View convertView, ViewGroup viewGroup)
{
StatElement entry = m_listData.get(position);
if (convertView == null)
{
LayoutInflater inflater = (LayoutInflater) m_context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.stat_row, null);
}
TextView tvName = (TextView) convertView.findViewById(R.id.TextViewName);
tvName.setText(entry.getName());
KbEntry kbentry = null;
if (m_kb != null)
{
kbentry = m_kb.findByStatElement(entry.getName(), entry.getFqn(m_context));
}
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this.m_context);
boolean bShowKb = sharedPrefs.getBoolean("enable_kb", true);
ImageView iconKb = (ImageView) convertView.findViewById(R.id.imageKB);
if ( (bShowKb) && (kbentry != null))
{
iconKb.setVisibility(View.VISIBLE);
}
else
{
iconKb.setVisibility(View.INVISIBLE);
}
TextView tvFqn = (TextView) convertView.findViewById(R.id.TextViewFqn);
tvFqn.setText(entry.getFqn(m_context));
TextView tvData = (TextView) convertView.findViewById(R.id.TextViewData);
tvData.setText(entry.getData());
LinearLayout myLayout = (LinearLayout) convertView.findViewById(R.id.LinearLayoutBar);
LinearLayout myFqnLayout = (LinearLayout) convertView.findViewById(R.id.LinearLayoutFqn);
LinearLayout myRow = (LinearLayout) convertView.findViewById(R.id.LinearLayoutEntry);
// long press for "copy to clipboard"
myRow.setOnLongClickListener(new OnItemLongClickListener(position));
GraphableBars buttonBar = (GraphableBars) convertView.findViewById(R.id.ButtonBar);
ImageView iconView = (ImageView) convertView.findViewById(R.id.icon);
if (sharedPrefs.getBoolean("hide_bars", false))
{
myLayout.setVisibility(View.GONE);
}
else
{
myLayout.setVisibility(View.VISIBLE);
int iHeight = 10;
try
{
iHeight = Integer.valueOf(sharedPrefs.getString("graph_bar_height", "10"));
}
catch (Exception e)
{
iHeight = 10;
}
if (iHeight == 0)
{
iHeight = 10;
}
buttonBar.setMinimumHeight(iHeight);
buttonBar.setName(entry.getName());
buttonBar.setValues(entry.getValues(), m_maxValue);
}
// add on click listener for the icon only if KB is enabled
if (bShowKb)
{
// set a click listener for the list
iconKb.setOnClickListener(new OnIconClickListener(position));
}
// show / hide fqn text
if ((entry instanceof Process) || (entry instanceof Alarm) || (entry instanceof NativeKernelWakelock) || (entry instanceof State) || (entry instanceof Misc))
{
myFqnLayout.setVisibility(View.GONE);
}
else
{
myFqnLayout.setVisibility(View.VISIBLE);
}
// show / hide package icons
if ((entry instanceof NativeKernelWakelock) || (entry instanceof State) || (entry instanceof Misc))
{
iconView.setVisibility(View.GONE);
}
else
{
iconView.setVisibility(View.VISIBLE);
iconView.setImageDrawable(entry.getIcon(m_context));
// set a click listener for the list
iconView.setOnClickListener(new OnPackageClickListener(position));
}
// add on click listener for the list entry if details are availble
if ( (entry instanceof Alarm) || (entry instanceof NativeKernelWakelock) )
{
convertView.setOnClickListener(new OnItemClickListener(position));
}
// // show / hide set dividers
// ListView myList = (ListView) convertView.getListView(); //findViewById(R.id.id.list);
// myList.setDivider(new ColorDrawable(0x99F10529));
// myList.setDividerHeight(1);
return convertView;
}
|
diff --git a/src/servers/src/org/xtreemfs/dir/DIR.java b/src/servers/src/org/xtreemfs/dir/DIR.java
index f2847c79..00d965b1 100644
--- a/src/servers/src/org/xtreemfs/dir/DIR.java
+++ b/src/servers/src/org/xtreemfs/dir/DIR.java
@@ -1,119 +1,119 @@
/* Copyright (c) 2009 Konrad-Zuse-Zentrum fuer Informationstechnik Berlin.
This file is part of XtreemFS. XtreemFS is part of XtreemOS, a Linux-based
Grid Operating System, see <http://www.xtreemos.eu> for more details.
The XtreemOS project has been developed with the financial support of the
European Commission's IST program under contract #FP6-033576.
XtreemFS is free software: you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free
Software Foundation, either version 2 of the License, or (at your option)
any later version.
XtreemFS is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with XtreemFS. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* AUTHORS: Jan Stender (ZIB)
*/
package org.xtreemfs.dir;
import java.io.IOException;
import org.xtreemfs.common.logging.Logging;
import org.xtreemfs.common.logging.Logging.Category;
import org.xtreemfs.include.common.config.BabuDBConfig;
import org.xtreemfs.include.common.config.ReplicationConfig;
/**
* This class can be used to start a new instance of the Directory Service.
*
* @author stender
*
*/
public class DIR {
/**
* @param args
* the command line arguments
*/
public static void main(String[] args) {
String configFileName = "../../etc/xos/xtreemfs/dirconfig.test";
String dbsConfigFileName = "../../etc/xos/xtreemfs/dirdbconfig.test";
if (args.length < 1 || args.length > 2) {
System.out.println("using default config file " + configFileName);
System.out.println("using default BabuDB config file "
+ dbsConfigFileName);
} else {
configFileName = args[0];
if (args.length == 2)
dbsConfigFileName = args[1];
else
System.out.println("using default BabuDB config file "
+ dbsConfigFileName);
}
DIRConfig config = null;
try {
config = new DIRConfig(configFileName);
} catch (IOException ex) {
ex.printStackTrace();
return;
}
BabuDBConfig dbsConfig = null;
try {
dbsConfig = new ReplicationConfig(dbsConfigFileName);
- } catch (IOException e) {
+ } catch (Throwable e) {
try {
dbsConfig = new BabuDBConfig(dbsConfigFileName);
} catch (IOException ex) {
ex.printStackTrace();
return;
}
}
Logging.start(config.getDebugLevel(), config.getDebugCategories());
if (Logging.isInfo())
Logging.logMessage(Logging.LEVEL_INFO, Category.misc, (Object) null, "JAVA_HOME=%s", System
.getProperty("java.home"));
try {
final DIRRequestDispatcher rq = new DIRRequestDispatcher(config, dbsConfig);
rq.startup();
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
try {
if (Logging.isInfo())
Logging.logMessage(Logging.LEVEL_INFO, Category.lifecycle, this,
"received shutdown signal!");
rq.shutdown();
if (Logging.isInfo())
Logging.logMessage(Logging.LEVEL_INFO, Category.lifecycle, this,
"DIR shotdown complete");
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
} catch (Exception ex) {
Logging.logMessage(Logging.LEVEL_CRIT, null,
"DIR could not start up due to an exception. Aborted.");
Logging.logError(Logging.LEVEL_CRIT, null, ex);
System.exit(1);
}
}
}
| true | true | public static void main(String[] args) {
String configFileName = "../../etc/xos/xtreemfs/dirconfig.test";
String dbsConfigFileName = "../../etc/xos/xtreemfs/dirdbconfig.test";
if (args.length < 1 || args.length > 2) {
System.out.println("using default config file " + configFileName);
System.out.println("using default BabuDB config file "
+ dbsConfigFileName);
} else {
configFileName = args[0];
if (args.length == 2)
dbsConfigFileName = args[1];
else
System.out.println("using default BabuDB config file "
+ dbsConfigFileName);
}
DIRConfig config = null;
try {
config = new DIRConfig(configFileName);
} catch (IOException ex) {
ex.printStackTrace();
return;
}
BabuDBConfig dbsConfig = null;
try {
dbsConfig = new ReplicationConfig(dbsConfigFileName);
} catch (IOException e) {
try {
dbsConfig = new BabuDBConfig(dbsConfigFileName);
} catch (IOException ex) {
ex.printStackTrace();
return;
}
}
Logging.start(config.getDebugLevel(), config.getDebugCategories());
if (Logging.isInfo())
Logging.logMessage(Logging.LEVEL_INFO, Category.misc, (Object) null, "JAVA_HOME=%s", System
.getProperty("java.home"));
try {
final DIRRequestDispatcher rq = new DIRRequestDispatcher(config, dbsConfig);
rq.startup();
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
try {
if (Logging.isInfo())
Logging.logMessage(Logging.LEVEL_INFO, Category.lifecycle, this,
"received shutdown signal!");
rq.shutdown();
if (Logging.isInfo())
Logging.logMessage(Logging.LEVEL_INFO, Category.lifecycle, this,
"DIR shotdown complete");
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
} catch (Exception ex) {
Logging.logMessage(Logging.LEVEL_CRIT, null,
"DIR could not start up due to an exception. Aborted.");
Logging.logError(Logging.LEVEL_CRIT, null, ex);
System.exit(1);
}
}
| public static void main(String[] args) {
String configFileName = "../../etc/xos/xtreemfs/dirconfig.test";
String dbsConfigFileName = "../../etc/xos/xtreemfs/dirdbconfig.test";
if (args.length < 1 || args.length > 2) {
System.out.println("using default config file " + configFileName);
System.out.println("using default BabuDB config file "
+ dbsConfigFileName);
} else {
configFileName = args[0];
if (args.length == 2)
dbsConfigFileName = args[1];
else
System.out.println("using default BabuDB config file "
+ dbsConfigFileName);
}
DIRConfig config = null;
try {
config = new DIRConfig(configFileName);
} catch (IOException ex) {
ex.printStackTrace();
return;
}
BabuDBConfig dbsConfig = null;
try {
dbsConfig = new ReplicationConfig(dbsConfigFileName);
} catch (Throwable e) {
try {
dbsConfig = new BabuDBConfig(dbsConfigFileName);
} catch (IOException ex) {
ex.printStackTrace();
return;
}
}
Logging.start(config.getDebugLevel(), config.getDebugCategories());
if (Logging.isInfo())
Logging.logMessage(Logging.LEVEL_INFO, Category.misc, (Object) null, "JAVA_HOME=%s", System
.getProperty("java.home"));
try {
final DIRRequestDispatcher rq = new DIRRequestDispatcher(config, dbsConfig);
rq.startup();
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
try {
if (Logging.isInfo())
Logging.logMessage(Logging.LEVEL_INFO, Category.lifecycle, this,
"received shutdown signal!");
rq.shutdown();
if (Logging.isInfo())
Logging.logMessage(Logging.LEVEL_INFO, Category.lifecycle, this,
"DIR shotdown complete");
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
} catch (Exception ex) {
Logging.logMessage(Logging.LEVEL_CRIT, null,
"DIR could not start up due to an exception. Aborted.");
Logging.logError(Logging.LEVEL_CRIT, null, ex);
System.exit(1);
}
}
|
diff --git a/src/api/org/openmrs/validator/ConceptValidator.java b/src/api/org/openmrs/validator/ConceptValidator.java
index c439d88f..01f76954 100644
--- a/src/api/org/openmrs/validator/ConceptValidator.java
+++ b/src/api/org/openmrs/validator/ConceptValidator.java
@@ -1,124 +1,124 @@
/**
* The contents of this file are subject to the OpenMRS Public License
* Version 1.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://license.openmrs.org
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
*
* Copyright (C) OpenMRS, LLC. All Rights Reserved.
*/
package org.openmrs.validator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openmrs.Concept;
import org.openmrs.annotation.Handler;
import org.openmrs.api.APIException;
import org.openmrs.api.DuplicateConceptNameException;
import org.openmrs.api.context.Context;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
/**
* Validates methods of the {@link Concept} object.
*/
@Handler(supports = { Concept.class }, order = 50)
public class ConceptValidator implements Validator {
/** Log for this class and subclasses */
protected final Log log = LogFactory.getLog(getClass());
/**
* Determines if the command object being submitted is a valid type
*
* @see org.springframework.validation.Validator#supports(java.lang.Class)
*/
@SuppressWarnings("unchecked")
public boolean supports(Class c) {
return c.equals(Concept.class);
}
/**
* Checks that a given concept object has a unique name or preferred name across the entire
* unretired and preferred concept name space in a given locale(should be the default
* application locale set in the openmrs context). Currently this method is called just before
* the concept is persisted in the database
*
* @should fail if there is a duplicate unretired concept name in the locale
* @should fail if the preferred name is an empty string
* @should fail if the object parameter is null
* @should pass if the found duplicate concept is actually retired
* @should pass if the concept is being updated with no name change
*/
public void validate(Object obj, Errors errorss) throws APIException, DuplicateConceptNameException {
if (obj == null || !(obj instanceof Concept)) {
if (log.isErrorEnabled())
log.error("The parameter obj should not be null and must be of type" + Concept.class);
throw new IllegalArgumentException("Concept name is null or of invalid class");
} else {
Concept newConcept = (Concept) obj;
String newName = null;
//no name to validate, but why is this the case?
if (newConcept.getName() == null)
return;
//if the new concept name is in a different locale other than openmrs' default one
- if (newConcept.getName().getLocale() != null && newConcept.getName().getLocale() != Context.getLocale())
+ if (newConcept.getName().getLocale() != null && !newConcept.getName().getLocale().equals(Context.getLocale()))
newName = newConcept.getName().getName();
else
newName = newConcept.getPreferredName(Context.getLocale()).getName();
if (StringUtils.isBlank(newName)) {
if (log.isErrorEnabled())
log.error("No preferred name specified for the concept to be validated");
throw new APIException("Concept name cannot be an empty String");
}
if (log.isDebugEnabled())
log.debug("Looking up concept names matching " + newName);
List<Concept> matchingConcepts = Context.getConceptService().getConceptsByName(newName);
Set<Concept> duplicates = new HashSet<Concept>();
for (Concept c : matchingConcepts) {
//If updating a concept, read past the concept being updated
- if (newConcept.getConceptId() != null && c.getConceptId() == newConcept.getConceptId())
+ if (newConcept.getConceptId() != null && c.getConceptId().intValue() == newConcept.getConceptId())
continue;
//get only duplicates that are not retired
if (c.getPreferredName(Context.getLocale()).getName().equalsIgnoreCase(newName) && !c.isRetired()) {
duplicates.add(c);
}
}
if (duplicates.size() > 0) {
for (Concept duplicate : duplicates) {
if (log.isErrorEnabled())
log.error("The name '" + newName + "' is already being used by concept with Id: "
+ duplicate.getConceptId());
throw new DuplicateConceptNameException("Duplicate concept name '" + newName + "'");
}
}
}
}
}
| false | true | public void validate(Object obj, Errors errorss) throws APIException, DuplicateConceptNameException {
if (obj == null || !(obj instanceof Concept)) {
if (log.isErrorEnabled())
log.error("The parameter obj should not be null and must be of type" + Concept.class);
throw new IllegalArgumentException("Concept name is null or of invalid class");
} else {
Concept newConcept = (Concept) obj;
String newName = null;
//no name to validate, but why is this the case?
if (newConcept.getName() == null)
return;
//if the new concept name is in a different locale other than openmrs' default one
if (newConcept.getName().getLocale() != null && newConcept.getName().getLocale() != Context.getLocale())
newName = newConcept.getName().getName();
else
newName = newConcept.getPreferredName(Context.getLocale()).getName();
if (StringUtils.isBlank(newName)) {
if (log.isErrorEnabled())
log.error("No preferred name specified for the concept to be validated");
throw new APIException("Concept name cannot be an empty String");
}
if (log.isDebugEnabled())
log.debug("Looking up concept names matching " + newName);
List<Concept> matchingConcepts = Context.getConceptService().getConceptsByName(newName);
Set<Concept> duplicates = new HashSet<Concept>();
for (Concept c : matchingConcepts) {
//If updating a concept, read past the concept being updated
if (newConcept.getConceptId() != null && c.getConceptId() == newConcept.getConceptId())
continue;
//get only duplicates that are not retired
if (c.getPreferredName(Context.getLocale()).getName().equalsIgnoreCase(newName) && !c.isRetired()) {
duplicates.add(c);
}
}
if (duplicates.size() > 0) {
for (Concept duplicate : duplicates) {
if (log.isErrorEnabled())
log.error("The name '" + newName + "' is already being used by concept with Id: "
+ duplicate.getConceptId());
throw new DuplicateConceptNameException("Duplicate concept name '" + newName + "'");
}
}
}
}
| public void validate(Object obj, Errors errorss) throws APIException, DuplicateConceptNameException {
if (obj == null || !(obj instanceof Concept)) {
if (log.isErrorEnabled())
log.error("The parameter obj should not be null and must be of type" + Concept.class);
throw new IllegalArgumentException("Concept name is null or of invalid class");
} else {
Concept newConcept = (Concept) obj;
String newName = null;
//no name to validate, but why is this the case?
if (newConcept.getName() == null)
return;
//if the new concept name is in a different locale other than openmrs' default one
if (newConcept.getName().getLocale() != null && !newConcept.getName().getLocale().equals(Context.getLocale()))
newName = newConcept.getName().getName();
else
newName = newConcept.getPreferredName(Context.getLocale()).getName();
if (StringUtils.isBlank(newName)) {
if (log.isErrorEnabled())
log.error("No preferred name specified for the concept to be validated");
throw new APIException("Concept name cannot be an empty String");
}
if (log.isDebugEnabled())
log.debug("Looking up concept names matching " + newName);
List<Concept> matchingConcepts = Context.getConceptService().getConceptsByName(newName);
Set<Concept> duplicates = new HashSet<Concept>();
for (Concept c : matchingConcepts) {
//If updating a concept, read past the concept being updated
if (newConcept.getConceptId() != null && c.getConceptId().intValue() == newConcept.getConceptId())
continue;
//get only duplicates that are not retired
if (c.getPreferredName(Context.getLocale()).getName().equalsIgnoreCase(newName) && !c.isRetired()) {
duplicates.add(c);
}
}
if (duplicates.size() > 0) {
for (Concept duplicate : duplicates) {
if (log.isErrorEnabled())
log.error("The name '" + newName + "' is already being used by concept with Id: "
+ duplicate.getConceptId());
throw new DuplicateConceptNameException("Duplicate concept name '" + newName + "'");
}
}
}
}
|
diff --git a/src/api/org/openmrs/validator/ObsValidator.java b/src/api/org/openmrs/validator/ObsValidator.java
index bb982916..4284ba2c 100644
--- a/src/api/org/openmrs/validator/ObsValidator.java
+++ b/src/api/org/openmrs/validator/ObsValidator.java
@@ -1,168 +1,167 @@
/**
* The contents of this file are subject to the OpenMRS Public License
* Version 1.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://license.openmrs.org
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
*
* Copyright (C) OpenMRS, LLC. All Rights Reserved.
*/
package org.openmrs.validator;
import java.util.ArrayList;
import java.util.List;
import org.openmrs.Concept;
import org.openmrs.ConceptDatatype;
import org.openmrs.ConceptNumeric;
import org.openmrs.Obs;
import org.openmrs.annotation.Handler;
import org.openmrs.api.context.Context;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
/**
* Validator for the Obs class. This class checks for anything set on the Obs object that will cause
* errors or is incorrect. Things checked are similar to:
* <ul>
* <li>all required properties are filled in on the Obs object.
* <li>checks for no recursion in the obs grouping.
* <li>Makes sure the obs has at least one value (if not an obs grouping)</li>
*
* @see org.openmrs.Obs
*/
@Handler(supports = { Obs.class }, order = 50)
public class ObsValidator implements Validator {
public final static int VALUE_TEXT_MAX_LENGTH = 50;
/**
* @see org.springframework.validation.Validator#supports(java.lang.Class)
*/
@SuppressWarnings("unchecked")
public boolean supports(Class c) {
return Obs.class.isAssignableFrom(c);
}
/**
* @see org.springframework.validation.Validator#validate(java.lang.Object,
* org.springframework.validation.Errors)
* @should fail validation if personId is null
* @should fail validation if obsDatetime is null
* @should fail validation if concept is null
* @should fail validation if concept datatype is boolean and valueBoolean is null
* @should fail validation if concept datatype is coded and valueCoded is null
* @should fail validation if concept datatype is date and valueDatetime is null
* @should fail validation if concept datatype is numeric and valueNumeric is null
* @should fail validation if concept datatype is text and valueText is null
* @should fail validation if obs ancestors contains obs
* @should pass validation if all values present
*/
public void validate(Object obj, Errors errors) {
Obs obs = (Obs) obj;
List<Obs> ancestors = new ArrayList<Obs>();
//ancestors.add(obs);
validateHelper(obs, errors, ancestors, true);
}
/**
* Checks whether obs has all required values, and also checks to make sure that no obs group
* contains any of its ancestors
*
* @param obs
* @param errors
* @param ancestors
* @param atRootNode whether or not this is the obs that validate() was originally called on. If
* not then we shouldn't reject fields by name.
*/
private void validateHelper(Obs obs, Errors errors, List<Obs> ancestors, boolean atRootNode) {
if (obs.getPersonId() == null)
errors.rejectValue("person", "error.null");
if (obs.getObsDatetime() == null)
errors.rejectValue("obsDatetime", "error.null");
Concept c = obs.getConcept();
if (c == null) {
errors.rejectValue("concept", "error.null");
} else {
ConceptDatatype dt = c.getDatatype();
if (dt.isBoolean() && obs.getValueAsBoolean() == null) {
if (atRootNode)
errors.rejectValue("valueNumeric", "error.null");
else
errors.rejectValue("groupMembers", "Obs.error.inGroupMember");
} else if (dt.isCoded() && obs.getValueCoded() == null) {
if (atRootNode)
errors.rejectValue("valueCoded", "error.null");
else
errors.rejectValue("groupMembers", "Obs.error.inGroupMember");
- } else if (dt.isDate() && obs.getValueDatetime() == null) {
+ } else if (dt.isDateTime() && obs.getValueDatetime() == null) {
if (atRootNode)
errors.rejectValue("valueDatetime", "error.null");
else
errors.rejectValue("groupMembers", "Obs.error.inGroupMember");
} else if (dt.isNumeric() && obs.getValueNumeric() == null) {
if (atRootNode)
errors.rejectValue("valueNumeric", "error.null");
else
errors.rejectValue("groupMembers", "Obs.error.inGroupMember");
} else if (dt.isNumeric()) {
ConceptNumeric cn = Context.getConceptService().getConceptNumeric(c.getConceptId());
// If the concept numeric is not precise, the value cannot be a float, so raise an error
if (!cn.isPrecise() && Math.ceil(obs.getValueNumeric()) != obs.getValueNumeric()) {
if (atRootNode)
errors.rejectValue("valueNumeric", "error.precision");
else
errors.rejectValue("groupMembers", "Obs.error.inGroupMember");
}
// If the number is higher than the absolute range, raise an error
if (cn.getHiAbsolute() != null && cn.getHiAbsolute() < obs.getValueNumeric()) {
if (atRootNode)
errors.rejectValue("valueNumeric", "error.outOfRange.high");
else
errors.rejectValue("groupMembers", "Obs.error.inGroupMember");
}
// If the number is lower than the absolute range, raise an error as well
if (cn.getLowAbsolute() != null && cn.getLowAbsolute() > obs.getValueNumeric()) {
if (atRootNode)
errors.rejectValue("valueNumeric", "error.outOfRange.low");
else
errors.rejectValue("groupMembers", "Obs.error.inGroupMember");
}
} else if (dt.isText() && obs.getValueText() == null) {
if (atRootNode)
errors.rejectValue("valueText", "error.null");
else
errors.rejectValue("groupMembers", "Obs.error.inGroupMember");
}
//If valueText is longer than the maxlength, raise an error as well.
- if (dt.isText() && obs.getValueText() != null
- && obs.getValueText().length() > VALUE_TEXT_MAX_LENGTH) {
+ if (dt.isText() && obs.getValueText() != null && obs.getValueText().length() > VALUE_TEXT_MAX_LENGTH) {
if (atRootNode)
errors.rejectValue("valueText", "error.exceededMaxLengthOfField");
else
errors.rejectValue("groupMembers", "Obs.error.inGroupMember");
}
}
// If an obs fails validation, don't bother checking its children
if (errors.hasErrors())
return;
if (ancestors.contains(obs))
errors.rejectValue("groupMembers", "Obs.error.groupContainsItself");
if (obs.isObsGrouping()) {
ancestors.add(obs);
for (Obs child : obs.getGroupMembers()) {
validateHelper(child, errors, ancestors, false);
}
ancestors.remove(ancestors.size() - 1);
}
}
}
| false | true | private void validateHelper(Obs obs, Errors errors, List<Obs> ancestors, boolean atRootNode) {
if (obs.getPersonId() == null)
errors.rejectValue("person", "error.null");
if (obs.getObsDatetime() == null)
errors.rejectValue("obsDatetime", "error.null");
Concept c = obs.getConcept();
if (c == null) {
errors.rejectValue("concept", "error.null");
} else {
ConceptDatatype dt = c.getDatatype();
if (dt.isBoolean() && obs.getValueAsBoolean() == null) {
if (atRootNode)
errors.rejectValue("valueNumeric", "error.null");
else
errors.rejectValue("groupMembers", "Obs.error.inGroupMember");
} else if (dt.isCoded() && obs.getValueCoded() == null) {
if (atRootNode)
errors.rejectValue("valueCoded", "error.null");
else
errors.rejectValue("groupMembers", "Obs.error.inGroupMember");
} else if (dt.isDate() && obs.getValueDatetime() == null) {
if (atRootNode)
errors.rejectValue("valueDatetime", "error.null");
else
errors.rejectValue("groupMembers", "Obs.error.inGroupMember");
} else if (dt.isNumeric() && obs.getValueNumeric() == null) {
if (atRootNode)
errors.rejectValue("valueNumeric", "error.null");
else
errors.rejectValue("groupMembers", "Obs.error.inGroupMember");
} else if (dt.isNumeric()) {
ConceptNumeric cn = Context.getConceptService().getConceptNumeric(c.getConceptId());
// If the concept numeric is not precise, the value cannot be a float, so raise an error
if (!cn.isPrecise() && Math.ceil(obs.getValueNumeric()) != obs.getValueNumeric()) {
if (atRootNode)
errors.rejectValue("valueNumeric", "error.precision");
else
errors.rejectValue("groupMembers", "Obs.error.inGroupMember");
}
// If the number is higher than the absolute range, raise an error
if (cn.getHiAbsolute() != null && cn.getHiAbsolute() < obs.getValueNumeric()) {
if (atRootNode)
errors.rejectValue("valueNumeric", "error.outOfRange.high");
else
errors.rejectValue("groupMembers", "Obs.error.inGroupMember");
}
// If the number is lower than the absolute range, raise an error as well
if (cn.getLowAbsolute() != null && cn.getLowAbsolute() > obs.getValueNumeric()) {
if (atRootNode)
errors.rejectValue("valueNumeric", "error.outOfRange.low");
else
errors.rejectValue("groupMembers", "Obs.error.inGroupMember");
}
} else if (dt.isText() && obs.getValueText() == null) {
if (atRootNode)
errors.rejectValue("valueText", "error.null");
else
errors.rejectValue("groupMembers", "Obs.error.inGroupMember");
}
//If valueText is longer than the maxlength, raise an error as well.
if (dt.isText() && obs.getValueText() != null
&& obs.getValueText().length() > VALUE_TEXT_MAX_LENGTH) {
if (atRootNode)
errors.rejectValue("valueText", "error.exceededMaxLengthOfField");
else
errors.rejectValue("groupMembers", "Obs.error.inGroupMember");
}
}
// If an obs fails validation, don't bother checking its children
if (errors.hasErrors())
return;
if (ancestors.contains(obs))
errors.rejectValue("groupMembers", "Obs.error.groupContainsItself");
if (obs.isObsGrouping()) {
ancestors.add(obs);
for (Obs child : obs.getGroupMembers()) {
validateHelper(child, errors, ancestors, false);
}
ancestors.remove(ancestors.size() - 1);
}
}
| private void validateHelper(Obs obs, Errors errors, List<Obs> ancestors, boolean atRootNode) {
if (obs.getPersonId() == null)
errors.rejectValue("person", "error.null");
if (obs.getObsDatetime() == null)
errors.rejectValue("obsDatetime", "error.null");
Concept c = obs.getConcept();
if (c == null) {
errors.rejectValue("concept", "error.null");
} else {
ConceptDatatype dt = c.getDatatype();
if (dt.isBoolean() && obs.getValueAsBoolean() == null) {
if (atRootNode)
errors.rejectValue("valueNumeric", "error.null");
else
errors.rejectValue("groupMembers", "Obs.error.inGroupMember");
} else if (dt.isCoded() && obs.getValueCoded() == null) {
if (atRootNode)
errors.rejectValue("valueCoded", "error.null");
else
errors.rejectValue("groupMembers", "Obs.error.inGroupMember");
} else if (dt.isDateTime() && obs.getValueDatetime() == null) {
if (atRootNode)
errors.rejectValue("valueDatetime", "error.null");
else
errors.rejectValue("groupMembers", "Obs.error.inGroupMember");
} else if (dt.isNumeric() && obs.getValueNumeric() == null) {
if (atRootNode)
errors.rejectValue("valueNumeric", "error.null");
else
errors.rejectValue("groupMembers", "Obs.error.inGroupMember");
} else if (dt.isNumeric()) {
ConceptNumeric cn = Context.getConceptService().getConceptNumeric(c.getConceptId());
// If the concept numeric is not precise, the value cannot be a float, so raise an error
if (!cn.isPrecise() && Math.ceil(obs.getValueNumeric()) != obs.getValueNumeric()) {
if (atRootNode)
errors.rejectValue("valueNumeric", "error.precision");
else
errors.rejectValue("groupMembers", "Obs.error.inGroupMember");
}
// If the number is higher than the absolute range, raise an error
if (cn.getHiAbsolute() != null && cn.getHiAbsolute() < obs.getValueNumeric()) {
if (atRootNode)
errors.rejectValue("valueNumeric", "error.outOfRange.high");
else
errors.rejectValue("groupMembers", "Obs.error.inGroupMember");
}
// If the number is lower than the absolute range, raise an error as well
if (cn.getLowAbsolute() != null && cn.getLowAbsolute() > obs.getValueNumeric()) {
if (atRootNode)
errors.rejectValue("valueNumeric", "error.outOfRange.low");
else
errors.rejectValue("groupMembers", "Obs.error.inGroupMember");
}
} else if (dt.isText() && obs.getValueText() == null) {
if (atRootNode)
errors.rejectValue("valueText", "error.null");
else
errors.rejectValue("groupMembers", "Obs.error.inGroupMember");
}
//If valueText is longer than the maxlength, raise an error as well.
if (dt.isText() && obs.getValueText() != null && obs.getValueText().length() > VALUE_TEXT_MAX_LENGTH) {
if (atRootNode)
errors.rejectValue("valueText", "error.exceededMaxLengthOfField");
else
errors.rejectValue("groupMembers", "Obs.error.inGroupMember");
}
}
// If an obs fails validation, don't bother checking its children
if (errors.hasErrors())
return;
if (ancestors.contains(obs))
errors.rejectValue("groupMembers", "Obs.error.groupContainsItself");
if (obs.isObsGrouping()) {
ancestors.add(obs);
for (Obs child : obs.getGroupMembers()) {
validateHelper(child, errors, ancestors, false);
}
ancestors.remove(ancestors.size() - 1);
}
}
|
diff --git a/src/org/geometerplus/zlibrary/text/view/ZLTextView.java b/src/org/geometerplus/zlibrary/text/view/ZLTextView.java
index c6625a85d..1d668622a 100644
--- a/src/org/geometerplus/zlibrary/text/view/ZLTextView.java
+++ b/src/org/geometerplus/zlibrary/text/view/ZLTextView.java
@@ -1,1569 +1,1569 @@
/*
* Copyright (C) 2007-2013 Geometer Plus <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
package org.geometerplus.zlibrary.text.view;
import java.util.*;
import org.geometerplus.zlibrary.core.application.ZLApplication;
import org.geometerplus.zlibrary.core.view.ZLPaintContext;
import org.geometerplus.zlibrary.core.filesystem.ZLFile;
import org.geometerplus.zlibrary.core.filesystem.ZLResourceFile;
import org.geometerplus.zlibrary.core.util.ZLColor;
import org.geometerplus.zlibrary.text.model.*;
import org.geometerplus.zlibrary.text.hyphenation.*;
import org.geometerplus.zlibrary.text.view.style.ZLTextStyleCollection;
public abstract class ZLTextView extends ZLTextViewBase {
public static final int MAX_SELECTION_DISTANCE = 10;
public interface ScrollingMode {
int NO_OVERLAPPING = 0;
int KEEP_LINES = 1;
int SCROLL_LINES = 2;
int SCROLL_PERCENTAGE = 3;
};
private ZLTextModel myModel;
private interface SizeUnit {
int PIXEL_UNIT = 0;
int LINE_UNIT = 1;
};
private int myScrollingMode;
private int myOverlappingValue;
private ZLTextPage myPreviousPage = new ZLTextPage();
private ZLTextPage myCurrentPage = new ZLTextPage();
private ZLTextPage myNextPage = new ZLTextPage();
private final HashMap<ZLTextLineInfo,ZLTextLineInfo> myLineInfoCache = new HashMap<ZLTextLineInfo,ZLTextLineInfo>();
private ZLTextRegion.Soul mySelectedRegionSoul;
private boolean myHighlightSelectedRegion = true;
private ZLTextSelection mySelection;
private ZLTextHighlighting myHighlighting;
public ZLTextView(ZLApplication application) {
super(application);
mySelection = new ZLTextSelection(this);
myHighlighting = new ZLTextHighlighting();
}
public synchronized void setModel(ZLTextModel model) {
ZLTextParagraphCursorCache.clear();
myModel = model;
myCurrentPage.reset();
myPreviousPage.reset();
myNextPage.reset();
if (myModel != null) {
final int paragraphsNumber = myModel.getParagraphsNumber();
if (paragraphsNumber > 0) {
myCurrentPage.moveStartCursor(ZLTextParagraphCursor.cursor(myModel, 0));
}
}
Application.getViewWidget().reset();
}
public ZLTextModel getModel() {
return myModel;
}
public ZLTextWordCursor getStartCursor() {
if (myCurrentPage.StartCursor.isNull()) {
preparePaintInfo(myCurrentPage);
}
return myCurrentPage.StartCursor;
}
public ZLTextWordCursor getEndCursor() {
if (myCurrentPage.EndCursor.isNull()) {
preparePaintInfo(myCurrentPage);
}
return myCurrentPage.EndCursor;
}
private synchronized void gotoMark(ZLTextMark mark) {
if (mark == null) {
return;
}
myPreviousPage.reset();
myNextPage.reset();
boolean doRepaint = false;
if (myCurrentPage.StartCursor.isNull()) {
doRepaint = true;
preparePaintInfo(myCurrentPage);
}
if (myCurrentPage.StartCursor.isNull()) {
return;
}
if (myCurrentPage.StartCursor.getParagraphIndex() != mark.ParagraphIndex ||
myCurrentPage.StartCursor.getMark().compareTo(mark) > 0) {
doRepaint = true;
gotoPosition(mark.ParagraphIndex, 0, 0);
preparePaintInfo(myCurrentPage);
}
if (myCurrentPage.EndCursor.isNull()) {
preparePaintInfo(myCurrentPage);
}
while (mark.compareTo(myCurrentPage.EndCursor.getMark()) > 0) {
doRepaint = true;
scrollPage(true, ScrollingMode.NO_OVERLAPPING, 0);
preparePaintInfo(myCurrentPage);
}
if (doRepaint) {
if (myCurrentPage.StartCursor.isNull()) {
preparePaintInfo(myCurrentPage);
}
Application.getViewWidget().reset();
Application.getViewWidget().repaint();
}
}
public synchronized int search(final String text, boolean ignoreCase, boolean wholeText, boolean backward, boolean thisSectionOnly) {
if (text.length() == 0) {
return 0;
}
int startIndex = 0;
int endIndex = myModel.getParagraphsNumber();
if (thisSectionOnly) {
// TODO: implement
}
int count = myModel.search(text, startIndex, endIndex, ignoreCase);
myPreviousPage.reset();
myNextPage.reset();
if (!myCurrentPage.StartCursor.isNull()) {
rebuildPaintInfo();
if (count > 0) {
ZLTextMark mark = myCurrentPage.StartCursor.getMark();
gotoMark(wholeText ?
(backward ? myModel.getLastMark() : myModel.getFirstMark()) :
(backward ? myModel.getPreviousMark(mark) : myModel.getNextMark(mark)));
}
Application.getViewWidget().reset();
Application.getViewWidget().repaint();
}
return count;
}
public boolean canFindNext() {
final ZLTextWordCursor end = myCurrentPage.EndCursor;
return !end.isNull() && (myModel != null) && (myModel.getNextMark(end.getMark()) != null);
}
public synchronized void findNext() {
final ZLTextWordCursor end = myCurrentPage.EndCursor;
if (!end.isNull()) {
gotoMark(myModel.getNextMark(end.getMark()));
}
}
public boolean canFindPrevious() {
final ZLTextWordCursor start = myCurrentPage.StartCursor;
return !start.isNull() && (myModel != null) && (myModel.getPreviousMark(start.getMark()) != null);
}
public synchronized void findPrevious() {
final ZLTextWordCursor start = myCurrentPage.StartCursor;
if (!start.isNull()) {
gotoMark(myModel.getPreviousMark(start.getMark()));
}
}
public void clearFindResults() {
if (!findResultsAreEmpty()) {
myModel.removeAllMarks();
rebuildPaintInfo();
Application.getViewWidget().reset();
Application.getViewWidget().repaint();
}
}
public boolean findResultsAreEmpty() {
return (myModel == null) || myModel.getMarks().isEmpty();
}
@Override
public synchronized void onScrollingFinished(PageIndex pageIndex) {
switch (pageIndex) {
case current:
break;
case previous:
{
final ZLTextPage swap = myNextPage;
myNextPage = myCurrentPage;
myCurrentPage = myPreviousPage;
myPreviousPage = swap;
myPreviousPage.reset();
if (myCurrentPage.PaintState == PaintStateEnum.NOTHING_TO_PAINT) {
preparePaintInfo(myNextPage);
myCurrentPage.EndCursor.setCursor(myNextPage.StartCursor);
myCurrentPage.PaintState = PaintStateEnum.END_IS_KNOWN;
} else if (!myCurrentPage.EndCursor.isNull() &&
!myNextPage.StartCursor.isNull() &&
!myCurrentPage.EndCursor.samePositionAs(myNextPage.StartCursor)) {
myNextPage.reset();
myNextPage.StartCursor.setCursor(myCurrentPage.EndCursor);
myNextPage.PaintState = PaintStateEnum.START_IS_KNOWN;
Application.getViewWidget().reset();
}
break;
}
case next:
{
final ZLTextPage swap = myPreviousPage;
myPreviousPage = myCurrentPage;
myCurrentPage = myNextPage;
myNextPage = swap;
myNextPage.reset();
switch (myCurrentPage.PaintState) {
case PaintStateEnum.NOTHING_TO_PAINT:
preparePaintInfo(myPreviousPage);
myCurrentPage.StartCursor.setCursor(myPreviousPage.EndCursor);
myCurrentPage.PaintState = PaintStateEnum.START_IS_KNOWN;
break;
case PaintStateEnum.READY:
myNextPage.StartCursor.setCursor(myCurrentPage.EndCursor);
myNextPage.PaintState = PaintStateEnum.START_IS_KNOWN;
break;
}
break;
}
}
}
public void highlight(ZLTextPosition start, ZLTextPosition end) {
myHighlighting.setup(start, end);
Application.getViewWidget().reset();
Application.getViewWidget().repaint();
}
public void clearHighlighting() {
if (myHighlighting.clear()) {
Application.getViewWidget().reset();
Application.getViewWidget().repaint();
}
}
protected void moveSelectionCursorTo(ZLTextSelectionCursor cursor, int x, int y) {
y -= ZLTextSelectionCursor.getHeight() / 2 + ZLTextSelectionCursor.getAccent() / 2;
mySelection.setCursorInMovement(cursor, x, y);
mySelection.expandTo(myCurrentPage, x, y);
Application.getViewWidget().reset();
Application.getViewWidget().repaint();
}
protected void releaseSelectionCursor() {
mySelection.stop();
Application.getViewWidget().reset();
Application.getViewWidget().repaint();
}
protected ZLTextSelectionCursor getSelectionCursorInMovement() {
return mySelection.getCursorInMovement();
}
private ZLTextSelection.Point getSelectionCursorPoint(ZLTextPage page, ZLTextSelectionCursor cursor) {
if (cursor == ZLTextSelectionCursor.None) {
return null;
}
if (cursor == mySelection.getCursorInMovement()) {
return mySelection.getCursorInMovementPoint();
}
if (cursor == ZLTextSelectionCursor.Left) {
if (mySelection.hasAPartBeforePage(page)) {
return null;
}
final ZLTextElementArea selectionStartArea = mySelection.getStartArea(page);
if (selectionStartArea != null) {
return new ZLTextSelection.Point(selectionStartArea.XStart, selectionStartArea.YEnd);
}
} else {
if (mySelection.hasAPartAfterPage(page)) {
return null;
}
final ZLTextElementArea selectionEndArea = mySelection.getEndArea(page);
if (selectionEndArea != null) {
return new ZLTextSelection.Point(selectionEndArea.XEnd, selectionEndArea.YEnd);
}
}
return null;
}
private int distanceToCursor(int x, int y, ZLTextSelection.Point cursorPoint) {
if (cursorPoint == null) {
return Integer.MAX_VALUE;
}
final int dX, dY;
final int w = ZLTextSelectionCursor.getWidth() / 2;
if (x < cursorPoint.X - w) {
dX = cursorPoint.X - w - x;
} else if (x > cursorPoint.X + w) {
dX = x - cursorPoint.X - w;
} else {
dX = 0;
}
final int h = ZLTextSelectionCursor.getHeight();
if (y < cursorPoint.Y) {
dY = cursorPoint.Y - y;
} else if (y > cursorPoint.Y + h) {
dY = y - cursorPoint.Y - h;
} else {
dY = 0;
}
return Math.max(dX, dY);
}
protected ZLTextSelectionCursor findSelectionCursor(int x, int y) {
return findSelectionCursor(x, y, Integer.MAX_VALUE);
}
protected ZLTextSelectionCursor findSelectionCursor(int x, int y, int maxDistance) {
if (mySelection.isEmpty()) {
return ZLTextSelectionCursor.None;
}
final int leftDistance = distanceToCursor(
x, y, getSelectionCursorPoint(myCurrentPage, ZLTextSelectionCursor.Left)
);
final int rightDistance = distanceToCursor(
x, y, getSelectionCursorPoint(myCurrentPage, ZLTextSelectionCursor.Right)
);
if (rightDistance < leftDistance) {
return rightDistance <= maxDistance ? ZLTextSelectionCursor.Right : ZLTextSelectionCursor.None;
} else {
return leftDistance <= maxDistance ? ZLTextSelectionCursor.Left : ZLTextSelectionCursor.None;
}
}
private void drawSelectionCursor(ZLPaintContext context, ZLTextSelection.Point pt) {
if (pt == null) {
return;
}
final int w = ZLTextSelectionCursor.getWidth() / 2;
final int h = ZLTextSelectionCursor.getHeight();
final int a = ZLTextSelectionCursor.getAccent();
final int[] xs = { pt.X, pt.X + w, pt.X + w, pt.X - w, pt.X - w };
final int[] ys = { pt.Y - a, pt.Y, pt.Y + h, pt.Y + h, pt.Y };
context.setFillColor(context.getBackgroundColor(), 192);
context.fillPolygon(xs, ys);
context.setLineColor(getTextColor(ZLTextHyperlink.NO_LINK));
context.drawPolygonalLine(xs, ys);
}
@Override
public synchronized void preparePage(ZLPaintContext context, PageIndex pageIndex) {
setContext(context);
preparePaintInfo(getPage(pageIndex));
}
@Override
public synchronized void paint(ZLPaintContext context, PageIndex pageIndex) {
setContext(context);
final ZLFile wallpaper = getWallpaperFile();
if (wallpaper != null) {
context.clear(wallpaper, getWallpaperMode());
} else {
context.clear(getBackgroundColor());
}
if (myModel == null || myModel.getParagraphsNumber() == 0) {
return;
}
ZLTextPage page;
switch (pageIndex) {
default:
case current:
page = myCurrentPage;
break;
case previous:
page = myPreviousPage;
if (myPreviousPage.PaintState == PaintStateEnum.NOTHING_TO_PAINT) {
preparePaintInfo(myCurrentPage);
myPreviousPage.EndCursor.setCursor(myCurrentPage.StartCursor);
myPreviousPage.PaintState = PaintStateEnum.END_IS_KNOWN;
}
break;
case next:
page = myNextPage;
if (myNextPage.PaintState == PaintStateEnum.NOTHING_TO_PAINT) {
preparePaintInfo(myCurrentPage);
myNextPage.StartCursor.setCursor(myCurrentPage.EndCursor);
myNextPage.PaintState = PaintStateEnum.START_IS_KNOWN;
}
}
page.TextElementMap.clear();
preparePaintInfo(page);
if (page.StartCursor.isNull() || page.EndCursor.isNull()) {
return;
}
final ArrayList<ZLTextLineInfo> lineInfos = page.LineInfos;
final int[] labels = new int[lineInfos.size() + 1];
int y = getTopMargin();
int index = 0;
for (ZLTextLineInfo info : lineInfos) {
prepareTextLine(page, info, y);
y += info.Height + info.Descent + info.VSpaceAfter;
labels[++index] = page.TextElementMap.size();
}
y = getTopMargin();
index = 0;
for (ZLTextLineInfo info : lineInfos) {
drawTextLine(page, info, labels[index], labels[index + 1], y);
y += info.Height + info.Descent + info.VSpaceAfter;
++index;
}
final ZLTextRegion selectedElementRegion = getSelectedRegion(page);
if (selectedElementRegion != null && myHighlightSelectedRegion) {
selectedElementRegion.draw(context);
}
drawSelectionCursor(context, getSelectionCursorPoint(page, ZLTextSelectionCursor.Left));
drawSelectionCursor(context, getSelectionCursorPoint(page, ZLTextSelectionCursor.Right));
}
private ZLTextPage getPage(PageIndex pageIndex) {
switch (pageIndex) {
default:
case current:
return myCurrentPage;
case previous:
return myPreviousPage;
case next:
return myNextPage;
}
}
public static final int SCROLLBAR_HIDE = 0;
public static final int SCROLLBAR_SHOW = 1;
public static final int SCROLLBAR_SHOW_AS_PROGRESS = 2;
public abstract int scrollbarType();
public final boolean isScrollbarShown() {
return scrollbarType() == SCROLLBAR_SHOW || scrollbarType() == SCROLLBAR_SHOW_AS_PROGRESS;
}
protected final synchronized int sizeOfTextBeforeParagraph(int paragraphIndex) {
return myModel != null ? myModel.getTextLength(paragraphIndex - 1) : 0;
}
protected final synchronized int sizeOfFullText() {
if (myModel == null || myModel.getParagraphsNumber() == 0) {
return 1;
}
return myModel.getTextLength(myModel.getParagraphsNumber() - 1);
}
private final synchronized int getCurrentCharNumber(PageIndex pageIndex, boolean startNotEndOfPage) {
if (myModel == null || myModel.getParagraphsNumber() == 0) {
return 0;
}
final ZLTextPage page = getPage(pageIndex);
preparePaintInfo(page);
if (startNotEndOfPage) {
return Math.max(0, sizeOfTextBeforeCursor(page.StartCursor));
} else {
int end = sizeOfTextBeforeCursor(page.EndCursor);
if (end == -1) {
end = myModel.getTextLength(myModel.getParagraphsNumber() - 1) - 1;
}
return Math.max(1, end);
}
}
@Override
public final synchronized int getScrollbarFullSize() {
return sizeOfFullText();
}
@Override
public final synchronized int getScrollbarThumbPosition(PageIndex pageIndex) {
return scrollbarType() == SCROLLBAR_SHOW_AS_PROGRESS ? 0 : getCurrentCharNumber(pageIndex, true);
}
@Override
public final synchronized int getScrollbarThumbLength(PageIndex pageIndex) {
int start = scrollbarType() == SCROLLBAR_SHOW_AS_PROGRESS
? 0 : getCurrentCharNumber(pageIndex, true);
int end = getCurrentCharNumber(pageIndex, false);
return Math.max(1, end - start);
}
private int sizeOfTextBeforeCursor(ZLTextWordCursor wordCursor) {
final ZLTextParagraphCursor paragraphCursor = wordCursor.getParagraphCursor();
if (paragraphCursor == null) {
return -1;
}
final int paragraphIndex = paragraphCursor.Index;
int sizeOfText = myModel.getTextLength(paragraphIndex - 1);
final int paragraphLength = paragraphCursor.getParagraphLength();
if (paragraphLength > 0) {
sizeOfText +=
(myModel.getTextLength(paragraphIndex) - sizeOfText)
* wordCursor.getElementIndex()
/ paragraphLength;
}
return sizeOfText;
}
// Can be called only when (myModel.getParagraphsNumber() != 0)
private synchronized float computeCharsPerPage() {
setTextStyle(ZLTextStyleCollection.Instance().getBaseStyle());
final int textWidth = getTextAreaWidth();
final int textHeight = getTextAreaHeight();
final int num = myModel.getParagraphsNumber();
final int totalTextSize = myModel.getTextLength(num - 1);
final float charsPerParagraph = ((float)totalTextSize) / num;
final float charWidth = computeCharWidth();
final int indentWidth = getElementWidth(ZLTextElement.Indent, 0);
final float effectiveWidth = textWidth - (indentWidth + 0.5f * textWidth) / charsPerParagraph;
float charsPerLine = Math.min(effectiveWidth / charWidth,
charsPerParagraph * 1.2f);
final int strHeight = getWordHeight() + getContext().getDescent();
final int effectiveHeight = (int) (textHeight - (getTextStyle().getSpaceBefore()
+ getTextStyle().getSpaceAfter()) / charsPerParagraph);
final int linesPerPage = effectiveHeight / strHeight;
return charsPerLine * linesPerPage;
}
private synchronized int computeTextPageNumber(int textSize) {
if (myModel == null || myModel.getParagraphsNumber() == 0) {
return 1;
}
final float factor = 1.0f / computeCharsPerPage();
final float pages = textSize * factor;
return Math.max((int)(pages + 1.0f - 0.5f * factor), 1);
}
private static final char[] ourDefaultLetters = "System developers have used modeling languages for decades to specify, visualize, construct, and document systems. The Unified Modeling Language (UML) is one of those languages. UML makes it possible for team members to collaborate by providing a common language that applies to a multitude of different systems. Essentially, it enables you to communicate solutions in a consistent, tool-supported language.".toCharArray();
private final char[] myLettersBuffer = new char[512];
private int myLettersBufferLength = 0;
private ZLTextModel myLettersModel = null;
private float myCharWidth = -1f;
private final float computeCharWidth() {
if (myLettersModel != myModel) {
myLettersModel = myModel;
myLettersBufferLength = 0;
myCharWidth = -1f;
int paragraph = 0;
final int textSize = myModel.getTextLength(myModel.getParagraphsNumber() - 1);
if (textSize > myLettersBuffer.length) {
paragraph = myModel.findParagraphByTextLength((textSize - myLettersBuffer.length) / 2);
}
while (paragraph < myModel.getParagraphsNumber()
&& myLettersBufferLength < myLettersBuffer.length) {
ZLTextParagraph.EntryIterator it = myModel.getParagraph(paragraph++).iterator();
while (it.hasNext()
&& myLettersBufferLength < myLettersBuffer.length) {
it.next();
if (it.getType() == ZLTextParagraph.Entry.TEXT) {
final int len = Math.min(it.getTextLength(),
myLettersBuffer.length - myLettersBufferLength);
System.arraycopy(it.getTextData(), it.getTextOffset(),
myLettersBuffer, myLettersBufferLength, len);
myLettersBufferLength += len;
}
}
}
if (myLettersBufferLength == 0) {
myLettersBufferLength = Math.min(myLettersBuffer.length, ourDefaultLetters.length);
System.arraycopy(ourDefaultLetters, 0, myLettersBuffer, 0, myLettersBufferLength);
}
}
if (myCharWidth < 0f) {
myCharWidth = computeCharWidth(myLettersBuffer, myLettersBufferLength);
}
return myCharWidth;
}
private final float computeCharWidth(char[] pattern, int length) {
return getContext().getStringWidth(pattern, 0, length) / ((float)length);
}
public static class PagePosition {
public final int Current;
public final int Total;
PagePosition(int current, int total) {
Current = current;
Total = total;
}
}
public final synchronized PagePosition pagePosition() {
int current = computeTextPageNumber(getCurrentCharNumber(PageIndex.current, false));
int total = computeTextPageNumber(sizeOfFullText());
if (total > 3) {
return new PagePosition(current, total);
}
preparePaintInfo(myCurrentPage);
ZLTextWordCursor cursor = myCurrentPage.StartCursor;
if (cursor == null || cursor.isNull()) {
return new PagePosition(current, total);
}
if (cursor.isStartOfText()) {
current = 1;
} else {
ZLTextWordCursor prevCursor = myPreviousPage.StartCursor;
if (prevCursor == null || prevCursor.isNull()) {
preparePaintInfo(myPreviousPage);
prevCursor = myPreviousPage.StartCursor;
}
if (prevCursor != null && !prevCursor.isNull()) {
current = prevCursor.isStartOfText() ? 2 : 3;
}
}
total = current;
cursor = myCurrentPage.EndCursor;
if (cursor == null || cursor.isNull()) {
return new PagePosition(current, total);
}
if (!cursor.isEndOfText()) {
ZLTextWordCursor nextCursor = myNextPage.EndCursor;
if (nextCursor == null || nextCursor.isNull()) {
preparePaintInfo(myNextPage);
nextCursor = myNextPage.EndCursor;
}
if (nextCursor != null) {
total += nextCursor.isEndOfText() ? 1 : 2;
}
}
return new PagePosition(current, total);
}
public final synchronized void gotoPage(int page) {
if (myModel == null || myModel.getParagraphsNumber() == 0) {
return;
}
final float factor = computeCharsPerPage();
final float textSize = page * factor;
int intTextSize = (int) textSize;
int paragraphIndex = myModel.findParagraphByTextLength(intTextSize);
if (paragraphIndex > 0 && myModel.getTextLength(paragraphIndex) > intTextSize) {
--paragraphIndex;
}
intTextSize = myModel.getTextLength(paragraphIndex);
int sizeOfTextBefore = myModel.getTextLength(paragraphIndex - 1);
while (paragraphIndex > 0 && intTextSize == sizeOfTextBefore) {
--paragraphIndex;
intTextSize = sizeOfTextBefore;
sizeOfTextBefore = myModel.getTextLength(paragraphIndex - 1);
}
final int paragraphLength = intTextSize - sizeOfTextBefore;
final int wordIndex;
if (paragraphLength == 0) {
wordIndex = 0;
} else {
preparePaintInfo(myCurrentPage);
final ZLTextWordCursor cursor = new ZLTextWordCursor(myCurrentPage.EndCursor);
cursor.moveToParagraph(paragraphIndex);
wordIndex = cursor.getParagraphCursor().getParagraphLength();
}
gotoPositionByEnd(paragraphIndex, wordIndex, 0);
}
public void gotoHome() {
final ZLTextWordCursor cursor = getStartCursor();
if (!cursor.isNull() && cursor.isStartOfParagraph() && cursor.getParagraphIndex() == 0) {
return;
}
gotoPosition(0, 0, 0);
preparePaintInfo();
}
private void drawBackgroung(
ZLTextAbstractHighlighting highligting, ZLColor color,
ZLTextPage page, ZLTextLineInfo info, int from, int to, int y
) {
if (!highligting.isEmpty() && from != to) {
final ZLTextElementArea fromArea = page.TextElementMap.get(from);
final ZLTextElementArea toArea = page.TextElementMap.get(to - 1);
final ZLTextElementArea selectionStartArea = highligting.getStartArea(page);
final ZLTextElementArea selectionEndArea = highligting.getEndArea(page);
if (selectionStartArea != null
&& selectionEndArea != null
&& selectionStartArea.compareTo(toArea) <= 0
&& selectionEndArea.compareTo(fromArea) >= 0) {
final int top = y + 1;
int left, right, bottom = y + info.Height + info.Descent;
if (selectionStartArea.compareTo(fromArea) < 0) {
left = getLeftMargin();
} else {
left = selectionStartArea.XStart;
}
if (selectionEndArea.compareTo(toArea) > 0) {
right = getLeftMargin() + getTextAreaWidth() - 1;
bottom += info.VSpaceAfter;
} else {
right = selectionEndArea.XEnd;
}
getContext().setFillColor(color);
getContext().fillRectangle(left, top, right, bottom);
}
}
}
private static final char[] SPACE = new char[] { ' ' };
private void drawTextLine(ZLTextPage page, ZLTextLineInfo info, int from, int to, int y) {
drawBackgroung(mySelection, getSelectedBackgroundColor(), page, info, from, to, y);
drawBackgroung(myHighlighting, getHighlightingColor(), page, info, from, to, y);
final ZLPaintContext context = getContext();
final ZLTextParagraphCursor paragraph = info.ParagraphCursor;
int index = from;
final int endElementIndex = info.EndElementIndex;
int charIndex = info.RealStartCharIndex;
for (int wordIndex = info.RealStartElementIndex; wordIndex != endElementIndex && index < to; ++wordIndex, charIndex = 0) {
final ZLTextElement element = paragraph.getElement(wordIndex);
final ZLTextElementArea area = page.TextElementMap.get(index);
if (element == area.Element) {
++index;
if (area.ChangeStyle) {
setTextStyle(area.Style);
}
final int areaX = area.XStart;
final int areaY = area.YEnd - getElementDescent(element) - getTextStyle().getVerticalShift();
if (element instanceof ZLTextWord) {
drawWord(
areaX, areaY, (ZLTextWord)element, charIndex, -1, false,
mySelection.isAreaSelected(area)
? getSelectedForegroundColor() : getTextColor(getTextStyle().Hyperlink)
);
} else if (element instanceof ZLTextImageElement) {
final ZLTextImageElement imageElement = (ZLTextImageElement)element;
context.drawImage(
areaX, areaY,
imageElement.ImageData,
getTextAreaSize(),
getScalingType(imageElement)
);
} else if (element == ZLTextElement.HSpace) {
final int cw = context.getSpaceWidth();
/*
context.setFillColor(getHighlightingColor());
context.fillRectangle(
area.XStart, areaY - context.getStringHeight(),
area.XEnd - 1, areaY + context.getDescent()
);
*/
for (int len = 0; len < area.XEnd - area.XStart; len += cw) {
context.drawString(areaX + len, areaY, SPACE, 0, 1);
}
}
}
}
if (index != to) {
ZLTextElementArea area = page.TextElementMap.get(index++);
if (area.ChangeStyle) {
setTextStyle(area.Style);
}
final int start = info.StartElementIndex == info.EndElementIndex
? info.StartCharIndex : 0;
final int len = info.EndCharIndex - start;
final ZLTextWord word = (ZLTextWord)paragraph.getElement(info.EndElementIndex);
drawWord(
area.XStart, area.YEnd - context.getDescent() - getTextStyle().getVerticalShift(),
word, start, len, area.AddHyphenationSign,
mySelection.isAreaSelected(area)
? getSelectedForegroundColor() : getTextColor(getTextStyle().Hyperlink)
);
}
}
private void buildInfos(ZLTextPage page, ZLTextWordCursor start, ZLTextWordCursor result) {
result.setCursor(start);
int textAreaHeight = getTextAreaHeight();
page.LineInfos.clear();
do {
resetTextStyle();
final ZLTextParagraphCursor paragraphCursor = result.getParagraphCursor();
final int wordIndex = result.getElementIndex();
applyStyleChanges(paragraphCursor, 0, wordIndex);
ZLTextLineInfo info = new ZLTextLineInfo(paragraphCursor, wordIndex, result.getCharIndex(), getTextStyle());
final int endIndex = info.ParagraphCursorLength;
while (info.EndElementIndex != endIndex) {
info = processTextLine(paragraphCursor, info.EndElementIndex, info.EndCharIndex, endIndex);
textAreaHeight -= info.Height + info.Descent;
if (textAreaHeight < 0 && page.LineInfos.size() > 0) {
break;
}
textAreaHeight -= info.VSpaceAfter;
result.moveTo(info.EndElementIndex, info.EndCharIndex);
page.LineInfos.add(info);
if (textAreaHeight < 0) {
break;
}
}
} while (result.isEndOfParagraph() && result.nextParagraph() && !result.getParagraphCursor().isEndOfSection() && textAreaHeight >= 0);
resetTextStyle();
}
private boolean isHyphenationPossible() {
return ZLTextStyleCollection.Instance().getBaseStyle().AutoHyphenationOption.getValue()
&& getTextStyle().allowHyphenations();
}
private ZLTextLineInfo processTextLine(
ZLTextParagraphCursor paragraphCursor,
final int startIndex,
final int startCharIndex,
final int endIndex
) {
final ZLPaintContext context = getContext();
final ZLTextLineInfo info = new ZLTextLineInfo(paragraphCursor, startIndex, startCharIndex, getTextStyle());
final ZLTextLineInfo cachedInfo = myLineInfoCache.get(info);
if (cachedInfo != null) {
applyStyleChanges(paragraphCursor, startIndex, cachedInfo.EndElementIndex);
return cachedInfo;
}
int currentElementIndex = startIndex;
int currentCharIndex = startCharIndex;
final boolean isFirstLine = startIndex == 0 && startCharIndex == 0;
if (isFirstLine) {
ZLTextElement element = paragraphCursor.getElement(currentElementIndex);
while (isStyleChangeElement(element)) {
applyStyleChangeElement(element);
++currentElementIndex;
currentCharIndex = 0;
if (currentElementIndex == endIndex) {
break;
}
element = paragraphCursor.getElement(currentElementIndex);
}
info.StartStyle = getTextStyle();
info.RealStartElementIndex = currentElementIndex;
info.RealStartCharIndex = currentCharIndex;
}
ZLTextStyle storedStyle = getTextStyle();
info.LeftIndent = getTextStyle().getLeftIndent();
if (isFirstLine) {
info.LeftIndent += getTextStyle().getFirstLineIndentDelta();
}
info.Width = info.LeftIndent;
if (info.RealStartElementIndex == endIndex) {
info.EndElementIndex = info.RealStartElementIndex;
info.EndCharIndex = info.RealStartCharIndex;
return info;
}
int newWidth = info.Width;
int newHeight = info.Height;
int newDescent = info.Descent;
- int maxWidth = getTextAreaWidth() - getTextStyle().getRightIndent();
+ int maxWidth = getTextAreaWidth();
boolean wordOccurred = false;
boolean isVisible = false;
int lastSpaceWidth = 0;
int internalSpaceCounter = 0;
boolean removeLastSpace = false;
do {
ZLTextElement element = paragraphCursor.getElement(currentElementIndex);
newWidth += getElementWidth(element, currentCharIndex);
newHeight = Math.max(newHeight, getElementHeight(element));
newDescent = Math.max(newDescent, getElementDescent(element));
if (element == ZLTextElement.HSpace) {
if (wordOccurred) {
wordOccurred = false;
internalSpaceCounter++;
lastSpaceWidth = context.getSpaceWidth();
newWidth += lastSpaceWidth;
}
} else if (element instanceof ZLTextWord) {
wordOccurred = true;
isVisible = true;
} else if (element instanceof ZLTextImageElement) {
wordOccurred = true;
isVisible = true;
} else if (isStyleChangeElement(element)) {
applyStyleChangeElement(element);
}
if (newWidth > maxWidth) {
if (info.EndElementIndex != startIndex || element instanceof ZLTextWord) {
break;
}
}
ZLTextElement previousElement = element;
++currentElementIndex;
currentCharIndex = 0;
boolean allowBreak = currentElementIndex == endIndex;
if (!allowBreak) {
element = paragraphCursor.getElement(currentElementIndex);
allowBreak = ((!(element instanceof ZLTextWord) || previousElement instanceof ZLTextWord) &&
!(element instanceof ZLTextImageElement) &&
!(element instanceof ZLTextControlElement));
}
if (allowBreak) {
info.IsVisible = isVisible;
info.Width = newWidth;
if (info.Height < newHeight) {
info.Height = newHeight;
}
if (info.Descent < newDescent) {
info.Descent = newDescent;
}
info.EndElementIndex = currentElementIndex;
info.EndCharIndex = currentCharIndex;
info.SpaceCounter = internalSpaceCounter;
storedStyle = getTextStyle();
removeLastSpace = !wordOccurred && (internalSpaceCounter > 0);
}
} while (currentElementIndex != endIndex);
if (currentElementIndex != endIndex &&
(isHyphenationPossible() || info.EndElementIndex == startIndex)) {
ZLTextElement element = paragraphCursor.getElement(currentElementIndex);
if (element instanceof ZLTextWord) {
final ZLTextWord word = (ZLTextWord)element;
newWidth -= getWordWidth(word, currentCharIndex);
int spaceLeft = maxWidth - newWidth;
if ((word.Length > 3 && spaceLeft > 2 * context.getSpaceWidth())
|| info.EndElementIndex == startIndex) {
ZLTextHyphenationInfo hyphenationInfo = ZLTextHyphenator.Instance().getInfo(word);
int hyphenationPosition = word.Length - 1;
int subwordWidth = 0;
for(; hyphenationPosition > currentCharIndex; hyphenationPosition--) {
if (hyphenationInfo.isHyphenationPossible(hyphenationPosition)) {
subwordWidth = getWordWidth(
word,
currentCharIndex,
hyphenationPosition - currentCharIndex,
word.Data[word.Offset + hyphenationPosition - 1] != '-'
);
if (subwordWidth <= spaceLeft) {
break;
}
}
}
if (hyphenationPosition == currentCharIndex && info.EndElementIndex == startIndex) {
hyphenationPosition = word.Length == currentCharIndex + 1 ? word.Length : word.Length - 1;
subwordWidth = getWordWidth(word, currentCharIndex, word.Length - currentCharIndex, false);
for(; hyphenationPosition > currentCharIndex + 1; hyphenationPosition--) {
subwordWidth = getWordWidth(
word,
currentCharIndex,
hyphenationPosition - currentCharIndex,
word.Data[word.Offset + hyphenationPosition - 1] != '-'
);
if (subwordWidth <= spaceLeft) {
break;
}
}
}
if (hyphenationPosition > currentCharIndex) {
info.IsVisible = true;
info.Width = newWidth + subwordWidth;
if (info.Height < newHeight) {
info.Height = newHeight;
}
if (info.Descent < newDescent) {
info.Descent = newDescent;
}
info.EndElementIndex = currentElementIndex;
info.EndCharIndex = hyphenationPosition;
info.SpaceCounter = internalSpaceCounter;
storedStyle = getTextStyle();
removeLastSpace = false;
}
}
}
}
if (removeLastSpace) {
info.Width -= lastSpaceWidth;
info.SpaceCounter--;
}
setTextStyle(storedStyle);
if (isFirstLine) {
info.Height += info.StartStyle.getSpaceBefore();
}
if (info.isEndOfParagraph()) {
info.VSpaceAfter = getTextStyle().getSpaceAfter();
}
if (info.EndElementIndex != endIndex || endIndex == info.ParagraphCursorLength) {
myLineInfoCache.put(info, info);
}
return info;
}
private void prepareTextLine(ZLTextPage page, ZLTextLineInfo info, int y) {
y = Math.min(y + info.Height, getTopMargin() + getTextAreaHeight() - 1);
final ZLPaintContext context = getContext();
final ZLTextParagraphCursor paragraphCursor = info.ParagraphCursor;
setTextStyle(info.StartStyle);
int spaceCounter = info.SpaceCounter;
int fullCorrection = 0;
final boolean endOfParagraph = info.isEndOfParagraph();
boolean wordOccurred = false;
boolean changeStyle = true;
int x = getLeftMargin() + info.LeftIndent;
final int maxWidth = getTextAreaWidth();
switch (getTextStyle().getAlignment()) {
case ZLTextAlignmentType.ALIGN_RIGHT:
x += maxWidth - getTextStyle().getRightIndent() - info.Width;
break;
case ZLTextAlignmentType.ALIGN_CENTER:
x += (maxWidth - getTextStyle().getRightIndent() - info.Width) / 2;
break;
case ZLTextAlignmentType.ALIGN_JUSTIFY:
if (!endOfParagraph && (paragraphCursor.getElement(info.EndElementIndex) != ZLTextElement.AfterParagraph)) {
fullCorrection = maxWidth - getTextStyle().getRightIndent() - info.Width;
}
break;
case ZLTextAlignmentType.ALIGN_LEFT:
case ZLTextAlignmentType.ALIGN_UNDEFINED:
break;
}
final ZLTextParagraphCursor paragraph = info.ParagraphCursor;
final int paragraphIndex = paragraph.Index;
final int endElementIndex = info.EndElementIndex;
int charIndex = info.RealStartCharIndex;
ZLTextElementArea spaceElement = null;
for (int wordIndex = info.RealStartElementIndex; wordIndex != endElementIndex; ++wordIndex, charIndex = 0) {
final ZLTextElement element = paragraph.getElement(wordIndex);
final int width = getElementWidth(element, charIndex);
if (element == ZLTextElement.HSpace) {
if (wordOccurred && (spaceCounter > 0)) {
final int correction = fullCorrection / spaceCounter;
final int spaceLength = context.getSpaceWidth() + correction;
if (getTextStyle().isUnderline()) {
spaceElement = new ZLTextElementArea(
paragraphIndex, wordIndex, 0,
0, // length
true, // is last in element
false, // add hyphenation sign
false, // changed style
getTextStyle(), element, x, x + spaceLength, y, y
);
} else {
spaceElement = null;
}
x += spaceLength;
fullCorrection -= correction;
wordOccurred = false;
--spaceCounter;
}
} else if (element instanceof ZLTextWord || element instanceof ZLTextImageElement) {
final int height = getElementHeight(element);
final int descent = getElementDescent(element);
final int length = element instanceof ZLTextWord ? ((ZLTextWord)element).Length : 0;
if (spaceElement != null) {
page.TextElementMap.add(spaceElement);
spaceElement = null;
}
page.TextElementMap.add(new ZLTextElementArea(
paragraphIndex, wordIndex, charIndex,
length - charIndex,
true, // is last in element
false, // add hyphenation sign
changeStyle, getTextStyle(), element,
x, x + width - 1, y - height + 1, y + descent
));
changeStyle = false;
wordOccurred = true;
} else if (isStyleChangeElement(element)) {
applyStyleChangeElement(element);
changeStyle = true;
}
x += width;
}
if (!endOfParagraph) {
final int len = info.EndCharIndex;
if (len > 0) {
final int wordIndex = info.EndElementIndex;
final ZLTextWord word = (ZLTextWord)paragraph.getElement(wordIndex);
final boolean addHyphenationSign = word.Data[word.Offset + len - 1] != '-';
final int width = getWordWidth(word, 0, len, addHyphenationSign);
final int height = getElementHeight(word);
final int descent = context.getDescent();
page.TextElementMap.add(
new ZLTextElementArea(
paragraphIndex, wordIndex, 0,
len,
false, // is last in element
addHyphenationSign,
changeStyle, getTextStyle(), word,
x, x + width - 1, y - height + 1, y + descent
)
);
}
}
}
public synchronized final void scrollPage(boolean forward, int scrollingMode, int value) {
preparePaintInfo(myCurrentPage);
myPreviousPage.reset();
myNextPage.reset();
if (myCurrentPage.PaintState == PaintStateEnum.READY) {
myCurrentPage.PaintState = forward ? PaintStateEnum.TO_SCROLL_FORWARD : PaintStateEnum.TO_SCROLL_BACKWARD;
myScrollingMode = scrollingMode;
myOverlappingValue = value;
}
}
public final synchronized void gotoPosition(ZLTextPosition position) {
if (position != null) {
gotoPosition(position.getParagraphIndex(), position.getElementIndex(), position.getCharIndex());
}
}
public final synchronized void gotoPosition(int paragraphIndex, int wordIndex, int charIndex) {
if (myModel != null && myModel.getParagraphsNumber() > 0) {
Application.getViewWidget().reset();
myCurrentPage.moveStartCursor(paragraphIndex, wordIndex, charIndex);
myPreviousPage.reset();
myNextPage.reset();
preparePaintInfo(myCurrentPage);
if (myCurrentPage.isEmptyPage()) {
scrollPage(true, ScrollingMode.NO_OVERLAPPING, 0);
}
}
}
private final synchronized void gotoPositionByEnd(int paragraphIndex, int wordIndex, int charIndex) {
if (myModel != null && myModel.getParagraphsNumber() > 0) {
myCurrentPage.moveEndCursor(paragraphIndex, wordIndex, charIndex);
myPreviousPage.reset();
myNextPage.reset();
preparePaintInfo(myCurrentPage);
if (myCurrentPage.isEmptyPage()) {
scrollPage(false, ScrollingMode.NO_OVERLAPPING, 0);
}
}
}
protected synchronized void preparePaintInfo() {
myPreviousPage.reset();
myNextPage.reset();
preparePaintInfo(myCurrentPage);
}
private synchronized void preparePaintInfo(ZLTextPage page) {
page.setSize(getTextAreaWidth(), getTextAreaHeight(), page == myPreviousPage);
if (page.PaintState == PaintStateEnum.NOTHING_TO_PAINT || page.PaintState == PaintStateEnum.READY) {
return;
}
final int oldState = page.PaintState;
final HashMap<ZLTextLineInfo,ZLTextLineInfo> cache = myLineInfoCache;
for (ZLTextLineInfo info : page.LineInfos) {
cache.put(info, info);
}
switch (page.PaintState) {
default:
break;
case PaintStateEnum.TO_SCROLL_FORWARD:
if (!page.EndCursor.isEndOfText()) {
final ZLTextWordCursor startCursor = new ZLTextWordCursor();
switch (myScrollingMode) {
case ScrollingMode.NO_OVERLAPPING:
break;
case ScrollingMode.KEEP_LINES:
page.findLineFromEnd(startCursor, myOverlappingValue);
break;
case ScrollingMode.SCROLL_LINES:
page.findLineFromStart(startCursor, myOverlappingValue);
if (startCursor.isEndOfParagraph()) {
startCursor.nextParagraph();
}
break;
case ScrollingMode.SCROLL_PERCENTAGE:
page.findPercentFromStart(startCursor, myOverlappingValue);
break;
}
if (!startCursor.isNull() && startCursor.samePositionAs(page.StartCursor)) {
page.findLineFromStart(startCursor, 1);
}
if (!startCursor.isNull()) {
final ZLTextWordCursor endCursor = new ZLTextWordCursor();
buildInfos(page, startCursor, endCursor);
if (!page.isEmptyPage() && (myScrollingMode != ScrollingMode.KEEP_LINES || !endCursor.samePositionAs(page.EndCursor))) {
page.StartCursor.setCursor(startCursor);
page.EndCursor.setCursor(endCursor);
break;
}
}
page.StartCursor.setCursor(page.EndCursor);
buildInfos(page, page.StartCursor, page.EndCursor);
}
break;
case PaintStateEnum.TO_SCROLL_BACKWARD:
if (!page.StartCursor.isStartOfText()) {
switch (myScrollingMode) {
case ScrollingMode.NO_OVERLAPPING:
page.StartCursor.setCursor(findStart(page.StartCursor, SizeUnit.PIXEL_UNIT, getTextAreaHeight()));
break;
case ScrollingMode.KEEP_LINES:
{
ZLTextWordCursor endCursor = new ZLTextWordCursor();
page.findLineFromStart(endCursor, myOverlappingValue);
if (!endCursor.isNull() && endCursor.samePositionAs(page.EndCursor)) {
page.findLineFromEnd(endCursor, 1);
}
if (!endCursor.isNull()) {
ZLTextWordCursor startCursor = findStart(endCursor, SizeUnit.PIXEL_UNIT, getTextAreaHeight());
if (startCursor.samePositionAs(page.StartCursor)) {
page.StartCursor.setCursor(findStart(page.StartCursor, SizeUnit.PIXEL_UNIT, getTextAreaHeight()));
} else {
page.StartCursor.setCursor(startCursor);
}
} else {
page.StartCursor.setCursor(findStart(page.StartCursor, SizeUnit.PIXEL_UNIT, getTextAreaHeight()));
}
break;
}
case ScrollingMode.SCROLL_LINES:
page.StartCursor.setCursor(findStart(page.StartCursor, SizeUnit.LINE_UNIT, myOverlappingValue));
break;
case ScrollingMode.SCROLL_PERCENTAGE:
page.StartCursor.setCursor(findStart(page.StartCursor, SizeUnit.PIXEL_UNIT, getTextAreaHeight() * myOverlappingValue / 100));
break;
}
buildInfos(page, page.StartCursor, page.EndCursor);
if (page.isEmptyPage()) {
page.StartCursor.setCursor(findStart(page.StartCursor, SizeUnit.LINE_UNIT, 1));
buildInfos(page, page.StartCursor, page.EndCursor);
}
}
break;
case PaintStateEnum.START_IS_KNOWN:
buildInfos(page, page.StartCursor, page.EndCursor);
break;
case PaintStateEnum.END_IS_KNOWN:
page.StartCursor.setCursor(findStart(page.EndCursor, SizeUnit.PIXEL_UNIT, getTextAreaHeight()));
buildInfos(page, page.StartCursor, page.EndCursor);
break;
}
page.PaintState = PaintStateEnum.READY;
// TODO: cache?
myLineInfoCache.clear();
if (page == myCurrentPage) {
if (oldState != PaintStateEnum.START_IS_KNOWN) {
myPreviousPage.reset();
}
if (oldState != PaintStateEnum.END_IS_KNOWN) {
myNextPage.reset();
}
}
}
public void clearCaches() {
resetMetrics();
rebuildPaintInfo();
Application.getViewWidget().reset();
myCharWidth = -1;
}
protected void rebuildPaintInfo() {
myPreviousPage.reset();
myNextPage.reset();
ZLTextParagraphCursorCache.clear();
if (myCurrentPage.PaintState != PaintStateEnum.NOTHING_TO_PAINT) {
myCurrentPage.LineInfos.clear();
if (!myCurrentPage.StartCursor.isNull()) {
myCurrentPage.StartCursor.rebuild();
myCurrentPage.EndCursor.reset();
myCurrentPage.PaintState = PaintStateEnum.START_IS_KNOWN;
} else if (!myCurrentPage.EndCursor.isNull()) {
myCurrentPage.EndCursor.rebuild();
myCurrentPage.StartCursor.reset();
myCurrentPage.PaintState = PaintStateEnum.END_IS_KNOWN;
}
}
myLineInfoCache.clear();
}
private int infoSize(ZLTextLineInfo info, int unit) {
return (unit == SizeUnit.PIXEL_UNIT) ? (info.Height + info.Descent + info.VSpaceAfter) : (info.IsVisible ? 1 : 0);
}
private int paragraphSize(ZLTextWordCursor cursor, boolean beforeCurrentPosition, int unit) {
final ZLTextParagraphCursor paragraphCursor = cursor.getParagraphCursor();
if (paragraphCursor == null) {
return 0;
}
final int endElementIndex =
beforeCurrentPosition ? cursor.getElementIndex() : paragraphCursor.getParagraphLength();
resetTextStyle();
int size = 0;
int wordIndex = 0;
int charIndex = 0;
while (wordIndex != endElementIndex) {
ZLTextLineInfo info = processTextLine(paragraphCursor, wordIndex, charIndex, endElementIndex);
wordIndex = info.EndElementIndex;
charIndex = info.EndCharIndex;
size += infoSize(info, unit);
}
return size;
}
private void skip(ZLTextWordCursor cursor, int unit, int size) {
final ZLTextParagraphCursor paragraphCursor = cursor.getParagraphCursor();
if (paragraphCursor == null) {
return;
}
final int endElementIndex = paragraphCursor.getParagraphLength();
resetTextStyle();
applyStyleChanges(paragraphCursor, 0, cursor.getElementIndex());
while (!cursor.isEndOfParagraph() && (size > 0)) {
ZLTextLineInfo info = processTextLine(paragraphCursor, cursor.getElementIndex(), cursor.getCharIndex(), endElementIndex);
cursor.moveTo(info.EndElementIndex, info.EndCharIndex);
size -= infoSize(info, unit);
}
}
private ZLTextWordCursor findStart(ZLTextWordCursor end, int unit, int size) {
final ZLTextWordCursor start = new ZLTextWordCursor(end);
size -= paragraphSize(start, true, unit);
boolean positionChanged = !start.isStartOfParagraph();
start.moveToParagraphStart();
while (size > 0) {
if (positionChanged && start.getParagraphCursor().isEndOfSection()) {
break;
}
if (!start.previousParagraph()) {
break;
}
if (!start.getParagraphCursor().isEndOfSection()) {
positionChanged = true;
}
size -= paragraphSize(start, false, unit);
}
skip(start, unit, -size);
if (unit == SizeUnit.PIXEL_UNIT) {
boolean sameStart = start.samePositionAs(end);
if (!sameStart && start.isEndOfParagraph() && end.isStartOfParagraph()) {
ZLTextWordCursor startCopy = start;
startCopy.nextParagraph();
sameStart = startCopy.samePositionAs(end);
}
if (sameStart) {
start.setCursor(findStart(end, SizeUnit.LINE_UNIT, 1));
}
}
return start;
}
protected ZLTextElementArea getElementByCoordinates(int x, int y) {
return myCurrentPage.TextElementMap.binarySearch(x, y);
}
@Override
public boolean onFingerMove(int x, int y) {
return false;
}
@Override
public boolean onFingerRelease(int x, int y) {
return false;
}
public void hideSelectedRegionBorder() {
myHighlightSelectedRegion = false;
Application.getViewWidget().reset();
}
private ZLTextRegion getSelectedRegion(ZLTextPage page) {
return page.TextElementMap.getRegion(mySelectedRegionSoul);
}
public ZLTextRegion getSelectedRegion() {
return getSelectedRegion(myCurrentPage);
}
protected ZLTextRegion findRegion(int x, int y, ZLTextRegion.Filter filter) {
return findRegion(x, y, Integer.MAX_VALUE - 1, filter);
}
protected ZLTextRegion findRegion(int x, int y, int maxDistance, ZLTextRegion.Filter filter) {
return myCurrentPage.TextElementMap.findRegion(x, y, maxDistance, filter);
}
public void selectRegion(ZLTextRegion region) {
final ZLTextRegion.Soul soul = region != null ? region.getSoul() : null;
if (soul == null || !soul.equals(mySelectedRegionSoul)) {
myHighlightSelectedRegion = true;
}
mySelectedRegionSoul = soul;
}
protected boolean initSelection(int x, int y) {
y -= ZLTextSelectionCursor.getHeight() / 2 + ZLTextSelectionCursor.getAccent() / 2;
if (!mySelection.start(x, y)) {
return false;
}
Application.getViewWidget().reset();
Application.getViewWidget().repaint();
return true;
}
public void clearSelection() {
if (mySelection.clear()) {
Application.getViewWidget().reset();
Application.getViewWidget().repaint();
}
}
public int getSelectionStartY() {
if (mySelection.isEmpty()) {
return 0;
}
final ZLTextElementArea selectionStartArea = mySelection.getStartArea(myCurrentPage);
if (selectionStartArea != null) {
return selectionStartArea.YStart;
}
if (mySelection.hasAPartBeforePage(myCurrentPage)) {
final ZLTextElementArea firstArea = myCurrentPage.TextElementMap.getFirstArea();
return firstArea != null ? firstArea.YStart : 0;
} else {
final ZLTextElementArea lastArea = myCurrentPage.TextElementMap.getLastArea();
return lastArea != null ? lastArea.YEnd : 0;
}
}
public int getSelectionEndY() {
if (mySelection.isEmpty()) {
return 0;
}
final ZLTextElementArea selectionEndArea = mySelection.getEndArea(myCurrentPage);
if (selectionEndArea != null) {
return selectionEndArea.YEnd;
}
if (mySelection.hasAPartAfterPage(myCurrentPage)) {
final ZLTextElementArea lastArea = myCurrentPage.TextElementMap.getLastArea();
return lastArea != null ? lastArea.YEnd : 0;
} else {
final ZLTextElementArea firstArea = myCurrentPage.TextElementMap.getFirstArea();
return firstArea != null ? firstArea.YStart : 0;
}
}
public ZLTextPosition getSelectionStartPosition() {
return mySelection.getStartPosition();
}
public ZLTextPosition getSelectionEndPosition() {
return mySelection.getEndPosition();
}
public boolean isSelectionEmpty() {
return mySelection.isEmpty();
}
public void resetRegionPointer() {
mySelectedRegionSoul = null;
myHighlightSelectedRegion = true;
}
public ZLTextRegion nextRegion(Direction direction, ZLTextRegion.Filter filter) {
return myCurrentPage.TextElementMap.nextRegion(getSelectedRegion(), direction, filter);
}
@Override
public boolean canScroll(PageIndex index) {
switch (index) {
default:
return true;
case next:
{
final ZLTextWordCursor cursor = getEndCursor();
return cursor != null && !cursor.isNull() && !cursor.isEndOfText();
}
case previous:
{
final ZLTextWordCursor cursor = getStartCursor();
return cursor != null && !cursor.isNull() && !cursor.isStartOfText();
}
}
}
}
| true | true | private ZLTextLineInfo processTextLine(
ZLTextParagraphCursor paragraphCursor,
final int startIndex,
final int startCharIndex,
final int endIndex
) {
final ZLPaintContext context = getContext();
final ZLTextLineInfo info = new ZLTextLineInfo(paragraphCursor, startIndex, startCharIndex, getTextStyle());
final ZLTextLineInfo cachedInfo = myLineInfoCache.get(info);
if (cachedInfo != null) {
applyStyleChanges(paragraphCursor, startIndex, cachedInfo.EndElementIndex);
return cachedInfo;
}
int currentElementIndex = startIndex;
int currentCharIndex = startCharIndex;
final boolean isFirstLine = startIndex == 0 && startCharIndex == 0;
if (isFirstLine) {
ZLTextElement element = paragraphCursor.getElement(currentElementIndex);
while (isStyleChangeElement(element)) {
applyStyleChangeElement(element);
++currentElementIndex;
currentCharIndex = 0;
if (currentElementIndex == endIndex) {
break;
}
element = paragraphCursor.getElement(currentElementIndex);
}
info.StartStyle = getTextStyle();
info.RealStartElementIndex = currentElementIndex;
info.RealStartCharIndex = currentCharIndex;
}
ZLTextStyle storedStyle = getTextStyle();
info.LeftIndent = getTextStyle().getLeftIndent();
if (isFirstLine) {
info.LeftIndent += getTextStyle().getFirstLineIndentDelta();
}
info.Width = info.LeftIndent;
if (info.RealStartElementIndex == endIndex) {
info.EndElementIndex = info.RealStartElementIndex;
info.EndCharIndex = info.RealStartCharIndex;
return info;
}
int newWidth = info.Width;
int newHeight = info.Height;
int newDescent = info.Descent;
int maxWidth = getTextAreaWidth() - getTextStyle().getRightIndent();
boolean wordOccurred = false;
boolean isVisible = false;
int lastSpaceWidth = 0;
int internalSpaceCounter = 0;
boolean removeLastSpace = false;
do {
ZLTextElement element = paragraphCursor.getElement(currentElementIndex);
newWidth += getElementWidth(element, currentCharIndex);
newHeight = Math.max(newHeight, getElementHeight(element));
newDescent = Math.max(newDescent, getElementDescent(element));
if (element == ZLTextElement.HSpace) {
if (wordOccurred) {
wordOccurred = false;
internalSpaceCounter++;
lastSpaceWidth = context.getSpaceWidth();
newWidth += lastSpaceWidth;
}
} else if (element instanceof ZLTextWord) {
wordOccurred = true;
isVisible = true;
} else if (element instanceof ZLTextImageElement) {
wordOccurred = true;
isVisible = true;
} else if (isStyleChangeElement(element)) {
applyStyleChangeElement(element);
}
if (newWidth > maxWidth) {
if (info.EndElementIndex != startIndex || element instanceof ZLTextWord) {
break;
}
}
ZLTextElement previousElement = element;
++currentElementIndex;
currentCharIndex = 0;
boolean allowBreak = currentElementIndex == endIndex;
if (!allowBreak) {
element = paragraphCursor.getElement(currentElementIndex);
allowBreak = ((!(element instanceof ZLTextWord) || previousElement instanceof ZLTextWord) &&
!(element instanceof ZLTextImageElement) &&
!(element instanceof ZLTextControlElement));
}
if (allowBreak) {
info.IsVisible = isVisible;
info.Width = newWidth;
if (info.Height < newHeight) {
info.Height = newHeight;
}
if (info.Descent < newDescent) {
info.Descent = newDescent;
}
info.EndElementIndex = currentElementIndex;
info.EndCharIndex = currentCharIndex;
info.SpaceCounter = internalSpaceCounter;
storedStyle = getTextStyle();
removeLastSpace = !wordOccurred && (internalSpaceCounter > 0);
}
} while (currentElementIndex != endIndex);
if (currentElementIndex != endIndex &&
(isHyphenationPossible() || info.EndElementIndex == startIndex)) {
ZLTextElement element = paragraphCursor.getElement(currentElementIndex);
if (element instanceof ZLTextWord) {
final ZLTextWord word = (ZLTextWord)element;
newWidth -= getWordWidth(word, currentCharIndex);
int spaceLeft = maxWidth - newWidth;
if ((word.Length > 3 && spaceLeft > 2 * context.getSpaceWidth())
|| info.EndElementIndex == startIndex) {
ZLTextHyphenationInfo hyphenationInfo = ZLTextHyphenator.Instance().getInfo(word);
int hyphenationPosition = word.Length - 1;
int subwordWidth = 0;
for(; hyphenationPosition > currentCharIndex; hyphenationPosition--) {
if (hyphenationInfo.isHyphenationPossible(hyphenationPosition)) {
subwordWidth = getWordWidth(
word,
currentCharIndex,
hyphenationPosition - currentCharIndex,
word.Data[word.Offset + hyphenationPosition - 1] != '-'
);
if (subwordWidth <= spaceLeft) {
break;
}
}
}
if (hyphenationPosition == currentCharIndex && info.EndElementIndex == startIndex) {
hyphenationPosition = word.Length == currentCharIndex + 1 ? word.Length : word.Length - 1;
subwordWidth = getWordWidth(word, currentCharIndex, word.Length - currentCharIndex, false);
for(; hyphenationPosition > currentCharIndex + 1; hyphenationPosition--) {
subwordWidth = getWordWidth(
word,
currentCharIndex,
hyphenationPosition - currentCharIndex,
word.Data[word.Offset + hyphenationPosition - 1] != '-'
);
if (subwordWidth <= spaceLeft) {
break;
}
}
}
if (hyphenationPosition > currentCharIndex) {
info.IsVisible = true;
info.Width = newWidth + subwordWidth;
if (info.Height < newHeight) {
info.Height = newHeight;
}
if (info.Descent < newDescent) {
info.Descent = newDescent;
}
info.EndElementIndex = currentElementIndex;
info.EndCharIndex = hyphenationPosition;
info.SpaceCounter = internalSpaceCounter;
storedStyle = getTextStyle();
removeLastSpace = false;
}
}
}
}
if (removeLastSpace) {
info.Width -= lastSpaceWidth;
info.SpaceCounter--;
}
setTextStyle(storedStyle);
if (isFirstLine) {
info.Height += info.StartStyle.getSpaceBefore();
}
if (info.isEndOfParagraph()) {
info.VSpaceAfter = getTextStyle().getSpaceAfter();
}
if (info.EndElementIndex != endIndex || endIndex == info.ParagraphCursorLength) {
myLineInfoCache.put(info, info);
}
return info;
}
| private ZLTextLineInfo processTextLine(
ZLTextParagraphCursor paragraphCursor,
final int startIndex,
final int startCharIndex,
final int endIndex
) {
final ZLPaintContext context = getContext();
final ZLTextLineInfo info = new ZLTextLineInfo(paragraphCursor, startIndex, startCharIndex, getTextStyle());
final ZLTextLineInfo cachedInfo = myLineInfoCache.get(info);
if (cachedInfo != null) {
applyStyleChanges(paragraphCursor, startIndex, cachedInfo.EndElementIndex);
return cachedInfo;
}
int currentElementIndex = startIndex;
int currentCharIndex = startCharIndex;
final boolean isFirstLine = startIndex == 0 && startCharIndex == 0;
if (isFirstLine) {
ZLTextElement element = paragraphCursor.getElement(currentElementIndex);
while (isStyleChangeElement(element)) {
applyStyleChangeElement(element);
++currentElementIndex;
currentCharIndex = 0;
if (currentElementIndex == endIndex) {
break;
}
element = paragraphCursor.getElement(currentElementIndex);
}
info.StartStyle = getTextStyle();
info.RealStartElementIndex = currentElementIndex;
info.RealStartCharIndex = currentCharIndex;
}
ZLTextStyle storedStyle = getTextStyle();
info.LeftIndent = getTextStyle().getLeftIndent();
if (isFirstLine) {
info.LeftIndent += getTextStyle().getFirstLineIndentDelta();
}
info.Width = info.LeftIndent;
if (info.RealStartElementIndex == endIndex) {
info.EndElementIndex = info.RealStartElementIndex;
info.EndCharIndex = info.RealStartCharIndex;
return info;
}
int newWidth = info.Width;
int newHeight = info.Height;
int newDescent = info.Descent;
int maxWidth = getTextAreaWidth();
boolean wordOccurred = false;
boolean isVisible = false;
int lastSpaceWidth = 0;
int internalSpaceCounter = 0;
boolean removeLastSpace = false;
do {
ZLTextElement element = paragraphCursor.getElement(currentElementIndex);
newWidth += getElementWidth(element, currentCharIndex);
newHeight = Math.max(newHeight, getElementHeight(element));
newDescent = Math.max(newDescent, getElementDescent(element));
if (element == ZLTextElement.HSpace) {
if (wordOccurred) {
wordOccurred = false;
internalSpaceCounter++;
lastSpaceWidth = context.getSpaceWidth();
newWidth += lastSpaceWidth;
}
} else if (element instanceof ZLTextWord) {
wordOccurred = true;
isVisible = true;
} else if (element instanceof ZLTextImageElement) {
wordOccurred = true;
isVisible = true;
} else if (isStyleChangeElement(element)) {
applyStyleChangeElement(element);
}
if (newWidth > maxWidth) {
if (info.EndElementIndex != startIndex || element instanceof ZLTextWord) {
break;
}
}
ZLTextElement previousElement = element;
++currentElementIndex;
currentCharIndex = 0;
boolean allowBreak = currentElementIndex == endIndex;
if (!allowBreak) {
element = paragraphCursor.getElement(currentElementIndex);
allowBreak = ((!(element instanceof ZLTextWord) || previousElement instanceof ZLTextWord) &&
!(element instanceof ZLTextImageElement) &&
!(element instanceof ZLTextControlElement));
}
if (allowBreak) {
info.IsVisible = isVisible;
info.Width = newWidth;
if (info.Height < newHeight) {
info.Height = newHeight;
}
if (info.Descent < newDescent) {
info.Descent = newDescent;
}
info.EndElementIndex = currentElementIndex;
info.EndCharIndex = currentCharIndex;
info.SpaceCounter = internalSpaceCounter;
storedStyle = getTextStyle();
removeLastSpace = !wordOccurred && (internalSpaceCounter > 0);
}
} while (currentElementIndex != endIndex);
if (currentElementIndex != endIndex &&
(isHyphenationPossible() || info.EndElementIndex == startIndex)) {
ZLTextElement element = paragraphCursor.getElement(currentElementIndex);
if (element instanceof ZLTextWord) {
final ZLTextWord word = (ZLTextWord)element;
newWidth -= getWordWidth(word, currentCharIndex);
int spaceLeft = maxWidth - newWidth;
if ((word.Length > 3 && spaceLeft > 2 * context.getSpaceWidth())
|| info.EndElementIndex == startIndex) {
ZLTextHyphenationInfo hyphenationInfo = ZLTextHyphenator.Instance().getInfo(word);
int hyphenationPosition = word.Length - 1;
int subwordWidth = 0;
for(; hyphenationPosition > currentCharIndex; hyphenationPosition--) {
if (hyphenationInfo.isHyphenationPossible(hyphenationPosition)) {
subwordWidth = getWordWidth(
word,
currentCharIndex,
hyphenationPosition - currentCharIndex,
word.Data[word.Offset + hyphenationPosition - 1] != '-'
);
if (subwordWidth <= spaceLeft) {
break;
}
}
}
if (hyphenationPosition == currentCharIndex && info.EndElementIndex == startIndex) {
hyphenationPosition = word.Length == currentCharIndex + 1 ? word.Length : word.Length - 1;
subwordWidth = getWordWidth(word, currentCharIndex, word.Length - currentCharIndex, false);
for(; hyphenationPosition > currentCharIndex + 1; hyphenationPosition--) {
subwordWidth = getWordWidth(
word,
currentCharIndex,
hyphenationPosition - currentCharIndex,
word.Data[word.Offset + hyphenationPosition - 1] != '-'
);
if (subwordWidth <= spaceLeft) {
break;
}
}
}
if (hyphenationPosition > currentCharIndex) {
info.IsVisible = true;
info.Width = newWidth + subwordWidth;
if (info.Height < newHeight) {
info.Height = newHeight;
}
if (info.Descent < newDescent) {
info.Descent = newDescent;
}
info.EndElementIndex = currentElementIndex;
info.EndCharIndex = hyphenationPosition;
info.SpaceCounter = internalSpaceCounter;
storedStyle = getTextStyle();
removeLastSpace = false;
}
}
}
}
if (removeLastSpace) {
info.Width -= lastSpaceWidth;
info.SpaceCounter--;
}
setTextStyle(storedStyle);
if (isFirstLine) {
info.Height += info.StartStyle.getSpaceBefore();
}
if (info.isEndOfParagraph()) {
info.VSpaceAfter = getTextStyle().getSpaceAfter();
}
if (info.EndElementIndex != endIndex || endIndex == info.ParagraphCursorLength) {
myLineInfoCache.put(info, info);
}
return info;
}
|
diff --git a/javamelody-core/src/main/java/net/bull/javamelody/HtmlController.java b/javamelody-core/src/main/java/net/bull/javamelody/HtmlController.java
index 3af66ad6..07b5aa0e 100644
--- a/javamelody-core/src/main/java/net/bull/javamelody/HtmlController.java
+++ b/javamelody-core/src/main/java/net/bull/javamelody/HtmlController.java
@@ -1,293 +1,294 @@
/*
* Copyright 2008-2010 by Emeric Vernat
*
* This file is part of Java Melody.
*
* Java Melody is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Java Melody is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Java Melody. If not, see <http://www.gnu.org/licenses/>.
*/
package net.bull.javamelody; // NOPMD
import static net.bull.javamelody.HttpParameters.CONNECTIONS_PART;
import static net.bull.javamelody.HttpParameters.COUNTER_PARAMETER;
import static net.bull.javamelody.HttpParameters.COUNTER_SUMMARY_PER_CLASS_PART;
import static net.bull.javamelody.HttpParameters.CURRENT_REQUESTS_PART;
import static net.bull.javamelody.HttpParameters.DATABASE_PART;
import static net.bull.javamelody.HttpParameters.FORMAT_PARAMETER;
import static net.bull.javamelody.HttpParameters.GRAPH_PARAMETER;
import static net.bull.javamelody.HttpParameters.GRAPH_PART;
import static net.bull.javamelody.HttpParameters.HEAP_HISTO_PART;
import static net.bull.javamelody.HttpParameters.HTML_BODY_FORMAT;
import static net.bull.javamelody.HttpParameters.HTML_CHARSET;
import static net.bull.javamelody.HttpParameters.HTML_CONTENT_TYPE;
import static net.bull.javamelody.HttpParameters.JNDI_PART;
import static net.bull.javamelody.HttpParameters.MBEANS_PART;
import static net.bull.javamelody.HttpParameters.PART_PARAMETER;
import static net.bull.javamelody.HttpParameters.PATH_PARAMETER;
import static net.bull.javamelody.HttpParameters.PROCESSES_PART;
import static net.bull.javamelody.HttpParameters.REQUEST_PARAMETER;
import static net.bull.javamelody.HttpParameters.SESSIONS_PART;
import static net.bull.javamelody.HttpParameters.SESSION_ID_PARAMETER;
import static net.bull.javamelody.HttpParameters.THREADS_PART;
import static net.bull.javamelody.HttpParameters.USAGES_PART;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Collections;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Contrôleur au sens MVC de l'ihm de monitoring pour la partie html.
* @author Emeric Vernat
*/
class HtmlController {
private final HttpCookieManager httpCookieManager = new HttpCookieManager();
private final Collector collector;
private final CollectorServer collectorServer;
private final String messageForReport;
private final String anchorNameForRedirect;
HtmlController(Collector collector, CollectorServer collectorServer, String messageForReport,
String anchorNameForRedirect) {
super();
assert collector != null;
this.collector = collector;
this.collectorServer = collectorServer;
this.messageForReport = messageForReport;
this.anchorNameForRedirect = anchorNameForRedirect;
}
void doHtml(HttpServletRequest httpRequest, HttpServletResponse httpResponse,
List<JavaInformations> javaInformationsList) throws IOException {
final String part = httpRequest.getParameter(PART_PARAMETER);
if (!isFromCollectorServer()
- && (part == null || CURRENT_REQUESTS_PART.equalsIgnoreCase(part) || GRAPH_PART
+ && (part == null || CURRENT_REQUESTS_PART.equalsIgnoreCase(part)
+ || GRAPH_PART.equalsIgnoreCase(part) || COUNTER_SUMMARY_PER_CLASS_PART
.equalsIgnoreCase(part))) {
// avant de faire l'affichage on fait une collecte, pour que les courbes
// et les compteurs par jour soit à jour avec les dernières requêtes
collector.collectLocalContextWithoutErrors();
}
// simple appel de monitoring sans format
httpResponse.setContentType(HTML_CONTENT_TYPE);
final BufferedWriter writer = getWriter(httpResponse);
try {
final Range range = httpCookieManager.getRange(httpRequest, httpResponse);
final HtmlReport htmlReport = new HtmlReport(collector, collectorServer,
javaInformationsList, range, writer);
if (part == null) {
htmlReport.toHtml(messageForReport, anchorNameForRedirect);
} else {
doHtmlPart(httpRequest, part, htmlReport);
}
} finally {
writer.close();
}
}
static BufferedWriter getWriter(HttpServletResponse httpResponse) throws IOException {
return new BufferedWriter(new OutputStreamWriter(httpResponse.getOutputStream(),
HTML_CHARSET));
}
private void doHtmlPart(HttpServletRequest httpRequest, String part, HtmlReport htmlReport)
throws IOException {
if (GRAPH_PART.equalsIgnoreCase(part)) {
final String graphName = httpRequest.getParameter(GRAPH_PARAMETER);
htmlReport.writeRequestAndGraphDetail(graphName);
} else if (USAGES_PART.equalsIgnoreCase(part)) {
final String graphName = httpRequest.getParameter(GRAPH_PARAMETER);
htmlReport.writeRequestUsages(graphName);
} else if (CURRENT_REQUESTS_PART.equalsIgnoreCase(part)) {
final boolean withoutHeaders = HTML_BODY_FORMAT.equalsIgnoreCase(httpRequest
.getParameter(FORMAT_PARAMETER));
doCurrentRequests(htmlReport, withoutHeaders);
} else if (THREADS_PART.equalsIgnoreCase(part)) {
htmlReport.writeAllThreadsAsPart();
} else if (COUNTER_SUMMARY_PER_CLASS_PART.equalsIgnoreCase(part)) {
final String counterName = httpRequest.getParameter(COUNTER_PARAMETER);
final String requestId = httpRequest.getParameter(GRAPH_PARAMETER);
htmlReport.writeCounterSummaryPerClass(counterName, requestId);
} else {
doHtmlPartForSystemActions(httpRequest, part, htmlReport);
}
}
private void doHtmlPartForSystemActions(HttpServletRequest httpRequest, String part,
HtmlReport htmlReport) throws IOException {
if (SESSIONS_PART.equalsIgnoreCase(part)) {
doSessions(htmlReport, httpRequest.getParameter(SESSION_ID_PARAMETER));
} else if (HEAP_HISTO_PART.equalsIgnoreCase(part)) {
doHeapHisto(htmlReport);
} else if (PROCESSES_PART.equalsIgnoreCase(part)) {
doProcesses(htmlReport);
} else if (DATABASE_PART.equalsIgnoreCase(part)) {
final int requestIndex = DatabaseInformations.parseRequestIndex(httpRequest
.getParameter(REQUEST_PARAMETER));
doDatabase(htmlReport, requestIndex);
} else if (CONNECTIONS_PART.equalsIgnoreCase(part)) {
final boolean withoutHeaders = HTML_BODY_FORMAT.equalsIgnoreCase(httpRequest
.getParameter(FORMAT_PARAMETER));
doConnections(htmlReport, withoutHeaders);
} else if (JNDI_PART.equalsIgnoreCase(part)) {
doJndi(htmlReport, httpRequest.getParameter(PATH_PARAMETER));
} else if (MBEANS_PART.equalsIgnoreCase(part)) {
final boolean withoutHeaders = HTML_BODY_FORMAT.equalsIgnoreCase(httpRequest
.getParameter(FORMAT_PARAMETER));
doMBeans(htmlReport, withoutHeaders);
} else {
throw new IllegalArgumentException(part);
}
}
private void doSessions(HtmlReport htmlReport, String sessionId) throws IOException {
// par sécurité
Action.checkSystemActionsEnabled();
final List<SessionInformations> sessionsInformations;
if (!isFromCollectorServer()) {
if (sessionId == null) {
sessionsInformations = SessionListener.getAllSessionsInformations();
} else {
sessionsInformations = Collections.singletonList(SessionListener
.getSessionInformationsBySessionId(sessionId));
}
} else {
sessionsInformations = collectorServer.collectSessionInformations(
collector.getApplication(), sessionId);
}
if (sessionId == null || sessionsInformations.isEmpty()) {
htmlReport.writeSessions(sessionsInformations, messageForReport, SESSIONS_PART);
} else {
final SessionInformations sessionInformation = sessionsInformations.get(0);
htmlReport.writeSessionDetail(sessionId, sessionInformation);
}
}
private void doCurrentRequests(HtmlReport htmlReport, boolean withoutHeaders)
throws IOException {
if (isFromCollectorServer()) {
// le html des requêtes en cours dans une page à part n'est utile que depuis une
// application monitorée (le serveur de collecte n'a pas les données requises)
throw new IllegalStateException();
}
htmlReport.writeAllCurrentRequestsAsPart(withoutHeaders);
}
private void doHeapHisto(HtmlReport htmlReport) throws IOException {
// par sécurité
Action.checkSystemActionsEnabled();
final HeapHistogram heapHistogram;
try {
if (!isFromCollectorServer()) {
heapHistogram = VirtualMachine.createHeapHistogram();
} else {
heapHistogram = collectorServer.collectHeapHistogram(collector.getApplication());
}
} catch (final Exception e) {
LOG.warn("heaphisto report failed", e);
htmlReport.writeMessageIfNotNull(String.valueOf(e.getMessage()), null);
return;
}
htmlReport.writeHeapHistogram(heapHistogram, messageForReport, HEAP_HISTO_PART);
}
private void doProcesses(HtmlReport htmlReport) throws IOException {
// par sécurité
Action.checkSystemActionsEnabled();
try {
htmlReport.writeProcesses(ProcessInformations.buildProcessInformations());
} catch (final Exception e) {
LOG.warn("processes report failed", e);
htmlReport.writeMessageIfNotNull(String.valueOf(e.getMessage()), null);
}
}
private void doDatabase(HtmlReport htmlReport, int index) throws IOException {
// par sécurité
Action.checkSystemActionsEnabled();
try {
final DatabaseInformations databaseInformations;
if (!isFromCollectorServer()) {
databaseInformations = new DatabaseInformations(index);
} else {
databaseInformations = collectorServer.collectDatabaseInformations(
collector.getApplication(), index);
}
htmlReport.writeDatabase(databaseInformations);
} catch (final Exception e) {
LOG.warn("database report failed", e);
htmlReport.writeMessageIfNotNull(String.valueOf(e.getMessage()), null);
}
}
private void doConnections(HtmlReport htmlReport, boolean withoutHeaders) throws IOException {
// par sécurité
Action.checkSystemActionsEnabled();
htmlReport.writeConnections(JdbcWrapper.getConnectionInformationsList(), withoutHeaders);
}
private void doJndi(HtmlReport htmlReport, String path) throws IOException {
// par sécurité
Action.checkSystemActionsEnabled();
try {
htmlReport.writeJndi(path);
} catch (final Exception e) {
LOG.warn("jndi report failed", e);
htmlReport.writeMessageIfNotNull(String.valueOf(e.getMessage()), null);
}
}
private void doMBeans(HtmlReport htmlReport, boolean withoutHeaders) throws IOException {
// par sécurité
Action.checkSystemActionsEnabled();
try {
htmlReport.writeMBeans(withoutHeaders);
} catch (final Exception e) {
LOG.warn("mbeans report failed", e);
htmlReport.writeMessageIfNotNull(String.valueOf(e.getMessage()), null);
}
}
void writeHtmlToLastShutdownFile() {
try {
final File dir = Parameters.getStorageDirectory(collector.getApplication());
if (!dir.mkdirs() && !dir.exists()) {
throw new IOException("JavaMelody directory can't be created: " + dir.getPath());
}
final File lastShutdownFile = new File(dir, "last_shutdown.html");
final BufferedWriter writer = new BufferedWriter(new FileWriter(lastShutdownFile));
try {
final JavaInformations javaInformations = new JavaInformations(
Parameters.getServletContext(), true);
// on pourrait faire I18N.bindLocale(Locale.getDefault()), mais cela se fera tout seul
final HtmlReport htmlReport = new HtmlReport(collector, collectorServer,
Collections.singletonList(javaInformations), Period.JOUR, writer);
htmlReport.writeLastShutdown();
} finally {
writer.close();
}
} catch (final IOException e) {
LOG.warn("exception while writing the last shutdown report", e);
}
}
private boolean isFromCollectorServer() {
return collectorServer != null;
}
}
| true | true | void doHtml(HttpServletRequest httpRequest, HttpServletResponse httpResponse,
List<JavaInformations> javaInformationsList) throws IOException {
final String part = httpRequest.getParameter(PART_PARAMETER);
if (!isFromCollectorServer()
&& (part == null || CURRENT_REQUESTS_PART.equalsIgnoreCase(part) || GRAPH_PART
.equalsIgnoreCase(part))) {
// avant de faire l'affichage on fait une collecte, pour que les courbes
// et les compteurs par jour soit à jour avec les dernières requêtes
collector.collectLocalContextWithoutErrors();
}
// simple appel de monitoring sans format
httpResponse.setContentType(HTML_CONTENT_TYPE);
final BufferedWriter writer = getWriter(httpResponse);
try {
final Range range = httpCookieManager.getRange(httpRequest, httpResponse);
final HtmlReport htmlReport = new HtmlReport(collector, collectorServer,
javaInformationsList, range, writer);
if (part == null) {
htmlReport.toHtml(messageForReport, anchorNameForRedirect);
} else {
doHtmlPart(httpRequest, part, htmlReport);
}
} finally {
writer.close();
}
}
| void doHtml(HttpServletRequest httpRequest, HttpServletResponse httpResponse,
List<JavaInformations> javaInformationsList) throws IOException {
final String part = httpRequest.getParameter(PART_PARAMETER);
if (!isFromCollectorServer()
&& (part == null || CURRENT_REQUESTS_PART.equalsIgnoreCase(part)
|| GRAPH_PART.equalsIgnoreCase(part) || COUNTER_SUMMARY_PER_CLASS_PART
.equalsIgnoreCase(part))) {
// avant de faire l'affichage on fait une collecte, pour que les courbes
// et les compteurs par jour soit à jour avec les dernières requêtes
collector.collectLocalContextWithoutErrors();
}
// simple appel de monitoring sans format
httpResponse.setContentType(HTML_CONTENT_TYPE);
final BufferedWriter writer = getWriter(httpResponse);
try {
final Range range = httpCookieManager.getRange(httpRequest, httpResponse);
final HtmlReport htmlReport = new HtmlReport(collector, collectorServer,
javaInformationsList, range, writer);
if (part == null) {
htmlReport.toHtml(messageForReport, anchorNameForRedirect);
} else {
doHtmlPart(httpRequest, part, htmlReport);
}
} finally {
writer.close();
}
}
|
diff --git a/hoya-core/src/main/java/org/apache/hoya/yarn/appmaster/HoyaAppMaster.java b/hoya-core/src/main/java/org/apache/hoya/yarn/appmaster/HoyaAppMaster.java
index bdc0d91c..7d18500b 100644
--- a/hoya-core/src/main/java/org/apache/hoya/yarn/appmaster/HoyaAppMaster.java
+++ b/hoya-core/src/main/java/org/apache/hoya/yarn/appmaster/HoyaAppMaster.java
@@ -1,1447 +1,1447 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hoya.yarn.appmaster;
import com.google.protobuf.BlockingService;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.CommonConfigurationKeysPublic;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hdfs.DFSConfigKeys;
import org.apache.hadoop.io.DataOutputBuffer;
import org.apache.hadoop.ipc.ProtocolSignature;
import org.apache.hadoop.security.Credentials;
import org.apache.hadoop.security.SaslRpcServer;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.security.token.Token;
import org.apache.hadoop.service.Service;
import org.apache.hadoop.service.ServiceStateChangeListener;
import org.apache.hadoop.yarn.api.ApplicationConstants;
import org.apache.hadoop.yarn.api.protocolrecords.RegisterApplicationMasterResponse;
import org.apache.hadoop.yarn.api.records.ApplicationAccessType;
import org.apache.hadoop.yarn.api.records.ApplicationAttemptId;
import org.apache.hadoop.yarn.api.records.ApplicationId;
import org.apache.hadoop.yarn.api.records.Container;
import org.apache.hadoop.yarn.api.records.ContainerId;
import org.apache.hadoop.yarn.api.records.ContainerLaunchContext;
import org.apache.hadoop.yarn.api.records.ContainerState;
import org.apache.hadoop.yarn.api.records.ContainerStatus;
import org.apache.hadoop.yarn.api.records.FinalApplicationStatus;
import org.apache.hadoop.yarn.api.records.NodeReport;
import org.apache.hadoop.yarn.api.records.Resource;
import org.apache.hadoop.yarn.client.api.async.AMRMClientAsync;
import org.apache.hadoop.yarn.client.api.async.NMClientAsync;
import org.apache.hadoop.yarn.client.api.async.impl.NMClientAsyncImpl;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.apache.hadoop.yarn.exceptions.YarnException;
import org.apache.hadoop.yarn.ipc.YarnRPC;
import org.apache.hadoop.yarn.security.AMRMTokenIdentifier;
import org.apache.hadoop.yarn.security.client.ClientToAMTokenSecretManager;
import org.apache.hadoop.yarn.service.launcher.RunService;
import org.apache.hadoop.yarn.service.launcher.ServiceLauncher;
import org.apache.hadoop.yarn.util.ConverterUtils;
import org.apache.hoya.HoyaExitCodes;
import org.apache.hoya.HoyaKeys;
import org.apache.hoya.api.ClusterDescription;
import org.apache.hoya.api.HoyaClusterProtocol;
import org.apache.hoya.api.OptionKeys;
import org.apache.hoya.api.RoleKeys;
import org.apache.hoya.api.proto.HoyaClusterAPI;
import org.apache.hoya.api.proto.Messages;
import org.apache.hoya.exceptions.BadCommandArgumentsException;
import org.apache.hoya.exceptions.HoyaException;
import org.apache.hoya.exceptions.HoyaInternalStateException;
import org.apache.hoya.exceptions.TriggerClusterTeardownException;
import org.apache.hoya.providers.ClientProvider;
import org.apache.hoya.providers.HoyaProviderFactory;
import org.apache.hoya.providers.ProviderRole;
import org.apache.hoya.providers.ProviderService;
import org.apache.hoya.providers.hoyaam.HoyaAMClientProvider;
import org.apache.hoya.servicemonitor.Probe;
import org.apache.hoya.servicemonitor.ProbeFailedException;
import org.apache.hoya.servicemonitor.ProbePhase;
import org.apache.hoya.servicemonitor.ProbeReportHandler;
import org.apache.hoya.servicemonitor.ProbeStatus;
import org.apache.hoya.servicemonitor.ReportingLoop;
import org.apache.hoya.tools.ConfigHelper;
import org.apache.hoya.tools.HoyaUtils;
import org.apache.hoya.tools.HoyaVersionInfo;
import org.apache.hoya.yarn.HoyaActions;
import org.apache.hoya.yarn.appmaster.rpc.HoyaAMPolicyProvider;
import org.apache.hoya.yarn.appmaster.rpc.HoyaClusterProtocolPBImpl;
import org.apache.hoya.yarn.appmaster.rpc.RpcBinder;
import org.apache.hoya.yarn.appmaster.state.AbstractRMOperation;
import org.apache.hoya.yarn.appmaster.state.AppState;
import org.apache.hoya.yarn.appmaster.state.ContainerAssignment;
import org.apache.hoya.yarn.appmaster.state.ContainerReleaseOperation;
import org.apache.hoya.yarn.appmaster.state.RMOperationHandler;
import org.apache.hoya.yarn.appmaster.state.RoleInstance;
import org.apache.hoya.yarn.appmaster.state.RoleStatus;
import org.apache.hoya.yarn.params.AbstractActionArgs;
import org.apache.hoya.yarn.params.HoyaAMArgs;
import org.apache.hoya.yarn.params.HoyaAMCreateAction;
import org.apache.hoya.yarn.service.CompoundLaunchedService;
import org.apache.hoya.yarn.service.EventCallback;
import org.apache.hoya.yarn.service.RpcService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.URI;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
/**
* This is the AM, which directly implements the callbacks from the AM and NM
*/
public class HoyaAppMaster extends CompoundLaunchedService
implements AMRMClientAsync.CallbackHandler,
NMClientAsync.CallbackHandler,
RunService,
HoyaExitCodes,
HoyaKeys,
HoyaClusterProtocol,
ServiceStateChangeListener,
RoleKeys,
EventCallback,
ContainerStartOperation,
ProbeReportHandler {
protected static final Logger log =
LoggerFactory.getLogger(HoyaAppMaster.class);
/**
* log for YARN events
*/
protected static final Logger LOG_YARN =
LoggerFactory.getLogger(
"org.apache.hoya.yarn.appmaster.HoyaAppMaster.yarn");
/**
* time to wait from shutdown signal being rx'd to telling
* the AM: {@value}
*/
public static final int TERMINATION_SIGNAL_PROPAGATION_DELAY = 1000;
public static final int HEARTBEAT_INTERVAL = 1000;
public static final int NUM_RPC_HANDLERS = 5;
public static final String SERVICE_CLASSNAME =
"org.apache.hoya.yarn.appmaster.HoyaAppMaster";
/** YARN RPC to communicate with the Resource Manager or Node Manager */
private YarnRPC yarnRPC;
/** Handle to communicate with the Resource Manager*/
private AMRMClientAsync asyncRMClient;
private RMOperationHandler rmOperationHandler;
/** Handle to communicate with the Node Manager*/
public NMClientAsync nmClientAsync;
YarnConfiguration conf;
/**
* token blob
*/
private ByteBuffer allTokens;
private RpcService rpcService;
/**
* Secret manager
*/
ClientToAMTokenSecretManager secretManager;
/** Hostname of the container*/
private String appMasterHostname = "";
/* Port on which the app master listens for status updates from clients*/
private int appMasterRpcPort = 0;
/** Tracking url to which app master publishes info for clients to monitor*/
private String appMasterTrackingUrl = "";
/** Application Attempt Id ( combination of attemptId and fail count )*/
private ApplicationAttemptId appAttemptID;
/**
* Security info client to AM key returned after registration
*/
private ByteBuffer clientToAMKey;
/**
* App ACLs
*/
protected Map<ApplicationAccessType, String> applicationACLs;
/**
* Ongoing state of the cluster: containers, nodes they
* live on, etc.
*/
private final AppState appState = new AppState(new ProtobufRecordFactory());
/**
* model the state using locks and conditions
*/
private final ReentrantLock AMExecutionStateLock = new ReentrantLock();
private final Condition isAMCompleted = AMExecutionStateLock.newCondition();
private int amExitCode = 0;
/**
* Flag set if the AM is to be shutdown
*/
private final AtomicBoolean amCompletionFlag = new AtomicBoolean(false);
private volatile boolean success = true;
/**
* Flag to set if the process exit code was set before shutdown started
*/
private boolean spawnedProcessExitedBeforeShutdownTriggered;
/** Arguments passed in : raw*/
private HoyaAMArgs serviceArgs;
/**
* ID of the AM container
*/
private ContainerId appMasterContainerID;
/**
* ProviderService of this cluster
*/
private ProviderService providerService;
/**
* Record of the max no. of cores allowed in this cluster
*/
private int containerMaxCores;
/**
* limit container memory
*/
private int containerMaxMemory;
private String amCompletionReason;
private RoleLaunchService launchService;
//username -null if it is not known/not to be set
private String hoyaUsername;
/**
* Service Constructor
*/
public HoyaAppMaster() {
super("HoyaMasterService");
}
/* =================================================================== */
/* service lifecycle methods */
/* =================================================================== */
@Override //AbstractService
public synchronized void serviceInit(Configuration conf) throws Exception {
// Load in the server configuration - if it is actually on the Classpath
Configuration serverConf =
ConfigHelper.loadFromResource(HOYA_SERVER_RESOURCE);
ConfigHelper.mergeConfigurations(conf, serverConf, HOYA_SERVER_RESOURCE);
AbstractActionArgs action = serviceArgs.getCoreAction();
HoyaAMCreateAction createAction = (HoyaAMCreateAction) action;
//sort out the location of the AM
serviceArgs.applyDefinitions(conf);
serviceArgs.applyFileSystemURL(conf);
String rmAddress = createAction.getRmAddress();
if (rmAddress != null) {
log.debug("Setting rm address from the command line: {}", rmAddress);
HoyaUtils.setRmSchedulerAddress(conf, rmAddress);
}
serviceArgs.applyDefinitions(conf);
serviceArgs.applyFileSystemURL(conf);
//init security with our conf
if (HoyaUtils.isClusterSecure(conf)) {
log.info("Secure mode with kerberos realm {}",
HoyaUtils.getKerberosRealm());
UserGroupInformation.setConfiguration(conf);
UserGroupInformation ugi = UserGroupInformation.getCurrentUser();
log.debug("Authenticating as " + ugi.toString());
HoyaUtils.verifyPrincipalSet(conf,
DFSConfigKeys.DFS_NAMENODE_USER_NAME_KEY);
// always enforce protocol to be token-based.
conf.set(
CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHENTICATION,
SaslRpcServer.AuthMethod.TOKEN.toString());
}
log.info("Login user is {}", UserGroupInformation.getLoginUser());
//look at settings of Hadoop Auth, to pick up a problem seen once
checkAndWarnForAuthTokenProblems();
super.serviceInit(conf);
}
/* =================================================================== */
/* RunService methods called from ServiceLauncher */
/* =================================================================== */
/**
* pick up the args from the service launcher
* @param config
* @param args argument list
*/
@Override // RunService
public Configuration bindArgs(Configuration config, String... args) throws
Exception {
config = super.bindArgs(config, args);
serviceArgs = new HoyaAMArgs(args);
serviceArgs.parse();
//yarn-ify
YarnConfiguration yarnConfiguration = new YarnConfiguration(config);
return HoyaUtils.patchConfiguration(yarnConfiguration);
}
/**
* this is called by service launcher; when it returns the application finishes
* @return the exit code to return by the app
* @throws Throwable
*/
@Override
public int runService() throws Throwable {
//choose the action
String action = serviceArgs.getAction();
List<String> actionArgs = serviceArgs.getActionArgs();
int exitCode = EXIT_SUCCESS;
if (action.equals(HoyaActions.ACTION_HELP)) {
log.info(getName() + serviceArgs.usage());
exitCode = HoyaExitCodes.EXIT_USAGE;
} else if (action.equals(HoyaActions.ACTION_CREATE)) {
exitCode = createAndRunCluster(actionArgs.get(0));
} else {
throw new HoyaException("Unimplemented: " + action);
}
log.info("Exiting HoyaAM; final exit code = {}", exitCode);
return exitCode;
}
/* =================================================================== */
/**
* Create and run the cluster.
* @return exit code
* @throws Throwable on a failure
*/
private int createAndRunCluster(String clustername) throws Throwable {
HoyaVersionInfo.loadAndPrintVersionInfo(log);
//load the cluster description from the cd argument
String hoyaClusterDir = serviceArgs.getHoyaClusterURI();
URI hoyaClusterURI = new URI(hoyaClusterDir);
Path clusterDirPath = new Path(hoyaClusterURI);
Path clusterSpecPath =
new Path(clusterDirPath, HoyaKeys.CLUSTER_SPECIFICATION_FILE);
FileSystem fs = getClusterFS();
ClusterDescription.verifyClusterSpecExists(clustername,
fs,
clusterSpecPath);
ClusterDescription clusterSpec = ClusterDescription.load(fs, clusterSpecPath);
log.info("Deploying cluster from {}:", clusterSpecPath);
log.info(clusterSpec.toString());
File confDir = getLocalConfDir();
if (!confDir.exists() || !confDir.isDirectory()) {
throw new BadCommandArgumentsException(
"Configuration directory %s doesn't exist", confDir);
}
conf = new YarnConfiguration(getConfig());
//get our provider
String providerType = clusterSpec.type;
log.info("Cluster provider type is {}", providerType);
HoyaProviderFactory factory =
HoyaProviderFactory.createHoyaProviderFactory(
providerType);
providerService = factory.createServerProvider();
ClientProvider providerClient = factory.createClientProvider();
runChildService(providerService);
//verify that the cluster specification is now valid
providerService.validateClusterSpec(clusterSpec);
HoyaAMClientProvider amClientProvider = new HoyaAMClientProvider(conf);
//check with the Hoya and Cluster-specific providers that the cluster state
// looks good from the perspective of the AM
Path generatedConfDirPath =
new Path(clusterDirPath, HoyaKeys.GENERATED_CONF_DIR_NAME);
boolean clusterSecure = HoyaUtils.isClusterSecure(conf);
amClientProvider.preflightValidateClusterConfiguration(fs, clustername,
conf, clusterSpec,
clusterDirPath,
generatedConfDirPath,
clusterSecure
);
providerClient.preflightValidateClusterConfiguration(fs, clustername, conf,
clusterSpec,
clusterDirPath,
generatedConfDirPath,
clusterSecure
);
InetSocketAddress address = HoyaUtils.getRmSchedulerAddress(conf);
log.info("RM is at {}", address);
yarnRPC = YarnRPC.create(conf);
appMasterContainerID = ConverterUtils.toContainerId(
HoyaUtils.mandatoryEnvVariable(
ApplicationConstants.Environment.CONTAINER_ID.name()));
appAttemptID = appMasterContainerID.getApplicationAttemptId();
ApplicationId appid = appAttemptID.getApplicationId();
log.info("Hoya AM for ID {}", appid.getId());
UserGroupInformation currentUser = UserGroupInformation.getCurrentUser();
Credentials credentials =
currentUser.getCredentials();
DataOutputBuffer dob = new DataOutputBuffer();
credentials.writeTokenStorageToStream(dob);
dob.close();
// Now remove the AM->RM token so that containers cannot access it.
Iterator<Token<?>> iter = credentials.getAllTokens().iterator();
while (iter.hasNext()) {
Token<?> token = iter.next();
log.info("Token {}", token.getKind());
if (token.getKind().equals(AMRMTokenIdentifier.KIND_NAME)) {
iter.remove();
}
}
allTokens = ByteBuffer.wrap(dob.getData(), 0, dob.getLength());
// set up secret manager
secretManager = new ClientToAMTokenSecretManager(appAttemptID, null);
// if not a secure cluster, extract the username -it will be
// propagated to workers
if (!UserGroupInformation.isSecurityEnabled()) {
hoyaUsername = System.getenv(HADOOP_USER_NAME);
log.info(HADOOP_USER_NAME + "='{}'", hoyaUsername);
}
int heartbeatInterval = HEARTBEAT_INTERVAL;
//add the RM client -this brings the callbacks in
asyncRMClient = AMRMClientAsync.createAMRMClientAsync(heartbeatInterval,
this);
addService(asyncRMClient);
//wrap it for the app state model
rmOperationHandler = new AsyncRMOperationHandler(asyncRMClient);
//now bring it up
runChildService(asyncRMClient);
//nmclient relays callbacks back to this class
nmClientAsync = new NMClientAsyncImpl("hoya", this);
runChildService(nmClientAsync);
//bring up the Hoya RPC service
startHoyaRPCServer();
InetSocketAddress rpcServiceAddr = rpcService.getConnectAddress();
appMasterHostname = rpcServiceAddr.getHostName();
appMasterRpcPort = rpcServiceAddr.getPort();
appMasterTrackingUrl = null;
log.info("HoyaAM Server is listening at {}:{}", appMasterHostname,
appMasterRpcPort);
//build the role map
List<ProviderRole> providerRoles =
new ArrayList<ProviderRole>(providerService.getRoles());
providerRoles.addAll(amClientProvider.getRoles());
/* DISABLED
// work out a port for the AM
int infoport = clusterSpec.getRoleOptInt(ROLE_HOYA_AM,
RoleKeys.APP_INFOPORT,
0);
if (0 == infoport) {
infoport =
HoyaUtils.findFreePort(providerService.getDefaultMasterInfoPort(), 128);
//need to get this to the app
clusterSpec.setRoleOpt(ROLE_HOYA_AM,
RoleKeys.APP_INFOPORT,
infoport);
}
appMasterTrackingUrl = "http://" + appMasterHostname + ":" + infoport;
*/
appMasterTrackingUrl = null;
// Register self with ResourceManager
// This will start heartbeating to the RM
// address = HoyaUtils.getRmSchedulerAddress(asyncRMClient.getConfig());
log.info("Connecting to RM at {},address tracking URL={}",
appMasterRpcPort, appMasterTrackingUrl);
RegisterApplicationMasterResponse response = asyncRMClient
.registerApplicationMaster(appMasterHostname,
appMasterRpcPort,
appMasterTrackingUrl);
Resource maxResources =
response.getMaximumResourceCapability();
containerMaxMemory = maxResources.getMemory();
containerMaxCores = maxResources.getVirtualCores();
appState.setContainerLimits(maxResources.getMemory(),
maxResources.getVirtualCores());
boolean securityEnabled = UserGroupInformation.isSecurityEnabled();
if (securityEnabled) {
secretManager.setMasterKey(
response.getClientToAMTokenMasterKey().array());
applicationACLs = response.getApplicationACLs();
//tell the server what the ACLs are
rpcService.getServer().refreshServiceAcl(conf, new HoyaAMPolicyProvider());
}
- //TODO: build from response once it is coming back
- List<Container> liveContainers = null;
+ // extract container list
+ List<Container> liveContainers = response.getContainersFromPreviousAttempt();
//now validate the dir by loading in a hadoop-site.xml file from it
Configuration siteConf;
String siteXMLFilename = providerService.getSiteXMLFilename();
if (siteXMLFilename != null) {
File siteXML = new File(confDir, siteXMLFilename);
if (!siteXML.exists()) {
throw new BadCommandArgumentsException(
"Configuration directory %s doesn't contain %s - listing is %s",
confDir, siteXMLFilename, HoyaUtils.listDir(confDir));
}
//now read it in
siteConf = ConfigHelper.loadConfFromFile(siteXML);
log.info("{} file is at {}", siteXMLFilename, siteXML);
log.info(ConfigHelper.dumpConfigToString(siteConf));
} else {
//no site configuration: have an empty one
siteConf = new Configuration(false);
}
providerService.validateApplicationConfiguration(clusterSpec, confDir, securityEnabled);
//determine the location for the role history data
Path historyDir = new Path(clusterDirPath, HISTORY_DIR_NAME);
//build the instance
appState.buildInstance(clusterSpec,
siteConf,
providerRoles,
fs,
historyDir,
liveContainers);
//before bothering to start the containers, bring up the master.
//This ensures that if the master doesn't come up, less
//cluster resources get wasted
appState.buildAppMasterNode(appMasterContainerID);
// build up environment variables that the AM wants set in every container
// irrespective of provider and role.
Map<String, String> envVars = new HashMap<String, String>();
if (hoyaUsername != null) {
envVars.put(HADOOP_USER_NAME, hoyaUsername);
}
//launcher service
launchService = new RoleLaunchService(this,
providerService,
getClusterFS(),
new Path(getDFSConfDir()),
envVars);
runChildService(launchService);
appState.noteAMLaunched();
// launch the provider; this is expected to trigger a callback that
// brings up the service
launchProviderService(clusterSpec, confDir);
try {
//now block waiting to be told to exit the process
waitForAMCompletionSignal();
//shutdown time
} finally {
finish();
}
return amExitCode;
}
/**
* looks for a specific case where a token file is provided as an environment
* variable, yet the file is not there.
*
* This surfaced (once) in HBase, where its HDFS library was looking for this,
* and somehow the token was missing. This is a check in the AM so that
* if the problem re-occurs, the AM can fail with a more meaningful message.
*
*/
private void checkAndWarnForAuthTokenProblems() {
String fileLocation =
System.getenv(UserGroupInformation.HADOOP_TOKEN_FILE_LOCATION);
if (fileLocation != null) {
File tokenFile = new File(fileLocation);
if (!tokenFile.exists()) {
log.warn("Token file {} specified in {} not found", tokenFile,
UserGroupInformation.HADOOP_TOKEN_FILE_LOCATION);
}
}
}
/**
* Build the configuration directory passed in or of the target FS
* @return the file
*/
public File getLocalConfDir() {
File confdir =
new File(HoyaKeys.PROPAGATED_CONF_DIR_NAME).getAbsoluteFile();
return confdir;
}
/**
* Get the path to the DFS configuration that is defined in the cluster specification
* @return
*/
public String getDFSConfDir() {
return getClusterSpec().generatedConfigurationPath;
}
/**
* Get the filesystem of this cluster
* @return the FS of the config
*/
public FileSystem getClusterFS() throws IOException {
return FileSystem.get(getConfig());
}
/**
* Block until it is signalled that the AM is done
*/
private void waitForAMCompletionSignal() {
AMExecutionStateLock.lock();
try {
if (!amCompletionFlag.get()) {
log.debug("blocking until signalled to terminate");
isAMCompleted.awaitUninterruptibly();
}
} finally {
AMExecutionStateLock.unlock();
}
//add a sleep here for about a second. Why? it
//stops RPC calls breaking so dramatically when the cluster
//is torn down mid-RPC
try {
Thread.sleep(TERMINATION_SIGNAL_PROPAGATION_DELAY);
} catch (InterruptedException ignored) {
//ignored
}
}
/**
* Declare that the AM is complete
* @param exitCode exit code for the aM
* @param reason reason for termination
*/
public synchronized void signalAMComplete(int exitCode, String reason) {
amCompletionReason = reason;
AMExecutionStateLock.lock();
try {
amCompletionFlag.set(true);
amExitCode = exitCode;
isAMCompleted.signal();
} finally {
AMExecutionStateLock.unlock();
}
}
/**
* shut down the cluster
*/
private synchronized void finish() {
FinalApplicationStatus appStatus;
log.info("Triggering shutdown of the AM: {}", amCompletionReason);
String appMessage = amCompletionReason;
//stop the daemon & grab its exit code
int exitCode = amExitCode;
success = exitCode == 0;
appStatus = success ? FinalApplicationStatus.SUCCEEDED:
FinalApplicationStatus.FAILED;
if (!spawnedProcessExitedBeforeShutdownTriggered) {
//stopped the forked process but don't worry about its exit code
exitCode = stopForkedProcess();
log.debug("Stopped forked process: exit code={}", exitCode);
}
//stop any launches in progress
launchService.stop();
//now release all containers
releaseAllContainers();
// When the application completes, it should send a finish application
// signal to the RM
log.info("Application completed. Signalling finish to RM");
//if there were failed containers and the app isn't already down as failing, it is now
int failedContainerCount = appState.getFailedCountainerCount();
if (failedContainerCount != 0 &&
appStatus == FinalApplicationStatus.SUCCEEDED) {
appStatus = FinalApplicationStatus.FAILED;
appMessage =
"Completed with exit code = " + exitCode + " - " + getContainerDiagnosticInfo();
success = false;
}
try {
log.info("Unregistering AM status={} message={}", appStatus, appMessage);
asyncRMClient.unregisterApplicationMaster(appStatus, appMessage, null);
} catch (YarnException e) {
log.info("Failed to unregister application: " + e, e);
} catch (IOException e) {
log.info("Failed to unregister application: " + e, e);
}
}
/**
* Get diagnostics info about containers
*/
private String getContainerDiagnosticInfo() {
return appState.getContainerDiagnosticInfo();
}
public Object getProxy(Class protocol, InetSocketAddress addr) {
return yarnRPC.getProxy(protocol, addr, getConfig());
}
/**
* Start the hoya RPC server
*/
private void startHoyaRPCServer() throws IOException {
HoyaClusterProtocolPBImpl protobufRelay = new HoyaClusterProtocolPBImpl(this);
BlockingService blockingService = HoyaClusterAPI.HoyaClusterProtocolPB
.newReflectiveBlockingService(
protobufRelay);
rpcService = new RpcService(RpcBinder.createProtobufServer(
new InetSocketAddress("0.0.0.0", 0),
getConfig(),
secretManager,
NUM_RPC_HANDLERS,
blockingService,
null));
runChildService(rpcService);
}
/* =================================================================== */
/* AMRMClientAsync callbacks */
/* =================================================================== */
/**
* Callback event when a container is allocated.
*
* The app state is updated with the allocation, and builds up a list
* of assignments and RM opreations. The assignments are
* handed off into the pool of service launchers to asynchronously schedule
* container launch operations.
*
* The operations are run in sequence; they are expected to be 0 or more
* release operations (to handle over-allocations)
*
* @param allocatedContainers list of containers that are now ready to be
* given work.
*/
@SuppressWarnings("SynchronizationOnLocalVariableOrMethodParameter")
@Override //AMRMClientAsync
public void onContainersAllocated(List<Container> allocatedContainers) {
LOG_YARN.info("onContainersAllocated({})", allocatedContainers.size());
List<ContainerAssignment> assignments = new ArrayList<ContainerAssignment>();
List<AbstractRMOperation> operations = new ArrayList<AbstractRMOperation>();
//app state makes all the decisions
appState.onContainersAllocated(allocatedContainers, assignments, operations);
//for each assignment: launch a thread to instantiate that role
for (ContainerAssignment assignment : assignments) {
RoleStatus role = assignment.role;
Container container = assignment.container;
launchService.launchRole(container, role, getClusterSpec());
}
//for all the operations, exec them
rmOperationHandler.execute(operations);
log.info("Diagnostics: " + getContainerDiagnosticInfo());
}
@Override //AMRMClientAsync
public synchronized void onContainersCompleted(List<ContainerStatus> completedContainers) {
LOG_YARN.info("onContainersCompleted([{}]", completedContainers.size());
for (ContainerStatus status : completedContainers) {
ContainerId containerId = status.getContainerId();
LOG_YARN.info("Container Completion for" +
" containerID={}," +
" state={}," +
" exitStatus={}," +
" diagnostics={}",
containerId, status.getState(),
status.getExitStatus(),
status.getDiagnostics());
// non complete containers should not be here
assert (status.getState() == ContainerState.COMPLETE);
AppState.NodeCompletionResult result = appState.onCompletedNode(conf, status);
if (result.containerFailed) {
RoleInstance ri = result.roleInstance;
log.error("Role instance {} failed ", ri);
}
}
// ask for more containers if any failed
// In the case of Hoya, we don't expect containers to complete since
// Hoya is a long running application. Keep track of how many containers
// are completing. If too many complete, abort the application
// TODO: this needs to be better thought about (and maybe something to
// better handle in Yarn for long running apps)
try {
reviewRequestAndReleaseNodes();
} catch (HoyaInternalStateException e) {
log.warn("Exception while flexing nodes", e);
}
}
/**
* Implementation of cluster flexing.
* This is synchronized so that it doesn't get confused by other requests coming
* in.
* It should be the only way that anything -even the AM itself on startup-
* asks for nodes.
* @param workers #of workers to add
* @param masters #of masters to request (if supported)
* @return true if the number of workers changed
* @throws IOException
*/
private boolean flexCluster(ClusterDescription updated)
throws IOException, HoyaInternalStateException {
//validation
try {
providerService.validateClusterSpec(updated);
} catch (HoyaException e) {
throw new IOException("Invalid cluster specification " + e, e);
}
appState.updateClusterSpec(updated);
// ask for more containers if needed
return reviewRequestAndReleaseNodes();
}
/**
* Look at where the current node state is -and whether it should be changed
*/
private synchronized boolean reviewRequestAndReleaseNodes()
throws HoyaInternalStateException {
log.debug("in reviewRequestAndReleaseNodes()");
if (amCompletionFlag.get()) {
log.info("Ignoring node review operation: shutdown in progress");
return false;
}
try {
List<AbstractRMOperation> allOperations = appState.reviewRequestAndReleaseNodes();
//now apply the operations
rmOperationHandler.execute(allOperations);
return !allOperations.isEmpty();
} catch (TriggerClusterTeardownException e) {
//App state has decided that it is time to exit
log.error("Cluster teardown triggered %s", e);
signalAMComplete(e.getExitCode(), e.toString());
return false;
}
}
/**
* Shutdown operation: release all containers
*/
private void releaseAllContainers() {
//now apply the operations
rmOperationHandler.execute(appState.releaseAllContainers());
}
/**
* RM wants to shut down the AM
*/
@Override //AMRMClientAsync
public void onShutdownRequest() {
LOG_YARN.info("Shutdown Request received");
signalAMComplete(EXIT_CLIENT_INITIATED_SHUTDOWN, "Shutdown requested from RM");
}
/**
* Monitored nodes have been changed
* @param updatedNodes list of updated nodes
*/
@Override //AMRMClientAsync
public void onNodesUpdated(List<NodeReport> updatedNodes) {
LOG_YARN.info("Nodes updated");
}
/**
* heartbeat operation; return the ratio of requested
* to actual
* @return progress
*/
@Override //AMRMClientAsync
public float getProgress() {
return appState.getApplicationProgressPercentage();
}
@Override //AMRMClientAsync
public void onError(Throwable e) {
//callback says it's time to finish
LOG_YARN.error("AMRMClientAsync.onError() received " + e, e);
signalAMComplete(EXIT_EXCEPTION_THROWN, "AMRMClientAsync.onError() received " + e);
}
/* =================================================================== */
/* HoyaClusterProtocol */
/* =================================================================== */
@Override //HoyaClusterProtocol
public ProtocolSignature getProtocolSignature(String protocol,
long clientVersion,
int clientMethodsHash) throws
IOException {
return ProtocolSignature.getProtocolSignature(
this, protocol, clientVersion, clientMethodsHash);
}
@Override //HoyaClusterProtocol
public long getProtocolVersion(String protocol, long clientVersion) throws
IOException {
return HoyaClusterProtocol.versionID;
}
/* =================================================================== */
/* HoyaClusterProtocol */
/* =================================================================== */
@Override //HoyaClusterProtocol
public Messages.StopClusterResponseProto stopCluster(Messages.StopClusterRequestProto request) throws
IOException,
YarnException {
HoyaUtils.getCurrentUser();
String message = request.getMessage();
log.info("HoyaAppMasterApi.stopCluster: {}",message);
signalAMComplete(EXIT_CLIENT_INITIATED_SHUTDOWN, message);
return Messages.StopClusterResponseProto.getDefaultInstance();
}
@Override //HoyaClusterProtocol
public Messages.FlexClusterResponseProto flexCluster(Messages.FlexClusterRequestProto request) throws
IOException,
YarnException {
HoyaUtils.getCurrentUser();
ClusterDescription updated =
ClusterDescription.fromJson(request.getClusterSpec());
boolean flexed = flexCluster(updated);
return Messages.FlexClusterResponseProto.newBuilder().setResponse(flexed).build();
}
@Override //HoyaClusterProtocol
public Messages.GetJSONClusterStatusResponseProto getJSONClusterStatus(
Messages.GetJSONClusterStatusRequestProto request) throws
IOException,
YarnException {
HoyaUtils.getCurrentUser();
String result;
//quick update
//query and json-ify
synchronized (this) {
updateClusterStatus();
result = getClusterDescription().toJsonString();
}
String stat = result;
return Messages.GetJSONClusterStatusResponseProto.newBuilder()
.setClusterSpec(stat)
.build();
}
@Override //HoyaClusterProtocol
public Messages.ListNodeUUIDsByRoleResponseProto listNodeUUIDsByRole(Messages.ListNodeUUIDsByRoleRequestProto request) throws
IOException,
YarnException {
HoyaUtils.getCurrentUser();
String role = request.getRole();
Messages.ListNodeUUIDsByRoleResponseProto.Builder builder =
Messages.ListNodeUUIDsByRoleResponseProto.newBuilder();
List<RoleInstance> nodes = appState.enumLiveNodesInRole(role);
for (RoleInstance node : nodes) {
builder.addUuid(node.uuid);
}
return builder.build();
}
@Override //HoyaClusterProtocol
public Messages.GetNodeResponseProto getNode(Messages.GetNodeRequestProto request) throws
IOException,
YarnException {
HoyaUtils.getCurrentUser();
RoleInstance instance = appState.getLiveInstanceByUUID(request.getUuid());
return Messages.GetNodeResponseProto.newBuilder()
.setClusterNode(instance.toProtobuf())
.build();
}
@Override //HoyaClusterProtocol
public Messages.GetClusterNodesResponseProto getClusterNodes(Messages.GetClusterNodesRequestProto request) throws
IOException,
YarnException {
HoyaUtils.getCurrentUser();
List<RoleInstance>
clusterNodes = appState.getLiveContainerInfosByUUID(request.getUuidList());
Messages.GetClusterNodesResponseProto.Builder builder =
Messages.GetClusterNodesResponseProto.newBuilder();
for (RoleInstance node : clusterNodes) {
builder.addClusterNode(node.toProtobuf());
}
//at this point: a possibly empty list of nodes
return builder.build();
}
@Override
public Messages.EchoResponseProto echo(Messages.EchoRequestProto request) throws
IOException,
YarnException {
Messages.EchoResponseProto.Builder builder =
Messages.EchoResponseProto.newBuilder();
String text = request.getText();
log.info("Echo request size ={}", text.length());
log.info(text);
//now return it
builder.setText(text);
return builder.build();
}
@Override
public Messages.KillContainerResponseProto killContainer(Messages.KillContainerRequestProto request) throws
IOException,
YarnException {
String containerID = request.getId();
log.info("Kill Container {}", containerID);
//throws NoSuchNodeException if it is missing
RoleInstance instance =
appState.getLiveInstanceByUUID(containerID);
List<AbstractRMOperation> opsList =
new LinkedList<AbstractRMOperation>();
ContainerReleaseOperation release =
new ContainerReleaseOperation(instance.getId());
opsList.add(release);
//now apply the operations
rmOperationHandler.execute(opsList);
Messages.KillContainerResponseProto.Builder builder =
Messages.KillContainerResponseProto.newBuilder();
builder.setSuccess(true);
return builder.build();
}
@Override
public Messages.AMSuicideResponseProto amSuicide(Messages.AMSuicideRequestProto request) throws
IOException,
YarnException {
int signal = request.getSignal();
String text = request.getText();
int delay = request.getDelay();
log.info("AM Suicide with signal {}, message {} delay = {}", signal, text, delay);
HoyaUtils.haltAM(signal, text, delay);
Messages.AMSuicideResponseProto.Builder builder =
Messages.AMSuicideResponseProto.newBuilder();
return builder.build();
}
/* =================================================================== */
/* END */
/* =================================================================== */
/**
* Update the cluster description with anything interesting
*/
private void updateClusterStatus() {
Map<String, String> providerStatus = providerService.buildProviderStatus();
assert providerStatus != null : "null provider status";
appState.refreshClusterStatus(providerStatus);
}
/**
* Launch the provider service
*
* @param cd
* @param confDir
* @throws IOException
* @throws HoyaException
*/
protected synchronized void launchProviderService(ClusterDescription cd,
File confDir)
throws IOException, HoyaException {
Map<String, String> env = new HashMap<String, String>();
boolean execStarted = providerService.exec(cd, confDir, env, this);
if (execStarted) {
providerService.registerServiceListener(this);
providerService.start();
} else {
// didn't start, so don't register
providerService.start();
// and send the started event ourselves
eventCallbackEvent();
}
}
/**
* Monitor operation
* TODO: implement.
* @return true if the monitor started
* @throws YarnException
* @throws IOException
*/
public boolean startReportingLoop() throws YarnException,
IOException {
if (!getClusterSpec().getOptionBool(OptionKeys.AM_MONITORING_ENABLED,
OptionKeys.AM_MONITORING_ENABLED_DEFAULT)) {
log.debug("AM Monitoring disabled");
return false;
}
ClusterDescription clusterSpec = getClusterSpec();
ReportingLoop masterReportingLoop;
Thread loopThread;
// build the probes
int timeout = 60000;
ProviderService provider = getProviderService();
List<Probe> probes =
provider.createProbes(clusterSpec, appMasterTrackingUrl, getConfig(),
timeout);
// start ReportingLoop only when there're probes
if (!probes.isEmpty()) {
masterReportingLoop =
new ReportingLoop("MasterStatusCheck", this, probes, null, 1000, 1000,
timeout, -1);
if (!masterReportingLoop.startReporting()) {
masterReportingLoop.close();
throw new HoyaInternalStateException("failed to start monitoring");
}
loopThread = new Thread(masterReportingLoop, "MasterStatusCheck");
loopThread.setDaemon(true);
loopThread.start();
int waittime = 0;
// now wait until finished
try {
loopThread.join(waittime * 1000L);
} catch (InterruptedException e) {
//interrupted
}
masterReportingLoop.close();
}
return false;
}
@Override // ProbeReportHandler
public void probeFailure(ProbeFailedException exception) {
}
@Override // ProbeReportHandler
public void probeBooted(ProbeStatus status) {
}
@Override // ProbeReportHandler
public boolean commence(String name, String description) {
return true;
}
@Override // ProbeReportHandler
public void unregister() {
}
@Override // ProbeReportHandler
public void probeTimedOut(ProbePhase currentPhase,
Probe probe,
ProbeStatus lastStatus,
long currentTime) {
}
@Override // ProbeReportHandler
public void liveProbeCycleCompleted() {
}
@Override // ProbeReportHandler
public void heartbeat(ProbeStatus status) {
}
/*
* Methods for ProbeReportHandler
*/
@Override // ProbeReportHandler
public void probeProcessStateChange(ProbePhase probePhase) {
}
@Override // ProbeReportHandler
public void probeResult(ProbePhase phase, ProbeStatus status) {
if (!status.isSuccess()) {
log.warn("Failed probe {}", status);
}
}
/* =================================================================== */
/* EventCallback from the child or ourselves directly */
/* =================================================================== */
@Override // EventCallback
public void eventCallbackEvent() {
// signalled that the child process is up.
appState.noteAMLive();
// now ask for the cluster nodes
try {
flexCluster(getClusterSpec());
} catch (Exception e) {
//this may happen in a separate thread, so the ability to act is limited
log.error("Failed to flex cluster nodes", e);
//declare a failure
finish();
}
}
/* =================================================================== */
/* ServiceStateChangeListener */
/* =================================================================== */
/**
* Received on listening service termination.
* @param service the service that has changed.
*/
@Override //ServiceStateChangeListener
public void stateChanged(Service service) {
if (service == providerService) {
//its the current master process in play
int exitCode = providerService.getExitCode();
int mappedProcessExitCode =
AMUtils.mapProcessExitCodeToYarnExitCode(exitCode);
boolean shouldTriggerFailure = !amCompletionFlag.get()
&& (AMUtils.isMappedExitAFailure(mappedProcessExitCode));
if (shouldTriggerFailure) {
//this wasn't expected: the process finished early
spawnedProcessExitedBeforeShutdownTriggered = true;
log.info(
"Process has exited with exit code {} mapped to {} -triggering termination",
exitCode,
mappedProcessExitCode);
//tell the AM the cluster is complete
signalAMComplete(mappedProcessExitCode,
"Spawned master exited with raw " + exitCode + " mapped to " +
mappedProcessExitCode);
} else {
//we don't care
log.info(
"Process has exited with exit code {} mapped to {} -ignoring",
exitCode,
mappedProcessExitCode);
}
}
}
/**
* stop forked process if it the running process var is not null
* @return the process exit code
*/
protected synchronized Integer stopForkedProcess() {
providerService.stop();
return providerService.getExitCode();
}
/**
* Async start container request
* @param container container
* @param ctx context
* @param instance node details
*/
@Override // ContainerStartOperation
public void startContainer(Container container,
ContainerLaunchContext ctx,
RoleInstance instance) {
// Set up tokens for the container too. Today, for normal shell commands,
// the container in distribute-shell doesn't need any tokens. We are
// populating them mainly for NodeManagers to be able to download any
// files in the distributed file-system. The tokens are otherwise also
// useful in cases, for e.g., when one is running a "hadoop dfs" command
// inside the distributed shell.
ctx.setTokens(allTokens.duplicate());
appState.containerStartSubmitted(container, instance);
nmClientAsync.startContainerAsync(container, ctx);
}
@Override // NMClientAsync.CallbackHandler
public void onContainerStopped(ContainerId containerId) {
// do nothing but log: container events from the AM
// are the source of container halt details to react to
log.info("onContainerStopped {} ", containerId);
}
@Override // NMClientAsync.CallbackHandler
public void onContainerStarted(ContainerId containerId,
Map<String, ByteBuffer> allServiceResponse) {
LOG_YARN.info("Started Container {} ", containerId);
RoleInstance cinfo = appState.onNodeManagerContainerStarted(containerId);
if (cinfo != null) {
LOG_YARN.info("Deployed instance of role {}", cinfo.role);
//trigger an async container status
nmClientAsync.getContainerStatusAsync(containerId,
cinfo.container.getNodeId());
} else {
//this is a hypothetical path not seen. We react by warning
log.error("Notified of started container that isn't pending {} - releasing",
containerId);
//then release it
asyncRMClient.releaseAssignedContainer(containerId);
}
}
@Override // NMClientAsync.CallbackHandler
public void onStartContainerError(ContainerId containerId, Throwable t) {
LOG_YARN.error("Failed to start Container " + containerId, t);
appState.onNodeManagerContainerStartFailed(containerId, t);
}
@Override // NMClientAsync.CallbackHandler
public void onContainerStatusReceived(ContainerId containerId,
ContainerStatus containerStatus) {
LOG_YARN.debug("Container Status: id={}, status={}", containerId,
containerStatus);
}
@Override // NMClientAsync.CallbackHandler
public void onGetContainerStatusError(
ContainerId containerId, Throwable t) {
LOG_YARN.error("Failed to query the status of Container {}", containerId);
}
@Override // NMClientAsync.CallbackHandler
public void onStopContainerError(ContainerId containerId, Throwable t) {
LOG_YARN.warn("Failed to stop Container {}", containerId);
}
/**
The cluster description published to callers
This is used as a synchronization point on activities that update
the CD, and also to update some of the structures that
feed in to the CD
*/
public ClusterDescription getClusterSpec() {
return appState.getClusterSpec();
}
/**
* This is the status, the live model
*/
public ClusterDescription getClusterDescription() {
return appState.getClusterDescription();
}
public ProviderService getProviderService() {
return providerService;
}
/**
* Get the username for the hoya cluster as set in the environment
* @return the username or null if none was set/it is a secure cluster
*/
public String getHoyaUsername() {
return hoyaUsername;
}
/**
* This is the main entry point for the service launcher.
* @param args command line arguments.
*/
public static void main(String[] args) {
//turn the args to a list
List<String> argsList = Arrays.asList(args);
//create a new list, as the ArrayList type doesn't push() on an insert
List<String> extendedArgs = new ArrayList<String>(argsList);
//insert the service name
extendedArgs.add(0, SERVICE_CLASSNAME);
//now have the service launcher do its work
ServiceLauncher.serviceMain(extendedArgs);
}
}
| true | true | private int createAndRunCluster(String clustername) throws Throwable {
HoyaVersionInfo.loadAndPrintVersionInfo(log);
//load the cluster description from the cd argument
String hoyaClusterDir = serviceArgs.getHoyaClusterURI();
URI hoyaClusterURI = new URI(hoyaClusterDir);
Path clusterDirPath = new Path(hoyaClusterURI);
Path clusterSpecPath =
new Path(clusterDirPath, HoyaKeys.CLUSTER_SPECIFICATION_FILE);
FileSystem fs = getClusterFS();
ClusterDescription.verifyClusterSpecExists(clustername,
fs,
clusterSpecPath);
ClusterDescription clusterSpec = ClusterDescription.load(fs, clusterSpecPath);
log.info("Deploying cluster from {}:", clusterSpecPath);
log.info(clusterSpec.toString());
File confDir = getLocalConfDir();
if (!confDir.exists() || !confDir.isDirectory()) {
throw new BadCommandArgumentsException(
"Configuration directory %s doesn't exist", confDir);
}
conf = new YarnConfiguration(getConfig());
//get our provider
String providerType = clusterSpec.type;
log.info("Cluster provider type is {}", providerType);
HoyaProviderFactory factory =
HoyaProviderFactory.createHoyaProviderFactory(
providerType);
providerService = factory.createServerProvider();
ClientProvider providerClient = factory.createClientProvider();
runChildService(providerService);
//verify that the cluster specification is now valid
providerService.validateClusterSpec(clusterSpec);
HoyaAMClientProvider amClientProvider = new HoyaAMClientProvider(conf);
//check with the Hoya and Cluster-specific providers that the cluster state
// looks good from the perspective of the AM
Path generatedConfDirPath =
new Path(clusterDirPath, HoyaKeys.GENERATED_CONF_DIR_NAME);
boolean clusterSecure = HoyaUtils.isClusterSecure(conf);
amClientProvider.preflightValidateClusterConfiguration(fs, clustername,
conf, clusterSpec,
clusterDirPath,
generatedConfDirPath,
clusterSecure
);
providerClient.preflightValidateClusterConfiguration(fs, clustername, conf,
clusterSpec,
clusterDirPath,
generatedConfDirPath,
clusterSecure
);
InetSocketAddress address = HoyaUtils.getRmSchedulerAddress(conf);
log.info("RM is at {}", address);
yarnRPC = YarnRPC.create(conf);
appMasterContainerID = ConverterUtils.toContainerId(
HoyaUtils.mandatoryEnvVariable(
ApplicationConstants.Environment.CONTAINER_ID.name()));
appAttemptID = appMasterContainerID.getApplicationAttemptId();
ApplicationId appid = appAttemptID.getApplicationId();
log.info("Hoya AM for ID {}", appid.getId());
UserGroupInformation currentUser = UserGroupInformation.getCurrentUser();
Credentials credentials =
currentUser.getCredentials();
DataOutputBuffer dob = new DataOutputBuffer();
credentials.writeTokenStorageToStream(dob);
dob.close();
// Now remove the AM->RM token so that containers cannot access it.
Iterator<Token<?>> iter = credentials.getAllTokens().iterator();
while (iter.hasNext()) {
Token<?> token = iter.next();
log.info("Token {}", token.getKind());
if (token.getKind().equals(AMRMTokenIdentifier.KIND_NAME)) {
iter.remove();
}
}
allTokens = ByteBuffer.wrap(dob.getData(), 0, dob.getLength());
// set up secret manager
secretManager = new ClientToAMTokenSecretManager(appAttemptID, null);
// if not a secure cluster, extract the username -it will be
// propagated to workers
if (!UserGroupInformation.isSecurityEnabled()) {
hoyaUsername = System.getenv(HADOOP_USER_NAME);
log.info(HADOOP_USER_NAME + "='{}'", hoyaUsername);
}
int heartbeatInterval = HEARTBEAT_INTERVAL;
//add the RM client -this brings the callbacks in
asyncRMClient = AMRMClientAsync.createAMRMClientAsync(heartbeatInterval,
this);
addService(asyncRMClient);
//wrap it for the app state model
rmOperationHandler = new AsyncRMOperationHandler(asyncRMClient);
//now bring it up
runChildService(asyncRMClient);
//nmclient relays callbacks back to this class
nmClientAsync = new NMClientAsyncImpl("hoya", this);
runChildService(nmClientAsync);
//bring up the Hoya RPC service
startHoyaRPCServer();
InetSocketAddress rpcServiceAddr = rpcService.getConnectAddress();
appMasterHostname = rpcServiceAddr.getHostName();
appMasterRpcPort = rpcServiceAddr.getPort();
appMasterTrackingUrl = null;
log.info("HoyaAM Server is listening at {}:{}", appMasterHostname,
appMasterRpcPort);
//build the role map
List<ProviderRole> providerRoles =
new ArrayList<ProviderRole>(providerService.getRoles());
providerRoles.addAll(amClientProvider.getRoles());
/* DISABLED
// work out a port for the AM
int infoport = clusterSpec.getRoleOptInt(ROLE_HOYA_AM,
RoleKeys.APP_INFOPORT,
0);
if (0 == infoport) {
infoport =
HoyaUtils.findFreePort(providerService.getDefaultMasterInfoPort(), 128);
//need to get this to the app
clusterSpec.setRoleOpt(ROLE_HOYA_AM,
RoleKeys.APP_INFOPORT,
infoport);
}
appMasterTrackingUrl = "http://" + appMasterHostname + ":" + infoport;
*/
appMasterTrackingUrl = null;
// Register self with ResourceManager
// This will start heartbeating to the RM
// address = HoyaUtils.getRmSchedulerAddress(asyncRMClient.getConfig());
log.info("Connecting to RM at {},address tracking URL={}",
appMasterRpcPort, appMasterTrackingUrl);
RegisterApplicationMasterResponse response = asyncRMClient
.registerApplicationMaster(appMasterHostname,
appMasterRpcPort,
appMasterTrackingUrl);
Resource maxResources =
response.getMaximumResourceCapability();
containerMaxMemory = maxResources.getMemory();
containerMaxCores = maxResources.getVirtualCores();
appState.setContainerLimits(maxResources.getMemory(),
maxResources.getVirtualCores());
boolean securityEnabled = UserGroupInformation.isSecurityEnabled();
if (securityEnabled) {
secretManager.setMasterKey(
response.getClientToAMTokenMasterKey().array());
applicationACLs = response.getApplicationACLs();
//tell the server what the ACLs are
rpcService.getServer().refreshServiceAcl(conf, new HoyaAMPolicyProvider());
}
//TODO: build from response once it is coming back
List<Container> liveContainers = null;
//now validate the dir by loading in a hadoop-site.xml file from it
Configuration siteConf;
String siteXMLFilename = providerService.getSiteXMLFilename();
if (siteXMLFilename != null) {
File siteXML = new File(confDir, siteXMLFilename);
if (!siteXML.exists()) {
throw new BadCommandArgumentsException(
"Configuration directory %s doesn't contain %s - listing is %s",
confDir, siteXMLFilename, HoyaUtils.listDir(confDir));
}
//now read it in
siteConf = ConfigHelper.loadConfFromFile(siteXML);
log.info("{} file is at {}", siteXMLFilename, siteXML);
log.info(ConfigHelper.dumpConfigToString(siteConf));
} else {
//no site configuration: have an empty one
siteConf = new Configuration(false);
}
providerService.validateApplicationConfiguration(clusterSpec, confDir, securityEnabled);
//determine the location for the role history data
Path historyDir = new Path(clusterDirPath, HISTORY_DIR_NAME);
//build the instance
appState.buildInstance(clusterSpec,
siteConf,
providerRoles,
fs,
historyDir,
liveContainers);
//before bothering to start the containers, bring up the master.
//This ensures that if the master doesn't come up, less
//cluster resources get wasted
appState.buildAppMasterNode(appMasterContainerID);
// build up environment variables that the AM wants set in every container
// irrespective of provider and role.
Map<String, String> envVars = new HashMap<String, String>();
if (hoyaUsername != null) {
envVars.put(HADOOP_USER_NAME, hoyaUsername);
}
//launcher service
launchService = new RoleLaunchService(this,
providerService,
getClusterFS(),
new Path(getDFSConfDir()),
envVars);
runChildService(launchService);
appState.noteAMLaunched();
// launch the provider; this is expected to trigger a callback that
// brings up the service
launchProviderService(clusterSpec, confDir);
try {
//now block waiting to be told to exit the process
waitForAMCompletionSignal();
//shutdown time
} finally {
finish();
}
return amExitCode;
}
| private int createAndRunCluster(String clustername) throws Throwable {
HoyaVersionInfo.loadAndPrintVersionInfo(log);
//load the cluster description from the cd argument
String hoyaClusterDir = serviceArgs.getHoyaClusterURI();
URI hoyaClusterURI = new URI(hoyaClusterDir);
Path clusterDirPath = new Path(hoyaClusterURI);
Path clusterSpecPath =
new Path(clusterDirPath, HoyaKeys.CLUSTER_SPECIFICATION_FILE);
FileSystem fs = getClusterFS();
ClusterDescription.verifyClusterSpecExists(clustername,
fs,
clusterSpecPath);
ClusterDescription clusterSpec = ClusterDescription.load(fs, clusterSpecPath);
log.info("Deploying cluster from {}:", clusterSpecPath);
log.info(clusterSpec.toString());
File confDir = getLocalConfDir();
if (!confDir.exists() || !confDir.isDirectory()) {
throw new BadCommandArgumentsException(
"Configuration directory %s doesn't exist", confDir);
}
conf = new YarnConfiguration(getConfig());
//get our provider
String providerType = clusterSpec.type;
log.info("Cluster provider type is {}", providerType);
HoyaProviderFactory factory =
HoyaProviderFactory.createHoyaProviderFactory(
providerType);
providerService = factory.createServerProvider();
ClientProvider providerClient = factory.createClientProvider();
runChildService(providerService);
//verify that the cluster specification is now valid
providerService.validateClusterSpec(clusterSpec);
HoyaAMClientProvider amClientProvider = new HoyaAMClientProvider(conf);
//check with the Hoya and Cluster-specific providers that the cluster state
// looks good from the perspective of the AM
Path generatedConfDirPath =
new Path(clusterDirPath, HoyaKeys.GENERATED_CONF_DIR_NAME);
boolean clusterSecure = HoyaUtils.isClusterSecure(conf);
amClientProvider.preflightValidateClusterConfiguration(fs, clustername,
conf, clusterSpec,
clusterDirPath,
generatedConfDirPath,
clusterSecure
);
providerClient.preflightValidateClusterConfiguration(fs, clustername, conf,
clusterSpec,
clusterDirPath,
generatedConfDirPath,
clusterSecure
);
InetSocketAddress address = HoyaUtils.getRmSchedulerAddress(conf);
log.info("RM is at {}", address);
yarnRPC = YarnRPC.create(conf);
appMasterContainerID = ConverterUtils.toContainerId(
HoyaUtils.mandatoryEnvVariable(
ApplicationConstants.Environment.CONTAINER_ID.name()));
appAttemptID = appMasterContainerID.getApplicationAttemptId();
ApplicationId appid = appAttemptID.getApplicationId();
log.info("Hoya AM for ID {}", appid.getId());
UserGroupInformation currentUser = UserGroupInformation.getCurrentUser();
Credentials credentials =
currentUser.getCredentials();
DataOutputBuffer dob = new DataOutputBuffer();
credentials.writeTokenStorageToStream(dob);
dob.close();
// Now remove the AM->RM token so that containers cannot access it.
Iterator<Token<?>> iter = credentials.getAllTokens().iterator();
while (iter.hasNext()) {
Token<?> token = iter.next();
log.info("Token {}", token.getKind());
if (token.getKind().equals(AMRMTokenIdentifier.KIND_NAME)) {
iter.remove();
}
}
allTokens = ByteBuffer.wrap(dob.getData(), 0, dob.getLength());
// set up secret manager
secretManager = new ClientToAMTokenSecretManager(appAttemptID, null);
// if not a secure cluster, extract the username -it will be
// propagated to workers
if (!UserGroupInformation.isSecurityEnabled()) {
hoyaUsername = System.getenv(HADOOP_USER_NAME);
log.info(HADOOP_USER_NAME + "='{}'", hoyaUsername);
}
int heartbeatInterval = HEARTBEAT_INTERVAL;
//add the RM client -this brings the callbacks in
asyncRMClient = AMRMClientAsync.createAMRMClientAsync(heartbeatInterval,
this);
addService(asyncRMClient);
//wrap it for the app state model
rmOperationHandler = new AsyncRMOperationHandler(asyncRMClient);
//now bring it up
runChildService(asyncRMClient);
//nmclient relays callbacks back to this class
nmClientAsync = new NMClientAsyncImpl("hoya", this);
runChildService(nmClientAsync);
//bring up the Hoya RPC service
startHoyaRPCServer();
InetSocketAddress rpcServiceAddr = rpcService.getConnectAddress();
appMasterHostname = rpcServiceAddr.getHostName();
appMasterRpcPort = rpcServiceAddr.getPort();
appMasterTrackingUrl = null;
log.info("HoyaAM Server is listening at {}:{}", appMasterHostname,
appMasterRpcPort);
//build the role map
List<ProviderRole> providerRoles =
new ArrayList<ProviderRole>(providerService.getRoles());
providerRoles.addAll(amClientProvider.getRoles());
/* DISABLED
// work out a port for the AM
int infoport = clusterSpec.getRoleOptInt(ROLE_HOYA_AM,
RoleKeys.APP_INFOPORT,
0);
if (0 == infoport) {
infoport =
HoyaUtils.findFreePort(providerService.getDefaultMasterInfoPort(), 128);
//need to get this to the app
clusterSpec.setRoleOpt(ROLE_HOYA_AM,
RoleKeys.APP_INFOPORT,
infoport);
}
appMasterTrackingUrl = "http://" + appMasterHostname + ":" + infoport;
*/
appMasterTrackingUrl = null;
// Register self with ResourceManager
// This will start heartbeating to the RM
// address = HoyaUtils.getRmSchedulerAddress(asyncRMClient.getConfig());
log.info("Connecting to RM at {},address tracking URL={}",
appMasterRpcPort, appMasterTrackingUrl);
RegisterApplicationMasterResponse response = asyncRMClient
.registerApplicationMaster(appMasterHostname,
appMasterRpcPort,
appMasterTrackingUrl);
Resource maxResources =
response.getMaximumResourceCapability();
containerMaxMemory = maxResources.getMemory();
containerMaxCores = maxResources.getVirtualCores();
appState.setContainerLimits(maxResources.getMemory(),
maxResources.getVirtualCores());
boolean securityEnabled = UserGroupInformation.isSecurityEnabled();
if (securityEnabled) {
secretManager.setMasterKey(
response.getClientToAMTokenMasterKey().array());
applicationACLs = response.getApplicationACLs();
//tell the server what the ACLs are
rpcService.getServer().refreshServiceAcl(conf, new HoyaAMPolicyProvider());
}
// extract container list
List<Container> liveContainers = response.getContainersFromPreviousAttempt();
//now validate the dir by loading in a hadoop-site.xml file from it
Configuration siteConf;
String siteXMLFilename = providerService.getSiteXMLFilename();
if (siteXMLFilename != null) {
File siteXML = new File(confDir, siteXMLFilename);
if (!siteXML.exists()) {
throw new BadCommandArgumentsException(
"Configuration directory %s doesn't contain %s - listing is %s",
confDir, siteXMLFilename, HoyaUtils.listDir(confDir));
}
//now read it in
siteConf = ConfigHelper.loadConfFromFile(siteXML);
log.info("{} file is at {}", siteXMLFilename, siteXML);
log.info(ConfigHelper.dumpConfigToString(siteConf));
} else {
//no site configuration: have an empty one
siteConf = new Configuration(false);
}
providerService.validateApplicationConfiguration(clusterSpec, confDir, securityEnabled);
//determine the location for the role history data
Path historyDir = new Path(clusterDirPath, HISTORY_DIR_NAME);
//build the instance
appState.buildInstance(clusterSpec,
siteConf,
providerRoles,
fs,
historyDir,
liveContainers);
//before bothering to start the containers, bring up the master.
//This ensures that if the master doesn't come up, less
//cluster resources get wasted
appState.buildAppMasterNode(appMasterContainerID);
// build up environment variables that the AM wants set in every container
// irrespective of provider and role.
Map<String, String> envVars = new HashMap<String, String>();
if (hoyaUsername != null) {
envVars.put(HADOOP_USER_NAME, hoyaUsername);
}
//launcher service
launchService = new RoleLaunchService(this,
providerService,
getClusterFS(),
new Path(getDFSConfDir()),
envVars);
runChildService(launchService);
appState.noteAMLaunched();
// launch the provider; this is expected to trigger a callback that
// brings up the service
launchProviderService(clusterSpec, confDir);
try {
//now block waiting to be told to exit the process
waitForAMCompletionSignal();
//shutdown time
} finally {
finish();
}
return amExitCode;
}
|
diff --git a/AuctionHouse/src/webServiceClient/WebServiceClientThread.java b/AuctionHouse/src/webServiceClient/WebServiceClientThread.java
index 96406d7..e271d08 100644
--- a/AuctionHouse/src/webServiceClient/WebServiceClientThread.java
+++ b/AuctionHouse/src/webServiceClient/WebServiceClientThread.java
@@ -1,231 +1,231 @@
package webServiceClient;
import interfaces.MediatorWeb;
import java.util.ArrayList;
import java.util.Date;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Random;
import data.LoginCred;
import data.Pair;
import data.Service;
import data.UserEntry;
import data.UserProfile;
import data.Service.Status;
import data.UserEntry.Offer;
import data.UserProfile.UserRole;
/**
* WebServiceClient module implementation.
*
* @author Paul Vlase <[email protected]>
*/
public class WebServiceClientThread extends Thread {
private boolean running;
private Random random;
private Date date;
private MediatorWeb med;
private Hashtable<String, Service> offers;
private Hashtable<String, UserProfile> users;
public WebServiceClientThread(MediatorWeb med) {
this.med = med;
random = new Random();
date = new Date();
users = new Hashtable<String, UserProfile>();
offers = new Hashtable<String, Service>();
users.put("pvlase", new UserProfile("pvlase", "Paul", "Vlase",
UserRole.BUYER, "parola"));
users.put("unix140", new UserProfile("unix140", "Ghennadi",
"Procopciuc", UserRole.BUYER, "marmota"));
}
public void run() {
int timeLimit = 2500;
running = true;
try {
while (isRunning()) {
int sleepTime = 1000 + random.nextInt(timeLimit);
Thread.sleep(sleepTime);
for (Map.Entry<String, Service> offer : offers.entrySet()) {
Service service = offer.getValue();
int event = random.nextInt(1000);
System.out.println("event = " + event);
if (event < 200) {
String username = getRandomString(5 + Math.abs(random
.nextInt(16)));
Long time = date.getTime()
- + Math.abs(random.nextInt(10000));
+ + 200 + Math.abs(random.nextInt(10000));
Double price = Math.abs(random.nextInt(10000)) / 100.0;
UserEntry user = new UserEntry(username,
Offer.NO_OFFER, time, price);
service.addUserEntry(user);
med.newUserNotify(service);
} else if (event < 400) {
List<UserEntry> users = service.getUsers();
if (users != null) {
int userIndex;
do {
userIndex = Math.abs(random.nextInt(service
.getUsers().size()));
} while (users.get(userIndex).getOffer() == Offer.OFFER_MADE
&& users.get(userIndex).getOffer() == Offer.OFFER_REFUSED);
double price = users.get(userIndex).getPrice();
if (price > 1) {
users.get(userIndex).setOffer(Offer.OFFER_MADE);
users.get(userIndex).setPrice(price - 1);
}
med.offerMadeNotify(service);
}
}
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private String getRandomString(int len) {
char[] str = new char[len];
for (int i = 0; i < len; i++) {
int c;
do {
c = 48 + random.nextInt(123 - 48);
} while ((c >= 91 && c <= 96) || (c >= 58 && c <= 64));
str[i] = (char) c;
}
System.out.println(new String(str));
return new String(str);
}
public synchronized void stopThread() {
running = false;
}
public synchronized boolean isRunning() {
return running;
}
public UserProfile logIn(LoginCred cred) {
UserProfile profile;
profile = getUserProfile(cred.getUsername());
if (profile == null) {
return null;
}
if (!profile.getPassword().equals(cred.getPassword())) {
return null;
}
return profile;
}
public void logOut() {
System.out.println("[WebServiceClientThread:logOut()] Bye bye");
}
public synchronized UserProfile getUserProfile(String username) {
return users.get(username);
}
public synchronized boolean setUserProfile(UserProfile profile) {
users.put(profile.getUsername(), profile);
med.profileChangedNotify(profile);
return true;
}
/* Common */
public synchronized boolean launchOffer(Service service) {
service.setStatus(Status.ACTIVE);
// service.setUsers(new ArrayList<UserEntry>());
offers.put(service.getName(), service);
med.launchOfferNotify(service);
System.out.println("[WebServiceClientMockup:addOffer] "
+ service.getName());
return true;
}
public synchronized boolean launchOffers(ArrayList<Service> services) {
for (Service service : services) {
service.setStatus(Status.ACTIVE);
// service.setUsers(new ArrayList<UserEntry>());
offers.put(service.getName(), service);
System.out.println("[WebServiceClientMockup:addOffers] "
+ service.getName());
}
med.launchOffersNotify(services);
return true;
}
public synchronized boolean dropOffer(Service service) {
service.setStatus(Status.INACTIVE);
service.setUsers(null);
offers.remove(service.getName());
System.out.println("[WebServiceClientMockup:dropOffer] "
+ service.getName());
med.dropOfferNotify(service);
return true;
}
public synchronized boolean dropOffers(ArrayList<Service> services) {
for (Service service : services) {
service.setStatus(Status.INACTIVE);
service.setStatus(null);
offers.remove(service.getName());
System.out.println("[WebServiceClientMockup:dropOffers] "
+ service.getName());
}
return true;
}
public synchronized boolean acceptOffer(Pair<Service, Integer> pair) {
Service service = pair.getKey();
ArrayList<UserEntry> users = service.getUsers();
for (UserEntry user : users) {
user.setOffer(Offer.OFFER_REFUSED);
}
UserEntry user = users.get(pair.getValue());
user.setOffer(Offer.OFFER_ACCEPTED);
/* TODO: communicate with server */
users.clear();
users.add(user);
return true;
}
public synchronized boolean refuseOffer(Pair<Service, Integer> pair) {
return true;
}
}
| true | true | public void run() {
int timeLimit = 2500;
running = true;
try {
while (isRunning()) {
int sleepTime = 1000 + random.nextInt(timeLimit);
Thread.sleep(sleepTime);
for (Map.Entry<String, Service> offer : offers.entrySet()) {
Service service = offer.getValue();
int event = random.nextInt(1000);
System.out.println("event = " + event);
if (event < 200) {
String username = getRandomString(5 + Math.abs(random
.nextInt(16)));
Long time = date.getTime()
+ Math.abs(random.nextInt(10000));
Double price = Math.abs(random.nextInt(10000)) / 100.0;
UserEntry user = new UserEntry(username,
Offer.NO_OFFER, time, price);
service.addUserEntry(user);
med.newUserNotify(service);
} else if (event < 400) {
List<UserEntry> users = service.getUsers();
if (users != null) {
int userIndex;
do {
userIndex = Math.abs(random.nextInt(service
.getUsers().size()));
} while (users.get(userIndex).getOffer() == Offer.OFFER_MADE
&& users.get(userIndex).getOffer() == Offer.OFFER_REFUSED);
double price = users.get(userIndex).getPrice();
if (price > 1) {
users.get(userIndex).setOffer(Offer.OFFER_MADE);
users.get(userIndex).setPrice(price - 1);
}
med.offerMadeNotify(service);
}
}
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
| public void run() {
int timeLimit = 2500;
running = true;
try {
while (isRunning()) {
int sleepTime = 1000 + random.nextInt(timeLimit);
Thread.sleep(sleepTime);
for (Map.Entry<String, Service> offer : offers.entrySet()) {
Service service = offer.getValue();
int event = random.nextInt(1000);
System.out.println("event = " + event);
if (event < 200) {
String username = getRandomString(5 + Math.abs(random
.nextInt(16)));
Long time = date.getTime()
+ 200 + Math.abs(random.nextInt(10000));
Double price = Math.abs(random.nextInt(10000)) / 100.0;
UserEntry user = new UserEntry(username,
Offer.NO_OFFER, time, price);
service.addUserEntry(user);
med.newUserNotify(service);
} else if (event < 400) {
List<UserEntry> users = service.getUsers();
if (users != null) {
int userIndex;
do {
userIndex = Math.abs(random.nextInt(service
.getUsers().size()));
} while (users.get(userIndex).getOffer() == Offer.OFFER_MADE
&& users.get(userIndex).getOffer() == Offer.OFFER_REFUSED);
double price = users.get(userIndex).getPrice();
if (price > 1) {
users.get(userIndex).setOffer(Offer.OFFER_MADE);
users.get(userIndex).setPrice(price - 1);
}
med.offerMadeNotify(service);
}
}
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
|
diff --git a/SaveStopper/src/org/bonsaimind/bukkitplugins/SaveStopper.java b/SaveStopper/src/org/bonsaimind/bukkitplugins/SaveStopper.java
index 4a9fda8..ef64582 100644
--- a/SaveStopper/src/org/bonsaimind/bukkitplugins/SaveStopper.java
+++ b/SaveStopper/src/org/bonsaimind/bukkitplugins/SaveStopper.java
@@ -1,174 +1,170 @@
/*
* This file is part of SaveStopper.
*
* SaveStopper is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SaveStopper is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SaveStopper. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* Author: Robert 'Bobby' Zenz
* Website: http://www.bonsaimind.org
* GitHub: https://github.com/RobertZenz/org.bonsaimind.bukkitplugins/tree/master/SaveStopper
* E-Mail: [email protected]
*/
package org.bonsaimind.bukkitplugins;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import org.bukkit.Server;
import org.bukkit.event.Event.Priority;
import org.bukkit.event.Event.Type;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
/**
*
* @author Robert 'Bobby' Zenz
*/
public class SaveStopper extends JavaPlugin {
private Server server = null;
private boolean isSaving = true;
private Map<String, Object> config = null;
private Timer timer = new Timer(true);
private SaveStopperPlayerListener listener = new SaveStopperPlayerListener(this);
public void onDisable() {
timer.cancel();
timer = null;
listener = null;
config.clear();
config = null;
server = null;
}
public void onEnable() {
server = getServer();
PluginManager pm = server.getPluginManager();
pm.registerEvent(Type.PLAYER_LOGIN, listener, Priority.Low, this);
pm.registerEvent(Type.PLAYER_QUIT, listener, Priority.Low, this);
PluginDescriptionFile pdfFile = this.getDescription();
System.out.println(pdfFile.getName() + " " + pdfFile.getVersion() + " is enabled.");
readConfiguration();
if ((Boolean) config.get("disableOnStart")) {
internalDisable();
}
}
protected void readConfiguration() {
YamlHelper helper = new YamlHelper("plugins/SaveStopper/config.yml");
config = helper.read();
if (config == null) {
- if ((Boolean) config.get("verbose")) {
- System.out.println("SaveStopper: No configuration file found, using defaults.");
- }
+ System.out.println("SaveStopper: No configuration file found, using defaults.");
config = new HashMap<String, Object>();
}
// Set the defaults
if (!config.containsKey("disableOnStart")) {
config.put("disableOnStart", true);
}
if (!config.containsKey("saveAll")) {
config.put("saveAll", true);
}
if (!config.containsKey("wait")) {
config.put("wait", 300);
}
if (!config.containsKey("verbose")) {
config.put("verbose", true);
}
if (!helper.exists()) {
- if ((Boolean) config.get("verbose")) {
- System.out.println("SaveStopper: Configuration file doesn't exist, dumping now...");
- }
+ System.out.println("SaveStopper: Configuration file doesn't exist, dumping now...");
helper.write(config);
}
}
/**
* Enable saving.
*/
protected void enable() {
if (server.getOnlinePlayers().length == 0 && isSaving && (Boolean) config.get("verbose")) {
System.out.println("SaveStopper: Canceling scheduled disabling...");
timer.purge();
}
if (!isSaving) {
if ((Boolean) config.get("verbose")) {
System.out.println("SaveStopper: Enabling saving...");
}
CommandHelper.queueConsoleCommand(server, "save-on");
isSaving = true;
}
}
/**
* Disable saving, check if we should use the timer or not.
*/
protected void disable() {
long wait = ((Number) config.get("wait")).longValue();
if (wait > 0) {
if ((Boolean) config.get("verbose")) {
System.out.println("SaveStopper: Scheduling disabling in " + Long.toString(wait) + " seconds...");
}
timer.schedule(new TimerTask() {
@Override
public void run() {
internalDisable();
}
},
wait * 1000);
} else {
internalDisable();
}
}
/**
* Disable saving.
*/
private void internalDisable() {
if (isSaving && server.getOnlinePlayers().length == 0) {
if ((Boolean) config.get("verbose")) {
System.out.println("SaveStopper: Disabling saving...");
}
if ((Boolean) config.get("saveAll")) {
CommandHelper.queueConsoleCommand(server, "save-all");
}
CommandHelper.queueConsoleCommand(server, "save-off");
isSaving = false;
}
}
}
| false | true | protected void readConfiguration() {
YamlHelper helper = new YamlHelper("plugins/SaveStopper/config.yml");
config = helper.read();
if (config == null) {
if ((Boolean) config.get("verbose")) {
System.out.println("SaveStopper: No configuration file found, using defaults.");
}
config = new HashMap<String, Object>();
}
// Set the defaults
if (!config.containsKey("disableOnStart")) {
config.put("disableOnStart", true);
}
if (!config.containsKey("saveAll")) {
config.put("saveAll", true);
}
if (!config.containsKey("wait")) {
config.put("wait", 300);
}
if (!config.containsKey("verbose")) {
config.put("verbose", true);
}
if (!helper.exists()) {
if ((Boolean) config.get("verbose")) {
System.out.println("SaveStopper: Configuration file doesn't exist, dumping now...");
}
helper.write(config);
}
}
| protected void readConfiguration() {
YamlHelper helper = new YamlHelper("plugins/SaveStopper/config.yml");
config = helper.read();
if (config == null) {
System.out.println("SaveStopper: No configuration file found, using defaults.");
config = new HashMap<String, Object>();
}
// Set the defaults
if (!config.containsKey("disableOnStart")) {
config.put("disableOnStart", true);
}
if (!config.containsKey("saveAll")) {
config.put("saveAll", true);
}
if (!config.containsKey("wait")) {
config.put("wait", 300);
}
if (!config.containsKey("verbose")) {
config.put("verbose", true);
}
if (!helper.exists()) {
System.out.println("SaveStopper: Configuration file doesn't exist, dumping now...");
helper.write(config);
}
}
|
diff --git a/src/com/android/timezonepicker/TimeZoneFilterTypeAdapter.java b/src/com/android/timezonepicker/TimeZoneFilterTypeAdapter.java
index 5d0e881..cadd4f2 100644
--- a/src/com/android/timezonepicker/TimeZoneFilterTypeAdapter.java
+++ b/src/com/android/timezonepicker/TimeZoneFilterTypeAdapter.java
@@ -1,535 +1,530 @@
/*
* Copyright (C) 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.timezonepicker;
import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;
import java.util.ArrayList;
public class TimeZoneFilterTypeAdapter extends BaseAdapter implements Filterable, OnClickListener {
public static final String TAG = "TimeZoneFilterTypeAdapter";
public static final int FILTER_TYPE_EMPTY = -1;
public static final int FILTER_TYPE_NONE = 0;
public static final int FILTER_TYPE_TIME = 1;
public static final int FILTER_TYPE_TIME_ZONE = 2;
public static final int FILTER_TYPE_COUNTRY = 3;
public static final int FILTER_TYPE_STATE = 4;
public static final int FILTER_TYPE_GMT = 5;
public interface OnSetFilterListener {
void onSetFilter(int filterType, String str, int time);
}
static class ViewHolder {
int filterType;
String str;
int time;
TextView typeTextView;
TextView strTextView;
static void setupViewHolder(View v) {
ViewHolder vh = new ViewHolder();
vh.typeTextView = (TextView) v.findViewById(R.id.type);
vh.strTextView = (TextView) v.findViewById(R.id.value);
v.setTag(vh);
}
}
class FilterTypeResult {
boolean showLabel;
int type;
String constraint;
public int time;
public FilterTypeResult(boolean showLabel, int type, String constraint, int time) {
this.showLabel = showLabel;
this.type = type;
this.constraint = constraint;
this.time = time;
}
@Override
public String toString() {
return constraint;
}
}
private ArrayList<FilterTypeResult> mLiveResults = new ArrayList<FilterTypeResult>();
private int mLiveResultsCount = 0;
private ArrayFilter mFilter;
private LayoutInflater mInflater;
private TimeZoneData mTimeZoneData;
private OnSetFilterListener mListener;
public TimeZoneFilterTypeAdapter(Context context, TimeZoneData tzd, OnSetFilterListener l) {
mTimeZoneData = tzd;
mListener = l;
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public boolean areAllItemsEnabled() {
return false;
}
@Override
public boolean isEnabled(int position) {
return !mLiveResults.get(position).showLabel;
}
@Override
public int getCount() {
return mLiveResultsCount;
}
@Override
public FilterTypeResult getItem(int position) {
return mLiveResults.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v;
if (convertView != null) {
v = convertView;
} else {
v = mInflater.inflate(R.layout.time_zone_filter_item, null);
ViewHolder.setupViewHolder(v);
}
ViewHolder vh = (ViewHolder) v.getTag();
if (position >= mLiveResults.size()) {
Log.e(TAG, "getView: " + position + " of " + mLiveResults.size());
}
FilterTypeResult filter = mLiveResults.get(position);
vh.filterType = filter.type;
vh.str = filter.constraint;
vh.time = filter.time;
if (filter.showLabel) {
int resId;
switch (filter.type) {
case FILTER_TYPE_GMT:
resId = R.string.gmt_offset;
break;
case FILTER_TYPE_TIME:
resId = R.string.local_time;
break;
case FILTER_TYPE_TIME_ZONE:
resId = R.string.time_zone;
break;
case FILTER_TYPE_COUNTRY:
resId = R.string.country;
break;
default:
throw new IllegalArgumentException();
}
vh.typeTextView.setText(resId);
vh.typeTextView.setVisibility(View.VISIBLE);
vh.strTextView.setVisibility(View.GONE);
} else {
vh.typeTextView.setVisibility(View.GONE);
vh.strTextView.setVisibility(View.VISIBLE);
}
vh.strTextView.setText(filter.constraint);
return v;
}
OnClickListener mDummyListener = new OnClickListener() {
@Override
public void onClick(View v) {
}
};
// Implements OnClickListener
// This onClickListener is actually called from the AutoCompleteTextView's
// onItemClickListener. Trying to update the text in AutoCompleteTextView
// is causing an infinite loop.
@Override
public void onClick(View v) {
if (mListener != null && v != null) {
ViewHolder vh = (ViewHolder) v.getTag();
mListener.onSetFilter(vh.filterType, vh.str, vh.time);
}
notifyDataSetInvalidated();
}
// Implements Filterable
@Override
public Filter getFilter() {
if (mFilter == null) {
mFilter = new ArrayFilter();
}
return mFilter;
}
private class ArrayFilter extends Filter {
@Override
protected FilterResults performFiltering(CharSequence prefix) {
Log.e(TAG, "performFiltering >>>> [" + prefix + "]");
FilterResults results = new FilterResults();
String prefixString = null;
if (prefix != null) {
prefixString = prefix.toString().trim().toLowerCase();
}
if (TextUtils.isEmpty(prefixString)) {
results.values = null;
results.count = 0;
return results;
}
// TODO Perf - we can loop through the filtered list if the new
// search string starts with the old search string
ArrayList<FilterTypeResult> filtered = new ArrayList<FilterTypeResult>();
// ////////////////////////////////////////
// Search by local time and GMT offset
// ////////////////////////////////////////
boolean gmtOnly = false;
int startParsePosition = 0;
if (prefixString.charAt(0) == '+' || prefixString.charAt(0) == '-') {
gmtOnly = true;
}
if (prefixString.startsWith("gmt")) {
startParsePosition = 3;
gmtOnly = true;
}
int num = parseNum(prefixString, startParsePosition);
if (num != Integer.MIN_VALUE) {
boolean positiveOnly = prefixString.length() > startParsePosition
&& prefixString.charAt(startParsePosition) == '+';
handleSearchByGmt(filtered, num, positiveOnly);
// Search by time
if (!gmtOnly) {
handleSearchByTime(filtered, num);
}
}
// ////////////////////////////////////////
// Search by country
// ////////////////////////////////////////
boolean first = true;
for (String country : mTimeZoneData.mTimeZonesByCountry.keySet()) {
// TODO Perf - cache toLowerCase()?
if (!TextUtils.isEmpty(country)) {
final String lowerCaseCountry = country.toLowerCase();
if (lowerCaseCountry.startsWith(prefixString)
|| (lowerCaseCountry.charAt(0) == prefixString.charAt(0) &&
isStartingInitialsFor(prefixString, lowerCaseCountry))) {
FilterTypeResult r;
- if (first) {
- r = new FilterTypeResult(true, FILTER_TYPE_COUNTRY, null, 0);
- filtered.add(r);
- first = false;
- }
r = new FilterTypeResult(false, FILTER_TYPE_COUNTRY, country, 0);
filtered.add(r);
}
}
}
// ////////////////////////////////////////
// Search by time zone name
// ////////////////////////////////////////
// first = true;
// for (String timeZoneName : mTimeZoneData.mTimeZoneNames) {
// // TODO Perf - cache toLowerCase()?
// if (timeZoneName.toLowerCase().startsWith(prefixString)) {
// FilterTypeResult r;
// if (first) {
// r = new FilterTypeResult(true, FILTER_TYPE_TIME_ZONE, null, 0);
// filtered.add(r);
// first = false;
// }
// r = new FilterTypeResult(false, FILTER_TYPE_TIME_ZONE, timeZoneName, 0);
// filtered.add(r);
// }
// }
// ////////////////////////////////////////
// TODO Search by state
// ////////////////////////////////////////
Log.e(TAG, "performFiltering <<<< " + filtered.size() + "[" + prefix + "]");
results.values = filtered;
results.count = filtered.size();
return results;
}
/**
* Returns true if the prefixString is an initial for string. Note that
* this method will return true even if prefixString does not cover all
* the words. Words are separated by non-letters which includes spaces
* and symbols).
*
* For example:
* isStartingInitialsFor("UA", "United Arb Emirates") would return true
* isStartingInitialsFor("US", "U.S. Virgin Island") would return true
* @param prefixString
* @param string
* @return
*/
private boolean isStartingInitialsFor(String prefixString, String string) {
final int initialLen = prefixString.length();
final int strLen = string.length();
int initialIdx = 0;
boolean wasWordBreak = true;
for (int i = 0; i < strLen; i++) {
if (!Character.isLetter(string.charAt(i))) {
wasWordBreak = true;
continue;
}
if (wasWordBreak) {
if (prefixString.charAt(initialIdx++) != string.charAt(i)) {
return false;
}
if (initialIdx == initialLen) {
return true;
}
wasWordBreak = false;
}
}
return false;
}
/**
* @param filtered
* @param num
*/
private void handleSearchByTime(ArrayList<FilterTypeResult> filtered, int num) {
int originalResultCount = filtered.size();
// Separator
FilterTypeResult r = new FilterTypeResult(true, FILTER_TYPE_TIME, null, 0);
filtered.add(r);
long now = System.currentTimeMillis();
boolean[] hasTz = new boolean[24];
// TODO make this faster
for (TimeZoneInfo tzi : mTimeZoneData.mTimeZones) {
int localHr = tzi.getLocalHr(now);
hasTz[localHr] = true;
}
if (hasTz[num]) {
r = new FilterTypeResult(false, FILTER_TYPE_TIME,
Integer.toString(num), num);
filtered.add(r);
}
int start = Integer.MAX_VALUE;
int end = Integer.MIN_VALUE;
if (TimeZoneData.is24HourFormat) {
switch (num) {
case 1:
start = 10;
end = 23;
break;
case 2:
start = 20;
end = 23;
break;
}
} else if (num == 1) {
start = 10;
end = 12;
}
for (int i = start; i < end; i++) {
if (hasTz[i]) {
r = new FilterTypeResult(false, FILTER_TYPE_TIME,
Integer.toString(i), i);
filtered.add(r);
}
}
// Nothing was added except for the separator. Let's remove it.
if (filtered.size() == originalResultCount + 1) {
filtered.remove(originalResultCount);
}
}
private void handleSearchByGmt(ArrayList<FilterTypeResult> filtered, int num,
boolean positiveOnly) {
FilterTypeResult r;
int originalResultCount = filtered.size();
// Separator
r = new FilterTypeResult(true, FILTER_TYPE_GMT, null, 0);
filtered.add(r);
if (num >= 0) {
if (num == 1) {
for (int i = 19; i >= 10; i--) {
if (mTimeZoneData.hasTimeZonesInHrOffset(i)) {
r = new FilterTypeResult(false, FILTER_TYPE_GMT, "GMT+" + i, i);
filtered.add(r);
}
}
}
if (mTimeZoneData.hasTimeZonesInHrOffset(num)) {
r = new FilterTypeResult(false, FILTER_TYPE_GMT, "GMT+" + num, num);
filtered.add(r);
}
num *= -1;
}
if (!positiveOnly && num != 0) {
if (mTimeZoneData.hasTimeZonesInHrOffset(num)) {
r = new FilterTypeResult(false, FILTER_TYPE_GMT, "GMT" + num, num);
filtered.add(r);
}
if (num == -1) {
for (int i = -10; i >= -19; i--) {
if (mTimeZoneData.hasTimeZonesInHrOffset(i)) {
r = new FilterTypeResult(false, FILTER_TYPE_GMT, "GMT" + i, i);
filtered.add(r);
}
}
}
}
// Nothing was added except for the separator. Let's remove it.
if (filtered.size() == originalResultCount + 1) {
filtered.remove(originalResultCount);
}
return;
}
/**
* Acceptable strings are in the following format: [+-]?[0-9]?[0-9]
*
* @param str
* @param startIndex
* @return Integer.MIN_VALUE as invalid
*/
public int parseNum(String str, int startIndex) {
int idx = startIndex;
int num = Integer.MIN_VALUE;
int negativeMultiplier = 1;
// First char - check for + and -
char ch = str.charAt(idx++);
switch (ch) {
case '-':
negativeMultiplier = -1;
// fall through
case '+':
if (idx >= str.length()) {
// No more digits
return Integer.MIN_VALUE;
}
ch = str.charAt(idx++);
break;
}
if (!Character.isDigit(ch)) {
// No digit
return Integer.MIN_VALUE;
}
// Got first digit
num = Character.digit(ch, 10);
// Check next char
if (idx < str.length()) {
ch = str.charAt(idx++);
if (Character.isDigit(ch)) {
// Got second digit
num = 10 * num + Character.digit(ch, 10);
} else {
return Integer.MIN_VALUE;
}
}
if (idx != str.length()) {
// Invalid
return Integer.MIN_VALUE;
}
Log.e(TAG, "Parsing " + str + " -> " + negativeMultiplier * num);
return negativeMultiplier * num;
}
@SuppressWarnings("unchecked")
@Override
protected void publishResults(CharSequence constraint, FilterResults
results) {
if (results.values == null || results.count == 0) {
if (mListener != null) {
int filterType;
if (TextUtils.isEmpty(constraint)) {
filterType = FILTER_TYPE_NONE;
} else {
filterType = FILTER_TYPE_EMPTY;
}
mListener.onSetFilter(filterType, null, 0);
}
Log.e(TAG, "publishResults: " + results.count + " of null [" + constraint);
} else {
mLiveResults = (ArrayList<FilterTypeResult>) results.values;
Log.e(TAG, "publishResults: " + results.count + " of " + mLiveResults.size() + " ["
+ constraint);
}
mLiveResultsCount = results.count;
if (results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
}
}
| true | true | protected FilterResults performFiltering(CharSequence prefix) {
Log.e(TAG, "performFiltering >>>> [" + prefix + "]");
FilterResults results = new FilterResults();
String prefixString = null;
if (prefix != null) {
prefixString = prefix.toString().trim().toLowerCase();
}
if (TextUtils.isEmpty(prefixString)) {
results.values = null;
results.count = 0;
return results;
}
// TODO Perf - we can loop through the filtered list if the new
// search string starts with the old search string
ArrayList<FilterTypeResult> filtered = new ArrayList<FilterTypeResult>();
// ////////////////////////////////////////
// Search by local time and GMT offset
// ////////////////////////////////////////
boolean gmtOnly = false;
int startParsePosition = 0;
if (prefixString.charAt(0) == '+' || prefixString.charAt(0) == '-') {
gmtOnly = true;
}
if (prefixString.startsWith("gmt")) {
startParsePosition = 3;
gmtOnly = true;
}
int num = parseNum(prefixString, startParsePosition);
if (num != Integer.MIN_VALUE) {
boolean positiveOnly = prefixString.length() > startParsePosition
&& prefixString.charAt(startParsePosition) == '+';
handleSearchByGmt(filtered, num, positiveOnly);
// Search by time
if (!gmtOnly) {
handleSearchByTime(filtered, num);
}
}
// ////////////////////////////////////////
// Search by country
// ////////////////////////////////////////
boolean first = true;
for (String country : mTimeZoneData.mTimeZonesByCountry.keySet()) {
// TODO Perf - cache toLowerCase()?
if (!TextUtils.isEmpty(country)) {
final String lowerCaseCountry = country.toLowerCase();
if (lowerCaseCountry.startsWith(prefixString)
|| (lowerCaseCountry.charAt(0) == prefixString.charAt(0) &&
isStartingInitialsFor(prefixString, lowerCaseCountry))) {
FilterTypeResult r;
if (first) {
r = new FilterTypeResult(true, FILTER_TYPE_COUNTRY, null, 0);
filtered.add(r);
first = false;
}
r = new FilterTypeResult(false, FILTER_TYPE_COUNTRY, country, 0);
filtered.add(r);
}
}
}
// ////////////////////////////////////////
// Search by time zone name
// ////////////////////////////////////////
// first = true;
// for (String timeZoneName : mTimeZoneData.mTimeZoneNames) {
// // TODO Perf - cache toLowerCase()?
// if (timeZoneName.toLowerCase().startsWith(prefixString)) {
// FilterTypeResult r;
// if (first) {
// r = new FilterTypeResult(true, FILTER_TYPE_TIME_ZONE, null, 0);
// filtered.add(r);
// first = false;
// }
// r = new FilterTypeResult(false, FILTER_TYPE_TIME_ZONE, timeZoneName, 0);
// filtered.add(r);
// }
// }
// ////////////////////////////////////////
// TODO Search by state
// ////////////////////////////////////////
Log.e(TAG, "performFiltering <<<< " + filtered.size() + "[" + prefix + "]");
results.values = filtered;
results.count = filtered.size();
return results;
}
| protected FilterResults performFiltering(CharSequence prefix) {
Log.e(TAG, "performFiltering >>>> [" + prefix + "]");
FilterResults results = new FilterResults();
String prefixString = null;
if (prefix != null) {
prefixString = prefix.toString().trim().toLowerCase();
}
if (TextUtils.isEmpty(prefixString)) {
results.values = null;
results.count = 0;
return results;
}
// TODO Perf - we can loop through the filtered list if the new
// search string starts with the old search string
ArrayList<FilterTypeResult> filtered = new ArrayList<FilterTypeResult>();
// ////////////////////////////////////////
// Search by local time and GMT offset
// ////////////////////////////////////////
boolean gmtOnly = false;
int startParsePosition = 0;
if (prefixString.charAt(0) == '+' || prefixString.charAt(0) == '-') {
gmtOnly = true;
}
if (prefixString.startsWith("gmt")) {
startParsePosition = 3;
gmtOnly = true;
}
int num = parseNum(prefixString, startParsePosition);
if (num != Integer.MIN_VALUE) {
boolean positiveOnly = prefixString.length() > startParsePosition
&& prefixString.charAt(startParsePosition) == '+';
handleSearchByGmt(filtered, num, positiveOnly);
// Search by time
if (!gmtOnly) {
handleSearchByTime(filtered, num);
}
}
// ////////////////////////////////////////
// Search by country
// ////////////////////////////////////////
boolean first = true;
for (String country : mTimeZoneData.mTimeZonesByCountry.keySet()) {
// TODO Perf - cache toLowerCase()?
if (!TextUtils.isEmpty(country)) {
final String lowerCaseCountry = country.toLowerCase();
if (lowerCaseCountry.startsWith(prefixString)
|| (lowerCaseCountry.charAt(0) == prefixString.charAt(0) &&
isStartingInitialsFor(prefixString, lowerCaseCountry))) {
FilterTypeResult r;
r = new FilterTypeResult(false, FILTER_TYPE_COUNTRY, country, 0);
filtered.add(r);
}
}
}
// ////////////////////////////////////////
// Search by time zone name
// ////////////////////////////////////////
// first = true;
// for (String timeZoneName : mTimeZoneData.mTimeZoneNames) {
// // TODO Perf - cache toLowerCase()?
// if (timeZoneName.toLowerCase().startsWith(prefixString)) {
// FilterTypeResult r;
// if (first) {
// r = new FilterTypeResult(true, FILTER_TYPE_TIME_ZONE, null, 0);
// filtered.add(r);
// first = false;
// }
// r = new FilterTypeResult(false, FILTER_TYPE_TIME_ZONE, timeZoneName, 0);
// filtered.add(r);
// }
// }
// ////////////////////////////////////////
// TODO Search by state
// ////////////////////////////////////////
Log.e(TAG, "performFiltering <<<< " + filtered.size() + "[" + prefix + "]");
results.values = filtered;
results.count = filtered.size();
return results;
}
|
diff --git a/Queuer/src/au/edu/uts/eng/remotelabs/schedserver/queuer/impl/Allocator.java b/Queuer/src/au/edu/uts/eng/remotelabs/schedserver/queuer/impl/Allocator.java
index b540bd2a..a998a881 100644
--- a/Queuer/src/au/edu/uts/eng/remotelabs/schedserver/queuer/impl/Allocator.java
+++ b/Queuer/src/au/edu/uts/eng/remotelabs/schedserver/queuer/impl/Allocator.java
@@ -1,199 +1,199 @@
/**
* SAHARA Scheduling Server
*
* Schedules and assigns local laboratory rigs.
*
* @license See LICENSE in the top level directory for complete license terms.
*
* Copyright (c) 2010, University of Technology, Sydney
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the University of Technology, Sydney nor the names
* of its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @author Michael Diponio (mdiponio)
* @date 4th January 2010
*/
package au.edu.uts.eng.remotelabs.schedserver.queuer.impl;
import java.util.Date;
import au.edu.uts.eng.remotelabs.schedserver.dataaccess.dao.SessionDao;
import au.edu.uts.eng.remotelabs.schedserver.dataaccess.entities.Rig;
import au.edu.uts.eng.remotelabs.schedserver.dataaccess.entities.Session;
import au.edu.uts.eng.remotelabs.schedserver.logger.Logger;
import au.edu.uts.eng.remotelabs.schedserver.logger.LoggerActivator;
import au.edu.uts.eng.remotelabs.schedserver.rigclientproxy.RigClientAsyncService;
import au.edu.uts.eng.remotelabs.schedserver.rigclientproxy.RigClientAsyncServiceCallbackHandler;
import au.edu.uts.eng.remotelabs.schedserver.rigclientproxy.intf.types.AllocateResponse;
import au.edu.uts.eng.remotelabs.schedserver.rigclientproxy.intf.types.ErrorType;
import au.edu.uts.eng.remotelabs.schedserver.rigclientproxy.intf.types.OperationResponseType;
/**
* Call back handler which sets the session to ready.
*/
public class Allocator extends RigClientAsyncServiceCallbackHandler
{
/** Session that is being allocated. */
private Session session;
/** Logger. */
private Logger logger;
public Allocator()
{
this.logger = LoggerActivator.getLogger();
}
/**
* Allocates the user in the session to the rig client by calling the rig
* client allocate operation.
*
* @param ses session information
* @param db database session
*/
public void allocate(Session ses, org.hibernate.Session db)
{
Rig rig = ses.getRig();
this.session = ses;
try
{
RigClientAsyncService service = new RigClientAsyncService(rig.getName(), db);
service.allocate(ses.getUserName(), this);
}
catch (Exception e)
{
this.logger.error("Failed calling rig client allocate to " + rig.getName() + " at " +
rig.getContactUrl() + " because of error " + e.getMessage() + ".");
/* Terminate the session. */
ses.setActive(false);
ses.setRemovalReason("Allocation fail to " + rig.getName() + ", with error " +
e.getMessage() + ".");
ses.setRemovalTime(new Date());
db.beginTransaction();
db.flush();
db.getTransaction().commit();
/* Put the rig offline. */
rig.setInSession(false);
rig.setOnline(false);
rig.setOfflineReason("Allocation failed for session " + ses.getId() + ".");
rig.setSession(null);
db.beginTransaction();
db.flush();
db.getTransaction().commit();
}
}
@Override
public void allocateResponseCallback(final AllocateResponse response)
{
OperationResponseType op = response.getAllocateResponse();
try
{
Thread.sleep(500);
}
catch (InterruptedException ex) { /* Embrassing timing jiffy, which empircally works. */ }
if (op.getWillCallback())
{
/* The response will come in a callback request so no work required now. */
this.logger.debug("Received notification allocation for rig " + this.session.getAssignedRigName() +
- " will can in a callback message.");
+ " will come in a callback message.");
return;
}
SessionDao dao = new SessionDao();
this.session = dao.merge(this.session);
if (op.getSuccess())
{
this.logger.debug("Received allocate response for " + this.session.getUserNamespace() + ':' +
this.session.getUserName() + ", allocation successful.");
/* The session is being set to ready, so it may be used. */
this.session.setReady(true);
dao.flush();
}
else
{
ErrorType err = op.getError();
this.logger.error("Received allocate response for " + this.session.getUserNamespace() + ':' +
this.session.getUserName() + ", allocation not successful. Error reason is '" + err.getReason() + "'.");
/* Allocation failed so end the session and take the rig off line depending on error. */
this.session.setActive(false);
this.session.setReady(false);
this.session.setRemovalReason("Allocation failure with reason '" + err.getReason() + "'.");
this.session.setRemovalTime(new Date());
dao.flush();
if (err.getCode() == 4) // Error code 4 is an existing session exists
{
this.logger.error("Allocation failure reason was caused by an existing session, so not putting rig offline " +
"because a session already has it.");
}
else
{
Rig rig = this.session.getRig();
rig.setInSession(false);
rig.setOnline(false);
rig.setOfflineReason("Allocation failured with reason '" + err.getReason() + "'.");
rig.setSession(null);
dao.flush();
}
}
dao.closeSession();
}
@Override
public void allocateErrorCallback(final Exception e)
{
SessionDao dao = new SessionDao();
this.session = dao.merge(this.session);
Rig rig = this.session.getRig();
this.logger.error("Received error response from allocation of " + this.session.getUserNamespace() + ':' +
this.session.getUserName() + " to rig " + rig.getName() + " at " + rig.getContactUrl() + ". Error message" +
" is '" + e.getMessage() + "'.");
/* Allocation failed so end the session and take the rig offline. */
this.session.setActive(false);
this.session.setReady(false);
this.session.setRemovalReason("Allocation failure with SOAP error '" + e.getMessage() + "'.");
this.session.setRemovalTime(new Date());
dao.flush();
rig.setInSession(false);
rig.setOnline(false);
rig.setOfflineReason("Allocation failed with SOAP error '" + e.getMessage() + "'.");
rig.setSession(null);
dao.flush();
dao.closeSession();
}
}
| true | true | public void allocateResponseCallback(final AllocateResponse response)
{
OperationResponseType op = response.getAllocateResponse();
try
{
Thread.sleep(500);
}
catch (InterruptedException ex) { /* Embrassing timing jiffy, which empircally works. */ }
if (op.getWillCallback())
{
/* The response will come in a callback request so no work required now. */
this.logger.debug("Received notification allocation for rig " + this.session.getAssignedRigName() +
" will can in a callback message.");
return;
}
SessionDao dao = new SessionDao();
this.session = dao.merge(this.session);
if (op.getSuccess())
{
this.logger.debug("Received allocate response for " + this.session.getUserNamespace() + ':' +
this.session.getUserName() + ", allocation successful.");
/* The session is being set to ready, so it may be used. */
this.session.setReady(true);
dao.flush();
}
else
{
ErrorType err = op.getError();
this.logger.error("Received allocate response for " + this.session.getUserNamespace() + ':' +
this.session.getUserName() + ", allocation not successful. Error reason is '" + err.getReason() + "'.");
/* Allocation failed so end the session and take the rig off line depending on error. */
this.session.setActive(false);
this.session.setReady(false);
this.session.setRemovalReason("Allocation failure with reason '" + err.getReason() + "'.");
this.session.setRemovalTime(new Date());
dao.flush();
if (err.getCode() == 4) // Error code 4 is an existing session exists
{
this.logger.error("Allocation failure reason was caused by an existing session, so not putting rig offline " +
"because a session already has it.");
}
else
{
Rig rig = this.session.getRig();
rig.setInSession(false);
rig.setOnline(false);
rig.setOfflineReason("Allocation failured with reason '" + err.getReason() + "'.");
rig.setSession(null);
dao.flush();
}
}
dao.closeSession();
}
| public void allocateResponseCallback(final AllocateResponse response)
{
OperationResponseType op = response.getAllocateResponse();
try
{
Thread.sleep(500);
}
catch (InterruptedException ex) { /* Embrassing timing jiffy, which empircally works. */ }
if (op.getWillCallback())
{
/* The response will come in a callback request so no work required now. */
this.logger.debug("Received notification allocation for rig " + this.session.getAssignedRigName() +
" will come in a callback message.");
return;
}
SessionDao dao = new SessionDao();
this.session = dao.merge(this.session);
if (op.getSuccess())
{
this.logger.debug("Received allocate response for " + this.session.getUserNamespace() + ':' +
this.session.getUserName() + ", allocation successful.");
/* The session is being set to ready, so it may be used. */
this.session.setReady(true);
dao.flush();
}
else
{
ErrorType err = op.getError();
this.logger.error("Received allocate response for " + this.session.getUserNamespace() + ':' +
this.session.getUserName() + ", allocation not successful. Error reason is '" + err.getReason() + "'.");
/* Allocation failed so end the session and take the rig off line depending on error. */
this.session.setActive(false);
this.session.setReady(false);
this.session.setRemovalReason("Allocation failure with reason '" + err.getReason() + "'.");
this.session.setRemovalTime(new Date());
dao.flush();
if (err.getCode() == 4) // Error code 4 is an existing session exists
{
this.logger.error("Allocation failure reason was caused by an existing session, so not putting rig offline " +
"because a session already has it.");
}
else
{
Rig rig = this.session.getRig();
rig.setInSession(false);
rig.setOnline(false);
rig.setOfflineReason("Allocation failured with reason '" + err.getReason() + "'.");
rig.setSession(null);
dao.flush();
}
}
dao.closeSession();
}
|
diff --git a/org.springsource.ide.eclipse.commons.gettingstarted/src/org/springsource/ide/eclipse/commons/gettingstarted/dashboard/WelcomeDashboardPage.java b/org.springsource.ide.eclipse.commons.gettingstarted/src/org/springsource/ide/eclipse/commons/gettingstarted/dashboard/WelcomeDashboardPage.java
index 7c20221a..5e5c3170 100644
--- a/org.springsource.ide.eclipse.commons.gettingstarted/src/org/springsource/ide/eclipse/commons/gettingstarted/dashboard/WelcomeDashboardPage.java
+++ b/org.springsource.ide.eclipse.commons.gettingstarted/src/org/springsource/ide/eclipse/commons/gettingstarted/dashboard/WelcomeDashboardPage.java
@@ -1,131 +1,131 @@
/*******************************************************************************
* Copyright (c) 2013 GoPivotal, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* GoPivotal, Inc. - initial API and implementation
*******************************************************************************/
package org.springsource.ide.eclipse.commons.gettingstarted.dashboard;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.swt.browser.Browser;
import org.eclipse.swt.browser.LocationEvent;
import org.eclipse.swt.browser.LocationListener;
import org.eclipse.ui.internal.browser.WebBrowserPreference;
import org.springsource.ide.eclipse.commons.gettingstarted.GettingStartedActivator;
import org.springsource.ide.eclipse.commons.gettingstarted.browser.BrowserContext;
import org.springsource.ide.eclipse.commons.gettingstarted.wizard.guides.GSImportWizard;
import org.springsource.ide.eclipse.commons.ui.UiUtil;
public class WelcomeDashboardPage extends WebDashboardPage {
private File welcomeHtml;
private DashboardEditor dashboard;
public WelcomeDashboardPage(DashboardEditor dashboard) throws URISyntaxException, IOException {
this.dashboard = dashboard;
URL entry = GettingStartedActivator.getDefault().getBundle().getEntry("resources/welcome/index.html");
welcomeHtml = new File(FileLocator.toFileURL(entry).toURI());
setName("Welcome");
setHomeUrl(welcomeHtml.toURI().toString());
}
@Override
protected boolean hasToolbar() {
return false;
}
@Override
public boolean canClose() {
//Shouldn't allow closing the main / welcome page.
return false;
}
@Override
protected void addBrowserHooks(Browser browser) {
super.addBrowserHooks(browser);
browser.addLocationListener(new URLInterceptor(browser));
}
/**
* Not used anymore. Now only using the JavaScript function approach.
*/
public class URLInterceptor extends BrowserContext implements LocationListener {
public URLInterceptor(Browser browser) {
super(browser);
}
@Override
public void changed(LocationEvent event) {
// TODO Auto-generated method stub
}
@SuppressWarnings("restriction")
@Override
public void changing(LocationEvent event) {
System.out.println("Navigation: "+event.location);
event.doit = false; //all navigation in welcome page must be intercepted.
//Be careful...any exception thrown out of here have a nasty tendency to deadlock Eclipse
// (By crashing native UI thread maybe?)
try {
URI uri = new URI(event.location);
//zip file containing a codeset single codeset:
// https://github.com/kdvolder/gs-one-codeset/archive/master.zip?sts_codeset=true
// Map<String, String> params = URIParams.parse(uri);
IPath path = new Path(uri.getPath());
String host = uri.getHost();
if (event.location.equals("http://dashboard/guides")) {
GSImportWizard.open(getShell(), null, false, true);
return;
}
- if (host.equals("dashboard")) {
+ if ("dashboard".equals(host)) {
if (dashboard.setActivePage(getPageId(path))) {
return;
}
}
if (WebBrowserPreference.getBrowserChoice()==WebBrowserPreference.INTERNAL) {
if (dashboard.openWebPage(event.location)) {
return;
}
}
//Nothing else worked so far, try the most generic way to open a web browser.
UiUtil.openUrl(event.location);
} catch (Throwable e) {
GettingStartedActivator.log(e);
}
}
private String getPageId(IPath path) {
String pageId = path.toString();
if (pageId.startsWith("/")) {
pageId = pageId.substring(1);
}
return pageId;
}
//
// @Override
// public void changed(LocationEvent event) {
// }
}
}
| true | true | public void changing(LocationEvent event) {
System.out.println("Navigation: "+event.location);
event.doit = false; //all navigation in welcome page must be intercepted.
//Be careful...any exception thrown out of here have a nasty tendency to deadlock Eclipse
// (By crashing native UI thread maybe?)
try {
URI uri = new URI(event.location);
//zip file containing a codeset single codeset:
// https://github.com/kdvolder/gs-one-codeset/archive/master.zip?sts_codeset=true
// Map<String, String> params = URIParams.parse(uri);
IPath path = new Path(uri.getPath());
String host = uri.getHost();
if (event.location.equals("http://dashboard/guides")) {
GSImportWizard.open(getShell(), null, false, true);
return;
}
if (host.equals("dashboard")) {
if (dashboard.setActivePage(getPageId(path))) {
return;
}
}
if (WebBrowserPreference.getBrowserChoice()==WebBrowserPreference.INTERNAL) {
if (dashboard.openWebPage(event.location)) {
return;
}
}
//Nothing else worked so far, try the most generic way to open a web browser.
UiUtil.openUrl(event.location);
} catch (Throwable e) {
GettingStartedActivator.log(e);
}
}
| public void changing(LocationEvent event) {
System.out.println("Navigation: "+event.location);
event.doit = false; //all navigation in welcome page must be intercepted.
//Be careful...any exception thrown out of here have a nasty tendency to deadlock Eclipse
// (By crashing native UI thread maybe?)
try {
URI uri = new URI(event.location);
//zip file containing a codeset single codeset:
// https://github.com/kdvolder/gs-one-codeset/archive/master.zip?sts_codeset=true
// Map<String, String> params = URIParams.parse(uri);
IPath path = new Path(uri.getPath());
String host = uri.getHost();
if (event.location.equals("http://dashboard/guides")) {
GSImportWizard.open(getShell(), null, false, true);
return;
}
if ("dashboard".equals(host)) {
if (dashboard.setActivePage(getPageId(path))) {
return;
}
}
if (WebBrowserPreference.getBrowserChoice()==WebBrowserPreference.INTERNAL) {
if (dashboard.openWebPage(event.location)) {
return;
}
}
//Nothing else worked so far, try the most generic way to open a web browser.
UiUtil.openUrl(event.location);
} catch (Throwable e) {
GettingStartedActivator.log(e);
}
}
|
diff --git a/src/main/java/com/comoyo/jelastic/PersistentStorage.java b/src/main/java/com/comoyo/jelastic/PersistentStorage.java
index 1c60b78..167dd72 100644
--- a/src/main/java/com/comoyo/jelastic/PersistentStorage.java
+++ b/src/main/java/com/comoyo/jelastic/PersistentStorage.java
@@ -1,88 +1,89 @@
package com.comoyo.jelastic;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import java.net.UnknownHostException;
import java.util.Date;
public class PersistentStorage {
public static void storeMatch(final String winner, final String loser) {
final DB pingpong = getDB();
Date date = new Date();
DBCollection matchesTable = pingpong.getCollection("matches");
BasicDBObject document = new BasicDBObject();
document.put("winner", winner);
document.put("loser", loser);
document.put("date", date);
matchesTable.insert(document);
}
private static DB getDB() {
Mongo mongoClient;
try {
mongoClient = new Mongo("mongodb-rankitapp.jelastic.dogado.eu", 27017);
} catch (UnknownHostException e) {
throw new RuntimeException(e);
}
final DB pingpong = mongoClient.getDB("pingpong");
final boolean auth = pingpong.authenticate("admin", "XIyqkxSMgQ".toCharArray());
if (!auth) {
- throw new RuntimeException("Mongo authentication failed!");
+ return pingpong;
+ //throw new RuntimeException("Mongo authentication failed!");
}
return pingpong;
}
public static String getMatches(final int limit) {
final DB pingpong = getDB();
DBCollection matchesTable = pingpong.getCollection("matches");
BasicDBObject query = new BasicDBObject();
query.put("winner", 1);
DBCursor cursor = matchesTable.find(query).sort(new BasicDBObject("date", 1)).limit(limit);
String result = "";
for (DBObject dbObject : cursor) {
result = result + dbObject + "\n";
}
return result;
}
public static Person getPerson(final String name) {
final DB pingpong = getDB();
DBCollection personTable = pingpong.getCollection("persons");
BasicDBObject query = new BasicDBObject("name", 1);
DBObject dbObject = personTable.findOne(query);
if (dbObject == null) {
return new Person(name, 1200);
}
return new Person(dbObject.get("name").toString(),
Double.parseDouble(dbObject.get("ranking").toString()));
}
public static void setPerson(final Person person) {
final DB pingpong = getDB();
DBCollection personTable = pingpong.getCollection("persons");
BasicDBObject query = new BasicDBObject("name", person.name);
BasicDBObject updatedPerson = new BasicDBObject();
updatedPerson.put("name", person.name);
updatedPerson.put("ranking", person.ranking);
personTable.update(query, new BasicDBObject("$set", updatedPerson));
}
public static String getRankingList() {
final DB pingpong = getDB();
DBCollection matchesTable = pingpong.getCollection("persons");
BasicDBObject query = new BasicDBObject();
query.put("name", 1);
DBCursor cursor = matchesTable.find(query).sort(new BasicDBObject("ranking", 1));
String result = "";
for (DBObject dbObject : cursor) {
result = result + dbObject + "\n";
}
return result;
}
}
| true | true | private static DB getDB() {
Mongo mongoClient;
try {
mongoClient = new Mongo("mongodb-rankitapp.jelastic.dogado.eu", 27017);
} catch (UnknownHostException e) {
throw new RuntimeException(e);
}
final DB pingpong = mongoClient.getDB("pingpong");
final boolean auth = pingpong.authenticate("admin", "XIyqkxSMgQ".toCharArray());
if (!auth) {
throw new RuntimeException("Mongo authentication failed!");
}
return pingpong;
}
| private static DB getDB() {
Mongo mongoClient;
try {
mongoClient = new Mongo("mongodb-rankitapp.jelastic.dogado.eu", 27017);
} catch (UnknownHostException e) {
throw new RuntimeException(e);
}
final DB pingpong = mongoClient.getDB("pingpong");
final boolean auth = pingpong.authenticate("admin", "XIyqkxSMgQ".toCharArray());
if (!auth) {
return pingpong;
//throw new RuntimeException("Mongo authentication failed!");
}
return pingpong;
}
|
diff --git a/src/java/net/sf/picard/analysis/CollectGcBiasMetrics.java b/src/java/net/sf/picard/analysis/CollectGcBiasMetrics.java
index e4e0843..0c43c58 100644
--- a/src/java/net/sf/picard/analysis/CollectGcBiasMetrics.java
+++ b/src/java/net/sf/picard/analysis/CollectGcBiasMetrics.java
@@ -1,319 +1,320 @@
/*
* The MIT License
*
* Copyright (c) 2009 The Broad Institute
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package net.sf.picard.analysis;
import net.sf.picard.PicardException;
import net.sf.picard.cmdline.CommandLineProgram;
import net.sf.picard.cmdline.Option;
import net.sf.picard.cmdline.StandardOptionDefinitions;
import net.sf.picard.reference.ReferenceSequenceFile;
import net.sf.picard.reference.ReferenceSequenceFileFactory;
import net.sf.picard.reference.ReferenceSequence;
import net.sf.picard.io.IoUtil;
import net.sf.picard.util.Log;
import net.sf.picard.util.PeekableIterator;
import net.sf.samtools.SAMFileHeader;
import net.sf.samtools.util.SequenceUtil;
import net.sf.picard.metrics.MetricsFile;
import net.sf.samtools.SAMRecord;
import net.sf.samtools.SAMFileReader;
import net.sf.samtools.SAMSequenceDictionary;
import net.sf.samtools.util.StringUtil;
import java.io.File;
import java.util.*;
import java.text.NumberFormat;
import net.sf.picard.util.RExecutor;
import net.sf.picard.util.QualityUtil;
/**
* Tool to collect information about GC bias in the reads in a given BAM file. Computes
* the number of windows (of size specified by WINDOW_SIZE) in the genome at each GC%
* and counts the number of read starts in each GC bin. What is output and plotted is
* the "normalized coverage" in each bin - i.e. the number of reads per window normalized
* to the average number of reads per window across the whole genome.
*
* @author Tim Fennell
*/
public class CollectGcBiasMetrics extends CommandLineProgram {
/** The location of the R script to do the plotting. */
private static final String R_SCRIPT = "net/sf/picard/analysis/gcBias.R";
@Option(shortName=StandardOptionDefinitions.REFERENCE_SHORT_NAME, doc="The reference sequence fasta file.")
public File REFERENCE_SEQUENCE;
@Option(shortName=StandardOptionDefinitions.INPUT_SHORT_NAME, doc="The BAM or SAM file containing aligned reads. " +
"Must be coordinate-sorted.")
public File INPUT;
@Option(shortName=StandardOptionDefinitions.OUTPUT_SHORT_NAME, doc="The text file to write the metrics table to.")
public File OUTPUT;
@Option(shortName="CHART", doc="The PDF file to render the chart to.")
public File CHART_OUTPUT;
@Option(shortName="S", doc="The text file to write summary metrics to.", optional=true)
public File SUMMARY_OUTPUT;
@Option(doc="The size of windows on the genome that are used to bin reads.")
public int WINDOW_SIZE = 100;
@Option(doc="For summary metrics, exclude GC windows that include less than this fraction of the genome.")
public double MINIMUM_GENOME_FRACTION = 0.00001;
@Option(doc="If true, assume that the input file is coordinate sorted, even if the header says otherwise.",
shortName=StandardOptionDefinitions.ASSUME_SORTED_SHORT_NAME)
public boolean ASSUME_SORTED = false;
private static final Log log = Log.getInstance(CollectGcBiasMetrics.class);
// Used to keep track of the total clusters as this is kinda important for bias
private int totalClusters = 0;
private int totalAlignedReads = 0;
/** Stock main method. */
public static void main(final String[] args) {
System.exit(new CollectGcBiasMetrics().instanceMain(args));
}
protected int doWork() {
IoUtil.assertFileIsReadable(REFERENCE_SEQUENCE);
IoUtil.assertFileIsReadable(INPUT);
IoUtil.assertFileIsWritable(OUTPUT);
IoUtil.assertFileIsWritable(CHART_OUTPUT);
if (SUMMARY_OUTPUT != null) IoUtil.assertFileIsWritable(SUMMARY_OUTPUT);
// Histograms to track the number of windows at each GC, and the number of read starts
// at windows of each GC
final int[] windowsByGc = new int[101];
final int[] readsByGc = new int[101];
final long[] basesByGc = new long[101];
final long[] errorsByGc = new long[101];
final SAMFileReader sam = new SAMFileReader(INPUT);
if (!ASSUME_SORTED && sam.getFileHeader().getSortOrder() != SAMFileHeader.SortOrder.coordinate) {
- throw new PicardException("Input file " + INPUT.getAbsolutePath() + " is not coordinate sorted.");
+ throw new PicardException("Header of input file " + INPUT.getAbsolutePath() + " indicates that it is not coordinate sorted. " +
+ "If you believe the records are in coordinate order, pass option ASSUME_SORTED=true. If not, sort the file with SortSam.");
}
final PeekableIterator<SAMRecord> iterator = new PeekableIterator<SAMRecord>(sam.iterator());
final ReferenceSequenceFile referenceFile = ReferenceSequenceFileFactory.getReferenceSequenceFile(REFERENCE_SEQUENCE);
{
// Check that the sequence dictionaries match if present
final SAMSequenceDictionary referenceDictionary= referenceFile.getSequenceDictionary();
final SAMSequenceDictionary samFileDictionary = sam.getFileHeader().getSequenceDictionary();
if (referenceDictionary != null && samFileDictionary != null) {
SequenceUtil.assertSequenceDictionariesEqual(referenceDictionary, samFileDictionary);
}
}
////////////////////////////////////////////////////////////////////////////
// Loop over the reference and the reads and calculate the basic metrics
////////////////////////////////////////////////////////////////////////////
ReferenceSequence ref = null;
while ((ref = referenceFile.nextSequence()) != null) {
final byte[] refBases = ref.getBases();
StringUtil.toUpperCase(refBases);
final int refLength = refBases.length;
final int lastWindowStart = refLength - WINDOW_SIZE;
final byte[] gc = calculateAllGcs(refBases, windowsByGc, lastWindowStart);
while (iterator.hasNext() && iterator.peek().getReferenceIndex() == ref.getContigIndex()) {
final SAMRecord rec = iterator.next();
if (!rec.getReadPairedFlag() || rec.getFirstOfPairFlag()) ++this.totalClusters;
if (!rec.getReadUnmappedFlag()) {
final int pos = rec.getReadNegativeStrandFlag() ? rec.getAlignmentEnd() - WINDOW_SIZE : rec.getAlignmentStart();
++this.totalAlignedReads;
if (pos > 0) {
final int windowGc = gc[pos];
if (windowGc >= 0) {
++readsByGc[windowGc];
basesByGc[windowGc] += rec.getReadLength();
errorsByGc[windowGc] +=
SequenceUtil.countMismatches(rec, refBases) +
SequenceUtil.countInsertedBases(rec) + SequenceUtil.countDeletedBases(rec);
}
}
}
}
log.info("Processed reference sequence: " + ref.getName());
}
// Finish up the reads, presumably all unaligned
while (iterator.hasNext()) {
final SAMRecord rec = iterator.next();
if (!rec.getReadPairedFlag() || rec.getFirstOfPairFlag()) ++this.totalClusters;
}
/////////////////////////////////////////////////////////////////////////////
// Synthesize the normalized coverage metrics and write it all out to a file
/////////////////////////////////////////////////////////////////////////////
final MetricsFile<GcBiasDetailMetrics,?> metricsFile = getMetricsFile();
final double totalWindows = sum(windowsByGc);
final double totalReads = sum(readsByGc);
final double meanReadsPerWindow = totalReads / totalWindows;
final double minimumWindowsToCountInSummary = totalWindows * this.MINIMUM_GENOME_FRACTION;
for (int i=0; i<windowsByGc.length; ++i) {
if (windowsByGc[i] == 0) continue;
GcBiasDetailMetrics m = new GcBiasDetailMetrics();
m.GC = i;
m.WINDOWS = windowsByGc[i];
m.READ_STARTS = readsByGc[i];
if (errorsByGc[i] > 0) m.MEAN_BASE_QUALITY = QualityUtil.getPhredScoreFromObsAndErrors(basesByGc[i], errorsByGc[i]);
m.NORMALIZED_COVERAGE = (m.READ_STARTS / (double) m.WINDOWS) / meanReadsPerWindow;
m.ERROR_BAR_WIDTH = (Math.sqrt(m.READ_STARTS) / (double) m.WINDOWS) / meanReadsPerWindow;
metricsFile.addMetric(m);
}
metricsFile.write(OUTPUT);
// Synthesize the high level metrics
if (SUMMARY_OUTPUT != null) {
final MetricsFile<GcBiasSummaryMetrics,?> summaryMetricsFile = getMetricsFile();
final GcBiasSummaryMetrics summary = new GcBiasSummaryMetrics();
summary.WINDOW_SIZE = this.WINDOW_SIZE;
summary.TOTAL_CLUSTERS = this.totalClusters;
summary.ALIGNED_READS = this.totalAlignedReads;
calculateDropoutMetrics(metricsFile.getMetrics(), summary);
summaryMetricsFile.addMetric(summary);
summaryMetricsFile.write(SUMMARY_OUTPUT);
}
// Plot the results
final NumberFormat fmt = NumberFormat.getIntegerInstance();
fmt.setGroupingUsed(true);
final String subtitle = "Total clusters: " + fmt.format(this.totalClusters) +
", Aligned reads: " + fmt.format(this.totalAlignedReads);
RExecutor.executeFromClasspath(R_SCRIPT,
OUTPUT.getAbsolutePath(),
CHART_OUTPUT.getAbsolutePath(),
INPUT.getName().replace(".duplicates_marked", "").replace(".aligned.bam", ""),
subtitle,
String.valueOf(WINDOW_SIZE));
return 0;
}
/** Sums the values in an int[]. */
private double sum(final int[] values) {
final int length = values.length;
double total = 0;
for (int i=0; i<length; ++i) {
total += values[i];
}
return total;
}
/** Calculates the Illumina style AT and GC dropout numbers. */
private void calculateDropoutMetrics(final Collection<GcBiasDetailMetrics> details,
final GcBiasSummaryMetrics summary) {
// First calculate the totals
double totalReads = 0;
double totalWindows = 0;
for (final GcBiasDetailMetrics detail : details) {
totalReads += detail.READ_STARTS;
totalWindows += detail.WINDOWS;
}
double atDropout = 0;
double gcDropout = 0;
for (final GcBiasDetailMetrics detail : details) {
final double relativeReads = detail.READ_STARTS / totalReads;
final double relativeWindows = detail.WINDOWS / totalWindows;
final double dropout = (relativeWindows - relativeReads) * 100;
if (dropout > 0) {
if (detail.GC <= 50) atDropout += dropout;
if (detail.GC >= 50) gcDropout += dropout;
}
}
summary.AT_DROPOUT = atDropout;
summary.GC_DROPOUT = gcDropout;
}
/** Calculcate all the GC values for all windows. */
private byte[] calculateAllGcs(final byte [] refBases, final int [] windowsByGc, final int lastWindowStart) {
final int refLength = refBases.length;
final byte[] gc = new byte[refLength + 1];
final CalculateGcState state = new CalculateGcState();
for (int i=1; i<lastWindowStart; ++i) {
final int windowEnd = i + WINDOW_SIZE;
final int windowGc = calculateGc(refBases, i, windowEnd, state) ;
gc[i] = (byte) windowGc;
if (windowGc != -1) windowsByGc[windowGc]++;
}
return gc;
}
/**
* Calculates GC as a number from 0 to 100 in the specified window. If the window includes
* more than five no-calls then -1 is returned.
*/
private int calculateGc(final byte[] bases, final int startIndex, final int endIndex, final CalculateGcState state) {
if (state.init) {
state.init = false ;
state.gcCount = 0;
state.nCount = 0;
for (int i=startIndex; i<endIndex; ++i) {
final byte base = bases[i];
if (base == 'G' || base == 'C') ++state.gcCount;
else if (base == 'N') ++state.nCount;
}
} else {
final byte newBase = bases[endIndex-1];
if (newBase == 'G' || newBase == 'C') ++state.gcCount;
else if (newBase == 'N') ++state.nCount;
if (state.priorBase == 'G' || state.priorBase == 'C') --state.gcCount;
else if (state.priorBase == 'N') --state.nCount;
}
state.priorBase = bases[startIndex];
if (state.nCount > 4) return -1;
else return (state.gcCount * 100) / (endIndex - startIndex);
}
/** Keeps track of current GC calculation state. */
class CalculateGcState {
boolean init = true ;
int nCount ;
int gcCount ;
byte priorBase ;
}
}
| true | true | protected int doWork() {
IoUtil.assertFileIsReadable(REFERENCE_SEQUENCE);
IoUtil.assertFileIsReadable(INPUT);
IoUtil.assertFileIsWritable(OUTPUT);
IoUtil.assertFileIsWritable(CHART_OUTPUT);
if (SUMMARY_OUTPUT != null) IoUtil.assertFileIsWritable(SUMMARY_OUTPUT);
// Histograms to track the number of windows at each GC, and the number of read starts
// at windows of each GC
final int[] windowsByGc = new int[101];
final int[] readsByGc = new int[101];
final long[] basesByGc = new long[101];
final long[] errorsByGc = new long[101];
final SAMFileReader sam = new SAMFileReader(INPUT);
if (!ASSUME_SORTED && sam.getFileHeader().getSortOrder() != SAMFileHeader.SortOrder.coordinate) {
throw new PicardException("Input file " + INPUT.getAbsolutePath() + " is not coordinate sorted.");
}
final PeekableIterator<SAMRecord> iterator = new PeekableIterator<SAMRecord>(sam.iterator());
final ReferenceSequenceFile referenceFile = ReferenceSequenceFileFactory.getReferenceSequenceFile(REFERENCE_SEQUENCE);
{
// Check that the sequence dictionaries match if present
final SAMSequenceDictionary referenceDictionary= referenceFile.getSequenceDictionary();
final SAMSequenceDictionary samFileDictionary = sam.getFileHeader().getSequenceDictionary();
if (referenceDictionary != null && samFileDictionary != null) {
SequenceUtil.assertSequenceDictionariesEqual(referenceDictionary, samFileDictionary);
}
}
////////////////////////////////////////////////////////////////////////////
// Loop over the reference and the reads and calculate the basic metrics
////////////////////////////////////////////////////////////////////////////
ReferenceSequence ref = null;
while ((ref = referenceFile.nextSequence()) != null) {
final byte[] refBases = ref.getBases();
StringUtil.toUpperCase(refBases);
final int refLength = refBases.length;
final int lastWindowStart = refLength - WINDOW_SIZE;
final byte[] gc = calculateAllGcs(refBases, windowsByGc, lastWindowStart);
while (iterator.hasNext() && iterator.peek().getReferenceIndex() == ref.getContigIndex()) {
final SAMRecord rec = iterator.next();
if (!rec.getReadPairedFlag() || rec.getFirstOfPairFlag()) ++this.totalClusters;
if (!rec.getReadUnmappedFlag()) {
final int pos = rec.getReadNegativeStrandFlag() ? rec.getAlignmentEnd() - WINDOW_SIZE : rec.getAlignmentStart();
++this.totalAlignedReads;
if (pos > 0) {
final int windowGc = gc[pos];
if (windowGc >= 0) {
++readsByGc[windowGc];
basesByGc[windowGc] += rec.getReadLength();
errorsByGc[windowGc] +=
SequenceUtil.countMismatches(rec, refBases) +
SequenceUtil.countInsertedBases(rec) + SequenceUtil.countDeletedBases(rec);
}
}
}
}
log.info("Processed reference sequence: " + ref.getName());
}
// Finish up the reads, presumably all unaligned
while (iterator.hasNext()) {
final SAMRecord rec = iterator.next();
if (!rec.getReadPairedFlag() || rec.getFirstOfPairFlag()) ++this.totalClusters;
}
/////////////////////////////////////////////////////////////////////////////
// Synthesize the normalized coverage metrics and write it all out to a file
/////////////////////////////////////////////////////////////////////////////
final MetricsFile<GcBiasDetailMetrics,?> metricsFile = getMetricsFile();
final double totalWindows = sum(windowsByGc);
final double totalReads = sum(readsByGc);
final double meanReadsPerWindow = totalReads / totalWindows;
final double minimumWindowsToCountInSummary = totalWindows * this.MINIMUM_GENOME_FRACTION;
for (int i=0; i<windowsByGc.length; ++i) {
if (windowsByGc[i] == 0) continue;
GcBiasDetailMetrics m = new GcBiasDetailMetrics();
m.GC = i;
m.WINDOWS = windowsByGc[i];
m.READ_STARTS = readsByGc[i];
if (errorsByGc[i] > 0) m.MEAN_BASE_QUALITY = QualityUtil.getPhredScoreFromObsAndErrors(basesByGc[i], errorsByGc[i]);
m.NORMALIZED_COVERAGE = (m.READ_STARTS / (double) m.WINDOWS) / meanReadsPerWindow;
m.ERROR_BAR_WIDTH = (Math.sqrt(m.READ_STARTS) / (double) m.WINDOWS) / meanReadsPerWindow;
metricsFile.addMetric(m);
}
metricsFile.write(OUTPUT);
// Synthesize the high level metrics
if (SUMMARY_OUTPUT != null) {
final MetricsFile<GcBiasSummaryMetrics,?> summaryMetricsFile = getMetricsFile();
final GcBiasSummaryMetrics summary = new GcBiasSummaryMetrics();
summary.WINDOW_SIZE = this.WINDOW_SIZE;
summary.TOTAL_CLUSTERS = this.totalClusters;
summary.ALIGNED_READS = this.totalAlignedReads;
calculateDropoutMetrics(metricsFile.getMetrics(), summary);
summaryMetricsFile.addMetric(summary);
summaryMetricsFile.write(SUMMARY_OUTPUT);
}
// Plot the results
final NumberFormat fmt = NumberFormat.getIntegerInstance();
fmt.setGroupingUsed(true);
final String subtitle = "Total clusters: " + fmt.format(this.totalClusters) +
", Aligned reads: " + fmt.format(this.totalAlignedReads);
RExecutor.executeFromClasspath(R_SCRIPT,
OUTPUT.getAbsolutePath(),
CHART_OUTPUT.getAbsolutePath(),
INPUT.getName().replace(".duplicates_marked", "").replace(".aligned.bam", ""),
subtitle,
String.valueOf(WINDOW_SIZE));
return 0;
}
| protected int doWork() {
IoUtil.assertFileIsReadable(REFERENCE_SEQUENCE);
IoUtil.assertFileIsReadable(INPUT);
IoUtil.assertFileIsWritable(OUTPUT);
IoUtil.assertFileIsWritable(CHART_OUTPUT);
if (SUMMARY_OUTPUT != null) IoUtil.assertFileIsWritable(SUMMARY_OUTPUT);
// Histograms to track the number of windows at each GC, and the number of read starts
// at windows of each GC
final int[] windowsByGc = new int[101];
final int[] readsByGc = new int[101];
final long[] basesByGc = new long[101];
final long[] errorsByGc = new long[101];
final SAMFileReader sam = new SAMFileReader(INPUT);
if (!ASSUME_SORTED && sam.getFileHeader().getSortOrder() != SAMFileHeader.SortOrder.coordinate) {
throw new PicardException("Header of input file " + INPUT.getAbsolutePath() + " indicates that it is not coordinate sorted. " +
"If you believe the records are in coordinate order, pass option ASSUME_SORTED=true. If not, sort the file with SortSam.");
}
final PeekableIterator<SAMRecord> iterator = new PeekableIterator<SAMRecord>(sam.iterator());
final ReferenceSequenceFile referenceFile = ReferenceSequenceFileFactory.getReferenceSequenceFile(REFERENCE_SEQUENCE);
{
// Check that the sequence dictionaries match if present
final SAMSequenceDictionary referenceDictionary= referenceFile.getSequenceDictionary();
final SAMSequenceDictionary samFileDictionary = sam.getFileHeader().getSequenceDictionary();
if (referenceDictionary != null && samFileDictionary != null) {
SequenceUtil.assertSequenceDictionariesEqual(referenceDictionary, samFileDictionary);
}
}
////////////////////////////////////////////////////////////////////////////
// Loop over the reference and the reads and calculate the basic metrics
////////////////////////////////////////////////////////////////////////////
ReferenceSequence ref = null;
while ((ref = referenceFile.nextSequence()) != null) {
final byte[] refBases = ref.getBases();
StringUtil.toUpperCase(refBases);
final int refLength = refBases.length;
final int lastWindowStart = refLength - WINDOW_SIZE;
final byte[] gc = calculateAllGcs(refBases, windowsByGc, lastWindowStart);
while (iterator.hasNext() && iterator.peek().getReferenceIndex() == ref.getContigIndex()) {
final SAMRecord rec = iterator.next();
if (!rec.getReadPairedFlag() || rec.getFirstOfPairFlag()) ++this.totalClusters;
if (!rec.getReadUnmappedFlag()) {
final int pos = rec.getReadNegativeStrandFlag() ? rec.getAlignmentEnd() - WINDOW_SIZE : rec.getAlignmentStart();
++this.totalAlignedReads;
if (pos > 0) {
final int windowGc = gc[pos];
if (windowGc >= 0) {
++readsByGc[windowGc];
basesByGc[windowGc] += rec.getReadLength();
errorsByGc[windowGc] +=
SequenceUtil.countMismatches(rec, refBases) +
SequenceUtil.countInsertedBases(rec) + SequenceUtil.countDeletedBases(rec);
}
}
}
}
log.info("Processed reference sequence: " + ref.getName());
}
// Finish up the reads, presumably all unaligned
while (iterator.hasNext()) {
final SAMRecord rec = iterator.next();
if (!rec.getReadPairedFlag() || rec.getFirstOfPairFlag()) ++this.totalClusters;
}
/////////////////////////////////////////////////////////////////////////////
// Synthesize the normalized coverage metrics and write it all out to a file
/////////////////////////////////////////////////////////////////////////////
final MetricsFile<GcBiasDetailMetrics,?> metricsFile = getMetricsFile();
final double totalWindows = sum(windowsByGc);
final double totalReads = sum(readsByGc);
final double meanReadsPerWindow = totalReads / totalWindows;
final double minimumWindowsToCountInSummary = totalWindows * this.MINIMUM_GENOME_FRACTION;
for (int i=0; i<windowsByGc.length; ++i) {
if (windowsByGc[i] == 0) continue;
GcBiasDetailMetrics m = new GcBiasDetailMetrics();
m.GC = i;
m.WINDOWS = windowsByGc[i];
m.READ_STARTS = readsByGc[i];
if (errorsByGc[i] > 0) m.MEAN_BASE_QUALITY = QualityUtil.getPhredScoreFromObsAndErrors(basesByGc[i], errorsByGc[i]);
m.NORMALIZED_COVERAGE = (m.READ_STARTS / (double) m.WINDOWS) / meanReadsPerWindow;
m.ERROR_BAR_WIDTH = (Math.sqrt(m.READ_STARTS) / (double) m.WINDOWS) / meanReadsPerWindow;
metricsFile.addMetric(m);
}
metricsFile.write(OUTPUT);
// Synthesize the high level metrics
if (SUMMARY_OUTPUT != null) {
final MetricsFile<GcBiasSummaryMetrics,?> summaryMetricsFile = getMetricsFile();
final GcBiasSummaryMetrics summary = new GcBiasSummaryMetrics();
summary.WINDOW_SIZE = this.WINDOW_SIZE;
summary.TOTAL_CLUSTERS = this.totalClusters;
summary.ALIGNED_READS = this.totalAlignedReads;
calculateDropoutMetrics(metricsFile.getMetrics(), summary);
summaryMetricsFile.addMetric(summary);
summaryMetricsFile.write(SUMMARY_OUTPUT);
}
// Plot the results
final NumberFormat fmt = NumberFormat.getIntegerInstance();
fmt.setGroupingUsed(true);
final String subtitle = "Total clusters: " + fmt.format(this.totalClusters) +
", Aligned reads: " + fmt.format(this.totalAlignedReads);
RExecutor.executeFromClasspath(R_SCRIPT,
OUTPUT.getAbsolutePath(),
CHART_OUTPUT.getAbsolutePath(),
INPUT.getName().replace(".duplicates_marked", "").replace(".aligned.bam", ""),
subtitle,
String.valueOf(WINDOW_SIZE));
return 0;
}
|
diff --git a/src/com/android/contacts/socialwidget/SocialWidgetProvider.java b/src/com/android/contacts/socialwidget/SocialWidgetProvider.java
index cd6a494b6..dd4431084 100644
--- a/src/com/android/contacts/socialwidget/SocialWidgetProvider.java
+++ b/src/com/android/contacts/socialwidget/SocialWidgetProvider.java
@@ -1,231 +1,235 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.contacts.socialwidget;
import com.android.contacts.ContactLoader;
import com.android.contacts.R;
import com.android.contacts.model.AccountType;
import com.android.contacts.model.AccountTypeManager;
import com.android.contacts.util.ContactBadgeUtil;
import com.android.contacts.util.StreamItemEntry;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.content.Loader;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.net.Uri;
import android.provider.ContactsContract.QuickContact;
import android.provider.ContactsContract.StreamItems;
import android.text.Html;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.StyleSpan;
import android.util.Log;
import android.util.SparseArray;
import android.view.View;
import android.widget.RemoteViews;
import java.util.List;
public class SocialWidgetProvider extends AppWidgetProvider {
private static final String TAG = "SocialWidgetProvider";
/**
* Max length of a snippet that is considered "short" and displayed in
* a separate line.
*/
private static final int SHORT_SNIPPET_LENGTH = 48;
private static SparseArray<ContactLoader> sLoaders = new SparseArray<ContactLoader>();
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
for (int appWidgetId : appWidgetIds) {
Log.d(TAG, "onUpdate called for " + appWidgetId);
}
for (int appWidgetId : appWidgetIds) {
loadWidgetData(context, appWidgetManager, appWidgetId, false);
}
}
@Override
public void onDeleted(Context context, int[] appWidgetIds) {
for (int appWidgetId : appWidgetIds) {
ContactLoader loader = sLoaders.get(appWidgetId);
if (loader != null) {
Log.d(TAG, "Stopping loader for widget with id=" + appWidgetId);
loader.stopLoading();
sLoaders.delete(appWidgetId);
}
}
SocialWidgetSettings.getInstance().remove(context, appWidgetIds);
}
public static void loadWidgetData(final Context context,
final AppWidgetManager appWidgetManager, final int widgetId, boolean forceLoad) {
ContactLoader previousLoader = sLoaders.get(widgetId);
if (previousLoader != null && !forceLoad) {
previousLoader.startLoading();
return;
}
if (previousLoader != null) {
previousLoader.reset();
}
// Show that we are loading
final RemoteViews loadingViews =
new RemoteViews(context.getPackageName(), R.layout.social_widget);
loadingViews.setTextViewText(R.id.name,
context.getString(R.string.social_widget_loading));
loadingViews.setViewVisibility(R.id.name, View.VISIBLE);
loadingViews.setViewVisibility(R.id.name_and_snippet, View.GONE);
appWidgetManager.updateAppWidget(widgetId, loadingViews);
// Load
final Uri contactUri =
SocialWidgetSettings.getInstance().getContactUri(context, widgetId);
if (contactUri == null) {
// Not yet set-up (this can happen while the Configuration activity is visible)
return;
}
final ContactLoader contactLoader = new ContactLoader(context, contactUri, false, true,
false);
contactLoader.registerListener(0,
new ContactLoader.OnLoadCompleteListener<ContactLoader.Result>() {
@Override
public void onLoadComplete(Loader<ContactLoader.Result> loader,
ContactLoader.Result contactData) {
bindRemoteViews(context, widgetId, appWidgetManager, contactData);
}
});
contactLoader.startLoading();
sLoaders.append(widgetId, contactLoader);
}
private static void bindRemoteViews(final Context context, final int widgetId,
final AppWidgetManager widgetManager, ContactLoader.Result contactData) {
Log.d(TAG, "Loaded " + contactData.getLookupKey()
+ " for widget with id=" + widgetId);
final RemoteViews views = new RemoteViews(context.getPackageName(),
R.layout.social_widget);
if (contactData.isError() || contactData == ContactLoader.Result.NOT_FOUND) {
setDisplayNameAndSnippet(context, views,
context.getString(R.string.invalidContactMessage), null, null, null);
setPhoto(views, ContactBadgeUtil.loadPlaceholderPhoto(context));
} else {
byte[] photo = contactData.getPhotoBinaryData();
setPhoto(views, photo != null
? BitmapFactory.decodeByteArray(photo, 0, photo.length)
: ContactBadgeUtil.loadPlaceholderPhoto(context));
// TODO: Rotate between all the stream items?
// OnClick launch QuickContact
final Intent intent = new Intent(QuickContact.ACTION_QUICK_CONTACT);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
intent.setData(contactData.getLookupUri());
intent.putExtra(QuickContact.EXTRA_MODE, QuickContact.MODE_SMALL);
final PendingIntent pendingIntent = PendingIntent.getActivity(context,
0, intent, 0);
views.setOnClickPendingIntent(R.id.border, pendingIntent);
setDisplayNameAndSnippet(context, views, contactData.getDisplayName(),
contactData.getPhoneticName(), contactData.getStreamItems(), pendingIntent);
}
// Configure UI
widgetManager.updateAppWidget(widgetId, views);
}
private static void setPhoto(RemoteViews views, Bitmap photo) {
views.setImageViewBitmap(R.id.image, photo);
}
/**
* Set the display name, phonetic name and the social snippet.
*/
private static void setDisplayNameAndSnippet(Context context, RemoteViews views,
CharSequence displayName, CharSequence phoneticName,
List<StreamItemEntry> streamItems, PendingIntent defaultIntent) {
SpannableStringBuilder sb = new SpannableStringBuilder();
CharSequence name = displayName;
// If there is no display name, use the default missing name string
if (TextUtils.isEmpty(name)) {
name = context.getString(R.string.missing_name);
}
if (!TextUtils.isEmpty(phoneticName)) {
name = context.getString(R.string.widget_name_and_phonetic,
name, phoneticName);
}
sb.append(name);
AbsoluteSizeSpan sizeSpan = new AbsoluteSizeSpan(
context.getResources().getDimensionPixelSize(R.dimen.widget_text_size_name));
StyleSpan styleSpan = new StyleSpan(Typeface.BOLD);
sb.setSpan(sizeSpan, 0, name.length(), 0);
sb.setSpan(styleSpan, 0, name.length(), 0);
if (streamItems == null || streamItems.isEmpty()) {
views.setTextViewText(R.id.name, sb);
views.setViewVisibility(R.id.name, View.VISIBLE);
views.setViewVisibility(R.id.name_and_snippet, View.GONE);
- views.setOnClickPendingIntent(R.id.widget_container, defaultIntent);
+ // Don't set a pending intent if the intent is null, otherwise the system will try
+ // to write the null intent to a Parcel.
+ if (defaultIntent != null) {
+ views.setOnClickPendingIntent(R.id.widget_container, defaultIntent);
+ }
} else {
// TODO: Rotate between all the stream items?
StreamItemEntry streamItem = streamItems.get(0);
CharSequence status = Html.fromHtml(streamItem.getText());
if (status.length() <= SHORT_SNIPPET_LENGTH) {
sb.append("\n");
} else {
sb.append(" ");
}
sb.append(status);
views.setTextViewText(R.id.name_and_snippet, sb);
views.setViewVisibility(R.id.name, View.GONE);
views.setViewVisibility(R.id.name_and_snippet, View.VISIBLE);
final AccountTypeManager manager = AccountTypeManager.getInstance(context);
final AccountType accountType =
manager.getAccountType(streamItem.getAccountType(), streamItem.getDataSet());
if (accountType.getViewStreamItemActivity() != null) {
final Uri uri = ContentUris.withAppendedId(StreamItems.CONTENT_URI,
streamItem.getId());
final Intent intent = new Intent(Intent.ACTION_VIEW, uri);
intent.setClassName(accountType.resPackageName,
accountType.getViewStreamItemActivity());
views.setOnClickPendingIntent(R.id.name_and_snippet_container,
PendingIntent.getActivity(context, 0, intent, 0));
}
}
}
}
| true | true | private static void setDisplayNameAndSnippet(Context context, RemoteViews views,
CharSequence displayName, CharSequence phoneticName,
List<StreamItemEntry> streamItems, PendingIntent defaultIntent) {
SpannableStringBuilder sb = new SpannableStringBuilder();
CharSequence name = displayName;
// If there is no display name, use the default missing name string
if (TextUtils.isEmpty(name)) {
name = context.getString(R.string.missing_name);
}
if (!TextUtils.isEmpty(phoneticName)) {
name = context.getString(R.string.widget_name_and_phonetic,
name, phoneticName);
}
sb.append(name);
AbsoluteSizeSpan sizeSpan = new AbsoluteSizeSpan(
context.getResources().getDimensionPixelSize(R.dimen.widget_text_size_name));
StyleSpan styleSpan = new StyleSpan(Typeface.BOLD);
sb.setSpan(sizeSpan, 0, name.length(), 0);
sb.setSpan(styleSpan, 0, name.length(), 0);
if (streamItems == null || streamItems.isEmpty()) {
views.setTextViewText(R.id.name, sb);
views.setViewVisibility(R.id.name, View.VISIBLE);
views.setViewVisibility(R.id.name_and_snippet, View.GONE);
views.setOnClickPendingIntent(R.id.widget_container, defaultIntent);
} else {
// TODO: Rotate between all the stream items?
StreamItemEntry streamItem = streamItems.get(0);
CharSequence status = Html.fromHtml(streamItem.getText());
if (status.length() <= SHORT_SNIPPET_LENGTH) {
sb.append("\n");
} else {
sb.append(" ");
}
sb.append(status);
views.setTextViewText(R.id.name_and_snippet, sb);
views.setViewVisibility(R.id.name, View.GONE);
views.setViewVisibility(R.id.name_and_snippet, View.VISIBLE);
final AccountTypeManager manager = AccountTypeManager.getInstance(context);
final AccountType accountType =
manager.getAccountType(streamItem.getAccountType(), streamItem.getDataSet());
if (accountType.getViewStreamItemActivity() != null) {
final Uri uri = ContentUris.withAppendedId(StreamItems.CONTENT_URI,
streamItem.getId());
final Intent intent = new Intent(Intent.ACTION_VIEW, uri);
intent.setClassName(accountType.resPackageName,
accountType.getViewStreamItemActivity());
views.setOnClickPendingIntent(R.id.name_and_snippet_container,
PendingIntent.getActivity(context, 0, intent, 0));
}
}
}
| private static void setDisplayNameAndSnippet(Context context, RemoteViews views,
CharSequence displayName, CharSequence phoneticName,
List<StreamItemEntry> streamItems, PendingIntent defaultIntent) {
SpannableStringBuilder sb = new SpannableStringBuilder();
CharSequence name = displayName;
// If there is no display name, use the default missing name string
if (TextUtils.isEmpty(name)) {
name = context.getString(R.string.missing_name);
}
if (!TextUtils.isEmpty(phoneticName)) {
name = context.getString(R.string.widget_name_and_phonetic,
name, phoneticName);
}
sb.append(name);
AbsoluteSizeSpan sizeSpan = new AbsoluteSizeSpan(
context.getResources().getDimensionPixelSize(R.dimen.widget_text_size_name));
StyleSpan styleSpan = new StyleSpan(Typeface.BOLD);
sb.setSpan(sizeSpan, 0, name.length(), 0);
sb.setSpan(styleSpan, 0, name.length(), 0);
if (streamItems == null || streamItems.isEmpty()) {
views.setTextViewText(R.id.name, sb);
views.setViewVisibility(R.id.name, View.VISIBLE);
views.setViewVisibility(R.id.name_and_snippet, View.GONE);
// Don't set a pending intent if the intent is null, otherwise the system will try
// to write the null intent to a Parcel.
if (defaultIntent != null) {
views.setOnClickPendingIntent(R.id.widget_container, defaultIntent);
}
} else {
// TODO: Rotate between all the stream items?
StreamItemEntry streamItem = streamItems.get(0);
CharSequence status = Html.fromHtml(streamItem.getText());
if (status.length() <= SHORT_SNIPPET_LENGTH) {
sb.append("\n");
} else {
sb.append(" ");
}
sb.append(status);
views.setTextViewText(R.id.name_and_snippet, sb);
views.setViewVisibility(R.id.name, View.GONE);
views.setViewVisibility(R.id.name_and_snippet, View.VISIBLE);
final AccountTypeManager manager = AccountTypeManager.getInstance(context);
final AccountType accountType =
manager.getAccountType(streamItem.getAccountType(), streamItem.getDataSet());
if (accountType.getViewStreamItemActivity() != null) {
final Uri uri = ContentUris.withAppendedId(StreamItems.CONTENT_URI,
streamItem.getId());
final Intent intent = new Intent(Intent.ACTION_VIEW, uri);
intent.setClassName(accountType.resPackageName,
accountType.getViewStreamItemActivity());
views.setOnClickPendingIntent(R.id.name_and_snippet_container,
PendingIntent.getActivity(context, 0, intent, 0));
}
}
}
|
diff --git a/pluginsource/org/enigma/EnigmaRunner.java b/pluginsource/org/enigma/EnigmaRunner.java
index d4ee010e..ceeb4059 100644
--- a/pluginsource/org/enigma/EnigmaRunner.java
+++ b/pluginsource/org/enigma/EnigmaRunner.java
@@ -1,456 +1,458 @@
/*
* Copyright (C) 2008, 2009 IsmAvatar <[email protected]>
*
* This file is part of Enigma Plugin.
*
* Enigma Plugin is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Enigma Plugin is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License (COPYING) for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.enigma;
import java.awt.Graphics;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JLayeredPane;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import org.enigma.backend.EnigmaStruct;
import org.enigma.backend.EnigmaStruct.SyntaxError;
import org.lateralgm.components.impl.CustomFileFilter;
import org.lateralgm.components.impl.ResNode;
import org.lateralgm.components.mdi.MDIFrame;
import org.lateralgm.main.LGM;
import org.lateralgm.resources.Resource;
import org.lateralgm.resources.Script;
import org.lateralgm.subframes.ScriptFrame;
import org.lateralgm.subframes.SubframeInformer;
import org.lateralgm.subframes.SubframeInformer.SubframeListener;
import com.sun.jna.StringArray;
public class EnigmaRunner implements ActionListener,SubframeListener
{
public static final String ENIGMA = "compileEGMf.exe";
public EnigmaFrame ef;
public JMenuItem run, debug, build, compile;
public EnigmaRunner()
{
populateMenu();
populateTree();
SubframeInformer.addSubframeListener(this);
applyBackground("org/enigma/enigma.png");
attemptUpdate();
System.out.print("Initializing Enigma: ");
int ret = EnigmaStruct.libInit();
System.out.println(ret == 0 ? "Done" : "Error " + ret);
//TODO: add whitespace support
EnigmaStruct.whitespaceModified("");
}
public void populateMenu()
{
JMenu menu = new JMenu("Enigma");
run = new JMenuItem("Run");
run.addActionListener(this);
menu.add(run);
debug = new JMenuItem("Debug");
debug.addActionListener(this);
menu.add(debug);
build = new JMenuItem("Build");
build.addActionListener(this);
menu.add(build);
compile = new JMenuItem("Compile");
compile.addActionListener(this);
menu.add(compile);
LGM.frame.getJMenuBar().add(menu,1);
}
public void populateTree()
{
EnigmaGroup node = new EnigmaGroup();
LGM.root.add(node);
node.add(new EnigmaNode("Whitespace"));
node.add(new EnigmaNode("Enigma Init"));
node.add(new EnigmaNode("Enigma Term"));
LGM.tree.updateUI();
}
public void applyBackground(String bgloc)
{
ImageIcon bg = findIcon(bgloc);
LGM.mdi.add(new MDIBackground(bg),JLayeredPane.FRAME_CONTENT_LAYER);
}
public void attemptUpdate()
{
try
{
EnigmaUpdater.checkForUpdates();
}
/**
* Usually you shouldn't catch an Error, however,
* in this case we catch it to abort the module,
* rather than allowing the failed module to cause
* the entire program/plugin to fail
*/
catch (NoClassDefFoundError e)
{
String error = "SvnKit missing, corrupted, or unusable. Please download and "
+ "place next to the enigma plugin in order to enable auto-update.";
System.err.println(error);
}
}
public class MDIBackground extends JComponent
{
private static final long serialVersionUID = 1L;
ImageIcon image;
public MDIBackground(ImageIcon icon)
{
image = icon;
if (image == null) return;
if (image.getIconWidth() <= 0) image = null;
}
public int getWidth()
{
return LGM.mdi.getWidth();
}
public int getHeight()
{
return LGM.mdi.getHeight();
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
if (image == null) return;
for (int y = 0; y < getHeight(); y += image.getIconHeight())
for (int x = 0; x < getWidth(); x += image.getIconWidth())
g.drawImage(image.getImage(),x,y,null);
}
}
public class EnigmaGroup extends ResNode
{
private static final long serialVersionUID = 1L;
public EnigmaGroup()
{
super("Enigma",ResNode.STATUS_PRIMARY,Resource.Kind.SCRIPT);
}
public void showMenu(MouseEvent e)
{
//No menu
}
public DataFlavor[] getTransferDataFlavors()
{
return null;
}
public boolean isDataFlavorSupported(DataFlavor flavor)
{
return false;
}
public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException
{
throw new UnsupportedFlavorException(flavor);
}
}
public class EnigmaNode extends ResNode implements ActionListener
{
private static final long serialVersionUID = 1L;
private JPopupMenu pm;
public EnigmaNode(String name)
{
super(name,ResNode.STATUS_SECONDARY,Resource.Kind.SCRIPT);
pm = new JPopupMenu();
pm.add(new JMenuItem("Edit")).addActionListener(this);
}
public void openFrame()
{
System.out.println("You can has " + getUserObject());
}
public void showMenu(MouseEvent e)
{
pm.show(e.getComponent(),e.getX(),e.getY());
}
public void actionPerformed(ActionEvent e)
{
openFrame();
}
public DataFlavor[] getTransferDataFlavors()
{
return null;
}
public boolean isDataFlavorSupported(DataFlavor flavor)
{
return false;
}
public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException
{
throw new UnsupportedFlavorException(flavor);
}
}
public String findEnigma(String expected)
{
File f = new File(expected);
if (f.exists()) return f.getAbsolutePath();
f = new File(LGM.workDir.getParent(),"plugins");
if (!f.exists()) f = new File(LGM.workDir.getParent(),"Plugins");
f = new File(f,expected);
if (f.exists()) return f.getAbsolutePath();
f = new File(System.getProperty("user.dir"),expected);
if (f.exists()) return f.getAbsolutePath();
f = new File(System.getProperty("user.home"));
if (!new File(f,expected).exists()) f = new File(f,"Desktop");
f = new File(f,expected);
if (f.exists()) return f.getAbsolutePath();
f = new File(f.getParent(),"plugins");
if (!f.exists()) f = new File(f.getParent(),"Plugins");
f = new File(f,expected);
if (f.exists()) return f.getAbsolutePath();
System.err.println("Unable to locate Enigma");
return null;
}
public void compile(final byte mode)
{
//modes: 0=run, 1=debug, 2=build, 3=compile
//determine where to output the exe
File exef = null;
try
{
if (mode < 2)
exef = File.createTempFile("egm",".exe");
else if (mode == 2) exef = File.createTempFile("egm",".emd");
if (exef != null) exef.deleteOnExit();
}
catch (IOException e)
{
e.printStackTrace();
return;
}
if (mode == 3)
{
JFileChooser fc = new JFileChooser();
fc.setFileFilter(new CustomFileFilter(".exe","Executable files"));
if (fc.showSaveDialog(LGM.frame) != JFileChooser.APPROVE_OPTION) return;
exef = fc.getSelectedFile();
}
LGM.commitAll();
// ef = new EnigmaFrame();
// System.out.println("Compiling with " + enigma);
EnigmaStruct es = EnigmaWriter.prepareStruct(LGM.currentFile);
System.out.println(EnigmaStruct.compileEGMf(es,exef.getAbsolutePath(),mode));
if (mode == 2)
{
try
{
EnigmaReader.readChanges(exef);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
public static SyntaxError checkSyntax(String code)
{
String osl[] = new String[LGM.currentFile.scripts.size()];
Script isl[] = LGM.currentFile.scripts.toArray(new Script[0]);
for (int i = 0; i < osl.length; i++)
osl[i] = isl[i].getName();
return EnigmaStruct.syntaxCheck(osl.length,new StringArray(osl),code);
/*
File sf = null;
try
{
sf = File.createTempFile("egm",".egm");
sf.deleteOnExit();
BufferedWriter f = new BufferedWriter(new FileWriter(sf));
f.write('1');
f.newLine();
for (Script scr : LGM.currentFile.scripts)
f.write(scr.getName() + ",");
f.newLine();
f.write(code);
f.close();
}
catch (IOException e)
{
e.printStackTrace();
if (sf != null) sf.delete();
return -1;
}
String path = "compileEGMf.exe";
File fi = new File(path);
if (!fi.exists()) path = System.getProperty("user.dir") + File.separator + path;
if (!new File(path).exists())
{
JOptionPane.showMessageDialog(null,"Unable to locate Enigma for Syntax Check");
sf.delete();
return -1;
}
if (!new File(path).equals(fi))
System.out.println(fi.getAbsolutePath() + " not found. Attempting " + path);
else
System.out.println("Checking syntax with " + fi.getAbsolutePath());
int r = -1;
try
{
Process p = Runtime.getRuntime().exec("\"" + path + "\" -s syntax.txt");
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
String output = "";
while ((line = input.readLine()) != null)
if (line.length() > 0) output += line + "\n";
input.close();
r = p.waitFor();
if (r != -1) JOptionPane.showMessageDialog(null,output);
}
catch (Exception e)
{
e.printStackTrace();
}
sf.delete();
return r;
*/}
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == run)
{
compile((byte) 1);
}
if (e.getSource() == debug)
{
compile((byte) 2);
}
if (e.getSource() == build)
{
compile((byte) 3);
}
if (e.getSource() == compile)
{
compile((byte) 4);
}
}
public void subframeAppeared(MDIFrame source)
{
if (!(source instanceof ScriptFrame)) return;
final ScriptFrame sf = (ScriptFrame) source;
JButton syntaxCheck;
ImageIcon i = findIcon("syntax.png");
if (i == null)
syntaxCheck = new JButton("Syntax");
else
{
syntaxCheck = new JButton(i);
syntaxCheck.setToolTipText("Syntax");
}
syntaxCheck.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
SyntaxError se = checkSyntax(sf.code.getText());
+ int max = sf.code.getDocumentLength() - 1;
+ if (se.absoluteIndex > max) se.absoluteIndex = max;
if (se.absoluteIndex != -1) //-1 = no error
{
sf.code.setSelectionStart(se.absoluteIndex);
sf.code.setSelectionEnd(se.absoluteIndex + 1);
//TODO: Statusbar with error message
}
}
});
sf.tool.add(syntaxCheck,5);
}
public ImageIcon findIcon(String loc)
{
ImageIcon ico = new ImageIcon(loc);
if (ico.getIconWidth() != -1) return ico;
URL url = this.getClass().getClassLoader().getResource(loc);
if (url != null) ico = new ImageIcon(url);
if (ico.getIconWidth() != -1) return ico;
loc = "org/enigma/" + loc;
ico = new ImageIcon(loc);
if (ico.getIconWidth() != -1) return ico;
url = this.getClass().getClassLoader().getResource(loc);
if (url != null) ico = new ImageIcon(url);
return ico;
}
public boolean subframeRequested(Resource<?,?> res, ResNode node)
{
return false;
}
public static void main(String[] args)
{
LGM.main(args);
new EnigmaRunner();
}
}
| true | true | public static SyntaxError checkSyntax(String code)
{
String osl[] = new String[LGM.currentFile.scripts.size()];
Script isl[] = LGM.currentFile.scripts.toArray(new Script[0]);
for (int i = 0; i < osl.length; i++)
osl[i] = isl[i].getName();
return EnigmaStruct.syntaxCheck(osl.length,new StringArray(osl),code);
/*
File sf = null;
try
{
sf = File.createTempFile("egm",".egm");
sf.deleteOnExit();
BufferedWriter f = new BufferedWriter(new FileWriter(sf));
f.write('1');
f.newLine();
for (Script scr : LGM.currentFile.scripts)
f.write(scr.getName() + ",");
f.newLine();
f.write(code);
f.close();
}
catch (IOException e)
{
e.printStackTrace();
if (sf != null) sf.delete();
return -1;
}
String path = "compileEGMf.exe";
File fi = new File(path);
if (!fi.exists()) path = System.getProperty("user.dir") + File.separator + path;
if (!new File(path).exists())
{
JOptionPane.showMessageDialog(null,"Unable to locate Enigma for Syntax Check");
sf.delete();
return -1;
}
if (!new File(path).equals(fi))
System.out.println(fi.getAbsolutePath() + " not found. Attempting " + path);
else
System.out.println("Checking syntax with " + fi.getAbsolutePath());
int r = -1;
try
{
Process p = Runtime.getRuntime().exec("\"" + path + "\" -s syntax.txt");
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
String output = "";
while ((line = input.readLine()) != null)
if (line.length() > 0) output += line + "\n";
input.close();
r = p.waitFor();
if (r != -1) JOptionPane.showMessageDialog(null,output);
}
catch (Exception e)
{
e.printStackTrace();
}
sf.delete();
return r;
*/}
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == run)
{
compile((byte) 1);
}
if (e.getSource() == debug)
{
compile((byte) 2);
}
if (e.getSource() == build)
{
compile((byte) 3);
}
if (e.getSource() == compile)
{
compile((byte) 4);
}
}
public void subframeAppeared(MDIFrame source)
{
if (!(source instanceof ScriptFrame)) return;
final ScriptFrame sf = (ScriptFrame) source;
JButton syntaxCheck;
ImageIcon i = findIcon("syntax.png");
if (i == null)
syntaxCheck = new JButton("Syntax");
else
{
syntaxCheck = new JButton(i);
syntaxCheck.setToolTipText("Syntax");
}
syntaxCheck.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
SyntaxError se = checkSyntax(sf.code.getText());
if (se.absoluteIndex != -1) //-1 = no error
{
sf.code.setSelectionStart(se.absoluteIndex);
sf.code.setSelectionEnd(se.absoluteIndex + 1);
//TODO: Statusbar with error message
}
}
});
sf.tool.add(syntaxCheck,5);
}
public ImageIcon findIcon(String loc)
{
ImageIcon ico = new ImageIcon(loc);
if (ico.getIconWidth() != -1) return ico;
URL url = this.getClass().getClassLoader().getResource(loc);
if (url != null) ico = new ImageIcon(url);
if (ico.getIconWidth() != -1) return ico;
loc = "org/enigma/" + loc;
ico = new ImageIcon(loc);
if (ico.getIconWidth() != -1) return ico;
url = this.getClass().getClassLoader().getResource(loc);
if (url != null) ico = new ImageIcon(url);
return ico;
}
public boolean subframeRequested(Resource<?,?> res, ResNode node)
{
return false;
}
public static void main(String[] args)
{
LGM.main(args);
new EnigmaRunner();
}
}
| public static SyntaxError checkSyntax(String code)
{
String osl[] = new String[LGM.currentFile.scripts.size()];
Script isl[] = LGM.currentFile.scripts.toArray(new Script[0]);
for (int i = 0; i < osl.length; i++)
osl[i] = isl[i].getName();
return EnigmaStruct.syntaxCheck(osl.length,new StringArray(osl),code);
/*
File sf = null;
try
{
sf = File.createTempFile("egm",".egm");
sf.deleteOnExit();
BufferedWriter f = new BufferedWriter(new FileWriter(sf));
f.write('1');
f.newLine();
for (Script scr : LGM.currentFile.scripts)
f.write(scr.getName() + ",");
f.newLine();
f.write(code);
f.close();
}
catch (IOException e)
{
e.printStackTrace();
if (sf != null) sf.delete();
return -1;
}
String path = "compileEGMf.exe";
File fi = new File(path);
if (!fi.exists()) path = System.getProperty("user.dir") + File.separator + path;
if (!new File(path).exists())
{
JOptionPane.showMessageDialog(null,"Unable to locate Enigma for Syntax Check");
sf.delete();
return -1;
}
if (!new File(path).equals(fi))
System.out.println(fi.getAbsolutePath() + " not found. Attempting " + path);
else
System.out.println("Checking syntax with " + fi.getAbsolutePath());
int r = -1;
try
{
Process p = Runtime.getRuntime().exec("\"" + path + "\" -s syntax.txt");
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
String output = "";
while ((line = input.readLine()) != null)
if (line.length() > 0) output += line + "\n";
input.close();
r = p.waitFor();
if (r != -1) JOptionPane.showMessageDialog(null,output);
}
catch (Exception e)
{
e.printStackTrace();
}
sf.delete();
return r;
*/}
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == run)
{
compile((byte) 1);
}
if (e.getSource() == debug)
{
compile((byte) 2);
}
if (e.getSource() == build)
{
compile((byte) 3);
}
if (e.getSource() == compile)
{
compile((byte) 4);
}
}
public void subframeAppeared(MDIFrame source)
{
if (!(source instanceof ScriptFrame)) return;
final ScriptFrame sf = (ScriptFrame) source;
JButton syntaxCheck;
ImageIcon i = findIcon("syntax.png");
if (i == null)
syntaxCheck = new JButton("Syntax");
else
{
syntaxCheck = new JButton(i);
syntaxCheck.setToolTipText("Syntax");
}
syntaxCheck.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
SyntaxError se = checkSyntax(sf.code.getText());
int max = sf.code.getDocumentLength() - 1;
if (se.absoluteIndex > max) se.absoluteIndex = max;
if (se.absoluteIndex != -1) //-1 = no error
{
sf.code.setSelectionStart(se.absoluteIndex);
sf.code.setSelectionEnd(se.absoluteIndex + 1);
//TODO: Statusbar with error message
}
}
});
sf.tool.add(syntaxCheck,5);
}
public ImageIcon findIcon(String loc)
{
ImageIcon ico = new ImageIcon(loc);
if (ico.getIconWidth() != -1) return ico;
URL url = this.getClass().getClassLoader().getResource(loc);
if (url != null) ico = new ImageIcon(url);
if (ico.getIconWidth() != -1) return ico;
loc = "org/enigma/" + loc;
ico = new ImageIcon(loc);
if (ico.getIconWidth() != -1) return ico;
url = this.getClass().getClassLoader().getResource(loc);
if (url != null) ico = new ImageIcon(url);
return ico;
}
public boolean subframeRequested(Resource<?,?> res, ResNode node)
{
return false;
}
public static void main(String[] args)
{
LGM.main(args);
new EnigmaRunner();
}
}
|
diff --git a/src/free/jin/freechess/JinFreechessConnection.java b/src/free/jin/freechess/JinFreechessConnection.java
index 77bf357..1ac04f4 100644
--- a/src/free/jin/freechess/JinFreechessConnection.java
+++ b/src/free/jin/freechess/JinFreechessConnection.java
@@ -1,2885 +1,2885 @@
/**
* Jin - a chess client for internet chess servers.
* More information is available at http://www.jinchess.com/.
* Copyright (C) 2002, 2003 Alexander Maryanovsky.
* All rights reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package free.jin.freechess;
import free.chess.*;
import free.chess.variants.BothSidesCastlingVariant;
import free.chess.variants.NoCastlingVariant;
import free.chess.variants.atomic.Atomic;
import free.chess.variants.bughouse.Bughouse;
import free.chess.variants.fischerrandom.FischerRandom;
import free.chess.variants.suicide.Suicide;
import free.chessclub.ChessclubConnection;
import free.freechess.*;
import free.jin.*;
import free.jin.event.*;
import free.jin.freechess.event.IvarStateChangeEvent;
import free.util.Pair;
import free.util.TextUtilities;
import javax.swing.*;
import java.io.IOException;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* An implementation of the JinConnection interface for the freechess.org
* server.
*/
public class JinFreechessConnection extends FreechessConnection implements Connection,
SeekConnection, PGNConnection, ChannelsConnection, MessagesConnection, BughouseConnection{
//TODO add implementation of FreechessChannelsConnection.
//TODO add methods and regular expressions to handle channel list events.
/**
* Overrides getConnectionName() method returning name of connection. whp 2006
*/
public String getConnectionName(){
return "FreechessConnection";
}
/**
* Boolean indicating whether this connection's method waits for game info from
* processing line about examined game.
*/
private boolean waiting = false;
/**
* The examined game Style12Struct.
*/
private Style12Struct examinedGameBoardData;
/**
* The number of examined game we are willing to gather information about.
*/
private int examinedGameId;
/**
* The variant of examined game.
*/
private String examinedGameVariant;
/**
* Boolean telling whether examined game is rated.
*/
private boolean isExaminedRated;
/**
* Boolean telling whether examined game is private.
*/
private boolean isExaminedPrivate;
/**
* Our listener manager.
*/
private final FreechessListenerManager listenerManager = new FreechessListenerManager(this);
/**
* Creates a new JinFreechessConnection with the specified hostname, port,
* requested username and password.
*/
public JinFreechessConnection(String requestedUsername, String password){
super(requestedUsername, password, System.out);
setInterface(Jin.getInstance().getAppName() + ' ' + Jin.getInstance().getAppVersion() +
" (" + System.getProperty("java.vendor") + ' ' + System.getProperty("java.version") +
", " + System.getProperty("os.name") + ' ' + getSafeOSVersion() + ')');
setStyle(12);
setIvarState(Ivar.GAMEINFO, true);
setIvarState(Ivar.SHOWOWNSEEK, true);
setIvarState(Ivar.PENDINFO, true);
setIvarState(Ivar.MOVECASE, true);
// setIvarState(Ivar.COMPRESSMOVE, true); Pending DAV's bugfixing spree
setIvarState(Ivar.LOCK, true);
}
/**
* <code>sendCommand()</code> method overriden
* to get rid of bug [ 1642877 ] Non-channel numbers list pass to channel manager
*/
public void sendCommand(String command){
super.sendCommand(command);
userChannelListNext = false;
}
/**
* Returns the OS version after stripping out the patch level from it.
* We do this to avoid revealing that information to everyone on the server.
*/
private static String getSafeOSVersion(){
String osVersion = System.getProperty("os.version");
int i = osVersion.indexOf(".", osVersion.indexOf(".") + 1);
if (i != -1)
osVersion = osVersion.substring(0, i) + ".x";
return osVersion;
}
/**
* Returns a Player object corresponding to the specified string. If the
* string is "W", returns <code>Player.WHITE</code>. If it's "B", returns
* <code>Player.BLACK</code>. Otherwise, throws an IllegalArgumentException.
*/
public static Player playerForString(String s){
if (s.equals("B"))
return Player.BLACK_PLAYER;
else if (s.equals("W"))
return Player.WHITE_PLAYER;
else
throw new IllegalArgumentException("Bad player string: "+s);
}
/**
* Returns our ListenerManager.
*/
public ListenerManager getListenerManager(){
return getFreechessListenerManager();
}
/**
* Returns out ListenerManager as a reference to FreechessListenerManager.
*/
public FreechessListenerManager getFreechessListenerManager(){
return listenerManager;
}
/**
* Fires an "attempting" connection event and invokes {@link free.util.Connection#initiateConnect(String, int)}.
*/
public void initiateConnectAndLogin(String hostname, int port){
listenerManager.fireConnectionAttempted(this, hostname, port);
initiateConnect(hostname, port);
}
/**
* Fires an "established" connection event.
*/
protected void handleConnected(){
listenerManager.fireConnectionEstablished(this);
super.handleConnected();
}
/**
* Fires a "failed" connection event.
*/
protected void handleConnectingFailed(IOException e){
listenerManager.fireConnectingFailed(this, e.getMessage());
super.handleConnectingFailed(e);
}
/**
* Fires a "login succeeded" connection event and performs other on-login tasks.
*/
protected void handleLoginSucceeded(){
super.handleLoginSucceeded();
sendCommand("$set bell 0");
filterLine("Bell off.");
listenerManager.fireLoginSucceeded(this);
}
/**
* Fires a "login failed" connection event.
*/
protected void handleLoginFailed(String reason){
listenerManager.fireLoginFailed(this, reason);
super.handleLoginFailed(reason);
}
/**
* Fires a "connection lost" connection event.
*/
protected void handleDisconnection(IOException e){
listenerManager.fireConnectionLost(this);
super.handleDisconnection(e);
}
/**
* Overrides {@link free.util.Connection#connectImpl(String, int)} to return a timesealing socket.
*/
protected Socket connectImpl(String hostname, int port) throws IOException{
// Comment this to disable timesealing
return new free.freechess.timeseal.TimesealingSocket(hostname, port);
// Comment this to enable timesealing
// return new Socket(hostname, port);
}
/**
* Notifies any interested PlainTextListener of the received line of otherwise
* unidentified text.
*/
protected void processLine(String line){
listenerManager.firePlainTextEvent(new PlainTextEvent(this, line));
}
/**
* Gets called when the server notifies us of a change in the state of some
* ivar.
*/
protected boolean processIvarStateChanged(Ivar ivar, boolean state){
IvarStateChangeEvent evt = new IvarStateChangeEvent(this, ivar, state);
listenerManager.fireIvarStateChangeEvent(evt);
return false;
}
/**
* Fires an appropriate ChatEvent.
*/
protected boolean processPersonalTell(String username, String titles, String message){
listenerManager.fireChatEvent(new ChatEvent(this, "tell", ChatEvent.PERSON_TO_PERSON_CHAT_CATEGORY,
username, (titles == null ? "" : titles), -1, message, null));
return true;
}
/**
* Fires an appropriate ChatEvent.
*/
protected boolean processSayTell(String username, String titles, int gameNumber, String message){
listenerManager.fireChatEvent(new ChatEvent(this, "say", ChatEvent.PERSON_TO_PERSON_CHAT_CATEGORY,
username, (titles == null ? "" : titles), -1, message, new Integer(gameNumber)));
return true;
}
/**
* Fires an appropriate ChatEvent.
*/
protected boolean processPTell(String username, String titles, String message){
listenerManager.fireChatEvent(new ChatEvent(this, "ptell", ChatEvent.PERSON_TO_PERSON_CHAT_CATEGORY,
username, (titles == null ? "" : titles), -1, message, null));
return true;
}
/**
* Fires an appropriate ChatEvent.
*/
protected boolean processChannelTell(String username, String titles, int channelNumber,
String message){
listenerManager.fireChatEvent(new ChatEvent(this, "channel-tell", ChatEvent.ROOM_CHAT_CATEGORY,
username, (titles == null ? "" : titles), -1, message, new Integer(channelNumber)));
return true;
}
/**
* Fires an appropriate ChatEvent.
*/
protected boolean processKibitz(String username, String titles, int rating, int gameNumber,
String message){
if (titles == null)
titles = "";
listenerManager.fireChatEvent(new ChatEvent(this, "kibitz", ChatEvent.GAME_CHAT_CATEGORY,
username, titles, rating, message, new Integer(gameNumber)));
return true;
}
/**
* Fires an appropriate ChatEvent.
*/
protected boolean processWhisper(String username, String titles, int rating, int gameNumber,
String message){
if (titles == null)
titles = "";
listenerManager.fireChatEvent(new ChatEvent(this, "whisper", ChatEvent.GAME_CHAT_CATEGORY,
username, titles, rating, message, new Integer(gameNumber)));
return true;
}
/**
* Regex for matching tourney tell qtells.
*/
private static final Pattern TOURNEY_TELL_REGEX =
Pattern.compile("^("+USERNAME_REGEX+")("+TITLES_REGEX+")?\\(T(\\d+)\\): (.*)");
/**
* Fires an appropriate ChatEvent.
*/
protected boolean processQTell(String message){
ChatEvent evt;
Matcher matcher = TOURNEY_TELL_REGEX.matcher(message);
if (matcher.matches()){
String sender = matcher.group(1);
String title = matcher.group(2);
if (title == null)
title = "";
Integer tourneyIndex = new Integer(matcher.group(3));
message = matcher.group(4);
evt = new ChatEvent(this, "qtell.tourney", ChatEvent.TOURNEY_CHAT_CATEGORY,
sender, title, -1, message, tourneyIndex);
}
else{
evt = new ChatEvent(this, "qtell", ChatEvent.PERSON_TO_PERSON_CHAT_CATEGORY,
null, null, -1, message, null);
}
listenerManager.fireChatEvent(evt);
return true;
}
/**
* Fires an appropriate ChatEvent.
*/
protected boolean processShout(String username, String titles, String message){
listenerManager.fireChatEvent(new ChatEvent(this, "shout", ChatEvent.ROOM_CHAT_CATEGORY,
username, (titles == null ? "" : titles), -1, message, null));
return true;
}
/**
* Fires an appropriate ChatEvent.
*/
protected boolean processIShout(String username, String titles, String message){
listenerManager.fireChatEvent(new ChatEvent(this, "ishout", ChatEvent.ROOM_CHAT_CATEGORY,
username, (titles == null ? "" : titles), -1, message, null));
return true;
}
/**
* Fires an appropriate ChatEvent.
*/
protected boolean processTShout(String username, String titles, String message){
listenerManager.fireChatEvent(new ChatEvent(this, "tshout", ChatEvent.TOURNEY_CHAT_CATEGORY,
username, (titles == null ? "" : titles), -1, message, null));
return true;
}
/**
* Fires an appropriate ChatEvent.
*/
protected boolean processCShout(String username, String titles, String message){
listenerManager.fireChatEvent(new ChatEvent(this, "cshout", ChatEvent.ROOM_CHAT_CATEGORY,
username, (titles == null ? "" : titles), -1, message, null));
return true;
}
/**
* Fires an appropriate ChatEvent.
*/
protected boolean processAnnouncement(String username, String message){
listenerManager.fireChatEvent(new ChatEvent(this, "announcement", ChatEvent.BROADCAST_CHAT_CATEGORY,
username, "", -1, message, null));
return true;
}
/**
* Fires an appropriate ChannelsEvent.
*/
protected boolean processChannelListChanged(String change, int channelNumber){
if (change.equals("added")){
int[] channelsNumbers = {999};
listenerManager.fireChannelsEvent(new ChannelsEvent(this, ChannelsEvent.CHANNEL_ADDED, channelNumber, channelsNumbers));
}
if (change.equals("removed")){
int[] channelsNumbers = {999};
listenerManager.fireChannelsEvent(new ChannelsEvent(this, ChannelsEvent.CHANNEL_REMOVED, channelNumber, channelsNumbers));
}
return false;
}
/**
* Field that states wether next line is user's channel list.
*/
boolean userChannelListNext = true;
/**
* Assures wether the next line is user's channel list.
*/
protected boolean processUserChannelListNext(String userName){
if (!userName.equals(Jin.getInstance().getConnManager().getSession().getUser().getUsername())){
this.userChannelListNext = false;
}
else{
this.userChannelListNext = true;
}
if (userName.equals("ok")){
this.userChannelListNext = true;
}
else{
this.userChannelListNext = false;
}
if (!this.fromPlugin){
return false;
}
else {
return true;
}
}
/**
* Fires an appropriate @{link}ChannelsEvent.
*/
protected boolean processChannelListArrives(String channelsNumbers){
//System.out.println(">>>USER_CHANNEL_LIST_NEXT = " + this.userChannelListNext);
if (userChannelListNext == false){
return false;
}
else{
int channelNumber = 999;
String[] channelsNumbersStrings = channelsNumbers.split("\\s{1,4}");
int[] channels = new int[channelsNumbersStrings.length];
for (int i = 0; i < channelsNumbersStrings.length; i++){
//System.out.println("#" + i + " CHANNEL = " + channelsNumbersStrings[i]);
channels[i] = Integer.parseInt(channelsNumbersStrings[i]);
}
listenerManager.fireChannelsEvent(new ChannelsEvent(this, ChannelsEvent.USER_CHANNEL_LIST_RECEIVED, channelNumber, channels));
//this.userChannelListNext = false;
}
if (this.fromPlugin == false){
return false;
}
else {
return true;
}
}
/**
* Fires an appropriate @{link}MessageEvent (the one with information about unread messages number).
*/
protected boolean processMessagesInfo(int allMessages, int unreadMessages){
System.out.println("YOU HAVE UNREAD MESSAGES. " + unreadMessages + " that is.");
return false;
}
/**
* Fires an appropriate @{link}MessageEvent (message's content, sender, date and number in messages list).
*/
protected boolean processMessages(int number, String user, String date, String content){
System.out.println("Message received:" + content);
return false;
}
/*;
* Returns the wild variant corresponding to the given server wild variant
* name/category name, or <code>null</code> if that category is not supported.
*/
private static WildVariant getVariant(String categoryName){
if (categoryName.equalsIgnoreCase("lightning") ||
categoryName.equalsIgnoreCase("blitz") ||
categoryName.equalsIgnoreCase("standard") ||
categoryName.equalsIgnoreCase("untimed"))
return Chess.getInstance();
if (categoryName.startsWith("wild/")){
String wildId = categoryName.substring("wild/".length());
if (wildId.equals("0") || wildId.equals("1"))
return new BothSidesCastlingVariant(Chess.INITIAL_POSITION_FEN, categoryName);
else if (wildId.equals("2") || wildId.equals("3"))
return new NoCastlingVariant(Chess.INITIAL_POSITION_FEN, categoryName);
else if (wildId.equals("5") || wildId.equals("8") || wildId.equals("8a"))
return new ChesslikeGenericVariant(Chess.INITIAL_POSITION_FEN, categoryName);
else if (wildId.equals("fr"))
return FischerRandom.getInstance();
}
else if (categoryName.equals("pawns/pawns-only"))
return new ChesslikeGenericVariant(Chess.INITIAL_POSITION_FEN, categoryName);
else if (categoryName.equals("nonstandard"))
return new ChesslikeGenericVariant(Chess.INITIAL_POSITION_FEN, categoryName);
else if (categoryName.equals("suicide"))
return Suicide.getInstance();
else if (categoryName.equals("losers"))
return new ChesslikeGenericVariant(Chess.INITIAL_POSITION_FEN, categoryName);
else if (categoryName.equals("atomic"))
return Atomic.getInstance();
else if (categoryName.equals("bughouse") || categoryName.equals("crazyhouse")){
return Bughouse.getInstance();
}
// This means it's a fake variant we're using because the server hasn't told us the real one.
else if (categoryName.equals("Unknown variant"))
return Chess.getInstance();
return null;
}
/**
* Returns the wild variant name corresponding to the specified wild variant,
* that can be used for issuing a seek, e.g. "w1" or "fr".
* Returns null if the specified wild variant is not supported by FICS.
*/
private String getWildName(WildVariant variant){
if (variant == null)
throw new IllegalArgumentException("Null variant");
String variantName = variant.getName();
if (variantName.startsWith("wild/"))
return "w" + variantName.substring("wild/".length());
else if (variant.equals(Chess.getInstance()))
return "";
else if (variant.equals(FischerRandom.getInstance()))
return "fr";
else if (variant.equals(Suicide.getInstance()))
return "suicide";
else if (variant.equals(Atomic.getInstance()))
return "atomic";
else if ("losers".equals(variantName))
return "losers";
else if (variantName.startsWith("uwild"))
return "uwild" + variantName.substring("uwild".length());
else if (variantName.startsWith("pawns"))
return "pawns" + variantName.substring("pawns".length());
else if (variantName.startsWith("odds"))
return "odds" + variantName.substring("odds".length());
else if (variantName.startsWith("misc"))
return "misc" + variantName.substring("misc".length());
else if (variantName.startsWith("openings"))
return "openings" + variantName.substring("openings".length());
return null;
}
/**
* A list of supported wild variants, initialized lazily.
*/
private static WildVariant [] wildVariants;
//TODO: Describe all the variants
/**
* Returns a list of support wild variants.
*/
public WildVariant [] getSupportedVariants(){
if (wildVariants == null){
wildVariants = new WildVariant[]{
Chess.getInstance(),
FischerRandom.getInstance(),
Suicide.getInstance(),
Atomic.getInstance(),
new ChesslikeGenericVariant(Chess.INITIAL_POSITION_FEN, "losers"),
new BothSidesCastlingVariant(Chess.INITIAL_POSITION_FEN, "wild/0"),
new BothSidesCastlingVariant(Chess.INITIAL_POSITION_FEN, "wild/1"),
new NoCastlingVariant(Chess.INITIAL_POSITION_FEN, "wild/2"),
new NoCastlingVariant(Chess.INITIAL_POSITION_FEN, "wild/3"),
new ChesslikeGenericVariant(Chess.INITIAL_POSITION_FEN, "wild/5"),
new ChesslikeGenericVariant(Chess.INITIAL_POSITION_FEN, "wild/8"),
new ChesslikeGenericVariant(Chess.INITIAL_POSITION_FEN, "wild/8a"),
new ChesslikeGenericVariant(Chess.INITIAL_POSITION_FEN, "misc little-game"),
new ChesslikeGenericVariant(Chess.INITIAL_POSITION_FEN, "pawns pawns-only"),
new ChesslikeGenericVariant(Chess.INITIAL_POSITION_FEN, "odds"),
new ChesslikeGenericVariant(Chess.INITIAL_POSITION_FEN, "openings"),
new ChesslikeGenericVariant(Chess.INITIAL_POSITION_FEN, "uwild"),
};
}
return (WildVariant [])wildVariants.clone();
}
/**
* A HashMap where we keep game numbers mapped to GameInfoStruct objects
* of games that haven't started yet.
*/
private final HashMap unstartedGamesData = new HashMap(1);
/**
* Maps game numbers to InternalGameData objects of ongoing games.
*/
private final HashMap ongoingGamesData = new HashMap(5);
/**
* A HashMap mapping Game objects to ArrayLists of moves which were sent for
* these games but the server didn't tell us yet whether the move is legal
* or not.
*/
private final HashMap unechoedMoves = new HashMap(1);
/**
* A list of game numbers of ongoing games which we can't support for some
* reason (not a supported variant for example).
*/
private final ArrayList unsupportedGames = new ArrayList();
/**
* The user's primary played (by the user) game, -1 if unknown. This is only
* set when the user is playing more than one game.
*/
private int primaryPlayedGame = -1;
/**
* The user's primary observed game, -1 if unknown. This is only set when
* the user is observing more than one game.
*/
private int primaryObservedGame = -1;
/**
* Returns the game with the specified number.
* This method (currently) exists solely for the benefit of the arrow/circle
* script.
*/
public Game getGame(int gameNumber) throws NoSuchGameException{
return getGameData(gameNumber).game;
}
/**
* Returns the InternalGameData for the ongoing game with the specified
* number. Throws a <code>NoSuchGameException</code> if there's no such game.
*/
private InternalGameData getGameData(int gameNumber) throws NoSuchGameException{
InternalGameData gameData = (InternalGameData)ongoingGamesData.get(new Integer(gameNumber));
if (gameData == null)
throw new NoSuchGameException();
return gameData;
}
/**
* Finds the (primary) game played by the user. Throws a
* <code>NoSuchGameException</code> if there's no such game.
*/
private InternalGameData findMyGame() throws NoSuchGameException{
if (primaryPlayedGame != -1)
return getGameData(primaryPlayedGame);
Iterator gameNumbers = ongoingGamesData.keySet().iterator();
while (gameNumbers.hasNext()){
Integer gameNumber = (Integer)gameNumbers.next();
InternalGameData gameData = (InternalGameData)ongoingGamesData.get(gameNumber);
Game game = gameData.game;
if (game.getGameType() == Game.MY_GAME)
return gameData;
}
throw new NoSuchGameException();
}
/**
* Finds the played user's game against the specified opponent.
* Returns the game number of null if no such game exists.
*/
private InternalGameData findMyGameAgainst(String playerName) throws NoSuchGameException{
Iterator gameNumbers = ongoingGamesData.keySet().iterator();
while (gameNumbers.hasNext()){
Integer gameNumber = (Integer)gameNumbers.next();
InternalGameData gameData = (InternalGameData)ongoingGamesData.get(gameNumber);
Game game = gameData.game;
Player userPlayer = game.getUserPlayer();
if (userPlayer == null) // Not our game or not played
continue;
Player oppPlayer = userPlayer.getOpponent();
if ((oppPlayer.isWhite() && game.getWhiteName().equals(playerName)) ||
(oppPlayer.isBlack() && game.getBlackName().equals(playerName)))
return gameData;
}
throw new NoSuchGameException();
}
/**
* Saves the GameInfoStruct until we receive enough info to fire a
* GameStartEvent.
*/
protected boolean processGameInfo(GameInfoStruct data){
unstartedGamesData.put(new Integer(data.getGameNumber()), data);
return true;
}
/**
* Fires an appropriate GameEvent depending on the situation.
*/
@Override
protected boolean processStyle12(Style12Struct boardData){
Integer gameNumber = new Integer(boardData.getGameNumber());
InternalGameData gameData = (InternalGameData)ongoingGamesData.get(gameNumber);
GameInfoStruct unstartedGameInfo = (GameInfoStruct)unstartedGamesData.remove(gameNumber);
if (unstartedGameInfo != null) // A new game
gameData = startGame(unstartedGameInfo, boardData);
else if (gameData != null){ // A known game
Style12Struct oldBoardData = gameData.boardData;
int plyDifference = boardData.getPlayedPlyCount() - oldBoardData.getPlayedPlyCount();
if (plyDifference < 0)
tryIssueTakeback(gameData, boardData);
else if (plyDifference == 0){
if (!oldBoardData.getBoardFEN().equals(boardData.getBoardFEN()))
changePosition(gameData, boardData);
// This happens if you:
// 1. Issue "refresh".
// 2. Make an illegal move, because the server will re-send us the board
// (although we don't need it)
// 3. Issue board setup commands.
// 4. Use "wname" or "bname" to change the names of the white or black
// players.
}
else if (plyDifference == 1){
if (boardData.getMoveVerbose() != null)
makeMove(gameData, boardData);
else
changePosition(gameData, boardData);
// This shouldn't happen, but I'll leave it just in case
}
else if (plyDifference > 1){
changePosition(gameData, boardData);
// This happens if you:
// 1. Issue "forward" with an argument of 2 or bigger.
}
}
else if (!unsupportedGames.contains(gameNumber)){
// Grr, the server started a game without sending us a GameInfo line.
// Currently happens if you start examining a game (26.08.2002), or
// doing "refresh <game>" (04.07.2004).
//TODO: Implement getting info for starting examined game
this.waiting = true;
askForMoreGameInfo(boardData.getGameNumber(), boardData);
// We have no choice but to fake the data, since the server simply doesn't
// send us this information.
}
if (gameData != null)
updateGame(gameData, boardData);
return true;
}
/**
* Method that process info about examined game.
* @param gameNr
* @param gameCategory
* @return
*/
protected boolean processExaminedGameInfo(int gameNr, String gameCategory) {
Style12Struct boardData = this.examinedGameBoardData;
InternalGameData gameData = (InternalGameData)ongoingGamesData.get(gameNr);
if (this.examinedGameId == gameNr){
String[] category = parseExaminedGameCategory(gameCategory);
System.out.println("CATEGORY STRING = " + category[0]);
this.examinedGameVariant = category[0];
if (category[1].equals("rated")){
this.isExaminedRated = true;
}else{
this.isExaminedRated = false;
}
System.out.println("RATED? = " + this.isExaminedRated);
System.out.println("THIRD IN CATEGORY = " + category[2]);
if (category[2].length() != 0){
this.isExaminedPrivate = true;
}
GameInfoStruct fakeGameInfo = new GameInfoStruct(boardData.getGameNumber(),
this.isExaminedPrivate, this.examinedGameVariant, this.isExaminedRated, false, false, boardData.getInitialTime(),
boardData.getIncrement(), boardData.getInitialTime(), boardData.getIncrement(),
0, -1, ' ', -1, ' ', false, false);
gameData = startGame(fakeGameInfo, boardData);
if (gameData != null){
updateGame(gameData, boardData);
}
this.waiting = false;
}
return false;
}
/**
* Method that parses through category string of examined game.
* @param s
* @return array of strings that is further processed
*/
private String[] parseExaminedGameCategory(String s) {
String[] categories = new String[3];
switch(s.charAt(s.length()-1)){
case 'r': categories[1] = "rated";
break;
case 'u': categories[1] = "unrated";
break;
}
switch(s.charAt(s.length()-2)){
case 's': categories[0] = "standard";
break;
case 'b': categories[0] = "blitz";
break;
case 'l': categories[0] = "lightning";
break;
case 'w': categories[0] = "wild";
break;
case 'x': categories[0] = "atomic";
break;
case 'B': categories[0] = "bughouse";
break;
case 'z': categories[0] = "crazyhouse";
break;
case 'L': categories[0] = "losers";
break;
case 'S': categories[0] = "suicide";
break;
case 'n': categories[0] = "nonstandard";
break;
default: categories[0] = "unknown";
}
if (s.length()>2){
categories[2] = "private";
}else {
categories[2] = "";
}
return categories;
}
/**
* Method that sends to server question for more info about game with specified number.
*/
private void askForMoreGameInfo(int gameNumber, Style12Struct boardData) {
this.examinedGameId = gameNumber;
this.examinedGameBoardData = boardData;
this.sendCommFromPlugin("games " + String.valueOf(gameNumber));
}
/**
* Processes a delta-board. Instead of actually handing the delta-board, this
* method, instead, creates a Style12Struct object and then asks
* <code>processStyle12</code> to handle it.
*/
protected boolean processDeltaBoard(DeltaBoardStruct data){
Integer gameNumber = new Integer(data.getGameNumber());
InternalGameData gameData = (InternalGameData)ongoingGamesData.get(gameNumber);
Game game = gameData.game;
if (game.getVariant() != Chess.getInstance())
throw new IllegalStateException("delta-boards should only be sent for regular chess");
Style12Struct lastBoardData = gameData.boardData;
ArrayList moveList = gameData.moveList;
Position pos = game.getInitialPosition();
for (int i = 0; i < moveList.size(); i++)
pos.makeMove((Move)moveList.get(i));
ChessMove move = (ChessMove)(Move.parseWarrenSmith(data.getMoveSmith(), pos, data.getMoveAlgebraic()));
Square startSquare = move.getStartingSquare();
ChessPiece movingPiece = (ChessPiece)((startSquare == null) ? null : pos.getPieceAt(startSquare));
pos.makeMove(move);
String boardLexigraphic = pos.getLexigraphic();
String currentPlayer = pos.getCurrentPlayer().isWhite() ? "W" : "B";
int doublePawnPushFile = move.getDoublePawnPushFile();
boolean kingMoved = movingPiece.isKing();
boolean canWhiteCastleKingside =
lastBoardData.canWhiteCastleKingside() && !kingMoved && !Square.getInstance(7, 0).equals(startSquare);
boolean canWhiteCastleQueenside =
lastBoardData.canBlackCastleQueenside() && !kingMoved && !Square.getInstance(0, 0).equals(startSquare);
boolean canBlackCastleKingside =
lastBoardData.canBlackCastleKingside() && !kingMoved && !Square.getInstance(7, 7).equals(startSquare);
boolean canBlackCastleQueenside =
lastBoardData.canBlackCastleQueenside() && !kingMoved && !Square.getInstance(0, 7).equals(startSquare);
boolean isIrreversibleMove = movingPiece.isPawn() || move.isCapture() ||
(canWhiteCastleKingside != lastBoardData.canWhiteCastleKingside()) ||
(canWhiteCastleQueenside != lastBoardData.canWhiteCastleQueenside()) ||
(canBlackCastleKingside != lastBoardData.canBlackCastleKingside()) ||
(canBlackCastleQueenside != lastBoardData.canBlackCastleQueenside());
int pliesSinceIrreversible = isIrreversibleMove ? 0 : lastBoardData.getPliesSinceIrreversible() + 1;
String whiteName = lastBoardData.getWhiteName();
String blackName = lastBoardData.getBlackName();
int gameType = lastBoardData.getGameType();
boolean isPlayedGame = lastBoardData.isPlayedGame();
boolean isMyTurn = pos.getCurrentPlayer() == game.getUserPlayer();
int initTime = lastBoardData.getInitialTime();
int inc = lastBoardData.getIncrement();
int whiteStrength = calcStrength(pos, Player.WHITE_PLAYER);
int blackStrength = calcStrength(pos, Player.BLACK_PLAYER);
int whiteTime = pos.getCurrentPlayer().isBlack() ? data.getRemainingTime() : lastBoardData.getWhiteTime();
int blackTime = pos.getCurrentPlayer().isWhite() ? data.getRemainingTime() : lastBoardData.getBlackTime();
int nextMoveNumber = lastBoardData.getNextMoveNumber() + (pos.getCurrentPlayer().isWhite() ? 1 : 0);
String moveVerbose = createVerboseMove(pos, move);
String moveSAN = data.getMoveAlgebraic();
int moveTime = data.getTakenTime();
boolean isBoardFlipped = lastBoardData.isBoardFlipped();
boolean isClockRunning = true;
int lag = 0; // The server doesn't currently send us this information
Style12Struct boardData = new Style12Struct(boardLexigraphic, currentPlayer, doublePawnPushFile,
canWhiteCastleKingside, canWhiteCastleQueenside, canBlackCastleKingside, canBlackCastleQueenside,
pliesSinceIrreversible, gameNumber.intValue(), whiteName, blackName, gameType, isPlayedGame,
isMyTurn, initTime, inc, whiteStrength, blackStrength, whiteTime, blackTime, nextMoveNumber,
moveVerbose, moveSAN, moveTime, isBoardFlipped, isClockRunning, lag);
processStyle12(boardData);
return true;
}
/**
* Calculates the material strength of the specified player in the specified
* position.
*/
private static int calcStrength(Position pos, Player player){
int count = 0;
for (int i = 0; i < 8; i++){
for (int j = 0; j < 8; j++){
ChessPiece piece = (ChessPiece)(pos.getPieceAt(i, j));
if ((piece != null) && (piece.getPlayer() == player)){
if (piece.isPawn())
count += 1;
else if (piece.isBishop())
count += 3;
else if (piece.isKnight())
count += 3;
else if (piece.isRook())
count += 5;
else if (piece.isQueen())
count += 9;
else if (piece.isKing())
count += 0;
}
}
}
return count;
}
/**
* Creates a verbose representation of the specified move in the specified
* position. The move has already been made in the position.
*/
private static String createVerboseMove(Position pos, ChessMove move){
if (move.isShortCastling())
return "o-o";
else if (move.isLongCastling())
return "o-o-o";
else{
ChessPiece piece = (ChessPiece)pos.getPieceAt(move.getEndingSquare());
String moveVerbose = piece.toShortString() + '/' + move.getStartingSquare() + '-' + move.getEndingSquare();
if (move.isPromotion())
return moveVerbose + '=' + move.getPromotionTarget().toShortString();
else
return moveVerbose;
}
}
/**
* Changes the bsetup state of the game.
*/
protected boolean processBSetupMode(boolean entered){
try{
findMyGame().isBSetup = entered;
} catch (NoSuchGameException e){}
return super.processBSetupMode(entered);
}
/**
* Sends command to server saying to clear messages from messageFromNumber to
* messageToNumber. If both numbers are set to zeros then all messages are cleared.
* If you pass invalid values to this method's params it will do nothing.
* @param messageFromNumber - message to start from
* @param messageToNumber - message to end with
*/
public void clearMessage(int messageFromNumber, int messageToNumber) {
if (messageFromNumber == 0 && messageToNumber == 0 ){
sendCommand("clearmessages *");
return;
}
else if (messageFromNumber == messageToNumber){
sendCommand("clearmessages " + String.valueOf(messageToNumber));
return;
}
else if (messageFromNumber < messageToNumber){
sendCommand("clearmessages " + String.valueOf(messageFromNumber) + "-" + String.valueOf(messageToNumber));
return;
}
else{return;}
}
/**
* Sends command to server for getting messages from messageFromNumber to
* messageToNumber. If both numbers are set to zeros then this method calls for all
* messages from server.
* @param messageFromNumber - message number to start from
* @param messageToNumber - message number to end with
*/
public void getMessages(int messageFromNumber, int messageToNumber) {
if (messageFromNumber == 0 && messageToNumber == 0){
sendCommand("messages");
return;
}
else if (messageFromNumber == messageToNumber){
sendCommand("messages " + String.valueOf(messageToNumber));
return;
}
else if (messageFromNumber < messageToNumber){
sendCommand("messages " + String.valueOf(messageFromNumber) + "-" + String.valueOf(messageToNumber));
return;
}
else{return;}
}
/**
* A small class for keeping internal data about a game.
*/
private static class InternalGameData{
/**
* The Game object representing the game.
*/
public final Game game;
/**
* A list of Moves done in the game.
*/
public ArrayList moveList = new ArrayList();
/**
* The last Style12Struct we got for this game.
*/
public Style12Struct boardData = null;
/**
* Is this game in bsetup mode?
*/
public boolean isBSetup = false;
/**
* Maps offer indices to offers. Offers are Pairs where the first element
* is the <code>Player</code> who made the offer and the 2nd is the offer
* id. Takeback offers are kept separately.
*/
public final HashMap indicesToOffers = new HashMap();
/**
* Maps takeback offer indices to takeback offers. Takeback offers are Pairs
* where the first element is the <code>Player</code> who made the offer
* and the 2nd is an <code>Integer</code> specifying the amount of plies
* offered to take back.
*/
public final HashMap indicesToTakebackOffers = new HashMap();
/**
* Works as a set of the offers currently in this game. The elements are
* Pairs in which the first item is the <code>Player</code> who made the
* offer and the second one is the offer id. Takeback offers are kept
* separately.
*/
private final HashMap offers = new HashMap();
/**
* The number of plies the white player offerred to takeback.
*/
private int whiteTakeback;
/**
* The number of plies the black player offerred to takeback.
*/
private int blackTakeback;
/**
* Creates a new InternalGameData.
*/
public InternalGameData(Game game){
this.game = game;
}
/**
* Returns the amount of moves made in the game (as far as we counted).
*/
public int getMoveCount(){
return moveList.size();
}
/**
* Adds the specified move to the moves list.
*/
public void addMove(Move move){
moveList.add(move);
}
/**
* Removes the last <code>count</code> moves from the movelist, if possible.
* Otherwise, throws an <code>IllegalArgumentException</code>.
*/
public void removeLastMoves(int count){
if (count > moveList.size())
throw new IllegalArgumentException("Can't remove more elements than there are elements");
int first = moveList.size() - 1;
int last = moveList.size() - count;
for (int i = first; i >= last; i--)
moveList.remove(i);
}
/**
* Removes all the moves made in the game.
*/
public void clearMoves(){
moveList.clear();
}
/**
* Returns true if the specified offer is currently made by the specified
* player in this game.
*/
public boolean isOffered(int offerId, Player player){
return offers.containsKey(new Pair(player, new Integer(offerId)));
}
/**
* Sets the state of the specified offer in the game. Takeback offers are
* handled by the setTakebackCount method.
*/
public void setOffer(int offerId, Player player, boolean isMade){
Pair offer = new Pair(player, new Integer(offerId));
if (isMade)
offers.put(offer, offer);
else
offers.remove(offer);
}
/**
* Sets the takeback offer in the game to the specified amount of plies.
*/
public void setTakebackOffer(Player player, int plies){
if (player.isWhite())
whiteTakeback = plies;
else
blackTakeback = plies;
}
/**
* Returns the amount of plies offered to take back by the specified player.
*/
public int getTakebackOffer(Player player){
if (player.isWhite())
return whiteTakeback;
else
return blackTakeback;
}
}
/**
* Changes the primary played game.
*/
protected boolean processSimulCurrentBoardChanged(int gameNumber, String oppName){
primaryPlayedGame = gameNumber;
return true;
}
/**
* Changes the primary observed game.
*/
protected boolean processPrimaryGameChanged(int gameNumber){
primaryObservedGame = gameNumber;
return true;
}
/**
* Method that processes information about available pieces for players in Bughouse game.
* Eventually it fire apopriate BughouseEvent
* @param gameNumber
* @param whiteAvailablePieces
* @param blackAvailablePieces
* @return
*/
protected boolean processBughouseHoldings(int gameNumber, String whiteAvailablePieces, String blackAvailablePieces) {
//System.out.println(">>>BUGHOUSE event occured with data: " + gameNumber + whiteAvailablePieces + blackAvailablePieces);
listenerManager.fireBughouseEvent(new BughouseEvent(this, gameNumber, whiteAvailablePieces, blackAvailablePieces));
return true;
}
/**
* Invokes <code>closeGame(int)</code>.
*/
//TODO review and make it smarter. Involves changing Game and GameEvent (Not sure
// about that.
protected boolean processGameEnd(int gameNumber, String whiteName, String blackName,
String reason, String result){
int resultCode;
if ("1-0".equals(result))
resultCode = Game.WHITE_WINS;
else if ("0-1".equals(result))
resultCode = Game.BLACK_WINS;
else if ("1/2-1/2".equals(result))
resultCode = Game.DRAW;
else
resultCode = Game.UNKNOWN_RESULT;
closeGame(gameNumber, resultCode);
return false;
}
/**
* Invokes <code>closeGame(int)</code>.
*/
protected boolean processStoppedObserving(int gameNumber){
closeGame(gameNumber, Game.UNKNOWN_RESULT);
return false;
}
/**
* Invokes <code>closeGame(int)</code>.
*/
protected boolean processStoppedExamining(int gameNumber){
closeGame(gameNumber, Game.UNKNOWN_RESULT);
return false;
}
/**
* Invokes <code>illegalMoveAttempted</code>.
*/
protected boolean processIllegalMove(String moveString, String reason){
illegalMoveAttempted(moveString);
return false;
}
/**
* Called when a new game is starting. Responsible for creating the game on
* the client side and firing appropriate events. Returns an InternalGameData
* instance for the newly created Game.
*/
private InternalGameData startGame(GameInfoStruct gameInfo, Style12Struct boardData){
String categoryName = gameInfo.getGameCategory();
WildVariant variant = getVariant(categoryName);
if (variant == null){
String starsPad = TextUtilities.padStart("", '*', categoryName.length()+2);
String spacePad = TextUtilities.padStart("", ' ', categoryName.length()+1) + '*';
processLine("********************************************************" + starsPad);
processLine("* This version of Tonic does not support the wild variant " + categoryName + " *");
processLine("* and is thus unable to display the game. " + spacePad);
processLine("* Please use the appropriate command to close the game. " + spacePad);
processLine("********************************************************" + starsPad);
unsupportedGames.add(new Integer(gameInfo.getGameNumber()));
return null;
}
int gameType;
switch (boardData.getGameType()){
case Style12Struct.MY_GAME: gameType = Game.MY_GAME; break;
case Style12Struct.OBSERVED_GAME: gameType = Game.OBSERVED_GAME; break;
case Style12Struct.ISOLATED_BOARD: gameType = Game.ISOLATED_BOARD; break;
default:
throw new IllegalArgumentException("Bad game type value: "+boardData.getGameType());
}
Position initPos = new Position(variant);
initPos.setFEN(boardData.getBoardFEN());
String whiteName = boardData.getWhiteName();
String blackName = boardData.getBlackName();
int whiteTime = 1000 * gameInfo.getWhiteTime();
int blackTime = 1000 * gameInfo.getBlackTime();
int whiteInc = 1000 * gameInfo.getWhiteInc();
int blackInc = 1000 * gameInfo.getBlackInc();
int whiteRating = gameInfo.isWhiteRegistered() ? -1 : gameInfo.getWhiteRating();
int blackRating = gameInfo.isBlackRegistered() ? -1 : gameInfo.getBlackRating();
String gameID = String.valueOf(gameInfo.getGameNumber());
boolean isRated = gameInfo.isGameRated();
boolean isPlayed = boardData.isPlayedGame();
String whiteTitles = "";
String blackTitles = "";
boolean initiallyFlipped = boardData.isBoardFlipped();
Player currentPlayer = playerForString(boardData.getCurrentPlayer());
Player userPlayer = null;
if ((gameType == Game.MY_GAME) && isPlayed)
userPlayer = boardData.isMyTurn() ? currentPlayer : currentPlayer.getOpponent();
Game game = new Game(gameType, initPos, boardData.getPlayedPlyCount(), whiteName, blackName,
whiteTime, whiteInc, blackTime, blackInc, whiteRating, blackRating, gameID, categoryName,
isRated, isPlayed, whiteTitles, blackTitles, initiallyFlipped, userPlayer);
InternalGameData gameData = new InternalGameData(game);
ongoingGamesData.put(new Integer(gameInfo.getGameNumber()), gameData);
listenerManager.fireGameEvent(new GameStartEvent(this, game));
// The server doesn't send us seek remove lines during games, so we have
// no choice but to remove *all* seeks during a game. The seeks are restored
// when a game ends by setting seekinfo to 1 again.
if (gameType == Game.MY_GAME)
removeAllSeeks();
return gameData;
}
/**
* Updates any game parameters that differ in the board data from the current
* game data.
*/
private void updateGame(InternalGameData gameData, Style12Struct boardData){
Game game = gameData.game;
Style12Struct oldBoardData = gameData.boardData;
updateClocks(gameData, boardData); // Update the clocks
// Flip board
if ((oldBoardData != null) && (oldBoardData.isBoardFlipped() != boardData.isBoardFlipped()))
flipBoard(gameData, boardData);
game.setWhiteName(boardData.getWhiteName()); // Change white name
game.setBlackName(boardData.getBlackName()); // Change black name
game.setWhiteTime(1000 * boardData.getInitialTime()); // Change white's initial time
game.setWhiteInc(1000 * boardData.getIncrement()); // Change white's increment
game.setBlackTime(1000 * boardData.getInitialTime()); // Change black's initial time
game.setBlackInc(1000 * boardData.getIncrement()); // Change black's increment
gameData.boardData = boardData;
}
/**
* Gets called when a move is made. Fires an appropriate MoveMadeEvent.
*/
private void makeMove(InternalGameData gameData, Style12Struct boardData){
Game game = gameData.game;
Style12Struct oldBoardData = gameData.boardData;
String moveVerbose = boardData.getMoveVerbose();
String moveSAN = boardData.getMoveSAN();
String currentPlayerName = boardData.getMovingPlayerName();
WildVariant variant = game.getVariant();
Position position = new Position(variant);
position.setLexigraphic(oldBoardData.getBoardLexigraphic());
Player currentPlayer = playerForString(oldBoardData.getCurrentPlayer());
position.setCurrentPlayer(currentPlayer);
Move move;
Square fromSquare, toSquare;
Piece promotionPiece = null;
//TODO: Start implementing bughouse and crazyhouse support from here. Look at second else if.
Piece dropPiece = null;
if (moveVerbose.equals("o-o"))
move = variant.createShortCastling(position);
else if (moveVerbose.equals("o-o-o"))
move = variant.createLongCastling(position);
else if (moveVerbose.indexOf('@') != -1){
toSquare = Square.parseSquare(moveVerbose.substring(5,7));
String dropPieceString = String.valueOf(moveVerbose.charAt(0));
if (currentPlayer.isBlack()){
dropPieceString = dropPieceString.toLowerCase();
}
dropPiece = variant.parsePiece(dropPieceString);
move = variant.createMove(position, dropPiece,null, toSquare, promotionPiece, moveSAN);
}
else{
fromSquare = Square.parseSquare(moveVerbose.substring(2, 4));
toSquare = Square.parseSquare(moveVerbose.substring(5, 7));
int promotionCharIndex = moveVerbose.indexOf("=")+1;
if (promotionCharIndex != 0){
String pieceString = moveVerbose.substring(promotionCharIndex, promotionCharIndex + 1);
if (currentPlayer.isBlack()) // The server always sends upper case characters, even for black pieces.
pieceString = pieceString.toLowerCase();
promotionPiece = variant.parsePiece(pieceString);
}
move = variant.createMove(position, fromSquare, toSquare, promotionPiece, moveSAN);
}
listenerManager.fireGameEvent(new MoveMadeEvent(this, game, move, true, currentPlayerName));
// (isNew == true) because FICS never sends the entire move history
ArrayList unechoedGameMoves = (ArrayList)unechoedMoves.get(game);
if ((unechoedGameMoves != null) && (unechoedGameMoves.size() != 0)){ // Looks like it's our move.
Move madeMove = (Move)unechoedGameMoves.get(0);
if (moveToString(game, move).equals(moveToString(game, madeMove))) // Same move.
unechoedGameMoves.remove(0);
}
gameData.addMove(move);
}
/**
* Fires an appropriate ClockAdjustmentEvent.
*/
private void updateClocks(InternalGameData gameData, Style12Struct boardData){
Game game = gameData.game;
int whiteTime = boardData.getWhiteTime();
int blackTime = boardData.getBlackTime();
Player currentPlayer = playerForString(boardData.getCurrentPlayer());
// Don't make clocks run for an isolated position.
boolean isIsolatedBoard = game.getGameType() == Game.ISOLATED_BOARD;
boolean whiteRunning = (!isIsolatedBoard) && boardData.isClockRunning() && currentPlayer.isWhite();
boolean blackRunning = (!isIsolatedBoard) && boardData.isClockRunning() && currentPlayer.isBlack();
listenerManager.fireGameEvent(new ClockAdjustmentEvent(this, game, Player.WHITE_PLAYER, whiteTime, whiteRunning));
listenerManager.fireGameEvent(new ClockAdjustmentEvent(this, game, Player.BLACK_PLAYER, blackTime, blackRunning));
}
/**
* Fires an appropriate GameEndEvent.
*/
private void closeGame(int gameNumber, int result){
Integer gameID = new Integer(gameNumber);
if (gameID.intValue() == primaryPlayedGame)
primaryPlayedGame = -1;
else if (gameID.intValue() == primaryObservedGame)
primaryObservedGame = -1;
InternalGameData gameData = (InternalGameData)ongoingGamesData.remove(gameID);
if (gameData != null){
Game game = gameData.game;
game.setResult(result);
listenerManager.fireGameEvent(new GameEndEvent(this, game, result));
if ((game.getGameType() == Game.MY_GAME) && getIvarState(Ivar.SEEKINFO))
setIvarState(Ivar.SEEKINFO, true); // Refresh the seeks
}
else
unsupportedGames.remove(gameID);
}
/**
* Fires an appropriate BoardFlipEvent.
*/
private void flipBoard(InternalGameData gameData, Style12Struct newBoardData){
listenerManager.fireGameEvent(new BoardFlipEvent(this, gameData.game, newBoardData.isBoardFlipped()));
}
/**
* Fires an appropriate IllegalMoveEvent.
*/
private void illegalMoveAttempted(String moveString){
try{
InternalGameData gameData = findMyGame();
Game game = gameData.game;
ArrayList unechoedGameMoves = (ArrayList)unechoedMoves.get(game);
// Not a move we made (probably the user typed it in)
if ((unechoedGameMoves == null) || (unechoedGameMoves.size() == 0))
return;
Move move = (Move)unechoedGameMoves.get(0);
// We have no choice but to allow (moveString == null) because the server
// doesn't always send us the move string (for example if it's not our turn).
if ((moveString == null) || moveToString(game, move).equals(moveString)){
// Our move, probably
unechoedGameMoves.clear();
listenerManager.fireGameEvent(new IllegalMoveEvent(this, game, move));
}
} catch (NoSuchGameException e){}
}
/**
* Determines whether it's possible to issue a takeback for the specified
* game change and if so calls issueTakeback, otherwise calls changePosition.
*/
private void tryIssueTakeback(InternalGameData gameData, Style12Struct boardData){
Style12Struct oldBoardData = gameData.boardData;
int plyDifference = oldBoardData.getPlayedPlyCount() - boardData.getPlayedPlyCount();
if ((gameData.getMoveCount() < plyDifference)) // Can't issue takeback
changePosition(gameData, boardData);
else if (gameData.isBSetup)
changePosition(gameData, boardData);
else{
Game game = gameData.game;
ArrayList moveList = gameData.moveList;
// Check whether the positions match, otherwise it could just be someone
// issuing "bsetup fen ..." after making a few moves which resets the ply
// count.
Position oldPos = game.getInitialPosition();
for (int i = 0; i < moveList.size() - plyDifference; i++){
Move move = (Move)moveList.get(i);
oldPos.makeMove(move);
}
Position newPos = game.getInitialPosition();
newPos.setFEN(boardData.getBoardFEN());
if (newPos.equals(oldPos)){
issueTakeback(gameData, boardData);
}else if (gameData.game.getVariant() instanceof Bughouse){
issueTakeback(gameData, boardData);
}else{
changePosition(gameData, boardData);
}
}
}
/**
* Fires an appropriate TakebackEvent.
*/
private void issueTakeback(InternalGameData gameData, Style12Struct newBoardData){
Style12Struct oldBoardData = gameData.boardData;
int takebackCount = oldBoardData.getPlayedPlyCount() - newBoardData.getPlayedPlyCount();
listenerManager.fireGameEvent(new TakebackEvent(this, gameData.game, takebackCount));
gameData.removeLastMoves(takebackCount);
}
/**
* Fires an appropriate PositionChangedEvent.
*/
private void changePosition(InternalGameData gameData, Style12Struct newBoardData){
Game game = gameData.game;
Position newPos = game.getInitialPosition();
newPos.setFEN(newBoardData.getBoardFEN());
game.setInitialPosition(newPos);
game.setPliesSinceStart(newBoardData.getPlayedPlyCount());
listenerManager.fireGameEvent(new PositionChangedEvent(this, game, newPos));
gameData.clearMoves();
// We do this because moves in bsetup mode cause position change events, not move events
if (gameData.isBSetup){
ArrayList unechoedGameMoves = (ArrayList)unechoedMoves.get(game);
if ((unechoedGameMoves != null) && (unechoedGameMoves.size() != 0))
unechoedGameMoves.remove(0);
}
}
/**
* Maps seek IDs to Seek objects currently in the sought list.
*/
private final HashMap seeks = new HashMap();
/**
* Returns the SeekListenerManager via which you can register and unregister
* SeekListeners.
*/
public SeekListenerManager getSeekListenerManager(){
return getFreechessListenerManager();
}
/**
* Creates an appropriate Seek object and fires a SeekEvent.
*/
protected boolean processSeekAdded(SeekInfoStruct seekInfo){
// We may get seeks after setting seekinfo to false because the server
// already sent them when we sent it the request to set seekInfo to false.
if (getRequestedIvarState(Ivar.SEEKINFO)){
WildVariant variant = getVariant(seekInfo.getMatchType());
if (variant != null){
String seekID = String.valueOf(seekInfo.getSeekIndex());
StringBuffer titlesBuf = new StringBuffer();
int titles = seekInfo.getSeekerTitles();
if ((titles & SeekInfoStruct.COMPUTER) != 0)
titlesBuf.append("(C)");
if ((titles & SeekInfoStruct.GM) != 0)
titlesBuf.append("(GM)");
if ((titles & SeekInfoStruct.IM) != 0)
titlesBuf.append("(IM)");
if ((titles & SeekInfoStruct.FM) != 0)
titlesBuf.append("(FM)");
if ((titles & SeekInfoStruct.WGM) != 0)
titlesBuf.append("(WGM)");
if ((titles & SeekInfoStruct.WIM) != 0)
titlesBuf.append("(WIM)");
if ((titles & SeekInfoStruct.WFM) != 0)
titlesBuf.append("(WFM)");
boolean isProvisional = (seekInfo.getSeekerProvShow() == 'P');
boolean isSeekerRated = (seekInfo.getSeekerRating() != 0);
boolean isRegistered = ((seekInfo.getSeekerTitles() & SeekInfoStruct.UNREGISTERED) == 0);
boolean isComputer = ((seekInfo.getSeekerTitles() & SeekInfoStruct.COMPUTER) != 0);
Player color;
switch (seekInfo.getSeekerColor()){
case 'W':
color = Player.WHITE_PLAYER;
break;
case 'B':
color = Player.BLACK_PLAYER;
break;
case '?':
color = null;
break;
default:
throw new IllegalStateException("Bad desired color char: "+seekInfo.getSeekerColor());
}
boolean isRatingLimited = ((seekInfo.getOpponentMinRating() > 0) || (seekInfo.getOpponentMaxRating() < 9999));
Seek seek = new Seek(seekID, seekInfo.getSeekerHandle(), titlesBuf.toString(), seekInfo.getSeekerRating(),
isProvisional, isRegistered, isSeekerRated, isComputer, variant, seekInfo.getMatchType(),
seekInfo.getMatchTime()*60*1000, seekInfo.getMatchIncrement()*1000, seekInfo.isMatchRated(), color,
isRatingLimited, seekInfo.getOpponentMinRating(), seekInfo.getOpponentMaxRating(),
!seekInfo.isAutomaticAccept(), seekInfo.isFormulaUsed());
Integer seekIndex = new Integer(seekInfo.getSeekIndex());
Seek oldSeek = (Seek)seeks.get(seekIndex);
if (oldSeek != null)
listenerManager.fireSeekEvent(new SeekEvent(this, SeekEvent.SEEK_REMOVED, oldSeek));
seeks.put(seekIndex, seek);
listenerManager.fireSeekEvent(new SeekEvent(this, SeekEvent.SEEK_ADDED, seek));
}
}
return true;
}
/**
* Issues the appropriate SeekEvents and removes the seeks.
*/
protected boolean processSeeksRemoved(int [] removedSeeks){
for (int i = 0; i < removedSeeks.length; i++){
Integer seekIndex = new Integer(removedSeeks[i]);
Seek seek = (Seek)seeks.get(seekIndex);
if (seek == null) // Happens if the seek is one we didn't fire an event for,
continue; // for example if we don't support the variant.
listenerManager.fireSeekEvent(new SeekEvent(this, SeekEvent.SEEK_REMOVED, seek));
seeks.remove(seekIndex);
}
return true;
}
/**
* Issues the appropriate SeeksEvents and removes the seeks.
*/
protected boolean processSeeksCleared(){
removeAllSeeks();
return true;
}
/**
* Removes all the seeks and notifies the listeners.
*/
private void removeAllSeeks(){
int seeksCount = seeks.size();
if (seeksCount != 0){
Object [] seeksIndices = new Object[seeksCount];
// Copy all the keys into a temporary array
Iterator seekIDsEnum = seeks.keySet().iterator();
for (int i = 0; i < seeksCount; i++)
seeksIndices[i] = seekIDsEnum.next();
// Remove all the seeks one by one, notifying any interested listeners.
for (int i = 0; i < seeksCount; i++){
Object seekIndex = seeksIndices[i];
Seek seek = (Seek)seeks.get(seekIndex);
listenerManager.fireSeekEvent(new SeekEvent(this, SeekEvent.SEEK_REMOVED, seek));
seeks.remove(seekIndex);
}
}
}
/**
* This method is called by our FreechessJinListenerManager when a new
* SeekListener is added and we already had registered listeners (meaning that
* iv_seekinfo was already on, so we need to notify the new listeners of all
* existing seeks as well).
*/
void notFirstListenerAdded(SeekListener listener){
Iterator seeksEnum = seeks.values().iterator();
while (seeksEnum.hasNext()){
Seek seek = (Seek)seeksEnum.next();
SeekEvent evt = new SeekEvent(this, SeekEvent.SEEK_ADDED, seek);
listener.seekAdded(evt);
}
}
/**
* This method is called by our ChessclubJinListenerManager when the last
* SeekListener is removed.
*/
void lastSeekListenerRemoved(){
seeks.clear();
}
/**
* Maps offer indices to the <code>InternalGameData</code> objects
* representing the games in which the offer was made.
*/
private final HashMap offerIndicesToGameData = new HashMap();
/**
* Override processOffer to always return true, since we don't want the
* user to ever see these messages.
*/
protected boolean processOffer(boolean toUser, String offerType, int offerIndex,
String oppName, String offerParams){
super.processOffer(toUser, offerType, offerIndex, oppName, offerParams);
return true;
}
/**
* Overrides the superclass' method only to return true.
*/
protected boolean processMatchOffered(boolean toUser, int offerIndex, String oppName,
String matchDetails){
super.processMatchOffered(toUser, offerIndex, oppName, matchDetails);
return true;
}
/**
* Fires the appropriate OfferEvent(s).
*/
protected boolean processTakebackOffered(boolean toUser, int offerIndex, String oppName,
int takebackCount){
super.processTakebackOffered(toUser, offerIndex, oppName, takebackCount);
try{
InternalGameData gameData = findMyGameAgainst(oppName);
Player userPlayer = gameData.game.getUserPlayer();
Player player = toUser ? userPlayer.getOpponent() : userPlayer;
offerIndicesToGameData.put(new Integer(offerIndex), gameData);
gameData.indicesToTakebackOffers.put(new Integer(offerIndex),
new Pair(player, new Integer(takebackCount)));
updateTakebackOffer(gameData, player, takebackCount);
} catch (NoSuchGameException e){}
return true;
}
/**
* Fires the appropriate OfferEvent(s).
*/
protected boolean processDrawOffered(boolean toUser, int offerIndex, String oppName){
super.processDrawOffered(toUser, offerIndex, oppName);
processOffered(toUser, offerIndex, oppName, OfferEvent.DRAW_OFFER);
return true;
}
/**
* Fires the appropriate OfferEvent(s).
*/
protected boolean processAbortOffered(boolean toUser, int offerIndex, String oppName){
super.processAbortOffered(toUser, offerIndex, oppName);
processOffered(toUser, offerIndex, oppName, OfferEvent.ABORT_OFFER);
return true;
}
/**
* Fires the appropriate OfferEvent(s).
*/
protected boolean processAdjournOffered(boolean toUser, int offerIndex, String oppName){
super.processAdjournOffered(toUser, offerIndex, oppName);
processOffered(toUser, offerIndex, oppName, OfferEvent.ADJOURN_OFFER);
return true;
}
/**
* Gets called by the various process[offerType]Offered() methods to handle
* the offers uniformly.
*/
private void processOffered(boolean toUser, int offerIndex, String oppName, int offerId){
try{
InternalGameData gameData = findMyGameAgainst(oppName);
Player userPlayer = gameData.game.getUserPlayer();
Player player = toUser ? userPlayer.getOpponent() : userPlayer;
offerIndicesToGameData.put(new Integer(offerIndex), gameData);
gameData.indicesToOffers.put(new Integer(offerIndex),
new Pair(player, new Integer(offerId)));
updateOffers(gameData, offerId, player, true);
} catch (NoSuchGameException e){}
}
/**
* Fires the appropriate OfferEvent(s).
*/
protected boolean processOfferRemoved(int offerIndex){
super.processOfferRemoved(offerIndex);
InternalGameData gameData =
(InternalGameData)offerIndicesToGameData.remove(new Integer(offerIndex));
if (gameData != null){
// Check regular offers
Pair offer = (Pair)gameData.indicesToOffers.remove(new Integer(offerIndex));
if (offer != null){
Player player = (Player)offer.getFirst();
int offerId = ((Integer)offer.getSecond()).intValue();
updateOffers(gameData, offerId, player, false);
}
else{
// Check takeback offers
offer = (Pair)gameData.indicesToTakebackOffers.remove(new Integer(offerIndex));
if (offer != null){
Player player = (Player)offer.getFirst();
updateTakebackOffer(gameData, player, 0);
}
}
}
return true;
}
/**
* Fires the appropriate OfferEvent(s).
*/
protected boolean processPlayerCounteredTakebackOffer(int gameNum, String playerName,
int takebackCount){
super.processPlayerCounteredTakebackOffer(gameNum, playerName, takebackCount);
try{
InternalGameData gameData = getGameData(gameNum);
Player player = gameData.game.getPlayerNamed(playerName);
updateTakebackOffer(gameData, player.getOpponent(), 0);
updateTakebackOffer(gameData, player, takebackCount);
} catch (NoSuchGameException e){}
return false;
}
/**
* Fires the appropriate OfferEvent(s).
*/
protected boolean processPlayerOffered(int gameNum, String playerName, String offerName){
super.processPlayerOffered(gameNum, playerName, offerName);
try{
InternalGameData gameData = getGameData(gameNum);
Player player = gameData.game.getPlayerNamed(playerName);
int offerId;
try{
offerId = offerIdForOfferName(offerName);
updateOffers(gameData, offerId, player, true);
} catch (IllegalArgumentException e){}
} catch (NoSuchGameException e){}
return false;
}
/**
* Fires the appropriate OfferEvent(s).
*/
protected boolean processPlayerDeclined(int gameNum, String playerName, String offerName){
super.processPlayerDeclined(gameNum, playerName, offerName);
try{
InternalGameData gameData = getGameData(gameNum);
Player player = gameData.game.getPlayerNamed(playerName);
int offerId;
try{
offerId = offerIdForOfferName(offerName);
updateOffers(gameData, offerId, player.getOpponent(), false);
} catch (IllegalArgumentException e){}
} catch (NoSuchGameException e){}
return false;
}
/**
* Fires the appropriate OfferEvent(s).
*/
protected boolean processPlayerWithdrew(int gameNum, String playerName, String offerName){
super.processPlayerWithdrew(gameNum, playerName, offerName);
try{
InternalGameData gameData = getGameData(gameNum);
Player player = gameData.game.getPlayerNamed(playerName);
int offerId;
try{
offerId = offerIdForOfferName(offerName);
updateOffers(gameData, offerId, player, false);
} catch (IllegalArgumentException e){}
} catch (NoSuchGameException e){}
return false;
}
/**
* Fires the appropriate OfferEvent(s).
*/
protected boolean processPlayerOfferedTakeback(int gameNum, String playerName, int takebackCount){
super.processPlayerOfferedTakeback(gameNum, playerName, takebackCount);
try{
InternalGameData gameData = getGameData(gameNum);
Player player = gameData.game.getPlayerNamed(playerName);
updateTakebackOffer(gameData, player, takebackCount);
} catch (NoSuchGameException e){}
return false;
}
/**
* Returns the offerId (as defined by OfferEvent) corresponding to the
* specified offer name. Throws an IllegalArgumentException if the offer name
* is not recognizes.
*/
private static int offerIdForOfferName(String offerName) throws IllegalArgumentException{
if ("draw".equals(offerName))
return OfferEvent.DRAW_OFFER;
else if ("abort".equals(offerName))
return OfferEvent.ABORT_OFFER;
else if ("adjourn".equals(offerName))
return OfferEvent.ADJOURN_OFFER;
else if ("takeback".equals(offerName))
return OfferEvent.TAKEBACK_OFFER;
else
throw new IllegalArgumentException("Unknown offer name: "+offerName);
}
/**
* Updates the specified offer, firing any necessary events.
*/
private void updateOffers(InternalGameData gameData, int offerId, Player player, boolean on){
Game game = gameData.game;
if (offerId == OfferEvent.TAKEBACK_OFFER){
// We're forced to fake this so that an event is fired even if we start observing a game
// with an existing takeback offer (of which we're not aware).
if ((!on) && (gameData.getTakebackOffer(player) == 0))
gameData.setTakebackOffer(player, 1);
updateTakebackOffer(gameData, player.getOpponent(), 0); // Remove any existing offers
updateTakebackOffer(gameData, player, on ? 1 : 0);
// 1 as the server doesn't tell us how many
}
else{// if (gameData.isOffered(offerId, player) != on){ this
// We check this because we might get such an event if we start observing a game with
// an existing offer.
gameData.setOffer(offerId, player, on);
listenerManager.fireGameEvent(new OfferEvent(this, game, offerId, on, player));
}
}
/**
* Updates the takeback offer in the specified game to the specified amount of
* plies.
*/
private void updateTakebackOffer(InternalGameData gameData, Player player, int takebackCount){
Game game = gameData.game;
int oldTakeback = gameData.getTakebackOffer(player);
if (oldTakeback != 0)
listenerManager.fireGameEvent(new OfferEvent(this, game, false, player, oldTakeback));
gameData.setTakebackOffer(player, takebackCount);
if (takebackCount != 0)
listenerManager.fireGameEvent(new OfferEvent(this, game, true, player, takebackCount));
}
/**
* Accepts the given seek. Note that the given seek must be an instance generated
* by this SeekJinConnection and it must be in the current sought list.
*/
public void acceptSeek(Seek seek){
if (!seeks.containsValue(seek))
throw new IllegalArgumentException("The specified seek is not on the seek list");
sendCommand("$play "+seek.getID());
}
/**
* Issues the specified seek.
*/
public void issueSeek(UserSeek seek){
WildVariant variant = seek.getVariant();
String wildName = getWildName(variant);
if (wildName == null)
throw new IllegalArgumentException("Unsupported variant: " + variant);
Player color = seek.getColor();
String seekCommand = "seek " + seek.getTime() + ' ' + seek.getInc() + ' ' +
(seek.isRated() ? "rated" : "unrated") + ' ' +
(color == null ? "" : color.isWhite() ? "white " : "black ") +
wildName + ' ' +
(seek.isManualAccept() ? "manual " : "") +
(seek.isFormula() ? "formula " : "") +
(seek.getMinRating() == Integer.MIN_VALUE ? "0" : String.valueOf(seek.getMinRating())) + '-' +
(seek.getMaxRating() == Integer.MAX_VALUE ? "9999" : String.valueOf(seek.getMaxRating())) + ' ';
sendCommand(seekCommand);
}
/**
* Sends the "exit" command to the server.
*/
public void exit(){
sendCommand("$quit");
}
/**
* Quits the specified game.
*/
public void quitGame(Game game){
Object id = game.getID();
switch (game.getGameType()){
case Game.MY_GAME:
if (game.isPlayed())
sendCommand("$resign");
else
sendCommand("$unexamine");
break;
case Game.OBSERVED_GAME:
sendCommand("$unobserve "+id);
break;
case Game.ISOLATED_BOARD:
break;
}
}
/**
* Makes the given move in the given game.
*/
public void makeMove(Game game, Move move){
- Iterator gamesDataEnum = ongoingGamesData.keySet().iterator();
+ Iterator gamesDataEnum = ongoingGamesData.values().iterator();
boolean ourGame = false;
while (gamesDataEnum.hasNext()){
InternalGameData gameData = (InternalGameData)gamesDataEnum.next();
if (gameData.game == game){
ourGame = true;
break;
}
}
if (!ourGame)
throw new IllegalArgumentException("The specified Game object was not created by this JinConnection or the game has ended.");
sendCommand(moveToString(game, move));
ArrayList unechoedGameMoves = (ArrayList)unechoedMoves.get(game);
if (unechoedGameMoves == null){
unechoedGameMoves = new ArrayList(2);
unechoedMoves.put(game, unechoedGameMoves);
}
unechoedGameMoves.add(move);
}
/**
* Converts the given move into a string we can send to the server.
*/
private static String moveToString(Game game, Move move){
WildVariant variant = game.getVariant();
if (move instanceof ChessMove){
ChessMove cmove = (ChessMove)move;
if (cmove.isShortCastling())
return "O-O";
else if (cmove.isLongCastling())
return "O-O-O";
String s = cmove.getStartingSquare().toString() + cmove.getEndingSquare().toString();
if (cmove.isPromotion())
return s + '=' + variant.pieceToString(cmove.getPromotionTarget());
else
return s;
}
else
throw new IllegalArgumentException("Unsupported Move type: "+move.getClass());
}
/**
* Resigns the given game. The given game must be a played game and of type
* Game.MY_GAME.
*/
public void resign(Game game){
checkGameMineAndPlayed(game);
sendCommand("$resign");
}
/**
* Sends a request to draw the given game. The given game must be a played
* game and of type Game.MY_GAME.
*/
public void requestDraw(Game game){
checkGameMineAndPlayed(game);
sendCommand("$draw");
}
/**
* Returns <code>true</code>.
*/
public boolean isAbortSupported(){
return true;
}
/**
* Sends a request to abort the given game. The given game must be a played
* game and of type Game.MY_GAME.
*/
public void requestAbort(Game game){
checkGameMineAndPlayed(game);
sendCommand("$abort");
}
/**
* Returns <code>true</code>.
*/
public boolean isAdjournSupported(){
return true;
}
/**
* Sends a request to adjourn the given game. The given game must be a played
* game and of type Game.MY_GAME.
*/
public void requestAdjourn(Game game){
checkGameMineAndPlayed(game);
sendCommand("$adjourn");
}
/**
* Returns <code>true</code>.
*/
public boolean isTakebackSupported(){
return true;
}
/**
* Sends "takeback 1" to the server.
*/
public void requestTakeback(Game game){
checkGameMineAndPlayed(game);
sendCommand("$takeback 1");
}
/**
* Returns <code>true</code>.
*/
public boolean isMultipleTakebackSupported(){
return true;
}
/**
* Sends "takeback plyCount" to the server.
*/
public void requestTakeback(Game game, int plyCount){
checkGameMineAndPlayed(game);
if (plyCount < 1)
throw new IllegalArgumentException("Illegal ply count: " + plyCount);
sendCommand("$takeback " + plyCount);
}
/**
* Goes back the given amount of plies in the given game. If the given amount
* of plies is bigger than the amount of plies since the beginning of the game,
* goes to the beginning of the game.
*/
public void goBackward(Game game, int plyCount){
checkGameMineAndExamined(game);
if (plyCount < 1)
throw new IllegalArgumentException("Illegal ply count: " + plyCount);
sendCommand("$backward " + plyCount);
}
/**
* Goes forward the given amount of plies in the given game. If the given amount
* of plies is bigger than the amount of plies remaining until the end of the
* game, goes to the end of the game.
*/
public void goForward(Game game, int plyCount){
checkGameMineAndExamined(game);
if (plyCount < 1)
throw new IllegalArgumentException("Illegal ply count: " + plyCount);
sendCommand("$forward " + plyCount);
}
/**
* Goes to the beginning of the given game.
*/
public void goToBeginning(Game game){
checkGameMineAndExamined(game);
sendCommand("$backward 999");
}
/**
* Goes to the end of the given game.
*/
public void goToEnd(Game game){
checkGameMineAndExamined(game);
sendCommand("$forward 999");
}
/**
* Throws an IllegalArgumentException if the given Game is not of type
* Game.MY_GAME or is not a played game. Otherwise, simply returns.
*/
private void checkGameMineAndPlayed(Game game){
if ((game.getGameType() != Game.MY_GAME) || (!game.isPlayed()))
throw new IllegalArgumentException("The given game must be of type Game.MY_GAME and a played one");
}
/**
* Throws an IllegalArgumentException if the given Game is not of type
* Game.MY_GAME or is a played game. Otherwise, simply returns.
*/
private void checkGameMineAndExamined(Game game){
if ((game.getGameType() != Game.MY_GAME)||game.isPlayed())
throw new IllegalArgumentException("The given game must be of type Game.MY_GAME and an examined one");
}
/**
* Sends the "help" command to the server.
*/
public void showServerHelp(){
sendCommand("help");
}
/**
* Sends the specified question string to channel 1.
*/
public void sendHelpQuestion(String question){
sendCommand("tell 1 [" + Jin.getInstance().getAppName() + ' ' + Jin.getInstance().getAppVersion() + "] "+ question);
}
/**
* Overrides ChessclubConnection.execRunnable(Runnable) to execute the
* runnable on the AWT thread using SwingUtilities.invokeLater(Runnable),
* since this class is meant to be used by Jin, a graphical interface using
* Swing.
*
* @see ChessclubConnection#execRunnable(Runnable)
* @see SwingUtilities.invokeLater(Runnable)
*/
public void execRunnable(Runnable runnable){
SwingUtilities.invokeLater(runnable);
}
/**
* Method called to get user's channel list from server.
*/
public void updateChannelsList() {
sendCommand("inch " + this.getUsername());
}
/**
* Method called to remove channel from user's channel list.
*
* @param channelNumber - the number of removed channel.
*/
public void removeChannel(int channelNumber) {
sendCommand("-channel " + channelNumber);
}
/**
* Method called to add channel to user's channel list.
*
* @param channelNumber - the number of added channel.
*/
public void addChannel(int channelNumber) {
sendCommand("+channel " + channelNumber);
}
/**
* Returns ListenerManager that lets us register listeners
*/
public ChannelsListenerManager getChannelsListenerManager() {
return getFreechessListenerManager();
}
}
| true | true | private void updateOffers(InternalGameData gameData, int offerId, Player player, boolean on){
Game game = gameData.game;
if (offerId == OfferEvent.TAKEBACK_OFFER){
// We're forced to fake this so that an event is fired even if we start observing a game
// with an existing takeback offer (of which we're not aware).
if ((!on) && (gameData.getTakebackOffer(player) == 0))
gameData.setTakebackOffer(player, 1);
updateTakebackOffer(gameData, player.getOpponent(), 0); // Remove any existing offers
updateTakebackOffer(gameData, player, on ? 1 : 0);
// 1 as the server doesn't tell us how many
}
else{// if (gameData.isOffered(offerId, player) != on){ this
// We check this because we might get such an event if we start observing a game with
// an existing offer.
gameData.setOffer(offerId, player, on);
listenerManager.fireGameEvent(new OfferEvent(this, game, offerId, on, player));
}
}
/**
* Updates the takeback offer in the specified game to the specified amount of
* plies.
*/
private void updateTakebackOffer(InternalGameData gameData, Player player, int takebackCount){
Game game = gameData.game;
int oldTakeback = gameData.getTakebackOffer(player);
if (oldTakeback != 0)
listenerManager.fireGameEvent(new OfferEvent(this, game, false, player, oldTakeback));
gameData.setTakebackOffer(player, takebackCount);
if (takebackCount != 0)
listenerManager.fireGameEvent(new OfferEvent(this, game, true, player, takebackCount));
}
/**
* Accepts the given seek. Note that the given seek must be an instance generated
* by this SeekJinConnection and it must be in the current sought list.
*/
public void acceptSeek(Seek seek){
if (!seeks.containsValue(seek))
throw new IllegalArgumentException("The specified seek is not on the seek list");
sendCommand("$play "+seek.getID());
}
/**
* Issues the specified seek.
*/
public void issueSeek(UserSeek seek){
WildVariant variant = seek.getVariant();
String wildName = getWildName(variant);
if (wildName == null)
throw new IllegalArgumentException("Unsupported variant: " + variant);
Player color = seek.getColor();
String seekCommand = "seek " + seek.getTime() + ' ' + seek.getInc() + ' ' +
(seek.isRated() ? "rated" : "unrated") + ' ' +
(color == null ? "" : color.isWhite() ? "white " : "black ") +
wildName + ' ' +
(seek.isManualAccept() ? "manual " : "") +
(seek.isFormula() ? "formula " : "") +
(seek.getMinRating() == Integer.MIN_VALUE ? "0" : String.valueOf(seek.getMinRating())) + '-' +
(seek.getMaxRating() == Integer.MAX_VALUE ? "9999" : String.valueOf(seek.getMaxRating())) + ' ';
sendCommand(seekCommand);
}
/**
* Sends the "exit" command to the server.
*/
public void exit(){
sendCommand("$quit");
}
/**
* Quits the specified game.
*/
public void quitGame(Game game){
Object id = game.getID();
switch (game.getGameType()){
case Game.MY_GAME:
if (game.isPlayed())
sendCommand("$resign");
else
sendCommand("$unexamine");
break;
case Game.OBSERVED_GAME:
sendCommand("$unobserve "+id);
break;
case Game.ISOLATED_BOARD:
break;
}
}
/**
* Makes the given move in the given game.
*/
public void makeMove(Game game, Move move){
Iterator gamesDataEnum = ongoingGamesData.keySet().iterator();
boolean ourGame = false;
while (gamesDataEnum.hasNext()){
InternalGameData gameData = (InternalGameData)gamesDataEnum.next();
if (gameData.game == game){
ourGame = true;
break;
}
}
if (!ourGame)
throw new IllegalArgumentException("The specified Game object was not created by this JinConnection or the game has ended.");
sendCommand(moveToString(game, move));
ArrayList unechoedGameMoves = (ArrayList)unechoedMoves.get(game);
if (unechoedGameMoves == null){
unechoedGameMoves = new ArrayList(2);
unechoedMoves.put(game, unechoedGameMoves);
}
unechoedGameMoves.add(move);
}
/**
* Converts the given move into a string we can send to the server.
*/
private static String moveToString(Game game, Move move){
WildVariant variant = game.getVariant();
if (move instanceof ChessMove){
ChessMove cmove = (ChessMove)move;
if (cmove.isShortCastling())
return "O-O";
else if (cmove.isLongCastling())
return "O-O-O";
String s = cmove.getStartingSquare().toString() + cmove.getEndingSquare().toString();
if (cmove.isPromotion())
return s + '=' + variant.pieceToString(cmove.getPromotionTarget());
else
return s;
}
else
throw new IllegalArgumentException("Unsupported Move type: "+move.getClass());
}
/**
* Resigns the given game. The given game must be a played game and of type
* Game.MY_GAME.
*/
public void resign(Game game){
checkGameMineAndPlayed(game);
sendCommand("$resign");
}
/**
* Sends a request to draw the given game. The given game must be a played
* game and of type Game.MY_GAME.
*/
public void requestDraw(Game game){
checkGameMineAndPlayed(game);
sendCommand("$draw");
}
/**
* Returns <code>true</code>.
*/
public boolean isAbortSupported(){
return true;
}
/**
* Sends a request to abort the given game. The given game must be a played
* game and of type Game.MY_GAME.
*/
public void requestAbort(Game game){
checkGameMineAndPlayed(game);
sendCommand("$abort");
}
/**
* Returns <code>true</code>.
*/
public boolean isAdjournSupported(){
return true;
}
/**
* Sends a request to adjourn the given game. The given game must be a played
* game and of type Game.MY_GAME.
*/
public void requestAdjourn(Game game){
checkGameMineAndPlayed(game);
sendCommand("$adjourn");
}
/**
* Returns <code>true</code>.
*/
public boolean isTakebackSupported(){
return true;
}
/**
* Sends "takeback 1" to the server.
*/
public void requestTakeback(Game game){
checkGameMineAndPlayed(game);
sendCommand("$takeback 1");
}
/**
* Returns <code>true</code>.
*/
public boolean isMultipleTakebackSupported(){
return true;
}
/**
* Sends "takeback plyCount" to the server.
*/
public void requestTakeback(Game game, int plyCount){
checkGameMineAndPlayed(game);
if (plyCount < 1)
throw new IllegalArgumentException("Illegal ply count: " + plyCount);
sendCommand("$takeback " + plyCount);
}
/**
* Goes back the given amount of plies in the given game. If the given amount
* of plies is bigger than the amount of plies since the beginning of the game,
* goes to the beginning of the game.
*/
public void goBackward(Game game, int plyCount){
checkGameMineAndExamined(game);
if (plyCount < 1)
throw new IllegalArgumentException("Illegal ply count: " + plyCount);
sendCommand("$backward " + plyCount);
}
/**
* Goes forward the given amount of plies in the given game. If the given amount
* of plies is bigger than the amount of plies remaining until the end of the
* game, goes to the end of the game.
*/
public void goForward(Game game, int plyCount){
checkGameMineAndExamined(game);
if (plyCount < 1)
throw new IllegalArgumentException("Illegal ply count: " + plyCount);
sendCommand("$forward " + plyCount);
}
/**
* Goes to the beginning of the given game.
*/
public void goToBeginning(Game game){
checkGameMineAndExamined(game);
sendCommand("$backward 999");
}
/**
* Goes to the end of the given game.
*/
public void goToEnd(Game game){
checkGameMineAndExamined(game);
sendCommand("$forward 999");
}
/**
* Throws an IllegalArgumentException if the given Game is not of type
* Game.MY_GAME or is not a played game. Otherwise, simply returns.
*/
private void checkGameMineAndPlayed(Game game){
if ((game.getGameType() != Game.MY_GAME) || (!game.isPlayed()))
throw new IllegalArgumentException("The given game must be of type Game.MY_GAME and a played one");
}
/**
* Throws an IllegalArgumentException if the given Game is not of type
* Game.MY_GAME or is a played game. Otherwise, simply returns.
*/
private void checkGameMineAndExamined(Game game){
if ((game.getGameType() != Game.MY_GAME)||game.isPlayed())
throw new IllegalArgumentException("The given game must be of type Game.MY_GAME and an examined one");
}
/**
* Sends the "help" command to the server.
*/
public void showServerHelp(){
sendCommand("help");
}
/**
* Sends the specified question string to channel 1.
*/
public void sendHelpQuestion(String question){
sendCommand("tell 1 [" + Jin.getInstance().getAppName() + ' ' + Jin.getInstance().getAppVersion() + "] "+ question);
}
/**
* Overrides ChessclubConnection.execRunnable(Runnable) to execute the
* runnable on the AWT thread using SwingUtilities.invokeLater(Runnable),
* since this class is meant to be used by Jin, a graphical interface using
* Swing.
*
* @see ChessclubConnection#execRunnable(Runnable)
* @see SwingUtilities.invokeLater(Runnable)
*/
public void execRunnable(Runnable runnable){
SwingUtilities.invokeLater(runnable);
}
/**
* Method called to get user's channel list from server.
*/
public void updateChannelsList() {
sendCommand("inch " + this.getUsername());
}
/**
* Method called to remove channel from user's channel list.
*
* @param channelNumber - the number of removed channel.
*/
public void removeChannel(int channelNumber) {
sendCommand("-channel " + channelNumber);
}
/**
* Method called to add channel to user's channel list.
*
* @param channelNumber - the number of added channel.
*/
public void addChannel(int channelNumber) {
sendCommand("+channel " + channelNumber);
}
/**
* Returns ListenerManager that lets us register listeners
*/
public ChannelsListenerManager getChannelsListenerManager() {
return getFreechessListenerManager();
}
}
| private void updateOffers(InternalGameData gameData, int offerId, Player player, boolean on){
Game game = gameData.game;
if (offerId == OfferEvent.TAKEBACK_OFFER){
// We're forced to fake this so that an event is fired even if we start observing a game
// with an existing takeback offer (of which we're not aware).
if ((!on) && (gameData.getTakebackOffer(player) == 0))
gameData.setTakebackOffer(player, 1);
updateTakebackOffer(gameData, player.getOpponent(), 0); // Remove any existing offers
updateTakebackOffer(gameData, player, on ? 1 : 0);
// 1 as the server doesn't tell us how many
}
else{// if (gameData.isOffered(offerId, player) != on){ this
// We check this because we might get such an event if we start observing a game with
// an existing offer.
gameData.setOffer(offerId, player, on);
listenerManager.fireGameEvent(new OfferEvent(this, game, offerId, on, player));
}
}
/**
* Updates the takeback offer in the specified game to the specified amount of
* plies.
*/
private void updateTakebackOffer(InternalGameData gameData, Player player, int takebackCount){
Game game = gameData.game;
int oldTakeback = gameData.getTakebackOffer(player);
if (oldTakeback != 0)
listenerManager.fireGameEvent(new OfferEvent(this, game, false, player, oldTakeback));
gameData.setTakebackOffer(player, takebackCount);
if (takebackCount != 0)
listenerManager.fireGameEvent(new OfferEvent(this, game, true, player, takebackCount));
}
/**
* Accepts the given seek. Note that the given seek must be an instance generated
* by this SeekJinConnection and it must be in the current sought list.
*/
public void acceptSeek(Seek seek){
if (!seeks.containsValue(seek))
throw new IllegalArgumentException("The specified seek is not on the seek list");
sendCommand("$play "+seek.getID());
}
/**
* Issues the specified seek.
*/
public void issueSeek(UserSeek seek){
WildVariant variant = seek.getVariant();
String wildName = getWildName(variant);
if (wildName == null)
throw new IllegalArgumentException("Unsupported variant: " + variant);
Player color = seek.getColor();
String seekCommand = "seek " + seek.getTime() + ' ' + seek.getInc() + ' ' +
(seek.isRated() ? "rated" : "unrated") + ' ' +
(color == null ? "" : color.isWhite() ? "white " : "black ") +
wildName + ' ' +
(seek.isManualAccept() ? "manual " : "") +
(seek.isFormula() ? "formula " : "") +
(seek.getMinRating() == Integer.MIN_VALUE ? "0" : String.valueOf(seek.getMinRating())) + '-' +
(seek.getMaxRating() == Integer.MAX_VALUE ? "9999" : String.valueOf(seek.getMaxRating())) + ' ';
sendCommand(seekCommand);
}
/**
* Sends the "exit" command to the server.
*/
public void exit(){
sendCommand("$quit");
}
/**
* Quits the specified game.
*/
public void quitGame(Game game){
Object id = game.getID();
switch (game.getGameType()){
case Game.MY_GAME:
if (game.isPlayed())
sendCommand("$resign");
else
sendCommand("$unexamine");
break;
case Game.OBSERVED_GAME:
sendCommand("$unobserve "+id);
break;
case Game.ISOLATED_BOARD:
break;
}
}
/**
* Makes the given move in the given game.
*/
public void makeMove(Game game, Move move){
Iterator gamesDataEnum = ongoingGamesData.values().iterator();
boolean ourGame = false;
while (gamesDataEnum.hasNext()){
InternalGameData gameData = (InternalGameData)gamesDataEnum.next();
if (gameData.game == game){
ourGame = true;
break;
}
}
if (!ourGame)
throw new IllegalArgumentException("The specified Game object was not created by this JinConnection or the game has ended.");
sendCommand(moveToString(game, move));
ArrayList unechoedGameMoves = (ArrayList)unechoedMoves.get(game);
if (unechoedGameMoves == null){
unechoedGameMoves = new ArrayList(2);
unechoedMoves.put(game, unechoedGameMoves);
}
unechoedGameMoves.add(move);
}
/**
* Converts the given move into a string we can send to the server.
*/
private static String moveToString(Game game, Move move){
WildVariant variant = game.getVariant();
if (move instanceof ChessMove){
ChessMove cmove = (ChessMove)move;
if (cmove.isShortCastling())
return "O-O";
else if (cmove.isLongCastling())
return "O-O-O";
String s = cmove.getStartingSquare().toString() + cmove.getEndingSquare().toString();
if (cmove.isPromotion())
return s + '=' + variant.pieceToString(cmove.getPromotionTarget());
else
return s;
}
else
throw new IllegalArgumentException("Unsupported Move type: "+move.getClass());
}
/**
* Resigns the given game. The given game must be a played game and of type
* Game.MY_GAME.
*/
public void resign(Game game){
checkGameMineAndPlayed(game);
sendCommand("$resign");
}
/**
* Sends a request to draw the given game. The given game must be a played
* game and of type Game.MY_GAME.
*/
public void requestDraw(Game game){
checkGameMineAndPlayed(game);
sendCommand("$draw");
}
/**
* Returns <code>true</code>.
*/
public boolean isAbortSupported(){
return true;
}
/**
* Sends a request to abort the given game. The given game must be a played
* game and of type Game.MY_GAME.
*/
public void requestAbort(Game game){
checkGameMineAndPlayed(game);
sendCommand("$abort");
}
/**
* Returns <code>true</code>.
*/
public boolean isAdjournSupported(){
return true;
}
/**
* Sends a request to adjourn the given game. The given game must be a played
* game and of type Game.MY_GAME.
*/
public void requestAdjourn(Game game){
checkGameMineAndPlayed(game);
sendCommand("$adjourn");
}
/**
* Returns <code>true</code>.
*/
public boolean isTakebackSupported(){
return true;
}
/**
* Sends "takeback 1" to the server.
*/
public void requestTakeback(Game game){
checkGameMineAndPlayed(game);
sendCommand("$takeback 1");
}
/**
* Returns <code>true</code>.
*/
public boolean isMultipleTakebackSupported(){
return true;
}
/**
* Sends "takeback plyCount" to the server.
*/
public void requestTakeback(Game game, int plyCount){
checkGameMineAndPlayed(game);
if (plyCount < 1)
throw new IllegalArgumentException("Illegal ply count: " + plyCount);
sendCommand("$takeback " + plyCount);
}
/**
* Goes back the given amount of plies in the given game. If the given amount
* of plies is bigger than the amount of plies since the beginning of the game,
* goes to the beginning of the game.
*/
public void goBackward(Game game, int plyCount){
checkGameMineAndExamined(game);
if (plyCount < 1)
throw new IllegalArgumentException("Illegal ply count: " + plyCount);
sendCommand("$backward " + plyCount);
}
/**
* Goes forward the given amount of plies in the given game. If the given amount
* of plies is bigger than the amount of plies remaining until the end of the
* game, goes to the end of the game.
*/
public void goForward(Game game, int plyCount){
checkGameMineAndExamined(game);
if (plyCount < 1)
throw new IllegalArgumentException("Illegal ply count: " + plyCount);
sendCommand("$forward " + plyCount);
}
/**
* Goes to the beginning of the given game.
*/
public void goToBeginning(Game game){
checkGameMineAndExamined(game);
sendCommand("$backward 999");
}
/**
* Goes to the end of the given game.
*/
public void goToEnd(Game game){
checkGameMineAndExamined(game);
sendCommand("$forward 999");
}
/**
* Throws an IllegalArgumentException if the given Game is not of type
* Game.MY_GAME or is not a played game. Otherwise, simply returns.
*/
private void checkGameMineAndPlayed(Game game){
if ((game.getGameType() != Game.MY_GAME) || (!game.isPlayed()))
throw new IllegalArgumentException("The given game must be of type Game.MY_GAME and a played one");
}
/**
* Throws an IllegalArgumentException if the given Game is not of type
* Game.MY_GAME or is a played game. Otherwise, simply returns.
*/
private void checkGameMineAndExamined(Game game){
if ((game.getGameType() != Game.MY_GAME)||game.isPlayed())
throw new IllegalArgumentException("The given game must be of type Game.MY_GAME and an examined one");
}
/**
* Sends the "help" command to the server.
*/
public void showServerHelp(){
sendCommand("help");
}
/**
* Sends the specified question string to channel 1.
*/
public void sendHelpQuestion(String question){
sendCommand("tell 1 [" + Jin.getInstance().getAppName() + ' ' + Jin.getInstance().getAppVersion() + "] "+ question);
}
/**
* Overrides ChessclubConnection.execRunnable(Runnable) to execute the
* runnable on the AWT thread using SwingUtilities.invokeLater(Runnable),
* since this class is meant to be used by Jin, a graphical interface using
* Swing.
*
* @see ChessclubConnection#execRunnable(Runnable)
* @see SwingUtilities.invokeLater(Runnable)
*/
public void execRunnable(Runnable runnable){
SwingUtilities.invokeLater(runnable);
}
/**
* Method called to get user's channel list from server.
*/
public void updateChannelsList() {
sendCommand("inch " + this.getUsername());
}
/**
* Method called to remove channel from user's channel list.
*
* @param channelNumber - the number of removed channel.
*/
public void removeChannel(int channelNumber) {
sendCommand("-channel " + channelNumber);
}
/**
* Method called to add channel to user's channel list.
*
* @param channelNumber - the number of added channel.
*/
public void addChannel(int channelNumber) {
sendCommand("+channel " + channelNumber);
}
/**
* Returns ListenerManager that lets us register listeners
*/
public ChannelsListenerManager getChannelsListenerManager() {
return getFreechessListenerManager();
}
}
|
diff --git a/src/main/java/org/logic2j/solve/DefaultGoalSolver.java b/src/main/java/org/logic2j/solve/DefaultGoalSolver.java
index 4ac35709..93ba93f1 100644
--- a/src/main/java/org/logic2j/solve/DefaultGoalSolver.java
+++ b/src/main/java/org/logic2j/solve/DefaultGoalSolver.java
@@ -1,226 +1,231 @@
/*
* logic2j - "Bring Logic to your Java" - Copyright (C) 2011 [email protected]
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package org.logic2j.solve;
import org.logic2j.ClauseProvider;
import org.logic2j.PrologImplementor;
import org.logic2j.model.Clause;
import org.logic2j.model.InvalidTermException;
import org.logic2j.model.prim.PrimitiveInfo;
import org.logic2j.model.symbol.Struct;
import org.logic2j.model.symbol.Term;
import org.logic2j.model.symbol.TermApi;
import org.logic2j.model.symbol.Var;
import org.logic2j.model.var.VarBindings;
import org.logic2j.solve.ioc.SolutionListener;
import org.logic2j.util.ReportUtils;
/**
* Solve goals.
*
*/
public class DefaultGoalSolver implements GoalSolver {
private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(DefaultGoalSolver.class);
private static final boolean debug = logger.isDebugEnabled();
private static final TermApi TERM_API = new TermApi();
public int internalCounter = 0;
private final PrologImplementor prolog;
public DefaultGoalSolver(PrologImplementor theProlog) {
this.prolog = theProlog;
}
@Override
public void solveGoal(final Term goalTerm, final VarBindings goalVars, final GoalFrame callerFrame,
final SolutionListener theSolutionListener) {
solveGoalRecursive(goalTerm, goalVars, callerFrame, theSolutionListener);
}
@Override
public void solveGoalRecursive(final Term goalTerm, final VarBindings goalVars, final GoalFrame callerFrame,
final SolutionListener theSolutionListener) {
if (debug) {
logger.debug("Entering solveRecursive({}), callerFrame={}", goalTerm, callerFrame);
}
if (!(goalTerm instanceof Struct)) {
throw new InvalidTermException("Goal \"" + goalTerm + "\" is not a Struct and cannot be solved");
}
// Check if goal is a system predicate or a simple one to match against the theory
final Struct goalStruct = (Struct) goalTerm;
final PrimitiveInfo prim = goalStruct.getPrimitiveInfo();
final String functor = goalStruct.getName();
final int arity = goalStruct.getArity();
- if (Struct.FUNCTOR_COMMA == functor) {
+ if (Struct.FUNCTOR_COMMA == functor) {
// Logical AND
final SolutionListener[] listeners = new SolutionListener[arity];
// The last listener is the one of this overall COMMA sequence
listeners[arity - 1] = theSolutionListener;
// Allocates N-1 listeners. On solution, each will trigger solving of the next term
for (int i = 0; i < arity - 1; i++) {
final int index = i;
listeners[index] = new SolutionListener() {
@Override
public boolean onSolution() {
DefaultGoalSolver.this.internalCounter++;
final int index2 = index + 1;
solveGoalRecursive(goalStruct.getArg(index2), goalVars, callerFrame, listeners[index2]);
return true;
}
};
}
// Solve the first goal, redirecting all solutions to the first listener defined above
solveGoalRecursive(goalStruct.getArg(0), goalVars, callerFrame, listeners[0]);
} else if (Struct.FUNCTOR_SEMICOLON == functor) {
// Logical OR
for (int i = 0; i < arity; i++) {
// Solve all the left and right-and-sides, sequentially
solveGoalRecursive(goalStruct.getArg(i), goalVars, callerFrame, theSolutionListener);
}
} else if (Struct.FUNCTOR_CALL == functor) {
// call/1 is handled here for efficiency
if (arity != 1) {
throw new InvalidTermException("Primitive 'call' accepts only one argument, got " + arity);
}
Term target = TERM_API.substitute(goalStruct.getArg(0), goalVars, null);
+ VarBindings effectiveGoalVars = goalVars;
+ // Hack
+ if (target!=goalStruct.getArg(0) && effectiveGoalVars.getBinding((short) 0)!=null && effectiveGoalVars.getBinding((short) 0).isLiteral()) {
+ effectiveGoalVars = effectiveGoalVars.getBinding((short) 0).getLiteralVarBindings();
+ }
if (target instanceof Var) {
throw new InvalidTermException("Argument to primitive 'call' may not be a variable, was" + target);
}
if (debug) {
logger.debug("Calling FUNCTOR_CALL ------------------ {}", target);
}
- solveGoalRecursive(target, goalVars, callerFrame, theSolutionListener);
+ solveGoalRecursive(target, effectiveGoalVars, callerFrame, theSolutionListener);
} else if (prim != null) {
// Primitive implemented in Java
final Object resultOfPrimitive = prim.invoke(goalStruct, goalVars, callerFrame, theSolutionListener);
// Extract necessary objects from our current state
switch (prim.getType()) {
case PREDICATE:
break;
case FUNCTOR:
if (debug) {
logger.debug("Result of Functor {}: {}", goalStruct, resultOfPrimitive);
}
logger.error("We should not pass here with functors!? Directive {} ignored", goalStruct);
break;
case DIRECTIVE:
logger.warn("Result of Directive {} not yet used", goalStruct);
break;
}
} else {
// Simple "user" goal to demonstrate - find matching goals
// Now ready to iteratively try clause by first attempting to unify with its headTerm
// For this we need a new TrailFrame
final GoalFrame frameForAttemptingClauses = new GoalFrame(callerFrame);
for (ClauseProvider provider : this.prolog.getClauseProviders()) {
// TODO See if we could parallelize instead of sequential iteration, see https://github.com/ltettoni/logic2j/issues/18
for (Clause clause : provider.listMatchingClauses(goalStruct)) {
if (debug) {
logger.debug("Trying clause {}", clause);
}
// Handle user cancellation at beginning of loop, not at the end.
// This is in case user code returns onSolution()=false (do not continue)
// on what happens to be the last normal solution - in this case we can't tell if
// we are exiting because user requested it, or because there's no other solution!
if (frameForAttemptingClauses.isUserCanceled()) {
if (debug) {
logger.debug("!!! Stopping on SolutionListener's request");
}
break;
}
if (frameForAttemptingClauses.isCut()) {
if (debug) {
logger.debug("!!! cut found in clause");
}
break;
}
if (frameForAttemptingClauses.hasCutInSiblingSubsequentGoal()) {
if (debug) {
logger.debug("!!! Stopping because of cut in sibling subsequent goal");
}
break;
}
final VarBindings immutableVars = clause.getVars();
final VarBindings clauseVars = new VarBindings(immutableVars);
final Term clauseHead = clause.getHead();
if (debug) {
logger.debug("Unifying: goal={} with goalVars={}", goalTerm, goalVars);
logger.debug(" to: clauseHead={} with clauseVars={}", clauseHead, clauseVars);
}
// Now unify - this is the only place where free variables may become bound, and
// the trailFrame will remember this.
// Solutions will be notified from within this method.
// As a consequence, deunification can happen immediately afterwards, in this method, not outside in the caller
final boolean unified = this.prolog.getUnifyer().unify(goalTerm, goalVars, clauseHead, clauseVars,
frameForAttemptingClauses);
if (debug) {
logger.debug(" result=" + unified + ", goalVars={}, clauseVars={}", goalVars, clauseVars);
}
if (unified) {
if (clause.isFact()) {
if (debug) {
logger.debug("{} is a fact", clauseHead);
}
final boolean userContinue = theSolutionListener.onSolution();
if (!userContinue) {
frameForAttemptingClauses.raiseUserCanceled();
}
} else {
final Term newGoalTerm = clause.getBody();
if (debug) {
logger.debug(">> RECURS: {} is a theorem, body={}", clauseHead, newGoalTerm);
}
solveGoalRecursive(newGoalTerm, clauseVars, frameForAttemptingClauses, theSolutionListener);
if (debug) {
logger.debug("<< RECURS");
}
}
// We have now fired our solution(s), we no longer need our bound vars and can deunify
// Go to next solution: start by clearing our trailing vars
this.prolog.getUnifyer().deunify(frameForAttemptingClauses);
}
}
if (debug) {
logger.debug("Leaving loop on Clauses of " + provider);
}
}
if (debug) {
logger.debug("Last ClauseProvider done");
}
}
if (debug) {
logger.debug("Leaving solveGoalRecursive({})", goalTerm);
}
}
@Override
public String toString() {
return ReportUtils.shortDescription(this);
}
}
| false | true | public void solveGoalRecursive(final Term goalTerm, final VarBindings goalVars, final GoalFrame callerFrame,
final SolutionListener theSolutionListener) {
if (debug) {
logger.debug("Entering solveRecursive({}), callerFrame={}", goalTerm, callerFrame);
}
if (!(goalTerm instanceof Struct)) {
throw new InvalidTermException("Goal \"" + goalTerm + "\" is not a Struct and cannot be solved");
}
// Check if goal is a system predicate or a simple one to match against the theory
final Struct goalStruct = (Struct) goalTerm;
final PrimitiveInfo prim = goalStruct.getPrimitiveInfo();
final String functor = goalStruct.getName();
final int arity = goalStruct.getArity();
if (Struct.FUNCTOR_COMMA == functor) {
// Logical AND
final SolutionListener[] listeners = new SolutionListener[arity];
// The last listener is the one of this overall COMMA sequence
listeners[arity - 1] = theSolutionListener;
// Allocates N-1 listeners. On solution, each will trigger solving of the next term
for (int i = 0; i < arity - 1; i++) {
final int index = i;
listeners[index] = new SolutionListener() {
@Override
public boolean onSolution() {
DefaultGoalSolver.this.internalCounter++;
final int index2 = index + 1;
solveGoalRecursive(goalStruct.getArg(index2), goalVars, callerFrame, listeners[index2]);
return true;
}
};
}
// Solve the first goal, redirecting all solutions to the first listener defined above
solveGoalRecursive(goalStruct.getArg(0), goalVars, callerFrame, listeners[0]);
} else if (Struct.FUNCTOR_SEMICOLON == functor) {
// Logical OR
for (int i = 0; i < arity; i++) {
// Solve all the left and right-and-sides, sequentially
solveGoalRecursive(goalStruct.getArg(i), goalVars, callerFrame, theSolutionListener);
}
} else if (Struct.FUNCTOR_CALL == functor) {
// call/1 is handled here for efficiency
if (arity != 1) {
throw new InvalidTermException("Primitive 'call' accepts only one argument, got " + arity);
}
Term target = TERM_API.substitute(goalStruct.getArg(0), goalVars, null);
if (target instanceof Var) {
throw new InvalidTermException("Argument to primitive 'call' may not be a variable, was" + target);
}
if (debug) {
logger.debug("Calling FUNCTOR_CALL ------------------ {}", target);
}
solveGoalRecursive(target, goalVars, callerFrame, theSolutionListener);
} else if (prim != null) {
// Primitive implemented in Java
final Object resultOfPrimitive = prim.invoke(goalStruct, goalVars, callerFrame, theSolutionListener);
// Extract necessary objects from our current state
switch (prim.getType()) {
case PREDICATE:
break;
case FUNCTOR:
if (debug) {
logger.debug("Result of Functor {}: {}", goalStruct, resultOfPrimitive);
}
logger.error("We should not pass here with functors!? Directive {} ignored", goalStruct);
break;
case DIRECTIVE:
logger.warn("Result of Directive {} not yet used", goalStruct);
break;
}
} else {
// Simple "user" goal to demonstrate - find matching goals
// Now ready to iteratively try clause by first attempting to unify with its headTerm
// For this we need a new TrailFrame
final GoalFrame frameForAttemptingClauses = new GoalFrame(callerFrame);
for (ClauseProvider provider : this.prolog.getClauseProviders()) {
// TODO See if we could parallelize instead of sequential iteration, see https://github.com/ltettoni/logic2j/issues/18
for (Clause clause : provider.listMatchingClauses(goalStruct)) {
if (debug) {
logger.debug("Trying clause {}", clause);
}
// Handle user cancellation at beginning of loop, not at the end.
// This is in case user code returns onSolution()=false (do not continue)
// on what happens to be the last normal solution - in this case we can't tell if
// we are exiting because user requested it, or because there's no other solution!
if (frameForAttemptingClauses.isUserCanceled()) {
if (debug) {
logger.debug("!!! Stopping on SolutionListener's request");
}
break;
}
if (frameForAttemptingClauses.isCut()) {
if (debug) {
logger.debug("!!! cut found in clause");
}
break;
}
if (frameForAttemptingClauses.hasCutInSiblingSubsequentGoal()) {
if (debug) {
logger.debug("!!! Stopping because of cut in sibling subsequent goal");
}
break;
}
final VarBindings immutableVars = clause.getVars();
final VarBindings clauseVars = new VarBindings(immutableVars);
final Term clauseHead = clause.getHead();
if (debug) {
logger.debug("Unifying: goal={} with goalVars={}", goalTerm, goalVars);
logger.debug(" to: clauseHead={} with clauseVars={}", clauseHead, clauseVars);
}
// Now unify - this is the only place where free variables may become bound, and
// the trailFrame will remember this.
// Solutions will be notified from within this method.
// As a consequence, deunification can happen immediately afterwards, in this method, not outside in the caller
final boolean unified = this.prolog.getUnifyer().unify(goalTerm, goalVars, clauseHead, clauseVars,
frameForAttemptingClauses);
if (debug) {
logger.debug(" result=" + unified + ", goalVars={}, clauseVars={}", goalVars, clauseVars);
}
if (unified) {
if (clause.isFact()) {
if (debug) {
logger.debug("{} is a fact", clauseHead);
}
final boolean userContinue = theSolutionListener.onSolution();
if (!userContinue) {
frameForAttemptingClauses.raiseUserCanceled();
}
} else {
final Term newGoalTerm = clause.getBody();
if (debug) {
logger.debug(">> RECURS: {} is a theorem, body={}", clauseHead, newGoalTerm);
}
solveGoalRecursive(newGoalTerm, clauseVars, frameForAttemptingClauses, theSolutionListener);
if (debug) {
logger.debug("<< RECURS");
}
}
// We have now fired our solution(s), we no longer need our bound vars and can deunify
// Go to next solution: start by clearing our trailing vars
this.prolog.getUnifyer().deunify(frameForAttemptingClauses);
}
}
if (debug) {
logger.debug("Leaving loop on Clauses of " + provider);
}
}
if (debug) {
logger.debug("Last ClauseProvider done");
}
}
if (debug) {
logger.debug("Leaving solveGoalRecursive({})", goalTerm);
}
}
| public void solveGoalRecursive(final Term goalTerm, final VarBindings goalVars, final GoalFrame callerFrame,
final SolutionListener theSolutionListener) {
if (debug) {
logger.debug("Entering solveRecursive({}), callerFrame={}", goalTerm, callerFrame);
}
if (!(goalTerm instanceof Struct)) {
throw new InvalidTermException("Goal \"" + goalTerm + "\" is not a Struct and cannot be solved");
}
// Check if goal is a system predicate or a simple one to match against the theory
final Struct goalStruct = (Struct) goalTerm;
final PrimitiveInfo prim = goalStruct.getPrimitiveInfo();
final String functor = goalStruct.getName();
final int arity = goalStruct.getArity();
if (Struct.FUNCTOR_COMMA == functor) {
// Logical AND
final SolutionListener[] listeners = new SolutionListener[arity];
// The last listener is the one of this overall COMMA sequence
listeners[arity - 1] = theSolutionListener;
// Allocates N-1 listeners. On solution, each will trigger solving of the next term
for (int i = 0; i < arity - 1; i++) {
final int index = i;
listeners[index] = new SolutionListener() {
@Override
public boolean onSolution() {
DefaultGoalSolver.this.internalCounter++;
final int index2 = index + 1;
solveGoalRecursive(goalStruct.getArg(index2), goalVars, callerFrame, listeners[index2]);
return true;
}
};
}
// Solve the first goal, redirecting all solutions to the first listener defined above
solveGoalRecursive(goalStruct.getArg(0), goalVars, callerFrame, listeners[0]);
} else if (Struct.FUNCTOR_SEMICOLON == functor) {
// Logical OR
for (int i = 0; i < arity; i++) {
// Solve all the left and right-and-sides, sequentially
solveGoalRecursive(goalStruct.getArg(i), goalVars, callerFrame, theSolutionListener);
}
} else if (Struct.FUNCTOR_CALL == functor) {
// call/1 is handled here for efficiency
if (arity != 1) {
throw new InvalidTermException("Primitive 'call' accepts only one argument, got " + arity);
}
Term target = TERM_API.substitute(goalStruct.getArg(0), goalVars, null);
VarBindings effectiveGoalVars = goalVars;
// Hack
if (target!=goalStruct.getArg(0) && effectiveGoalVars.getBinding((short) 0)!=null && effectiveGoalVars.getBinding((short) 0).isLiteral()) {
effectiveGoalVars = effectiveGoalVars.getBinding((short) 0).getLiteralVarBindings();
}
if (target instanceof Var) {
throw new InvalidTermException("Argument to primitive 'call' may not be a variable, was" + target);
}
if (debug) {
logger.debug("Calling FUNCTOR_CALL ------------------ {}", target);
}
solveGoalRecursive(target, effectiveGoalVars, callerFrame, theSolutionListener);
} else if (prim != null) {
// Primitive implemented in Java
final Object resultOfPrimitive = prim.invoke(goalStruct, goalVars, callerFrame, theSolutionListener);
// Extract necessary objects from our current state
switch (prim.getType()) {
case PREDICATE:
break;
case FUNCTOR:
if (debug) {
logger.debug("Result of Functor {}: {}", goalStruct, resultOfPrimitive);
}
logger.error("We should not pass here with functors!? Directive {} ignored", goalStruct);
break;
case DIRECTIVE:
logger.warn("Result of Directive {} not yet used", goalStruct);
break;
}
} else {
// Simple "user" goal to demonstrate - find matching goals
// Now ready to iteratively try clause by first attempting to unify with its headTerm
// For this we need a new TrailFrame
final GoalFrame frameForAttemptingClauses = new GoalFrame(callerFrame);
for (ClauseProvider provider : this.prolog.getClauseProviders()) {
// TODO See if we could parallelize instead of sequential iteration, see https://github.com/ltettoni/logic2j/issues/18
for (Clause clause : provider.listMatchingClauses(goalStruct)) {
if (debug) {
logger.debug("Trying clause {}", clause);
}
// Handle user cancellation at beginning of loop, not at the end.
// This is in case user code returns onSolution()=false (do not continue)
// on what happens to be the last normal solution - in this case we can't tell if
// we are exiting because user requested it, or because there's no other solution!
if (frameForAttemptingClauses.isUserCanceled()) {
if (debug) {
logger.debug("!!! Stopping on SolutionListener's request");
}
break;
}
if (frameForAttemptingClauses.isCut()) {
if (debug) {
logger.debug("!!! cut found in clause");
}
break;
}
if (frameForAttemptingClauses.hasCutInSiblingSubsequentGoal()) {
if (debug) {
logger.debug("!!! Stopping because of cut in sibling subsequent goal");
}
break;
}
final VarBindings immutableVars = clause.getVars();
final VarBindings clauseVars = new VarBindings(immutableVars);
final Term clauseHead = clause.getHead();
if (debug) {
logger.debug("Unifying: goal={} with goalVars={}", goalTerm, goalVars);
logger.debug(" to: clauseHead={} with clauseVars={}", clauseHead, clauseVars);
}
// Now unify - this is the only place where free variables may become bound, and
// the trailFrame will remember this.
// Solutions will be notified from within this method.
// As a consequence, deunification can happen immediately afterwards, in this method, not outside in the caller
final boolean unified = this.prolog.getUnifyer().unify(goalTerm, goalVars, clauseHead, clauseVars,
frameForAttemptingClauses);
if (debug) {
logger.debug(" result=" + unified + ", goalVars={}, clauseVars={}", goalVars, clauseVars);
}
if (unified) {
if (clause.isFact()) {
if (debug) {
logger.debug("{} is a fact", clauseHead);
}
final boolean userContinue = theSolutionListener.onSolution();
if (!userContinue) {
frameForAttemptingClauses.raiseUserCanceled();
}
} else {
final Term newGoalTerm = clause.getBody();
if (debug) {
logger.debug(">> RECURS: {} is a theorem, body={}", clauseHead, newGoalTerm);
}
solveGoalRecursive(newGoalTerm, clauseVars, frameForAttemptingClauses, theSolutionListener);
if (debug) {
logger.debug("<< RECURS");
}
}
// We have now fired our solution(s), we no longer need our bound vars and can deunify
// Go to next solution: start by clearing our trailing vars
this.prolog.getUnifyer().deunify(frameForAttemptingClauses);
}
}
if (debug) {
logger.debug("Leaving loop on Clauses of " + provider);
}
}
if (debug) {
logger.debug("Last ClauseProvider done");
}
}
if (debug) {
logger.debug("Leaving solveGoalRecursive({})", goalTerm);
}
}
|
diff --git a/src/main/java/org/basex/query/func/JavaMapping.java b/src/main/java/org/basex/query/func/JavaMapping.java
index afc0f42bd..b01b93e8a 100644
--- a/src/main/java/org/basex/query/func/JavaMapping.java
+++ b/src/main/java/org/basex/query/func/JavaMapping.java
@@ -1,272 +1,273 @@
package org.basex.query.func;
import static javax.xml.datatype.DatatypeConstants.*;
import static org.basex.query.QueryText.*;
import static org.basex.query.util.Err.*;
import static org.basex.util.Token.*;
import java.lang.reflect.*;
import java.math.*;
import java.net.*;
import java.util.*;
import javax.xml.datatype.*;
import javax.xml.namespace.*;
import org.basex.core.*;
import org.basex.query.*;
import org.basex.query.expr.*;
import org.basex.query.item.*;
import org.basex.query.item.Type;
import org.basex.query.iter.*;
import org.basex.query.util.pkg.*;
import org.basex.util.*;
import org.w3c.dom.*;
import org.w3c.dom.Text;
/**
* This class contains common methods for executing Java code and mapping
* Java objects to XQuery values.
*
* @author BaseX Team 2005-12, BSD License
* @author Christian Gruen
*/
public abstract class JavaMapping extends Arr {
/** New keyword. */
static final String NEW = "new";
/** Input Java types. */
private static final Class<?>[] JAVA = {
String.class, boolean.class, Boolean.class, byte.class,
Byte.class, short.class, Short.class, int.class,
Integer.class, long.class, Long.class, float.class,
Float.class, double.class, Double.class, BigDecimal.class,
BigInteger.class, QName.class, CharSequence.class, char.class,
Character.class, URI.class, URL.class, Map.class
};
/** Resulting XQuery types. */
private static final Type[] XQUERY = {
AtomType.STR, AtomType.BLN, AtomType.BLN, AtomType.BYT,
AtomType.BYT, AtomType.SHR, AtomType.SHR, AtomType.INT,
AtomType.INT, AtomType.LNG, AtomType.LNG, AtomType.FLT,
AtomType.FLT, AtomType.DBL, AtomType.DBL, AtomType.DEC,
AtomType.ITR, AtomType.QNM, AtomType.STR, AtomType.STR,
AtomType.STR, AtomType.URI, AtomType.URI, FuncType.ANY_FUN
};
/**
* Constructor.
* @param ii input info
* @param a arguments
*/
JavaMapping(final InputInfo ii, final Expr[] a) {
super(ii, a);
}
@Override
public final Iter iter(final QueryContext ctx) throws QueryException {
return value(ctx).iter();
}
@Override
public final Value value(final QueryContext ctx) throws QueryException {
final Value[] args = new Value[expr.length];
for(int a = 0; a < expr.length; ++a) {
args[a] = ctx.value(expr[a]);
if(args[a].isEmpty()) XPEMPTY.thrw(info, description());
}
return toValue(eval(args, ctx));
}
/**
* Returns the result of the evaluated Java function.
* @param args arguments
* @param ctx query context
* @return arguments
* @throws QueryException query exception
*/
protected abstract Object eval(final Value[] args, final QueryContext ctx)
throws QueryException;
/**
* Converts the specified result to an XQuery value.
* @param res result object
* @return value
* @throws QueryException query exception
*/
public static Value toValue(final Object res) throws QueryException {
if(res == null) return Empty.SEQ;
if(res instanceof Value) return (Value) res;
if(res instanceof Iter) return ((Iter) res).value();
// find XQuery mapping for specified type
final Type type = type(res);
if(type != null) return type.cast(res, null);
if(!res.getClass().isArray()) return new Jav(res);
final ValueBuilder vb = new ValueBuilder();
if(res instanceof boolean[]) {
for(final boolean o : (boolean[]) res) vb.add(Bln.get(o));
} else if(res instanceof char[]) {
vb.add(Str.get(new String((char[]) res)));
} else if(res instanceof byte[]) {
for(final byte o : (byte[]) res) vb.add(new Int(o, AtomType.BYT));
} else if(res instanceof short[]) {
for(final short o : (short[]) res) vb.add(Int.get(o));
} else if(res instanceof int[]) {
for(final int o : (int[]) res) vb.add(Int.get(o));
} else if(res instanceof long[]) {
for(final long o : (long[]) res) vb.add(Int.get(o));
} else if(res instanceof float[]) {
for(final float o : (float[]) res) vb.add(Flt.get(o));
} else if(res instanceof double[]) {
for(final double o : (double[]) res) vb.add(Dbl.get(o));
} else {
for(final Object o : (Object[]) res) {
vb.add(o instanceof Value ? (Value) o : new Jav(o));
}
}
return vb.value();
}
/**
* Returns a new Java function instance.
* @param name function name
* @param args arguments
* @param ctx query context
* @param ii input info
* @return Java function, or {@code null}
* @throws QueryException query exception
*/
static JavaMapping get(final QNm name, final Expr[] args, final QueryContext ctx,
final InputInfo ii) throws QueryException {
// check for "java:" prefix
final byte[] uri = name.uri();
final byte[] ln = name.local();
final boolean java = startsWith(uri, JAVAPREF);
final QNm nm = new QNm(ln, java ? substring(uri, JAVAPREF.length) : uri);
// rewrite function name: convert dashes to upper-case initials
final TokenBuilder m = new TokenBuilder();
boolean dash = false;
for(int p = 0; p < ln.length; p += cl(ln, p)) {
final int ch = cp(ln, p);
if(dash) {
m.add(Character.toUpperCase(ch));
dash = false;
} else {
dash = ch == '-';
if(!dash) m.add(ch);
}
}
final String mth = m.toString();
// check imported Java modules
String path = string(nm.uri());
final String p = ModuleLoader.uri2path(path);
if(p != null) path = p;
path = path.replace("/", ".").substring(1);
final Object jm = ctx.modules.findImport(path);
if(jm != null) {
for(final Method meth : jm.getClass().getMethods()) {
- if(meth.getName().equals(mth)) {
+ // accept any method with identical name and arity
+ if(meth.getName().equals(mth) && meth.getParameterTypes().length == args.length) {
// check if user has sufficient permissions to call the function
Perm perm = Perm.ADMIN;
final QueryModule.Requires req = meth.getAnnotation(QueryModule.Requires.class);
if(req != null) perm = Perm.get(req.value().name());
if(!ctx.context.user.has(perm)) return null;
return new JavaModuleFunc(ii, jm, meth, args);
}
}
throw WHICHJAVA.thrw(ii, path + ':' + mth);
}
// only allowed with administrator permissions
if(!ctx.context.user.has(Perm.ADMIN)) return null;
// check addressed class
try {
return new JavaFunc(ii, ctx.modules.findClass(path), mth, args);
} catch(final ClassNotFoundException ex) {
// only throw exception if "java:" prefix was explicitly specified
if(java) throw WHICHJAVA.thrw(ii, uri);
} catch(final Throwable th) {
Util.debug(th);
throw INITJAVA.thrw(ii, th);
}
// no function found
return null;
}
/**
* Returns an appropriate XQuery data type for the specified Java object.
* @param o object
* @return xquery type, or {@code null} if no appropriate type was found
*/
public static Type type(final Object o) {
final Type t = type(o.getClass());
if(t != null) return t;
if(o instanceof Element) return NodeType.ELM;
if(o instanceof Document) return NodeType.DOC;
if(o instanceof DocumentFragment) return NodeType.DOC;
if(o instanceof Attr) return NodeType.ATT;
if(o instanceof Comment) return NodeType.COM;
if(o instanceof ProcessingInstruction) return NodeType.PI;
if(o instanceof Text) return NodeType.TXT;
if(o instanceof Duration) {
final Duration d = (Duration) o;
return !d.isSet(YEARS) && !d.isSet(MONTHS) ? AtomType.DTD :
!d.isSet(HOURS) && !d.isSet(MINUTES) && !d.isSet(SECONDS) ?
AtomType.YMD : AtomType.DUR;
}
if(o instanceof XMLGregorianCalendar) {
final QName type = ((XMLGregorianCalendar) o).getXMLSchemaType();
if(type == DATE) return AtomType.DAT;
if(type == DATETIME) return AtomType.DTM;
if(type == TIME) return AtomType.TIM;
if(type == GYEARMONTH) return AtomType.YMO;
if(type == GMONTHDAY) return AtomType.MDA;
if(type == GYEAR) return AtomType.YEA;
if(type == GMONTH) return AtomType.MON;
if(type == GDAY) return AtomType.DAY;
}
return null;
}
/**
* Returns an appropriate XQuery data type for the specified Java class.
* @param type Java type
* @return xquery type
*/
protected static Type type(final Class<?> type) {
for(int j = 0; j < JAVA.length; ++j) {
if(JAVA[j].isAssignableFrom(type)) return XQUERY[j];
}
return null;
}
/**
* Returns a string representation of all found arguments.
* @param args array with arguments
* @return string representation
*/
protected static String foundArgs(final Value[] args) {
// compose found arguments
final StringBuilder found = new StringBuilder();
for(final Value a : args) {
if(found.length() != 0) found.append(", ");
found.append(a.type());
}
return found.toString();
}
@Override
public boolean uses(final Use u) {
return u == Use.NDT || super.uses(u);
}
}
| true | true | static JavaMapping get(final QNm name, final Expr[] args, final QueryContext ctx,
final InputInfo ii) throws QueryException {
// check for "java:" prefix
final byte[] uri = name.uri();
final byte[] ln = name.local();
final boolean java = startsWith(uri, JAVAPREF);
final QNm nm = new QNm(ln, java ? substring(uri, JAVAPREF.length) : uri);
// rewrite function name: convert dashes to upper-case initials
final TokenBuilder m = new TokenBuilder();
boolean dash = false;
for(int p = 0; p < ln.length; p += cl(ln, p)) {
final int ch = cp(ln, p);
if(dash) {
m.add(Character.toUpperCase(ch));
dash = false;
} else {
dash = ch == '-';
if(!dash) m.add(ch);
}
}
final String mth = m.toString();
// check imported Java modules
String path = string(nm.uri());
final String p = ModuleLoader.uri2path(path);
if(p != null) path = p;
path = path.replace("/", ".").substring(1);
final Object jm = ctx.modules.findImport(path);
if(jm != null) {
for(final Method meth : jm.getClass().getMethods()) {
if(meth.getName().equals(mth)) {
// check if user has sufficient permissions to call the function
Perm perm = Perm.ADMIN;
final QueryModule.Requires req = meth.getAnnotation(QueryModule.Requires.class);
if(req != null) perm = Perm.get(req.value().name());
if(!ctx.context.user.has(perm)) return null;
return new JavaModuleFunc(ii, jm, meth, args);
}
}
throw WHICHJAVA.thrw(ii, path + ':' + mth);
}
// only allowed with administrator permissions
if(!ctx.context.user.has(Perm.ADMIN)) return null;
// check addressed class
try {
return new JavaFunc(ii, ctx.modules.findClass(path), mth, args);
} catch(final ClassNotFoundException ex) {
// only throw exception if "java:" prefix was explicitly specified
if(java) throw WHICHJAVA.thrw(ii, uri);
} catch(final Throwable th) {
Util.debug(th);
throw INITJAVA.thrw(ii, th);
}
// no function found
return null;
}
| static JavaMapping get(final QNm name, final Expr[] args, final QueryContext ctx,
final InputInfo ii) throws QueryException {
// check for "java:" prefix
final byte[] uri = name.uri();
final byte[] ln = name.local();
final boolean java = startsWith(uri, JAVAPREF);
final QNm nm = new QNm(ln, java ? substring(uri, JAVAPREF.length) : uri);
// rewrite function name: convert dashes to upper-case initials
final TokenBuilder m = new TokenBuilder();
boolean dash = false;
for(int p = 0; p < ln.length; p += cl(ln, p)) {
final int ch = cp(ln, p);
if(dash) {
m.add(Character.toUpperCase(ch));
dash = false;
} else {
dash = ch == '-';
if(!dash) m.add(ch);
}
}
final String mth = m.toString();
// check imported Java modules
String path = string(nm.uri());
final String p = ModuleLoader.uri2path(path);
if(p != null) path = p;
path = path.replace("/", ".").substring(1);
final Object jm = ctx.modules.findImport(path);
if(jm != null) {
for(final Method meth : jm.getClass().getMethods()) {
// accept any method with identical name and arity
if(meth.getName().equals(mth) && meth.getParameterTypes().length == args.length) {
// check if user has sufficient permissions to call the function
Perm perm = Perm.ADMIN;
final QueryModule.Requires req = meth.getAnnotation(QueryModule.Requires.class);
if(req != null) perm = Perm.get(req.value().name());
if(!ctx.context.user.has(perm)) return null;
return new JavaModuleFunc(ii, jm, meth, args);
}
}
throw WHICHJAVA.thrw(ii, path + ':' + mth);
}
// only allowed with administrator permissions
if(!ctx.context.user.has(Perm.ADMIN)) return null;
// check addressed class
try {
return new JavaFunc(ii, ctx.modules.findClass(path), mth, args);
} catch(final ClassNotFoundException ex) {
// only throw exception if "java:" prefix was explicitly specified
if(java) throw WHICHJAVA.thrw(ii, uri);
} catch(final Throwable th) {
Util.debug(th);
throw INITJAVA.thrw(ii, th);
}
// no function found
return null;
}
|
diff --git a/gruppe32/src/Aktion.java b/gruppe32/src/Aktion.java
index 1cd5309..dd3d6b2 100644
--- a/gruppe32/src/Aktion.java
+++ b/gruppe32/src/Aktion.java
@@ -1,261 +1,261 @@
import javax.swing.JFrame;
import javax.swing.JLabel;
/**
* Klassenkommentar:
* Hauptspiellogik bzw. was tun wenn was passiert
*
*/
public class Aktion{
private static int figurX;
private static int figurY;
private static int aktuellesLevel = 0;
private static final int BODEN = 0;
private static final int MAUER = 1;
private static final int START = 2;
private static final int ZIEL = 3;
private static final int FALLE = 4;
private static final int MOB = 5;
private static final int FIGUR = 6;
private static final int SIEG = 7;
private static final int RECHTS = 0;
private static final int UNTEN = 1;
private static final int LINKS = 2;
private static final int OBEN= 3;
private static final int CHECKPOINT = 8;
int leben=3;
boolean reachedCheckpoint;
/**
* Methode bewegt Figur anhand von Koordinaten
*
*/
public void figurBewegen(int richtung){
if (richtung == RECHTS){
if ((Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX+1,figurY)==BODEN)
|(Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX+1,figurY)==FIGUR)){
Menu.figurBewegen(aktuellesLevel,figurX,figurY,figurX+1,figurY);
figurX=figurX+1;
}
else if ((Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX+1,figurY)==START)&(aktuellesLevel>0)){
aktuellesLevel--;
Menu.levelDarstellen(aktuellesLevel);
Menu.figurZumZiel(aktuellesLevel);
}
else if (Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX+1,figurY)==ZIEL){
aktuellesLevel++;
Menu.levelDarstellen(aktuellesLevel);
Menu.figurReset(aktuellesLevel, figurX, figurY);
}
else if ((Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX+1,figurY)==FALLE)|(Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX+1,figurY)==MOB)){
if ((leben>0)&reachedCheckpoint==true){
aktuellesLevel=2;
Menu.levelDarstellen(2);
Menu.figurReset(2, figurX, figurY);
leben--;
}
else {
reachedCheckpoint=false;
Menu.figurReset(0,figurX,figurY);
Menu.levelDarstellen(0);
Menu.gameOver();
}
}
else if (Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX+1,figurY)==SIEG){
aktuellesLevel=0;
Menu.sieg();
//Menu.levelDarstellen(aktuellesLevel);
//Menu.figurReset(aktuellesLevel, figurX, figurY);
}
else if (Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX+1,figurY)==CHECKPOINT){
reachedCheckpoint=true;
Menu.figurBewegen(aktuellesLevel,figurX,figurY,figurX+1,figurY);
figurX=figurX+1;
Spielfeld.wertSetzenBeiXY(2,9,13,BODEN);
}
}
else if (richtung == UNTEN){
if ((Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX,figurY-1)==BODEN)
- |(Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX,figurY+1)==FIGUR)){
+ |(Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX,figurY-1)==FIGUR)){
Menu.figurBewegen(aktuellesLevel,figurX,figurY,figurX,figurY-1);
figurY=figurY-1;
}
else if ((Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX,figurY-1)==START)&(aktuellesLevel>0)){
aktuellesLevel--;
Menu.levelDarstellen(aktuellesLevel);
Menu.figurZumZiel(aktuellesLevel);
}
else if (Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX,figurY-1)==ZIEL){
//Menu.figurBewegen(aktuellesLevel,figurX,figurY,figurX,figurY-1);
aktuellesLevel++;
Menu.levelDarstellen(aktuellesLevel);
Menu.figurReset(aktuellesLevel, figurX, figurY);
}
else if ((Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX,figurY-1)==FALLE)|(Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX,figurY-1)==MOB)){
if ((leben>0)&reachedCheckpoint==true){
aktuellesLevel=2;
Menu.levelDarstellen(2);
Menu.figurReset(2, figurX, figurY);
leben--;
}
else {
reachedCheckpoint=false;
Menu.figurReset(0,figurX,figurY);
Menu.levelDarstellen(0);
Menu.gameOver();
}
}
else if (Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX,figurY-1)==SIEG){
aktuellesLevel=0;
Menu.sieg();
//Menu.levelDarstellen(aktuellesLevel);
//Menu.figurReset(aktuellesLevel, figurX, figurY);
}
else if (Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX,figurY-1)==CHECKPOINT){
reachedCheckpoint=true;
Menu.figurBewegen(aktuellesLevel,figurX,figurY,figurX,figurY-1);
figurY=figurY-1;
Spielfeld.wertSetzenBeiXY(2,9,13,BODEN);
}
}
else if (richtung == LINKS){ //links
if ((Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX-1,figurY)==BODEN)
|(Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX-1,figurY)==FIGUR)){
Menu.figurBewegen(aktuellesLevel,figurX,figurY,figurX-1,figurY);
figurX=figurX-1;
}
else if ((Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX-1,figurY)==START)&(aktuellesLevel>0)){
aktuellesLevel--;
Menu.levelDarstellen(aktuellesLevel);
Menu.figurZumZiel(aktuellesLevel);
}
else if (Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX-1,figurY)==ZIEL){
//Menu.figurBewegen(aktuellesLevel,figurX,figurY,figurX+1,figurY);
aktuellesLevel++;
Menu.levelDarstellen(aktuellesLevel);
Menu.figurReset(aktuellesLevel, figurX, figurY);
}
else if ((Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX-1,figurY)==FALLE)|(Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX-1,figurY)==MOB)){
if (leben>0){
aktuellesLevel=2;
Menu.levelDarstellen(2);
Menu.figurReset(2, figurX, figurY);
leben--;
}
else {
reachedCheckpoint=false;
Menu.figurReset(0,figurX,figurY);
Menu.levelDarstellen(0);
Menu.gameOver();
}
}
else if (Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX-1,figurY)==SIEG){
aktuellesLevel=0;
Menu.sieg();
//Menu.levelDarstellen(aktuellesLevel);
//Menu.figurReset(aktuellesLevel, figurX, figurY);
}
else if (Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX-1,figurY)==CHECKPOINT){
reachedCheckpoint=true;
Menu.figurBewegen(aktuellesLevel,figurX,figurY,figurX-1,figurY);
figurX=figurX-1;
Spielfeld.wertSetzenBeiXY(2,9,13,BODEN);
}
}
else if (richtung == OBEN){ //oben
if ((Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX,figurY+1)==BODEN)
|(Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX,figurY+1)==FIGUR)){
Menu.figurBewegen(aktuellesLevel,figurX,figurY,figurX,figurY+1);
figurY=figurY+1;
}
else if ((Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX,figurY+1)==START)&(aktuellesLevel>0)){
aktuellesLevel--;
Menu.levelDarstellen(aktuellesLevel);
Menu.figurZumZiel(aktuellesLevel);
}
else if (Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX,figurY+1)==ZIEL){
aktuellesLevel++;
Menu.levelDarstellen(aktuellesLevel);
Menu.figurReset(aktuellesLevel, figurX, figurY);
}
else if ((Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX,figurY+1)==FALLE)
|(Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX,figurY+1)==MOB)){
if (leben>0){
aktuellesLevel=2;
Menu.levelDarstellen(2);
Menu.figurReset(2, figurX, figurY);
leben--;
}
else {
reachedCheckpoint=false;
Menu.figurReset(0,figurX,figurY);
Menu.levelDarstellen(0);
Menu.gameOver();
}
}
else if (Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX,figurY+1)==SIEG){
//aktuellesLevel=0;
Menu.sieg();
//Menu.levelDarstellen(aktuellesLevel);
//Menu.figurReset(aktuellesLevel, figurX, figurY);
}
else if (Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX,figurY+1)==CHECKPOINT){
reachedCheckpoint=true;
Menu.figurBewegen(aktuellesLevel,figurX,figurY,figurX,figurY+1);
figurY=figurY+1;
Spielfeld.wertSetzenBeiXY(2,9,13,BODEN);
}
}
}
/**
* Methode setzt Figur
*
*/
public static void setFigurXY(int x, int y){
figurX=x;
figurY=y;
}
/**
*
* Methode setzt das aktuelle Level
*
*/
public static void setLevel(int level){
aktuellesLevel = level;
}
}
| true | true | public void figurBewegen(int richtung){
if (richtung == RECHTS){
if ((Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX+1,figurY)==BODEN)
|(Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX+1,figurY)==FIGUR)){
Menu.figurBewegen(aktuellesLevel,figurX,figurY,figurX+1,figurY);
figurX=figurX+1;
}
else if ((Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX+1,figurY)==START)&(aktuellesLevel>0)){
aktuellesLevel--;
Menu.levelDarstellen(aktuellesLevel);
Menu.figurZumZiel(aktuellesLevel);
}
else if (Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX+1,figurY)==ZIEL){
aktuellesLevel++;
Menu.levelDarstellen(aktuellesLevel);
Menu.figurReset(aktuellesLevel, figurX, figurY);
}
else if ((Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX+1,figurY)==FALLE)|(Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX+1,figurY)==MOB)){
if ((leben>0)&reachedCheckpoint==true){
aktuellesLevel=2;
Menu.levelDarstellen(2);
Menu.figurReset(2, figurX, figurY);
leben--;
}
else {
reachedCheckpoint=false;
Menu.figurReset(0,figurX,figurY);
Menu.levelDarstellen(0);
Menu.gameOver();
}
}
else if (Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX+1,figurY)==SIEG){
aktuellesLevel=0;
Menu.sieg();
//Menu.levelDarstellen(aktuellesLevel);
//Menu.figurReset(aktuellesLevel, figurX, figurY);
}
else if (Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX+1,figurY)==CHECKPOINT){
reachedCheckpoint=true;
Menu.figurBewegen(aktuellesLevel,figurX,figurY,figurX+1,figurY);
figurX=figurX+1;
Spielfeld.wertSetzenBeiXY(2,9,13,BODEN);
}
}
else if (richtung == UNTEN){
if ((Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX,figurY-1)==BODEN)
|(Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX,figurY+1)==FIGUR)){
Menu.figurBewegen(aktuellesLevel,figurX,figurY,figurX,figurY-1);
figurY=figurY-1;
}
else if ((Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX,figurY-1)==START)&(aktuellesLevel>0)){
aktuellesLevel--;
Menu.levelDarstellen(aktuellesLevel);
Menu.figurZumZiel(aktuellesLevel);
}
else if (Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX,figurY-1)==ZIEL){
//Menu.figurBewegen(aktuellesLevel,figurX,figurY,figurX,figurY-1);
aktuellesLevel++;
Menu.levelDarstellen(aktuellesLevel);
Menu.figurReset(aktuellesLevel, figurX, figurY);
}
else if ((Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX,figurY-1)==FALLE)|(Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX,figurY-1)==MOB)){
if ((leben>0)&reachedCheckpoint==true){
aktuellesLevel=2;
Menu.levelDarstellen(2);
Menu.figurReset(2, figurX, figurY);
leben--;
}
else {
reachedCheckpoint=false;
Menu.figurReset(0,figurX,figurY);
Menu.levelDarstellen(0);
Menu.gameOver();
}
}
else if (Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX,figurY-1)==SIEG){
aktuellesLevel=0;
Menu.sieg();
//Menu.levelDarstellen(aktuellesLevel);
//Menu.figurReset(aktuellesLevel, figurX, figurY);
}
else if (Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX,figurY-1)==CHECKPOINT){
reachedCheckpoint=true;
Menu.figurBewegen(aktuellesLevel,figurX,figurY,figurX,figurY-1);
figurY=figurY-1;
Spielfeld.wertSetzenBeiXY(2,9,13,BODEN);
}
}
else if (richtung == LINKS){ //links
if ((Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX-1,figurY)==BODEN)
|(Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX-1,figurY)==FIGUR)){
Menu.figurBewegen(aktuellesLevel,figurX,figurY,figurX-1,figurY);
figurX=figurX-1;
}
else if ((Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX-1,figurY)==START)&(aktuellesLevel>0)){
aktuellesLevel--;
Menu.levelDarstellen(aktuellesLevel);
Menu.figurZumZiel(aktuellesLevel);
}
else if (Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX-1,figurY)==ZIEL){
//Menu.figurBewegen(aktuellesLevel,figurX,figurY,figurX+1,figurY);
aktuellesLevel++;
Menu.levelDarstellen(aktuellesLevel);
Menu.figurReset(aktuellesLevel, figurX, figurY);
}
else if ((Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX-1,figurY)==FALLE)|(Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX-1,figurY)==MOB)){
if (leben>0){
aktuellesLevel=2;
Menu.levelDarstellen(2);
Menu.figurReset(2, figurX, figurY);
leben--;
}
else {
reachedCheckpoint=false;
Menu.figurReset(0,figurX,figurY);
Menu.levelDarstellen(0);
Menu.gameOver();
}
}
else if (Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX-1,figurY)==SIEG){
aktuellesLevel=0;
Menu.sieg();
//Menu.levelDarstellen(aktuellesLevel);
//Menu.figurReset(aktuellesLevel, figurX, figurY);
}
else if (Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX-1,figurY)==CHECKPOINT){
reachedCheckpoint=true;
Menu.figurBewegen(aktuellesLevel,figurX,figurY,figurX-1,figurY);
figurX=figurX-1;
Spielfeld.wertSetzenBeiXY(2,9,13,BODEN);
}
}
else if (richtung == OBEN){ //oben
if ((Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX,figurY+1)==BODEN)
|(Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX,figurY+1)==FIGUR)){
Menu.figurBewegen(aktuellesLevel,figurX,figurY,figurX,figurY+1);
figurY=figurY+1;
}
else if ((Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX,figurY+1)==START)&(aktuellesLevel>0)){
aktuellesLevel--;
Menu.levelDarstellen(aktuellesLevel);
Menu.figurZumZiel(aktuellesLevel);
}
else if (Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX,figurY+1)==ZIEL){
aktuellesLevel++;
Menu.levelDarstellen(aktuellesLevel);
Menu.figurReset(aktuellesLevel, figurX, figurY);
}
else if ((Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX,figurY+1)==FALLE)
|(Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX,figurY+1)==MOB)){
if (leben>0){
aktuellesLevel=2;
Menu.levelDarstellen(2);
Menu.figurReset(2, figurX, figurY);
leben--;
}
else {
reachedCheckpoint=false;
Menu.figurReset(0,figurX,figurY);
Menu.levelDarstellen(0);
Menu.gameOver();
}
}
else if (Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX,figurY+1)==SIEG){
//aktuellesLevel=0;
Menu.sieg();
//Menu.levelDarstellen(aktuellesLevel);
//Menu.figurReset(aktuellesLevel, figurX, figurY);
}
else if (Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX,figurY+1)==CHECKPOINT){
reachedCheckpoint=true;
Menu.figurBewegen(aktuellesLevel,figurX,figurY,figurX,figurY+1);
figurY=figurY+1;
Spielfeld.wertSetzenBeiXY(2,9,13,BODEN);
}
}
}
| public void figurBewegen(int richtung){
if (richtung == RECHTS){
if ((Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX+1,figurY)==BODEN)
|(Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX+1,figurY)==FIGUR)){
Menu.figurBewegen(aktuellesLevel,figurX,figurY,figurX+1,figurY);
figurX=figurX+1;
}
else if ((Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX+1,figurY)==START)&(aktuellesLevel>0)){
aktuellesLevel--;
Menu.levelDarstellen(aktuellesLevel);
Menu.figurZumZiel(aktuellesLevel);
}
else if (Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX+1,figurY)==ZIEL){
aktuellesLevel++;
Menu.levelDarstellen(aktuellesLevel);
Menu.figurReset(aktuellesLevel, figurX, figurY);
}
else if ((Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX+1,figurY)==FALLE)|(Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX+1,figurY)==MOB)){
if ((leben>0)&reachedCheckpoint==true){
aktuellesLevel=2;
Menu.levelDarstellen(2);
Menu.figurReset(2, figurX, figurY);
leben--;
}
else {
reachedCheckpoint=false;
Menu.figurReset(0,figurX,figurY);
Menu.levelDarstellen(0);
Menu.gameOver();
}
}
else if (Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX+1,figurY)==SIEG){
aktuellesLevel=0;
Menu.sieg();
//Menu.levelDarstellen(aktuellesLevel);
//Menu.figurReset(aktuellesLevel, figurX, figurY);
}
else if (Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX+1,figurY)==CHECKPOINT){
reachedCheckpoint=true;
Menu.figurBewegen(aktuellesLevel,figurX,figurY,figurX+1,figurY);
figurX=figurX+1;
Spielfeld.wertSetzenBeiXY(2,9,13,BODEN);
}
}
else if (richtung == UNTEN){
if ((Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX,figurY-1)==BODEN)
|(Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX,figurY-1)==FIGUR)){
Menu.figurBewegen(aktuellesLevel,figurX,figurY,figurX,figurY-1);
figurY=figurY-1;
}
else if ((Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX,figurY-1)==START)&(aktuellesLevel>0)){
aktuellesLevel--;
Menu.levelDarstellen(aktuellesLevel);
Menu.figurZumZiel(aktuellesLevel);
}
else if (Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX,figurY-1)==ZIEL){
//Menu.figurBewegen(aktuellesLevel,figurX,figurY,figurX,figurY-1);
aktuellesLevel++;
Menu.levelDarstellen(aktuellesLevel);
Menu.figurReset(aktuellesLevel, figurX, figurY);
}
else if ((Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX,figurY-1)==FALLE)|(Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX,figurY-1)==MOB)){
if ((leben>0)&reachedCheckpoint==true){
aktuellesLevel=2;
Menu.levelDarstellen(2);
Menu.figurReset(2, figurX, figurY);
leben--;
}
else {
reachedCheckpoint=false;
Menu.figurReset(0,figurX,figurY);
Menu.levelDarstellen(0);
Menu.gameOver();
}
}
else if (Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX,figurY-1)==SIEG){
aktuellesLevel=0;
Menu.sieg();
//Menu.levelDarstellen(aktuellesLevel);
//Menu.figurReset(aktuellesLevel, figurX, figurY);
}
else if (Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX,figurY-1)==CHECKPOINT){
reachedCheckpoint=true;
Menu.figurBewegen(aktuellesLevel,figurX,figurY,figurX,figurY-1);
figurY=figurY-1;
Spielfeld.wertSetzenBeiXY(2,9,13,BODEN);
}
}
else if (richtung == LINKS){ //links
if ((Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX-1,figurY)==BODEN)
|(Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX-1,figurY)==FIGUR)){
Menu.figurBewegen(aktuellesLevel,figurX,figurY,figurX-1,figurY);
figurX=figurX-1;
}
else if ((Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX-1,figurY)==START)&(aktuellesLevel>0)){
aktuellesLevel--;
Menu.levelDarstellen(aktuellesLevel);
Menu.figurZumZiel(aktuellesLevel);
}
else if (Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX-1,figurY)==ZIEL){
//Menu.figurBewegen(aktuellesLevel,figurX,figurY,figurX+1,figurY);
aktuellesLevel++;
Menu.levelDarstellen(aktuellesLevel);
Menu.figurReset(aktuellesLevel, figurX, figurY);
}
else if ((Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX-1,figurY)==FALLE)|(Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX-1,figurY)==MOB)){
if (leben>0){
aktuellesLevel=2;
Menu.levelDarstellen(2);
Menu.figurReset(2, figurX, figurY);
leben--;
}
else {
reachedCheckpoint=false;
Menu.figurReset(0,figurX,figurY);
Menu.levelDarstellen(0);
Menu.gameOver();
}
}
else if (Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX-1,figurY)==SIEG){
aktuellesLevel=0;
Menu.sieg();
//Menu.levelDarstellen(aktuellesLevel);
//Menu.figurReset(aktuellesLevel, figurX, figurY);
}
else if (Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX-1,figurY)==CHECKPOINT){
reachedCheckpoint=true;
Menu.figurBewegen(aktuellesLevel,figurX,figurY,figurX-1,figurY);
figurX=figurX-1;
Spielfeld.wertSetzenBeiXY(2,9,13,BODEN);
}
}
else if (richtung == OBEN){ //oben
if ((Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX,figurY+1)==BODEN)
|(Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX,figurY+1)==FIGUR)){
Menu.figurBewegen(aktuellesLevel,figurX,figurY,figurX,figurY+1);
figurY=figurY+1;
}
else if ((Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX,figurY+1)==START)&(aktuellesLevel>0)){
aktuellesLevel--;
Menu.levelDarstellen(aktuellesLevel);
Menu.figurZumZiel(aktuellesLevel);
}
else if (Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX,figurY+1)==ZIEL){
aktuellesLevel++;
Menu.levelDarstellen(aktuellesLevel);
Menu.figurReset(aktuellesLevel, figurX, figurY);
}
else if ((Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX,figurY+1)==FALLE)
|(Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX,figurY+1)==MOB)){
if (leben>0){
aktuellesLevel=2;
Menu.levelDarstellen(2);
Menu.figurReset(2, figurX, figurY);
leben--;
}
else {
reachedCheckpoint=false;
Menu.figurReset(0,figurX,figurY);
Menu.levelDarstellen(0);
Menu.gameOver();
}
}
else if (Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX,figurY+1)==SIEG){
//aktuellesLevel=0;
Menu.sieg();
//Menu.levelDarstellen(aktuellesLevel);
//Menu.figurReset(aktuellesLevel, figurX, figurY);
}
else if (Spielfeld.wertLesenBeiXY(aktuellesLevel,figurX,figurY+1)==CHECKPOINT){
reachedCheckpoint=true;
Menu.figurBewegen(aktuellesLevel,figurX,figurY,figurX,figurY+1);
figurY=figurY+1;
Spielfeld.wertSetzenBeiXY(2,9,13,BODEN);
}
}
}
|
diff --git a/src/com/android/email/activity/setup/AccountSettings.java b/src/com/android/email/activity/setup/AccountSettings.java
index 26481ef9..056934a9 100644
--- a/src/com/android/email/activity/setup/AccountSettings.java
+++ b/src/com/android/email/activity/setup/AccountSettings.java
@@ -1,391 +1,391 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.email.activity.setup;
import com.android.email.Email;
import com.android.email.R;
import com.android.email.mail.MessagingException;
import com.android.email.mail.Sender;
import com.android.email.mail.Store;
import com.android.email.provider.EmailContent.Account;
import com.android.email.provider.EmailContent.AccountColumns;
import com.android.email.provider.EmailContent.HostAuth;
import com.android.email.provider.EmailContent.HostAuthColumns;
import com.android.exchange.Eas;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceCategory;
import android.preference.RingtonePreference;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.KeyEvent;
public class AccountSettings extends PreferenceActivity {
private static final String PREFERENCE_TOP_CATEGORY = "account_settings";
private static final String PREFERENCE_DESCRIPTION = "account_description";
private static final String PREFERENCE_NAME = "account_name";
private static final String PREFERENCE_FREQUENCY = "account_check_frequency";
private static final String PREFERENCE_DEFAULT = "account_default";
private static final String PREFERENCE_NOTIFY = "account_notify";
private static final String PREFERENCE_VIBRATE = "account_vibrate";
private static final String PREFERENCE_RINGTONE = "account_ringtone";
private static final String PREFERENCE_SERVER_CATERGORY = "account_servers";
private static final String PREFERENCE_INCOMING = "incoming";
private static final String PREFERENCE_OUTGOING = "outgoing";
private static final String PREFERENCE_SYNC_CONTACTS = "account_sync_contacts";
// NOTE: This string must match the one in res/xml/account_preferences.xml
public static final String ACTION_ACCOUNT_MANAGER_ENTRY =
"com.android.email.activity.setup.ACCOUNT_MANAGER_ENTRY";
// NOTE: This constant should eventually be defined in android.accounts.Constants, but for
// now we define it here
private static final String ACCOUNT_MANAGER_EXTRA_ACCOUNT = "account";
private static final String EXTRA_ACCOUNT_ID = "account_id";
private long mAccountId = -1;
private Account mAccount;
private boolean mAccountDirty;
private EditTextPreference mAccountDescription;
private EditTextPreference mAccountName;
private ListPreference mCheckFrequency;
private ListPreference mSyncWindow;
private CheckBoxPreference mAccountDefault;
private CheckBoxPreference mAccountNotify;
private CheckBoxPreference mAccountVibrate;
private RingtonePreference mAccountRingtone;
private CheckBoxPreference mSyncContacts;
/**
* Display (and edit) settings for a specific account
*/
public static void actionSettings(Activity fromActivity, long accountId) {
Intent i = new Intent(fromActivity, AccountSettings.class);
i.putExtra(EXTRA_ACCOUNT_ID, accountId);
fromActivity.startActivity(i);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent i = getIntent();
- if (i.getAction().equals(ACTION_ACCOUNT_MANAGER_ENTRY)) {
+ if (ACTION_ACCOUNT_MANAGER_ENTRY.equals(i.getAction())) {
// This case occurs if we're changing account settings from Settings -> Accounts
setAccountIdFromAccountManagerIntent();
} else {
// Otherwise, we're called from within the Email app and look for our extra
mAccountId = i.getLongExtra(EXTRA_ACCOUNT_ID, -1);
}
// If there's no accountId, we're done
if (mAccountId == -1) {
finish();
return;
}
mAccount = Account.restoreAccountWithId(this, mAccountId);
// Similarly, if the account has been deleted
if (mAccount == null) {
finish();
return;
}
mAccount.mHostAuthRecv = HostAuth.restoreHostAuthWithId(this, mAccount.mHostAuthKeyRecv);
mAccount.mHostAuthSend = HostAuth.restoreHostAuthWithId(this, mAccount.mHostAuthKeySend);
// Or if HostAuth's have been deleted
if (mAccount.mHostAuthRecv == null || mAccount.mHostAuthSend == null) {
finish();
return;
}
mAccountDirty = false;
addPreferencesFromResource(R.xml.account_settings_preferences);
PreferenceCategory topCategory = (PreferenceCategory) findPreference(PREFERENCE_TOP_CATEGORY);
topCategory.setTitle(getString(R.string.account_settings_title_fmt));
mAccountDescription = (EditTextPreference) findPreference(PREFERENCE_DESCRIPTION);
mAccountDescription.setSummary(mAccount.getDisplayName());
mAccountDescription.setText(mAccount.getDisplayName());
mAccountDescription.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
final String summary = newValue.toString();
mAccountDescription.setSummary(summary);
mAccountDescription.setText(summary);
return false;
}
});
mAccountName = (EditTextPreference) findPreference(PREFERENCE_NAME);
mAccountName.setSummary(mAccount.getSenderName());
mAccountName.setText(mAccount.getSenderName());
mAccountName.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
final String summary = newValue.toString();
mAccountName.setSummary(summary);
mAccountName.setText(summary);
return false;
}
});
mCheckFrequency = (ListPreference) findPreference(PREFERENCE_FREQUENCY);
// Before setting value, we may need to adjust the lists
Store.StoreInfo info = Store.StoreInfo.getStoreInfo(mAccount.getStoreUri(this), this);
if (info.mPushSupported) {
mCheckFrequency.setEntries(R.array.account_settings_check_frequency_entries_push);
mCheckFrequency.setEntryValues(R.array.account_settings_check_frequency_values_push);
}
mCheckFrequency.setValue(String.valueOf(mAccount.getSyncInterval()));
mCheckFrequency.setSummary(mCheckFrequency.getEntry());
mCheckFrequency.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
final String summary = newValue.toString();
int index = mCheckFrequency.findIndexOfValue(summary);
mCheckFrequency.setSummary(mCheckFrequency.getEntries()[index]);
mCheckFrequency.setValue(summary);
return false;
}
});
// Add check window preference
mSyncWindow = null;
if (info.mVisibleLimitDefault == -1) {
mSyncWindow = new ListPreference(this);
mSyncWindow.setTitle(R.string.account_setup_options_mail_window_label);
mSyncWindow.setEntries(R.array.account_settings_mail_window_entries);
mSyncWindow.setEntryValues(R.array.account_settings_mail_window_values);
mSyncWindow.setValue(String.valueOf(mAccount.getSyncLookback()));
mSyncWindow.setSummary(mSyncWindow.getEntry());
mSyncWindow.setOrder(4);
mSyncWindow.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
final String summary = newValue.toString();
int index = mSyncWindow.findIndexOfValue(summary);
mSyncWindow.setSummary(mSyncWindow.getEntries()[index]);
mSyncWindow.setValue(summary);
return false;
}
});
topCategory.addPreference(mSyncWindow);
}
mAccountDefault = (CheckBoxPreference) findPreference(PREFERENCE_DEFAULT);
mAccountDefault.setChecked(mAccount.mId == Account.getDefaultAccountId(this));
mAccountNotify = (CheckBoxPreference) findPreference(PREFERENCE_NOTIFY);
mAccountNotify.setChecked(0 != (mAccount.getFlags() & Account.FLAGS_NOTIFY_NEW_MAIL));
mAccountRingtone = (RingtonePreference) findPreference(PREFERENCE_RINGTONE);
// XXX: The following two lines act as a workaround for the RingtonePreference
// which does not let us set/get the value programmatically
SharedPreferences prefs = mAccountRingtone.getPreferenceManager().getSharedPreferences();
prefs.edit().putString(PREFERENCE_RINGTONE, mAccount.getRingtone()).commit();
mAccountVibrate = (CheckBoxPreference) findPreference(PREFERENCE_VIBRATE);
mAccountVibrate.setChecked(0 !=
(mAccount.getFlags() & Account.FLAGS_VIBRATE));
findPreference(PREFERENCE_INCOMING).setOnPreferenceClickListener(
new Preference.OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
onIncomingSettings();
return true;
}
});
// Hide the outgoing account setup link if it's not activated
Preference prefOutgoing = findPreference(PREFERENCE_OUTGOING);
boolean showOutgoing = true;
try {
Sender sender = Sender.getInstance(getApplication(), mAccount.getSenderUri(this));
if (sender != null) {
Class<? extends android.app.Activity> setting = sender.getSettingActivityClass();
showOutgoing = (setting != null);
}
} catch (MessagingException me) {
// just leave showOutgoing as true - bias towards showing it, so user can fix it
}
if (showOutgoing) {
prefOutgoing.setOnPreferenceClickListener(
new Preference.OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
onOutgoingSettings();
return true;
}
});
} else {
PreferenceCategory serverCategory = (PreferenceCategory) findPreference(
PREFERENCE_SERVER_CATERGORY);
serverCategory.removePreference(prefOutgoing);
}
mSyncContacts = (CheckBoxPreference) findPreference(PREFERENCE_SYNC_CONTACTS);
if (mAccount.mHostAuthRecv.mProtocol.equals("eas")) {
String login = mAccount.mHostAuthRecv.mLogin;
android.accounts.Account acct =
new android.accounts.Account(login, Eas.ACCOUNT_MANAGER_TYPE);
mSyncContacts.setChecked(ContentResolver
.getSyncAutomatically(acct, ContactsContract.AUTHORITY));
} else {
PreferenceCategory serverCategory = (PreferenceCategory) findPreference(
PREFERENCE_SERVER_CATERGORY);
serverCategory.removePreference(mSyncContacts);
}
}
private void setAccountIdFromAccountManagerIntent() {
// First, get the AccountManager account that we've been ask to handle
android.accounts.Account acct =
(android.accounts.Account)getIntent()
.getParcelableExtra(ACCOUNT_MANAGER_EXTRA_ACCOUNT);
// Find a HostAuth using eas and whose login is the name of the AccountManager account
Cursor c = getContentResolver().query(HostAuth.CONTENT_URI,
new String[] {HostAuthColumns.ID}, HostAuth.LOGIN + "=? AND "
+ HostAuthColumns.PROTOCOL + "=?",
new String[] {acct.name, "eas"}, null);
try {
if (c.moveToFirst()) {
// This gives us the HostAuth's id
String hostAuthId = c.getString(0);
// Now, find the EmailProvider Account for this HostAuth
Cursor ac = getContentResolver().query(Account.CONTENT_URI,
new String[] {AccountColumns.ID},
AccountColumns.HOST_AUTH_KEY_RECV + "=? OR "
+ AccountColumns.HOST_AUTH_KEY_SEND + "=?",
new String[] {hostAuthId, hostAuthId}, null);
try {
// And if we find one, set mAccountId accordingly
if (ac.moveToFirst()) {
mAccountId = ac.getLong(0);
}
} finally {
ac.close();
}
}
} finally {
c.close();
}
}
@Override
public void onResume() {
super.onResume();
if (mAccountDirty) {
// if we are coming back from editing incoming or outgoing settings,
// we need to refresh them here so we don't accidentally overwrite the
// old values we're still holding here
mAccount.mHostAuthRecv =
HostAuth.restoreHostAuthWithId(this, mAccount.mHostAuthKeyRecv);
mAccount.mHostAuthSend =
HostAuth.restoreHostAuthWithId(this, mAccount.mHostAuthKeySend);
// Because "delete policy" UI is on edit incoming settings, we have
// to refresh that as well.
Account refreshedAccount = Account.restoreAccountWithId(this, mAccount.mId);
if (refreshedAccount == null || mAccount.mHostAuthRecv == null
|| mAccount.mHostAuthSend == null) {
finish();
return;
}
mAccount.setDeletePolicy(refreshedAccount.getDeletePolicy());
mAccountDirty = false;
}
}
private void saveSettings() {
int newFlags = mAccount.getFlags() &
~(Account.FLAGS_NOTIFY_NEW_MAIL | Account.FLAGS_VIBRATE);
mAccount.setDefaultAccount(mAccountDefault.isChecked());
mAccount.setDisplayName(mAccountDescription.getText());
mAccount.setSenderName(mAccountName.getText());
newFlags |= mAccountNotify.isChecked() ? Account.FLAGS_NOTIFY_NEW_MAIL : 0;
mAccount.setSyncInterval(Integer.parseInt(mCheckFrequency.getValue()));
if (mSyncWindow != null) {
mAccount.setSyncLookback(Integer.parseInt(mSyncWindow.getValue()));
}
newFlags |= mAccountVibrate.isChecked() ? Account.FLAGS_VIBRATE : 0;
SharedPreferences prefs = mAccountRingtone.getPreferenceManager().getSharedPreferences();
mAccount.setRingtone(prefs.getString(PREFERENCE_RINGTONE, null));
mAccount.setFlags(newFlags);
if (mAccount.mHostAuthRecv.mProtocol.equals("eas")) {
String login = mAccount.mHostAuthRecv.mLogin;
android.accounts.Account acct =
new android.accounts.Account(login, Eas.ACCOUNT_MANAGER_TYPE);
ContentResolver.setSyncAutomatically(acct, ContactsContract.AUTHORITY,
mSyncContacts.isChecked());
}
AccountSettingsUtils.commitSettings(this, mAccount);
Email.setServicesEnabled(this);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
saveSettings();
}
return super.onKeyDown(keyCode, event);
}
private void onIncomingSettings() {
try {
Store store = Store.getInstance(mAccount.getStoreUri(this), getApplication(), null);
if (store != null) {
Class<? extends android.app.Activity> setting = store.getSettingActivityClass();
if (setting != null) {
java.lang.reflect.Method m = setting.getMethod("actionEditIncomingSettings",
android.app.Activity.class, Account.class);
m.invoke(null, this, mAccount);
mAccountDirty = true;
}
}
} catch (Exception e) {
Log.d(Email.LOG_TAG, "Error while trying to invoke store settings.", e);
}
}
private void onOutgoingSettings() {
try {
Sender sender = Sender.getInstance(getApplication(), mAccount.getSenderUri(this));
if (sender != null) {
Class<? extends android.app.Activity> setting = sender.getSettingActivityClass();
if (setting != null) {
java.lang.reflect.Method m = setting.getMethod("actionEditOutgoingSettings",
android.app.Activity.class, Account.class);
m.invoke(null, this, mAccount);
mAccountDirty = true;
}
}
} catch (Exception e) {
Log.d(Email.LOG_TAG, "Error while trying to invoke sender settings.", e);
}
}
}
| true | true | public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent i = getIntent();
if (i.getAction().equals(ACTION_ACCOUNT_MANAGER_ENTRY)) {
// This case occurs if we're changing account settings from Settings -> Accounts
setAccountIdFromAccountManagerIntent();
} else {
// Otherwise, we're called from within the Email app and look for our extra
mAccountId = i.getLongExtra(EXTRA_ACCOUNT_ID, -1);
}
// If there's no accountId, we're done
if (mAccountId == -1) {
finish();
return;
}
mAccount = Account.restoreAccountWithId(this, mAccountId);
// Similarly, if the account has been deleted
if (mAccount == null) {
finish();
return;
}
mAccount.mHostAuthRecv = HostAuth.restoreHostAuthWithId(this, mAccount.mHostAuthKeyRecv);
mAccount.mHostAuthSend = HostAuth.restoreHostAuthWithId(this, mAccount.mHostAuthKeySend);
// Or if HostAuth's have been deleted
if (mAccount.mHostAuthRecv == null || mAccount.mHostAuthSend == null) {
finish();
return;
}
mAccountDirty = false;
addPreferencesFromResource(R.xml.account_settings_preferences);
PreferenceCategory topCategory = (PreferenceCategory) findPreference(PREFERENCE_TOP_CATEGORY);
topCategory.setTitle(getString(R.string.account_settings_title_fmt));
mAccountDescription = (EditTextPreference) findPreference(PREFERENCE_DESCRIPTION);
mAccountDescription.setSummary(mAccount.getDisplayName());
mAccountDescription.setText(mAccount.getDisplayName());
mAccountDescription.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
final String summary = newValue.toString();
mAccountDescription.setSummary(summary);
mAccountDescription.setText(summary);
return false;
}
});
mAccountName = (EditTextPreference) findPreference(PREFERENCE_NAME);
mAccountName.setSummary(mAccount.getSenderName());
mAccountName.setText(mAccount.getSenderName());
mAccountName.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
final String summary = newValue.toString();
mAccountName.setSummary(summary);
mAccountName.setText(summary);
return false;
}
});
mCheckFrequency = (ListPreference) findPreference(PREFERENCE_FREQUENCY);
// Before setting value, we may need to adjust the lists
Store.StoreInfo info = Store.StoreInfo.getStoreInfo(mAccount.getStoreUri(this), this);
if (info.mPushSupported) {
mCheckFrequency.setEntries(R.array.account_settings_check_frequency_entries_push);
mCheckFrequency.setEntryValues(R.array.account_settings_check_frequency_values_push);
}
mCheckFrequency.setValue(String.valueOf(mAccount.getSyncInterval()));
mCheckFrequency.setSummary(mCheckFrequency.getEntry());
mCheckFrequency.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
final String summary = newValue.toString();
int index = mCheckFrequency.findIndexOfValue(summary);
mCheckFrequency.setSummary(mCheckFrequency.getEntries()[index]);
mCheckFrequency.setValue(summary);
return false;
}
});
// Add check window preference
mSyncWindow = null;
if (info.mVisibleLimitDefault == -1) {
mSyncWindow = new ListPreference(this);
mSyncWindow.setTitle(R.string.account_setup_options_mail_window_label);
mSyncWindow.setEntries(R.array.account_settings_mail_window_entries);
mSyncWindow.setEntryValues(R.array.account_settings_mail_window_values);
mSyncWindow.setValue(String.valueOf(mAccount.getSyncLookback()));
mSyncWindow.setSummary(mSyncWindow.getEntry());
mSyncWindow.setOrder(4);
mSyncWindow.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
final String summary = newValue.toString();
int index = mSyncWindow.findIndexOfValue(summary);
mSyncWindow.setSummary(mSyncWindow.getEntries()[index]);
mSyncWindow.setValue(summary);
return false;
}
});
topCategory.addPreference(mSyncWindow);
}
mAccountDefault = (CheckBoxPreference) findPreference(PREFERENCE_DEFAULT);
mAccountDefault.setChecked(mAccount.mId == Account.getDefaultAccountId(this));
mAccountNotify = (CheckBoxPreference) findPreference(PREFERENCE_NOTIFY);
mAccountNotify.setChecked(0 != (mAccount.getFlags() & Account.FLAGS_NOTIFY_NEW_MAIL));
mAccountRingtone = (RingtonePreference) findPreference(PREFERENCE_RINGTONE);
// XXX: The following two lines act as a workaround for the RingtonePreference
// which does not let us set/get the value programmatically
SharedPreferences prefs = mAccountRingtone.getPreferenceManager().getSharedPreferences();
prefs.edit().putString(PREFERENCE_RINGTONE, mAccount.getRingtone()).commit();
mAccountVibrate = (CheckBoxPreference) findPreference(PREFERENCE_VIBRATE);
mAccountVibrate.setChecked(0 !=
(mAccount.getFlags() & Account.FLAGS_VIBRATE));
findPreference(PREFERENCE_INCOMING).setOnPreferenceClickListener(
new Preference.OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
onIncomingSettings();
return true;
}
});
// Hide the outgoing account setup link if it's not activated
Preference prefOutgoing = findPreference(PREFERENCE_OUTGOING);
boolean showOutgoing = true;
try {
Sender sender = Sender.getInstance(getApplication(), mAccount.getSenderUri(this));
if (sender != null) {
Class<? extends android.app.Activity> setting = sender.getSettingActivityClass();
showOutgoing = (setting != null);
}
} catch (MessagingException me) {
// just leave showOutgoing as true - bias towards showing it, so user can fix it
}
if (showOutgoing) {
prefOutgoing.setOnPreferenceClickListener(
new Preference.OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
onOutgoingSettings();
return true;
}
});
} else {
PreferenceCategory serverCategory = (PreferenceCategory) findPreference(
PREFERENCE_SERVER_CATERGORY);
serverCategory.removePreference(prefOutgoing);
}
mSyncContacts = (CheckBoxPreference) findPreference(PREFERENCE_SYNC_CONTACTS);
if (mAccount.mHostAuthRecv.mProtocol.equals("eas")) {
String login = mAccount.mHostAuthRecv.mLogin;
android.accounts.Account acct =
new android.accounts.Account(login, Eas.ACCOUNT_MANAGER_TYPE);
mSyncContacts.setChecked(ContentResolver
.getSyncAutomatically(acct, ContactsContract.AUTHORITY));
} else {
PreferenceCategory serverCategory = (PreferenceCategory) findPreference(
PREFERENCE_SERVER_CATERGORY);
serverCategory.removePreference(mSyncContacts);
}
}
| public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent i = getIntent();
if (ACTION_ACCOUNT_MANAGER_ENTRY.equals(i.getAction())) {
// This case occurs if we're changing account settings from Settings -> Accounts
setAccountIdFromAccountManagerIntent();
} else {
// Otherwise, we're called from within the Email app and look for our extra
mAccountId = i.getLongExtra(EXTRA_ACCOUNT_ID, -1);
}
// If there's no accountId, we're done
if (mAccountId == -1) {
finish();
return;
}
mAccount = Account.restoreAccountWithId(this, mAccountId);
// Similarly, if the account has been deleted
if (mAccount == null) {
finish();
return;
}
mAccount.mHostAuthRecv = HostAuth.restoreHostAuthWithId(this, mAccount.mHostAuthKeyRecv);
mAccount.mHostAuthSend = HostAuth.restoreHostAuthWithId(this, mAccount.mHostAuthKeySend);
// Or if HostAuth's have been deleted
if (mAccount.mHostAuthRecv == null || mAccount.mHostAuthSend == null) {
finish();
return;
}
mAccountDirty = false;
addPreferencesFromResource(R.xml.account_settings_preferences);
PreferenceCategory topCategory = (PreferenceCategory) findPreference(PREFERENCE_TOP_CATEGORY);
topCategory.setTitle(getString(R.string.account_settings_title_fmt));
mAccountDescription = (EditTextPreference) findPreference(PREFERENCE_DESCRIPTION);
mAccountDescription.setSummary(mAccount.getDisplayName());
mAccountDescription.setText(mAccount.getDisplayName());
mAccountDescription.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
final String summary = newValue.toString();
mAccountDescription.setSummary(summary);
mAccountDescription.setText(summary);
return false;
}
});
mAccountName = (EditTextPreference) findPreference(PREFERENCE_NAME);
mAccountName.setSummary(mAccount.getSenderName());
mAccountName.setText(mAccount.getSenderName());
mAccountName.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
final String summary = newValue.toString();
mAccountName.setSummary(summary);
mAccountName.setText(summary);
return false;
}
});
mCheckFrequency = (ListPreference) findPreference(PREFERENCE_FREQUENCY);
// Before setting value, we may need to adjust the lists
Store.StoreInfo info = Store.StoreInfo.getStoreInfo(mAccount.getStoreUri(this), this);
if (info.mPushSupported) {
mCheckFrequency.setEntries(R.array.account_settings_check_frequency_entries_push);
mCheckFrequency.setEntryValues(R.array.account_settings_check_frequency_values_push);
}
mCheckFrequency.setValue(String.valueOf(mAccount.getSyncInterval()));
mCheckFrequency.setSummary(mCheckFrequency.getEntry());
mCheckFrequency.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
final String summary = newValue.toString();
int index = mCheckFrequency.findIndexOfValue(summary);
mCheckFrequency.setSummary(mCheckFrequency.getEntries()[index]);
mCheckFrequency.setValue(summary);
return false;
}
});
// Add check window preference
mSyncWindow = null;
if (info.mVisibleLimitDefault == -1) {
mSyncWindow = new ListPreference(this);
mSyncWindow.setTitle(R.string.account_setup_options_mail_window_label);
mSyncWindow.setEntries(R.array.account_settings_mail_window_entries);
mSyncWindow.setEntryValues(R.array.account_settings_mail_window_values);
mSyncWindow.setValue(String.valueOf(mAccount.getSyncLookback()));
mSyncWindow.setSummary(mSyncWindow.getEntry());
mSyncWindow.setOrder(4);
mSyncWindow.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
final String summary = newValue.toString();
int index = mSyncWindow.findIndexOfValue(summary);
mSyncWindow.setSummary(mSyncWindow.getEntries()[index]);
mSyncWindow.setValue(summary);
return false;
}
});
topCategory.addPreference(mSyncWindow);
}
mAccountDefault = (CheckBoxPreference) findPreference(PREFERENCE_DEFAULT);
mAccountDefault.setChecked(mAccount.mId == Account.getDefaultAccountId(this));
mAccountNotify = (CheckBoxPreference) findPreference(PREFERENCE_NOTIFY);
mAccountNotify.setChecked(0 != (mAccount.getFlags() & Account.FLAGS_NOTIFY_NEW_MAIL));
mAccountRingtone = (RingtonePreference) findPreference(PREFERENCE_RINGTONE);
// XXX: The following two lines act as a workaround for the RingtonePreference
// which does not let us set/get the value programmatically
SharedPreferences prefs = mAccountRingtone.getPreferenceManager().getSharedPreferences();
prefs.edit().putString(PREFERENCE_RINGTONE, mAccount.getRingtone()).commit();
mAccountVibrate = (CheckBoxPreference) findPreference(PREFERENCE_VIBRATE);
mAccountVibrate.setChecked(0 !=
(mAccount.getFlags() & Account.FLAGS_VIBRATE));
findPreference(PREFERENCE_INCOMING).setOnPreferenceClickListener(
new Preference.OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
onIncomingSettings();
return true;
}
});
// Hide the outgoing account setup link if it's not activated
Preference prefOutgoing = findPreference(PREFERENCE_OUTGOING);
boolean showOutgoing = true;
try {
Sender sender = Sender.getInstance(getApplication(), mAccount.getSenderUri(this));
if (sender != null) {
Class<? extends android.app.Activity> setting = sender.getSettingActivityClass();
showOutgoing = (setting != null);
}
} catch (MessagingException me) {
// just leave showOutgoing as true - bias towards showing it, so user can fix it
}
if (showOutgoing) {
prefOutgoing.setOnPreferenceClickListener(
new Preference.OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
onOutgoingSettings();
return true;
}
});
} else {
PreferenceCategory serverCategory = (PreferenceCategory) findPreference(
PREFERENCE_SERVER_CATERGORY);
serverCategory.removePreference(prefOutgoing);
}
mSyncContacts = (CheckBoxPreference) findPreference(PREFERENCE_SYNC_CONTACTS);
if (mAccount.mHostAuthRecv.mProtocol.equals("eas")) {
String login = mAccount.mHostAuthRecv.mLogin;
android.accounts.Account acct =
new android.accounts.Account(login, Eas.ACCOUNT_MANAGER_TYPE);
mSyncContacts.setChecked(ContentResolver
.getSyncAutomatically(acct, ContactsContract.AUTHORITY));
} else {
PreferenceCategory serverCategory = (PreferenceCategory) findPreference(
PREFERENCE_SERVER_CATERGORY);
serverCategory.removePreference(mSyncContacts);
}
}
|
diff --git a/src/main/java/de/thomasvoecking/screenruler/ui/ScreenrulerFrame.java b/src/main/java/de/thomasvoecking/screenruler/ui/ScreenrulerFrame.java
index d6f98f6..5e06646 100644
--- a/src/main/java/de/thomasvoecking/screenruler/ui/ScreenrulerFrame.java
+++ b/src/main/java/de/thomasvoecking/screenruler/ui/ScreenrulerFrame.java
@@ -1,315 +1,315 @@
package de.thomasvoecking.screenruler.ui;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.JFrame;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.sun.awt.AWTUtilities;
import de.thomasvoecking.screenruler.ui.buttons.CloseButton;
/**
* The main frame. All components are directly painted on this component.
* Also controls all dragging events.
*
* @author thomas
*/
public class ScreenrulerFrame extends JFrame implements MouseListener, MouseMotionListener
{
/**
* SUID
*/
private static final long serialVersionUID = 2158183440540339826L;
/**
* The logger
*/
private static final Log log = LogFactory.getLog(ScreenrulerFrame.class);
/**
* The configuration
*/
private final Configuration configuration;
/**
* The padding between the ruler and the resize controls.
*/
private static final int rulerPadding = 10;
/**
* The overlay color
*/
private static final Color overlayColor = new Color(255, 245, 173);
/**
* The left resize control
*/
private final ScreenrulerResizeControl leftResizeControl = ScreenrulerResizeControl.LEFT;
/**
* The right resize control
*/
private final ScreenrulerResizeControl rightResizeControl = ScreenrulerResizeControl.RIGHT;
/**
* The ruler
*/
private final Ruler ruler = new Ruler("cm", 48, 129);
/**
* The close button
*/
private final CloseButton closeButton = new CloseButton();
/**
* Contains stateful data that is necessary for the dragging behaviour.
*/
private ScreenrulerDraggingData screenrulerDraggingData = new ScreenrulerDraggingData();
/**
* Constructor
*
* @param configuration The configuration
*/
public ScreenrulerFrame(final Configuration configuration)
{
log.debug("Initializing frame.");
this.configuration = configuration;
// Set window properties
this.setUndecorated(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final Dimension size = new Dimension(
this.configuration.getInt("screenrulerFrame.size[@width]"),
this.configuration.getInt("screenrulerFrame.size[@height]"));
log.debug("Setting size: " + size);
this.setSize(size);
this.setResizable(false);
log.debug("Setting opacity: " + this.configuration.getFloat("screenrulerFrame.window[@opacity]"));
AWTUtilities.setWindowOpacity(this, this.configuration.getFloat("screenrulerFrame.window[@opacity]"));
this.addMouseListener(this);
this.addMouseMotionListener(this);
}
/**
* @see java.awt.Window#paint(java.awt.Graphics)
*/
@Override
public void paint(final Graphics g)
{
final Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g.clearRect(0, 0, this.getWidth(), this.getHeight());
// When the ruler is currently in resizing state, draw no ruler and no resize controls.
// Instead draw an overlay.
final boolean paintOverlay =
this.screenrulerDraggingData.draggingMode == DraggingMode.RESIZE_LEFT || this.screenrulerDraggingData.draggingMode == DraggingMode.RESIZE_RIGHT;
if (paintOverlay)
{
this.paintOverlay(g);
}
else
{
this.paintArrows(g);
this.ruler.paint(g, new Rectangle(
- this.configuration.getInt("screenrulerFrame.resizeControl.size[@height]") + rulerPadding,
+ this.configuration.getInt("screenrulerFrame.resizeControl.size[@width]") + rulerPadding,
0,
this.getWidth() - 2 * this.configuration.getInt("screenrulerFrame.resizeControl.size[@width]") - 2 * rulerPadding,
this.getHeight()));
this.closeButton.paint(g, this.getCloseButtonBoundingBox());
}
}
/**
* Paints the overlay.
*
* @param g The {@link Graphics} Object.
*/
private void paintOverlay(final Graphics g)
{
final Color color = g.getColor();
g.setColor(overlayColor);
g.fillRect(0, 0, this.getWidth() + 100, this.getHeight());
g.setColor(color);
g.drawLine(
this.configuration.getInt("screenrulerFrame.resizeControl.size[@width]") + rulerPadding, 0,
this.configuration.getInt("screenrulerFrame.resizeControl.size[@width]") + rulerPadding, (int) (this.getHeight() / 2.0));
g.drawLine(
this.getWidth() - this.configuration.getInt("screenrulerFrame.resizeControl.size[@width]") - rulerPadding, 0,
this.getWidth() - this.configuration.getInt("screenrulerFrame.resizeControl.size[@width]") - rulerPadding, (int) (this.getHeight() / 2.0));
}
/**
* Paints the resize controls.
*
* @param g The {@link Graphics} Object.
*/
private void paintArrows(final Graphics g)
{
this.leftResizeControl.paint(g, this.getLeftResizeControlBoundingBox());
this.rightResizeControl.paint(g, this.getRightResizeControlBoundingBox());
}
/**
* @see java.awt.event.MouseListener#mousePressed(java.awt.event.MouseEvent)
*/
@Override
public void mousePressed(final MouseEvent e)
{
if (e.getButton() == MouseEvent.BUTTON1)
{
this.screenrulerDraggingData.componentRelativeMouseLocationFromLeft = e.getPoint();
this.screenrulerDraggingData.componentRelativeMouseLocationFromRight = new Point(
(int) (this.getWidth() - e.getPoint().getX()),
(int) (this.getHeight() - e.getPoint().getY()));
this.screenrulerDraggingData.bottomRight = new Point(
(int) (this.getLocationOnScreen().getX() + this.getWidth()),
(int) (this.getLocationOnScreen().getY() + this.getHeight()));
if (this.getLeftResizeControlBoundingBox().contains(e.getPoint()))
this.screenrulerDraggingData.draggingMode = DraggingMode.RESIZE_LEFT;
else if (this.getRightResizeControlBoundingBox().contains(e.getPoint()))
this.screenrulerDraggingData.draggingMode = DraggingMode.RESIZE_RIGHT;
else
this.screenrulerDraggingData.draggingMode = DraggingMode.MOVE;
log.debug("New dragging mode: " + this.screenrulerDraggingData.draggingMode);
}
}
/**
* @see java.awt.event.MouseMotionListener#mouseDragged(java.awt.event.MouseEvent)
*/
@Override
public void mouseDragged(final MouseEvent e)
{
if (this.screenrulerDraggingData.draggingMode == DraggingMode.RESIZE_LEFT)
{
final Rectangle newBounds = new Rectangle(
(int) (e.getLocationOnScreen().getX() - this.screenrulerDraggingData.componentRelativeMouseLocationFromLeft.getX()),
(int) (this.getLocationOnScreen().getY()),
(int) (this.screenrulerDraggingData.bottomRight.getX() - e.getLocationOnScreen().getX() - this.screenrulerDraggingData.componentRelativeMouseLocationFromLeft.getX()),
this.getHeight());
if (newBounds.getWidth() >= this.configuration.getInt("screenrulerFrame.size[@minWidth]")) this.setBounds(newBounds);
}
else if (this.screenrulerDraggingData.draggingMode == DraggingMode.RESIZE_RIGHT)
{
final Dimension newSize = new Dimension(
(int) (e.getLocationOnScreen().getX() - this.getLocationOnScreen().getX() + this.screenrulerDraggingData.componentRelativeMouseLocationFromRight.getX()),
this.getHeight());
if (newSize.getWidth() >= this.configuration.getInt("screenrulerFrame.size[@minWidth]")) this.setSize(newSize);
}
else if (this.screenrulerDraggingData.draggingMode == DraggingMode.MOVE)
{
this.setLocation(
(int) (e.getLocationOnScreen().getX() - this.screenrulerDraggingData.componentRelativeMouseLocationFromLeft.getX()),
(int) (e.getLocationOnScreen().getY() - this.screenrulerDraggingData.componentRelativeMouseLocationFromLeft.getY()));
}
}
/**
* @see java.awt.event.MouseListener#mouseReleased(java.awt.event.MouseEvent)
*/
@Override
public void mouseReleased(final MouseEvent e)
{
if (this.screenrulerDraggingData.draggingMode != null)
{
log.debug("Releasing dragging mode: " + this.screenrulerDraggingData.draggingMode);
this.screenrulerDraggingData.draggingMode = null;
this.repaint();
}
}
/**
* @return the bounding box for the left resize control.
*/
private Rectangle getLeftResizeControlBoundingBox()
{
return new Rectangle(0, 0,
this.configuration.getInt("screenrulerFrame.resizeControl.size[@width]"),
this.configuration.getInt("screenrulerFrame.resizeControl.size[@height]"));
}
/**
* @return the bounding box for the right resize control.
*/
private Rectangle getRightResizeControlBoundingBox()
{
return new Rectangle(
this.getWidth() - this.configuration.getInt("screenrulerFrame.resizeControl.size[@width]"),
0,
this.configuration.getInt("screenrulerFrame.resizeControl.size[@width]"),
this.configuration.getInt("screenrulerFrame.resizeControl.size[@height]"));
}
/**
* @return the bounding box where the close button should be drawn to.
*/
private Rectangle getCloseButtonBoundingBox()
{
return new Rectangle(4, this.getHeight() - 20, 16, 16);
}
/**
* @see java.awt.event.MouseMotionListener#mouseMoved(java.awt.event.MouseEvent)
*/
@Override
public void mouseMoved(final MouseEvent e)
{
// Check if we are over the close button
final Rectangle closeButtonBoundingBox = this.getCloseButtonBoundingBox();
if (this.closeButton.setMouseOver(closeButtonBoundingBox.contains(e.getPoint()))) this.repaint(
(int) closeButtonBoundingBox.getX(), (int) closeButtonBoundingBox.getY(),
(int) closeButtonBoundingBox.getWidth(), (int) closeButtonBoundingBox.getHeight());
}
/**
* @see java.awt.event.MouseListener#mouseClicked(java.awt.event.MouseEvent)
*/
@Override
public void mouseClicked(final MouseEvent e)
{
// Check if we have clicked the exit button
if (this.getCloseButtonBoundingBox().contains(e.getPoint())) System.exit(0);
}
/**
* @see java.awt.event.MouseListener#mouseEntered(java.awt.event.MouseEvent)
*/
@Override
public void mouseEntered(final MouseEvent e) { /* unused */ }
/**
* @see java.awt.event.MouseListener#mouseExited(java.awt.event.MouseEvent)
*/
@Override
public void mouseExited(final MouseEvent e) { /* unused */ }
}
| true | true | public void paint(final Graphics g)
{
final Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g.clearRect(0, 0, this.getWidth(), this.getHeight());
// When the ruler is currently in resizing state, draw no ruler and no resize controls.
// Instead draw an overlay.
final boolean paintOverlay =
this.screenrulerDraggingData.draggingMode == DraggingMode.RESIZE_LEFT || this.screenrulerDraggingData.draggingMode == DraggingMode.RESIZE_RIGHT;
if (paintOverlay)
{
this.paintOverlay(g);
}
else
{
this.paintArrows(g);
this.ruler.paint(g, new Rectangle(
this.configuration.getInt("screenrulerFrame.resizeControl.size[@height]") + rulerPadding,
0,
this.getWidth() - 2 * this.configuration.getInt("screenrulerFrame.resizeControl.size[@width]") - 2 * rulerPadding,
this.getHeight()));
this.closeButton.paint(g, this.getCloseButtonBoundingBox());
}
}
| public void paint(final Graphics g)
{
final Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g.clearRect(0, 0, this.getWidth(), this.getHeight());
// When the ruler is currently in resizing state, draw no ruler and no resize controls.
// Instead draw an overlay.
final boolean paintOverlay =
this.screenrulerDraggingData.draggingMode == DraggingMode.RESIZE_LEFT || this.screenrulerDraggingData.draggingMode == DraggingMode.RESIZE_RIGHT;
if (paintOverlay)
{
this.paintOverlay(g);
}
else
{
this.paintArrows(g);
this.ruler.paint(g, new Rectangle(
this.configuration.getInt("screenrulerFrame.resizeControl.size[@width]") + rulerPadding,
0,
this.getWidth() - 2 * this.configuration.getInt("screenrulerFrame.resizeControl.size[@width]") - 2 * rulerPadding,
this.getHeight()));
this.closeButton.paint(g, this.getCloseButtonBoundingBox());
}
}
|
diff --git a/src/usp/ime/line/ivprog/model/domainaction/NewVariable.java b/src/usp/ime/line/ivprog/model/domainaction/NewVariable.java
index f96d54d..1c74af7 100644
--- a/src/usp/ime/line/ivprog/model/domainaction/NewVariable.java
+++ b/src/usp/ime/line/ivprog/model/domainaction/NewVariable.java
@@ -1,64 +1,56 @@
package usp.ime.line.ivprog.model.domainaction;
import usp.ime.line.ivprog.Services;
import usp.ime.line.ivprog.model.IVPProgram;
import usp.ime.line.ivprog.model.components.datafactory.dataobjetcs.Variable;
import ilm.framework.assignment.model.DomainAction;
import ilm.framework.domain.DomainModel;
public class NewVariable extends DomainAction{
private IVPProgram model;
private String scopeID;
private String varID;
public NewVariable(String name, String description) {
super(name, description);
}
public void setDomainModel(DomainModel m) {
model = (IVPProgram)m;
}
protected void executeAction() {
- // TODO o problema est� aqui. de onde vem o varID?
- System.out.println("Execute action: "+varID);
- if(varID!=null){
- Variable v = (Variable) Services.getService().getModelMapping().get(varID);
- System.out.println("VARIABLE "+v);
- }
- /*if(varID == null)
+ if(varID == null)
varID = model.createVariable(scopeID);
else
- model.restoreVariable(scopeID, varID);*/
- //System.out.println("IDDDDD: "+);
- varID = model.createVariable(scopeID);
+ model.restoreVariable(scopeID, varID);
}
protected void undoAction() {
System.out.println("undoAction: "+varID);
model.removeVariable(scopeID, varID);
}
public boolean equals(DomainAction a) {
return false;
}
public String getScopeID() {
return scopeID;
}
public void setScopeID(String scopeID) {
this.scopeID = scopeID;
}
public String getVarID() {
return varID;
}
public void setVarID(String varID) {
this.varID = varID;
}
}
| false | true | protected void executeAction() {
// TODO o problema est� aqui. de onde vem o varID?
System.out.println("Execute action: "+varID);
if(varID!=null){
Variable v = (Variable) Services.getService().getModelMapping().get(varID);
System.out.println("VARIABLE "+v);
}
/*if(varID == null)
varID = model.createVariable(scopeID);
else
model.restoreVariable(scopeID, varID);*/
//System.out.println("IDDDDD: "+);
varID = model.createVariable(scopeID);
}
| protected void executeAction() {
if(varID == null)
varID = model.createVariable(scopeID);
else
model.restoreVariable(scopeID, varID);
}
|
diff --git a/version2/androidclient/src/be/ugent/ods/osgi/protocolabstraction/ModuleAccessor.java b/version2/androidclient/src/be/ugent/ods/osgi/protocolabstraction/ModuleAccessor.java
index 50e33e9..fdf11c0 100644
--- a/version2/androidclient/src/be/ugent/ods/osgi/protocolabstraction/ModuleAccessor.java
+++ b/version2/androidclient/src/be/ugent/ods/osgi/protocolabstraction/ModuleAccessor.java
@@ -1,157 +1,157 @@
package be.ugent.ods.osgi.protocolabstraction;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import org.osgi.framework.BundleContext;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceReference;
import org.osgi.service.remoteserviceadmin.EndpointDescription;
import org.osgi.service.remoteserviceadmin.RemoteServiceAdmin;
import android.provider.SyncStateContract.Helpers;
import be.ugent.ods.osgi.felix.OSGiRuntime;
import be.ugent.ods.testapplications.service.interfaces.EchoService;
import be.ugent.ods.testapplications.service.interfaces.GlowFilterService;
import be.ugent.ods.testapplications.service.interfaces.VideoService;
import be.ugent.ods.testapplications.service.list.TestApplicationProtocolList;
public class ModuleAccessor {
private BundleContext context;
private RemoteServiceAdmin currentrsa;
private int currentrsaindex;
public ModuleAccessor(OSGiRuntime runtime) {
super();
this.context = runtime.getBundleContext();
this.currentrsa = null;
this.currentrsaindex = -1;
}
/**
* Get the number of possible ways to call remote methods.
* (number of RSA's)
* @return
*/
public int getNumberOfRSAModules() {
return TestApplicationProtocolList.protocols.length;
}
/**
* Get the name of a RSA
* @param index
* @return
*/
public String getRSAModuleName(int index) {
if(index==TestApplicationProtocolList.PROTOCOL_LOCAL) {
return "Lokaal";
}else{
return TestApplicationProtocolList.protocolnames[index];
}
}
/**
* USE RSA WITH INDEX index
* @param index
*/
public void setUseRSAModule(int index) {
if(index==TestApplicationProtocolList.PROTOCOL_LOCAL) {
currentrsa = null;
}else{
if(index<0 || index >= getNumberOfRSAModules()) {
throw new IllegalArgumentException("Not a valid index in setUseRSAModule");
}
Collection<ServiceReference<RemoteServiceAdmin>> refs;
try {
refs = context.getServiceReferences(RemoteServiceAdmin.class, TestApplicationProtocolList.protocols[index]);
} catch (InvalidSyntaxException e) {
throw new RuntimeException("Error: Sorry, but the filter \""+TestApplicationProtocolList.protocols[index]+"\" is not correct.", e);
}
if(refs.size()==0) {
throw new RuntimeException("Error: Sorry, but we did not find that RSA module!");
}
if(refs.size()>1) {
throw new RuntimeException("Error: We found more than one RSA module for this filter!");
}
ServiceReference<RemoteServiceAdmin> rsaref = refs.iterator().next();
currentrsa = context.getService(rsaref);
}
currentrsaindex = index;
}
/**
* Get a module from somewhere...
*
* @param c
* @param endpoint
* @return
*/
public <T> T getModule(Class<T> c){
if(currentrsa==null) {
ServiceReference<T> ref = context.getServiceReference(c);
return context.getService(ref);
}else{
try{
EndpointDescription endpoint = getCurrentEndpointDescriptionFor(c);
ServiceReference<T> ref = (ServiceReference<T>) currentrsa.importService(endpoint).getImportReference().getImportedService();
return context.getService(ref);
}catch (Exception e) {
throw new RuntimeException("Could not import the service...", e);
}
}
}
public EndpointDescription getCurrentEndpointDescriptionFor(Class<?> c){
Map<String, String> rosgitim_ids = new HashMap<String, String>();
rosgitim_ids.put(EchoService.class.getName(), "44");
rosgitim_ids.put(GlowFilterService.class.getName(), "45");
rosgitim_ids.put(VideoService.class.getName(), "46");
Map<Integer, EndpointDescription> endpoints = new HashMap<Integer, EndpointDescription>();
//lokaal
endpoints.put(TestApplicationProtocolList.PROTOCOL_LOCAL, null);
//r-osgi-tim server
Map<String, Object> properties = new HashMap<String, Object>();
- //properties.put("endpoint.id", "r-osgi://10.0.2.2:9278#"+rosgitim_ids.get(c.getName()));// TODO: put IP in property file or something like that (or in gui)
- properties.put("endpoint.id", "r-osgi://192.168.2.5:9278#"+rosgitim_ids.get(c.getName()));// TODO: put IP in property file or something like that (or in gui)
+ properties.put("endpoint.id", "r-osgi://10.0.2.2:9278#"+rosgitim_ids.get(c.getName()));// TODO: put IP in property file or something like that (or in gui)
+ //properties.put("endpoint.id", "r-osgi://192.168.2.5:9278#"+rosgitim_ids.get(c.getName()));// TODO: put IP in property file or something like that (or in gui)
properties.put("service.imported.configs", "r-osgi");
properties.put("objectClass", new String[]{c.getName()});
EndpointDescription endpoint = new EndpointDescription(properties);
endpoints.put(TestApplicationProtocolList.PROTOCOL_ROSGI_TIM, endpoint);
//r-osgi-tim-udp server
properties = new HashMap<String, Object>();
- //properties.put("endpoint.id", "r-osgi://10.0.2.2:9279#"+rosgitim_ids.get(c.getName()));// TODO: put IP in property file or something like that (or in gui)
- properties.put("endpoint.id", "r-osgi://192.168.2.5:9279#"+rosgitim_ids.get(c.getName()));// TODO: put IP in property file or something like that (or in gui)
+ properties.put("endpoint.id", "r-osgi://10.0.2.2:9279#"+rosgitim_ids.get(c.getName()));// TODO: put IP in property file or something like that (or in gui)
+ //properties.put("endpoint.id", "r-osgi://192.168.2.5:9279#"+rosgitim_ids.get(c.getName()));// TODO: put IP in property file or something like that (or in gui)
properties.put("service.imported.configs", "r-osgi-udp");
properties.put("objectClass", new String[]{c.getName()});
endpoint = new EndpointDescription(properties);
endpoints.put(TestApplicationProtocolList.PROTOCOL_ROSGI_UDP, endpoint);
// other...
properties = new HashMap<String, Object>();
- // properties.put("endpoint.id", "http://10.0.2.2:8080/" + rosgitim_ids.get(c.getName()) + "/");
- properties.put("endpoint.id", "http://192.168.2.5:8080/" + rosgitim_ids.get(c.getName()) + "/");
+ properties.put("endpoint.id", "http://10.0.2.2:8080/" + rosgitim_ids.get(c.getName()) + "/");
+ //properties.put("endpoint.id", "http://192.168.2.5:8080/" + rosgitim_ids.get(c.getName()) + "/");
properties.put("service.imported.configs", "r-osgi-other");
properties.put("objectClass", new String[]{c.getName()});
properties.put("interface", c);
endpoint = new EndpointDescription(properties);
endpoints.put(TestApplicationProtocolList.PROTOCOL_OTHER, endpoint);
// pick correct one
return endpoints.get(currentrsaindex);
}
public int getCurrentRsaIndex(){
return currentrsaindex;
}
}
| false | true | public EndpointDescription getCurrentEndpointDescriptionFor(Class<?> c){
Map<String, String> rosgitim_ids = new HashMap<String, String>();
rosgitim_ids.put(EchoService.class.getName(), "44");
rosgitim_ids.put(GlowFilterService.class.getName(), "45");
rosgitim_ids.put(VideoService.class.getName(), "46");
Map<Integer, EndpointDescription> endpoints = new HashMap<Integer, EndpointDescription>();
//lokaal
endpoints.put(TestApplicationProtocolList.PROTOCOL_LOCAL, null);
//r-osgi-tim server
Map<String, Object> properties = new HashMap<String, Object>();
//properties.put("endpoint.id", "r-osgi://10.0.2.2:9278#"+rosgitim_ids.get(c.getName()));// TODO: put IP in property file or something like that (or in gui)
properties.put("endpoint.id", "r-osgi://192.168.2.5:9278#"+rosgitim_ids.get(c.getName()));// TODO: put IP in property file or something like that (or in gui)
properties.put("service.imported.configs", "r-osgi");
properties.put("objectClass", new String[]{c.getName()});
EndpointDescription endpoint = new EndpointDescription(properties);
endpoints.put(TestApplicationProtocolList.PROTOCOL_ROSGI_TIM, endpoint);
//r-osgi-tim-udp server
properties = new HashMap<String, Object>();
//properties.put("endpoint.id", "r-osgi://10.0.2.2:9279#"+rosgitim_ids.get(c.getName()));// TODO: put IP in property file or something like that (or in gui)
properties.put("endpoint.id", "r-osgi://192.168.2.5:9279#"+rosgitim_ids.get(c.getName()));// TODO: put IP in property file or something like that (or in gui)
properties.put("service.imported.configs", "r-osgi-udp");
properties.put("objectClass", new String[]{c.getName()});
endpoint = new EndpointDescription(properties);
endpoints.put(TestApplicationProtocolList.PROTOCOL_ROSGI_UDP, endpoint);
// other...
properties = new HashMap<String, Object>();
// properties.put("endpoint.id", "http://10.0.2.2:8080/" + rosgitim_ids.get(c.getName()) + "/");
properties.put("endpoint.id", "http://192.168.2.5:8080/" + rosgitim_ids.get(c.getName()) + "/");
properties.put("service.imported.configs", "r-osgi-other");
properties.put("objectClass", new String[]{c.getName()});
properties.put("interface", c);
endpoint = new EndpointDescription(properties);
endpoints.put(TestApplicationProtocolList.PROTOCOL_OTHER, endpoint);
// pick correct one
return endpoints.get(currentrsaindex);
}
| public EndpointDescription getCurrentEndpointDescriptionFor(Class<?> c){
Map<String, String> rosgitim_ids = new HashMap<String, String>();
rosgitim_ids.put(EchoService.class.getName(), "44");
rosgitim_ids.put(GlowFilterService.class.getName(), "45");
rosgitim_ids.put(VideoService.class.getName(), "46");
Map<Integer, EndpointDescription> endpoints = new HashMap<Integer, EndpointDescription>();
//lokaal
endpoints.put(TestApplicationProtocolList.PROTOCOL_LOCAL, null);
//r-osgi-tim server
Map<String, Object> properties = new HashMap<String, Object>();
properties.put("endpoint.id", "r-osgi://10.0.2.2:9278#"+rosgitim_ids.get(c.getName()));// TODO: put IP in property file or something like that (or in gui)
//properties.put("endpoint.id", "r-osgi://192.168.2.5:9278#"+rosgitim_ids.get(c.getName()));// TODO: put IP in property file or something like that (or in gui)
properties.put("service.imported.configs", "r-osgi");
properties.put("objectClass", new String[]{c.getName()});
EndpointDescription endpoint = new EndpointDescription(properties);
endpoints.put(TestApplicationProtocolList.PROTOCOL_ROSGI_TIM, endpoint);
//r-osgi-tim-udp server
properties = new HashMap<String, Object>();
properties.put("endpoint.id", "r-osgi://10.0.2.2:9279#"+rosgitim_ids.get(c.getName()));// TODO: put IP in property file or something like that (or in gui)
//properties.put("endpoint.id", "r-osgi://192.168.2.5:9279#"+rosgitim_ids.get(c.getName()));// TODO: put IP in property file or something like that (or in gui)
properties.put("service.imported.configs", "r-osgi-udp");
properties.put("objectClass", new String[]{c.getName()});
endpoint = new EndpointDescription(properties);
endpoints.put(TestApplicationProtocolList.PROTOCOL_ROSGI_UDP, endpoint);
// other...
properties = new HashMap<String, Object>();
properties.put("endpoint.id", "http://10.0.2.2:8080/" + rosgitim_ids.get(c.getName()) + "/");
//properties.put("endpoint.id", "http://192.168.2.5:8080/" + rosgitim_ids.get(c.getName()) + "/");
properties.put("service.imported.configs", "r-osgi-other");
properties.put("objectClass", new String[]{c.getName()});
properties.put("interface", c);
endpoint = new EndpointDescription(properties);
endpoints.put(TestApplicationProtocolList.PROTOCOL_OTHER, endpoint);
// pick correct one
return endpoints.get(currentrsaindex);
}
|
diff --git a/src/main/java/com/plivo/helper/api/client/RestAPI.java b/src/main/java/com/plivo/helper/api/client/RestAPI.java
index e63a39e..cf7a1c8 100644
--- a/src/main/java/com/plivo/helper/api/client/RestAPI.java
+++ b/src/main/java/com/plivo/helper/api/client/RestAPI.java
@@ -1,557 +1,557 @@
package com.plivo.helper.api.client;
//Exceptions
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.client.ClientProtocolException;
import com.plivo.helper.api.response.account.*;
import com.plivo.helper.api.response.application.*;
import com.plivo.helper.api.response.call.*;
import com.plivo.helper.api.response.conference.*;
import com.plivo.helper.api.response.endpoint.*;
import com.plivo.helper.api.response.message.*;
import com.plivo.helper.api.response.number.*;
import com.plivo.helper.api.response.carrier.*;
import com.plivo.helper.api.response.response.*;
import com.plivo.helper.api.response.pricing.PlivoPricing;
import com.plivo.helper.exception.PlivoException;
// Plivo resources
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.ProtocolVersion;
import java.util.LinkedHashMap;
import java.util.Map.Entry;
// Authentication for HTTP resources
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
// Handle HTTP requests
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicHttpResponse;
import org.apache.http.protocol.HTTP;
//Add pay load to POST request
import org.apache.http.entity.StringEntity;
// Handle JSON response
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
// Handle unicode characters
import com.plivo.helper.util.HtmlEntity;
public class RestAPI {
public String AUTH_ID;
private String AUTH_TOKEN;
private final String PLIVO_URL = "https://api.plivo.com";
public String PLIVO_VERSION = "v1";
private String BaseURI;
private DefaultHttpClient Client;
private Gson gson;
public RestAPI(String auth_id, String auth_token, String version)
{
AUTH_ID = auth_id;
AUTH_TOKEN = auth_token;
PLIVO_VERSION = version;
BaseURI = String.format("%s/%s/Account/%s", PLIVO_URL, PLIVO_VERSION, AUTH_ID);
Client = new DefaultHttpClient();
Client.getCredentialsProvider().setCredentials(
new AuthScope("api.plivo.com", 443),
new UsernamePasswordCredentials(AUTH_ID, AUTH_TOKEN)
);
gson = new Gson();
}
public String request(String method, String resource, LinkedHashMap<String, String> parameters)
throws PlivoException
{
HttpResponse response = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1),
HttpStatus.SC_OK, "OK");
String json = "";
try {
if ( method == "GET" ) {
// Prepare a String with GET parameters
String getparams = "?";
for ( Entry<String, String> pair : parameters.entrySet() )
getparams += pair.getKey() + "=" + pair.getValue() + "&";
// remove the trailing '&'
getparams = getparams.substring(0, getparams.length() - 1);
HttpGet httpget = new HttpGet(this.BaseURI + resource + getparams);
response = this.Client.execute(httpget);
}
else if ( method == "POST" ) {
HttpPost httpost = new HttpPost(this.BaseURI + resource);
Gson gson = new GsonBuilder().serializeNulls().create();
// Create a String entity with the POST parameters
- StringEntity se = new StringEntity(gson.toJson(parameters));
+ StringEntity se = new StringEntity(gson.toJson(parameters),"utf-8");
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
// Now, attach the pay load to the request
httpost.setEntity(se);
response = this.Client.execute(httpost);
}
else if ( method == "DELETE" ) {
HttpDelete httpdelete = new HttpDelete(this.BaseURI + resource);
response = this.Client.execute(httpdelete);
}
Integer serverCode = response.getStatusLine().getStatusCode();
if ( response.getEntity() != null ) {
json = this.convertStreamToString(response.getEntity().getContent()).replaceFirst("\\{", String.format("{ \"server_code\": %s, ", serverCode.toString()));
} else {
// dummy response
json = String.format("{\"message\":\"no response\",\"api_id\":\"unknown\", \"server_code\":%s}", serverCode.toString());
}
} catch (ClientProtocolException e) {
throw new PlivoException(e.getLocalizedMessage());
} catch (IOException e) {
throw new PlivoException(e.getLocalizedMessage());
} catch (IllegalStateException e) {
throw new PlivoException(e.getLocalizedMessage());
} finally {
this.Client.getConnectionManager().shutdown();
}
return json;
}
private String convertStreamToString(InputStream istream)
throws IOException {
BufferedReader breader = new BufferedReader(new InputStreamReader(istream));
StringBuilder responseString = new StringBuilder();
String line = "";
while ((line = breader.readLine()) != null) {
responseString.append(line);
}
breader.close();
return responseString.toString();
}
private String getKeyValue(LinkedHashMap<String, String> params, String key) throws PlivoException {
String value = "";
if (params.containsKey(key)) {
value = params.get(key);
params.remove(key);
} else {
throw new PlivoException("Missing mandatory parameter " + key);
}
return value;
}
// Account
public Account getAccount() throws PlivoException {
return this.gson.fromJson(request("GET", "/", new LinkedHashMap<String, String>()), Account.class);
}
public GenericResponse editAccount(LinkedHashMap<String, String> parameters) throws PlivoException {
return this.gson.fromJson(request("POST", "/", parameters), GenericResponse.class);
}
public SubAccountFactory getSubaccounts() throws PlivoException {
return this.gson.fromJson(request("GET", "/Subaccount/", new LinkedHashMap<String, String>()), SubAccountFactory.class);
}
public SubAccount getSubaccount(LinkedHashMap<String, String> parameters) throws PlivoException {
String subauth_id = this.getKeyValue(parameters, "subauth_id");
return this.gson.fromJson(request("GET", String.format("/Subaccount/%s/", subauth_id), parameters), SubAccount.class);
}
public GenericResponse createSubaccount(LinkedHashMap<String, String> parameters) throws PlivoException {
return this.gson.fromJson(request("POST", "/Subaccount/", parameters), GenericResponse.class);
}
public GenericResponse editSubaccount(LinkedHashMap<String, String> parameters) throws PlivoException {
return this.gson.fromJson(request("POST", "/Subaccount/", parameters), GenericResponse.class);
}
public GenericResponse deleteSubaccount(LinkedHashMap<String, String> parameters) throws PlivoException {
String subauth_id = this.getKeyValue(parameters, "subauth_id");
return this.gson.fromJson(request("DELETE", String.format("/Subaccount/%s/", subauth_id), parameters), GenericResponse.class);
}
// Application
public ApplicationFactory getApplications() throws PlivoException {
return this.gson.fromJson(request("GET", "/Application/", new LinkedHashMap<String, String>()), ApplicationFactory.class);
}
public Application getApplication(LinkedHashMap<String, String> parameters) throws PlivoException {
String app_id = this.getKeyValue(parameters, "app_id");
return this.gson.fromJson(request("GET", String.format("/Application/%s/", app_id),
new LinkedHashMap<String, String>()), Application.class);
}
public GenericResponse createApplication(LinkedHashMap<String, String> parameters) throws PlivoException {
return this.gson.fromJson(request("POST", "/Application/", parameters), GenericResponse.class);
}
public GenericResponse editApplication(LinkedHashMap<String, String> parameters) throws PlivoException {
String app_id = this.getKeyValue(parameters, "app_id");
return this.gson.fromJson(request("POST", String.format("/Application/%s/", app_id), parameters), GenericResponse.class);
}
public GenericResponse deleteApplication(LinkedHashMap<String, String> parameters) throws PlivoException {
String app_id = this.getKeyValue(parameters, "app_id");
return this.gson.fromJson(request("DELETE", String.format("/Application/%s/", app_id), parameters), GenericResponse.class);
}
// Call
public CDRFactory getCDRs(LinkedHashMap<String, String> parameters) throws PlivoException {
return this.gson.fromJson(request("GET", "/Call/", parameters), CDRFactory.class);
}
public CDR getCDR(LinkedHashMap<String, String> parameters) throws PlivoException {
String record_id = getKeyValue(parameters, "record_id");
return this.gson.fromJson(request("GET", String.format("/Call/%s/", record_id),
new LinkedHashMap<String, String>()), CDR.class);
}
public LiveCallFactory getLiveCalls() throws PlivoException {
LinkedHashMap<String, String> parameters= new LinkedHashMap<String, String>();
parameters.put("status", "live");
return this.gson.fromJson(request("GET", "/Call/", parameters), LiveCallFactory.class);
}
public LiveCall getLiveCall(LinkedHashMap<String, String> parameters) throws PlivoException {
String call_uuid = getKeyValue(parameters, "call_uuid");
parameters.put("status", "live");
return this.gson.fromJson(request("GET", String.format("/Call/%s/", call_uuid), parameters), LiveCall.class);
}
public Call makeCall(LinkedHashMap<String, String> parameters) throws PlivoException {
return this.gson.fromJson(request("POST", "/Call/", parameters), Call.class);
}
public GenericResponse hangupAllCalls() throws PlivoException {
return this.gson.fromJson(request("DELETE", "/Call/", new LinkedHashMap<String, String>()), GenericResponse.class);
}
public GenericResponse hangupCall(LinkedHashMap<String, String> parameters) throws PlivoException {
String call_uuid = getKeyValue(parameters, "call_uuid");
return this.gson.fromJson(request("DELETE", String.format("/Call/%s/", call_uuid),
new LinkedHashMap<String, String>()), GenericResponse.class);
}
public GenericResponse transferCall(LinkedHashMap<String, String> parameters) throws PlivoException {
String call_uuid = getKeyValue(parameters, "call_uuid");
return this.gson.fromJson(request("POST", String.format("/Call/%s/", call_uuid), parameters), GenericResponse.class);
}
public Record record(LinkedHashMap<String, String> parameters) throws PlivoException {
String call_uuid = getKeyValue(parameters, "call_uuid");
return this.gson.fromJson(request("POST", String.format("/Call/%s/Record/", call_uuid), parameters), Record.class);
}
public GenericResponse stopRecord(LinkedHashMap<String, String> parameters) throws PlivoException {
String call_uuid = getKeyValue(parameters, "call_uuid");
return this.gson.fromJson(request("DELETE", String.format("/Call/%s/Record/", call_uuid),
new LinkedHashMap<String, String>()), GenericResponse.class);
}
public GenericResponse play(LinkedHashMap<String, String> parameters) throws PlivoException {
String call_uuid = getKeyValue(parameters, "call_uuid");
return this.gson.fromJson(request("POST", String.format("/Call/%s/Play/", call_uuid), parameters), GenericResponse.class);
}
public GenericResponse stopPlay(LinkedHashMap<String, String> parameters) throws PlivoException {
String call_uuid = getKeyValue(parameters, "call_uuid");
return this.gson.fromJson(request("DELETE", String.format("/Call/%s/Play/", call_uuid),
new LinkedHashMap<String, String>()), GenericResponse.class);
}
public GenericResponse speak(LinkedHashMap<String, String> parameters) throws PlivoException {
String text = HtmlEntity.convert(getKeyValue(parameters, "text"));
parameters.put("text", text);
String call_uuid = getKeyValue(parameters, "call_uuid");
return this.gson.fromJson(request("POST", String.format("/Call/%s/Speak/", call_uuid), parameters), GenericResponse.class);
}
public GenericResponse sendDigits(LinkedHashMap<String, String> parameters) throws PlivoException {
String call_uuid = getKeyValue(parameters, "call_uuid");
return this.gson.fromJson(request("POST", String.format("/Call/%s/DTMF/", call_uuid), parameters), GenericResponse.class);
}
// Conference
public LiveConferenceFactory getLiveConferences() throws PlivoException {
return this.gson.fromJson(request("GET", "/Conference/", new LinkedHashMap<String, String>()), LiveConferenceFactory.class);
}
public GenericResponse hangupAllConferences() throws PlivoException {
return this.gson.fromJson(request("DELETE", "/Conference/", new LinkedHashMap<String, String>()), GenericResponse.class);
}
public Conference getLiveConference(LinkedHashMap<String, String> parameters) throws PlivoException{
String conference_name = getKeyValue(parameters, "conference_name");
return this.gson.fromJson(request("GET", String.format("/Conference/%s/", conference_name),
new LinkedHashMap<String, String>()), Conference.class);
}
public GenericResponse hangupConference(LinkedHashMap<String, String> parameters) throws PlivoException {
String conference_name = getKeyValue(parameters, "conference_name");
return this.gson.fromJson(request("DELETE", String.format("/Conference/%s/", conference_name),
new LinkedHashMap<String, String>()), GenericResponse.class);
}
public GenericResponse hangupMember(LinkedHashMap<String, String> parameters) throws PlivoException {
String conference_name = getKeyValue(parameters, "conference_name");
String member_id = getKeyValue(parameters, "member_id");
return this.gson.fromJson(request("DELETE", String.format("/Conference/%1$s/Member/%2$s/", conference_name, member_id),
new LinkedHashMap<String, String>()), GenericResponse.class);
}
public GenericResponse playMember(LinkedHashMap<String, String> parameters) throws PlivoException {
String conference_name = getKeyValue(parameters, "conference_name");
String member_id = getKeyValue(parameters, "member_id");
return this.gson.fromJson(request("POST", String.format("/Conference/%1$s/Member/%2$s/Play/", conference_name, member_id),
new LinkedHashMap<String, String>()), GenericResponse.class);
}
public GenericResponse stopPlayMember(LinkedHashMap<String, String> parameters) throws PlivoException {
String conference_name = getKeyValue(parameters, "conference_name");
String member_id = getKeyValue(parameters, "member_id");
return this.gson.fromJson(request("DELETE", String.format("/Conference/%1$s/Member/%2$s/Play/", conference_name, member_id),
new LinkedHashMap<String, String>()), GenericResponse.class);
}
public GenericResponse speakMember(LinkedHashMap<String, String> parameters) throws PlivoException {
String text = HtmlEntity.convert(getKeyValue(parameters, "text"));
parameters.put("text", text);
String conference_name = getKeyValue(parameters, "conference_name");
String member_id = getKeyValue(parameters, "member_id");
return this.gson.fromJson(request("POST", String.format("/Conference/%1$s/Member/%2$s/Speak/", conference_name, member_id),
new LinkedHashMap<String, String>()), GenericResponse.class);
}
public GenericResponse deafMember(LinkedHashMap<String, String> parameters) throws PlivoException {
String conference_name = getKeyValue(parameters, "conference_name");
String memberId = getKeyValue(parameters, "member_id");
return this.gson.fromJson(request("POST", String.format("/Conference/%1$s/Member/%2$s/Deaf/", conference_name, memberId),
new LinkedHashMap<String, String>()), GenericResponse.class);
}
public GenericResponse undeafMember(LinkedHashMap<String, String> parameters) throws PlivoException {
String conference_name = getKeyValue(parameters, "conference_name");
String memberId = getKeyValue(parameters, "member_id");
return this.gson.fromJson(request("DELETE", String.format("/Conference/%1$s/Member/%2$s/Deaf/", conference_name, memberId),
new LinkedHashMap<String, String>()), GenericResponse.class);
}
public GenericResponse muteMember(LinkedHashMap<String, String> parameters) throws PlivoException {
String conference_name = getKeyValue(parameters, "conference_name");
String member_id = getKeyValue(parameters, "member_id");
return this.gson.fromJson(request("POST", String.format("/Conference/%1$s/Member/%2$s/Mute/", conference_name, member_id),
new LinkedHashMap<String, String>()), GenericResponse.class);
}
public GenericResponse unmuteMember(LinkedHashMap<String, String> parameters) throws PlivoException {
String conference_name = getKeyValue(parameters, "conference_name");
String member_id = getKeyValue(parameters, "member_id");
return this.gson.fromJson(request("DELETE", String.format("/Conference/%1$s/Member/%2$s/Mute/", conference_name, member_id),
new LinkedHashMap<String, String>()), GenericResponse.class);
}
public GenericResponse kickMember(LinkedHashMap<String, String> parameters) throws PlivoException {
String conference_name = getKeyValue(parameters, "conference_name");
String member_id = getKeyValue(parameters, "member_id");
return this.gson.fromJson(request("POST", String.format("/Conference/%1$s/Member/%2$s/Kick/", conference_name, member_id),
new LinkedHashMap<String, String>()), GenericResponse.class);
}
public Record recordConference(LinkedHashMap<String, String> parameters) throws PlivoException {
String conference_name = getKeyValue(parameters, "conference_name");
return this.gson.fromJson(request("POST", String.format("/Conference/%s/Record/", conference_name), parameters), Record.class);
}
public GenericResponse stopRecordConference(LinkedHashMap<String, String> parameters) throws PlivoException {
String conference_name = getKeyValue(parameters, "conference_name");
return this.gson.fromJson(request("DELETE", String.format("/Conference/%s/Record/", conference_name),
new LinkedHashMap<String, String>()),GenericResponse.class);
}
// Endpoint
public EndpointFactory getEndpoints(LinkedHashMap<String, String> parameters) throws PlivoException {
return this.gson.fromJson(request("GET", "/Endpoint/", parameters), EndpointFactory.class);
}
public GenericResponse createEndpoint(LinkedHashMap<String, String> parameters) throws PlivoException {
return this.gson.fromJson(request("POST", "/Endpoint/", parameters),GenericResponse.class);
}
public Endpoint getEndpoint(LinkedHashMap<String, String> parameters) throws PlivoException {
String endpoint_id = getKeyValue(parameters, "endpoint_id");
return this.gson.fromJson(request("GET", String.format("/Endpoint/%s/", endpoint_id),
new LinkedHashMap<String, String>()), Endpoint.class);
}
public GenericResponse editEndpoint(LinkedHashMap<String, String> parameters) throws PlivoException {
String endpoint_id = getKeyValue(parameters, "endpoint_id");
return this.gson.fromJson(request("POST", String.format("/Endpoint/%s/", endpoint_id), parameters), GenericResponse.class);
}
public GenericResponse deleteEndpoint(LinkedHashMap<String, String> parameters) throws PlivoException {
String endpoint_id = getKeyValue(parameters, "endpoint_id");
return this.gson.fromJson(request("DELETE", String.format("/Endpoint/%s/", endpoint_id),
new LinkedHashMap<String, String>()), GenericResponse.class);
}
// Number
public NumberSearchFactory getNumbers() throws PlivoException {
return this.gson.fromJson(request("GET", "/Number/", new LinkedHashMap<String, String>()), NumberSearchFactory.class);
}
public NumberSearchFactory getNumbers(LinkedHashMap<String, String> parameters) throws PlivoException {
return this.gson.fromJson(request("GET", "/Number/", parameters), NumberSearchFactory.class);
}
@Deprecated
public NumberSearchFactory searchNumbers(LinkedHashMap<String, String> parameters) throws PlivoException {
return this.gson.fromJson(request("GET", "/AvailableNumber/", parameters), NumberSearchFactory.class);
}
@Deprecated
public GenericResponse rentNumber(LinkedHashMap<String, String> parameters) throws PlivoException {
String number = getKeyValue(parameters, "number");
return this.gson.fromJson(request("POST", String.format("/AvailableNumber/%s/", number, parameters),
new LinkedHashMap<String, String>()), GenericResponse.class);
}
public NumberGroupFactory searchNumberGroups(LinkedHashMap<String, String> parameters) throws PlivoException {
return this.gson.fromJson(request("GET", "/AvailableNumberGroup/", parameters), NumberGroupFactory.class);
}
public NumberResponse rentNumbers(LinkedHashMap<String, String> parameters) throws PlivoException {
String groupId = getKeyValue(parameters, "group_id");
return this.gson.fromJson(request("POST", String.format("/AvailableNumberGroup/%s/", groupId), parameters), NumberResponse.class);
}
public GenericResponse unRentNumber(LinkedHashMap<String, String> parameters) throws PlivoException {
String number = getKeyValue(parameters, "number");
return this.gson.fromJson(request("DELETE", String.format("/Number/%s/", number), parameters), GenericResponse.class);
}
public GenericResponse linkApplicationNumber(LinkedHashMap<String, String> parameters) throws PlivoException {
String number = getKeyValue(parameters, "number");
return this.gson.fromJson(request("POST", String.format("/Number/%s/", number), parameters), GenericResponse.class);
}
public GenericResponse unlinkApplicationNumber(LinkedHashMap<String, String> parameters) throws PlivoException {
String number = getKeyValue(parameters, "number");
parameters.put("app_id", "");
return this.gson.fromJson(request("POST", String.format("/Number/%s/", number), parameters), GenericResponse.class);
}
// Message
public MessageResponse sendMessage(LinkedHashMap<String, String> parameters) throws PlivoException {
return this.gson.fromJson(request("POST", "/Message/", parameters), MessageResponse.class);
}
public Message getMessage(LinkedHashMap<String, String> parameters) throws PlivoException {
String record_id = getKeyValue(parameters, "record_id");
return this.gson.fromJson(request("GET", String.format("/Message/%s/", record_id),
new LinkedHashMap<String, String>()), Message.class);
}
public MessageFactory getMessages() throws PlivoException {
return this.gson.fromJson(request("GET", "/Message/", new LinkedHashMap<String, String>()), MessageFactory.class);
}
public MessageFactory getMessages(LinkedHashMap<String, String> parameters) throws PlivoException {
return this.gson.fromJson(request("GET", "/Message/", parameters), MessageFactory.class);
}
// Incoming Carrier
public IncomingCarrierFactory getIncomingCarriers(LinkedHashMap<String, String> parameters) throws PlivoException {
return this.gson.fromJson(request("GET", "/IncomingCarrier/", parameters), IncomingCarrierFactory.class);
}
public IncomingCarrier getIncomingCarrier(LinkedHashMap<String, String> parameters) throws PlivoException {
String carrier = getKeyValue(parameters, "carrier_id");
return this.gson.fromJson(request("GET", String.format("/IncomingCarrier/%s/", carrier), parameters), IncomingCarrier.class);
}
public GenericResponse addIncomingCarrier(LinkedHashMap<String, String> parameters) throws PlivoException {
return this.gson.fromJson(request("POST", "/IncomingCarrier/", parameters), GenericResponse.class);
}
public GenericResponse editIncomingCarrier(LinkedHashMap<String, String> parameters) throws PlivoException {
String carrier = getKeyValue(parameters, "carrier_id");
return this.gson.fromJson(request("POST", String.format("/IncomingCarrier/", carrier), parameters), GenericResponse.class);
}
public GenericResponse dropIncomingCarrier(LinkedHashMap<String, String> parameters) throws PlivoException {
String carrier = getKeyValue(parameters, "carrier_id");
return this.gson.fromJson(request("DELETE", String.format("/IncomingCarrier/%s/", carrier), parameters), GenericResponse.class);
}
// Outgoing Carrier
public OutgoingCarrierFactory getOutgoingCarriers(LinkedHashMap<String, String> parameters) throws PlivoException {
return this.gson.fromJson(request("GET", "/OutgoingCarrier/", parameters), OutgoingCarrierFactory.class);
}
public OutgoingCarrier getOutgoingCarrier(LinkedHashMap<String, String> parameters) throws PlivoException {
String carrier = getKeyValue(parameters, "carrier_id");
return this.gson.fromJson(request("GET", String.format("/OutgoingCarrier/%s/", carrier), parameters), OutgoingCarrier.class);
}
public OutgoingCarrierCreatedResponse addOutgoingCarrier(LinkedHashMap<String, String> parameters) throws PlivoException {
return this.gson.fromJson(request("POST", "/OutgoingCarrier/", parameters), OutgoingCarrierCreatedResponse.class);
}
public GenericResponse editOutgoingCarrier(LinkedHashMap<String, String> parameters) throws PlivoException {
String carrier = getKeyValue(parameters, "carrier_id");
return this.gson.fromJson(request("POST", String.format("/OutgoingCarrier/%s/", carrier), parameters), GenericResponse.class);
}
public GenericResponse dropOutgoingCarrier(LinkedHashMap<String, String> parameters) throws PlivoException {
String carrier = getKeyValue(parameters, "carrier_id");
return this.gson.fromJson(request("DELETE", String.format("/OutgoingCarrier/%s/", carrier), parameters), GenericResponse.class);
}
// Outgoing Carrier Routing
public OutgoingCarrierRoutingFactory getOutgoingCarrierRoutings(LinkedHashMap<String, String> parameters) throws PlivoException {
return this.gson.fromJson(request("GET", "/OutgoingCarrierRouting/", parameters), OutgoingCarrierRoutingFactory.class);
}
public OutgoingCarrierRouting getOutgoingCarrierRouting(LinkedHashMap<String, String> parameters) throws PlivoException {
String carrier = getKeyValue(parameters, "routing_id");
return this.gson.fromJson(request("GET", String.format("/OutgoingCarrierRouting/%s/", carrier), parameters), OutgoingCarrierRouting.class);
}
public OutgoingCarrierRoutingCreatedResponse addOutgoingCarrierRouting(LinkedHashMap<String, String> parameters) throws PlivoException {
return this.gson.fromJson(request("POST", "/OutgoingCarrierRouting/", parameters), OutgoingCarrierRoutingCreatedResponse.class);
}
public GenericResponse editOutgoingCarrierRouting(LinkedHashMap<String, String> parameters) throws PlivoException {
String routing_id = getKeyValue(parameters, "routing_id");
return this.gson.fromJson(request("POST", String.format("/OutgoingCarrierRouting/%s/", routing_id), parameters), GenericResponse.class);
}
public GenericResponse dropOutgoingCarrierRouting(LinkedHashMap<String, String> parameters) throws PlivoException {
String routing_id = getKeyValue(parameters, "routing_id");
return this.gson.fromJson(request("DELETE", String.format("/OutgoingCarrierRouting/%s/", routing_id), parameters), GenericResponse.class);
}
// Pricing
public PlivoPricing getPricing(LinkedHashMap<String, String> parameters) throws PlivoException {
return this.gson.fromJson(request("GET", "/Pricing/", parameters), PlivoPricing.class);
}
}
| true | true | public String request(String method, String resource, LinkedHashMap<String, String> parameters)
throws PlivoException
{
HttpResponse response = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1),
HttpStatus.SC_OK, "OK");
String json = "";
try {
if ( method == "GET" ) {
// Prepare a String with GET parameters
String getparams = "?";
for ( Entry<String, String> pair : parameters.entrySet() )
getparams += pair.getKey() + "=" + pair.getValue() + "&";
// remove the trailing '&'
getparams = getparams.substring(0, getparams.length() - 1);
HttpGet httpget = new HttpGet(this.BaseURI + resource + getparams);
response = this.Client.execute(httpget);
}
else if ( method == "POST" ) {
HttpPost httpost = new HttpPost(this.BaseURI + resource);
Gson gson = new GsonBuilder().serializeNulls().create();
// Create a String entity with the POST parameters
StringEntity se = new StringEntity(gson.toJson(parameters));
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
// Now, attach the pay load to the request
httpost.setEntity(se);
response = this.Client.execute(httpost);
}
else if ( method == "DELETE" ) {
HttpDelete httpdelete = new HttpDelete(this.BaseURI + resource);
response = this.Client.execute(httpdelete);
}
Integer serverCode = response.getStatusLine().getStatusCode();
if ( response.getEntity() != null ) {
json = this.convertStreamToString(response.getEntity().getContent()).replaceFirst("\\{", String.format("{ \"server_code\": %s, ", serverCode.toString()));
} else {
// dummy response
json = String.format("{\"message\":\"no response\",\"api_id\":\"unknown\", \"server_code\":%s}", serverCode.toString());
}
} catch (ClientProtocolException e) {
throw new PlivoException(e.getLocalizedMessage());
} catch (IOException e) {
throw new PlivoException(e.getLocalizedMessage());
} catch (IllegalStateException e) {
throw new PlivoException(e.getLocalizedMessage());
} finally {
this.Client.getConnectionManager().shutdown();
}
return json;
}
| public String request(String method, String resource, LinkedHashMap<String, String> parameters)
throws PlivoException
{
HttpResponse response = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1),
HttpStatus.SC_OK, "OK");
String json = "";
try {
if ( method == "GET" ) {
// Prepare a String with GET parameters
String getparams = "?";
for ( Entry<String, String> pair : parameters.entrySet() )
getparams += pair.getKey() + "=" + pair.getValue() + "&";
// remove the trailing '&'
getparams = getparams.substring(0, getparams.length() - 1);
HttpGet httpget = new HttpGet(this.BaseURI + resource + getparams);
response = this.Client.execute(httpget);
}
else if ( method == "POST" ) {
HttpPost httpost = new HttpPost(this.BaseURI + resource);
Gson gson = new GsonBuilder().serializeNulls().create();
// Create a String entity with the POST parameters
StringEntity se = new StringEntity(gson.toJson(parameters),"utf-8");
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
// Now, attach the pay load to the request
httpost.setEntity(se);
response = this.Client.execute(httpost);
}
else if ( method == "DELETE" ) {
HttpDelete httpdelete = new HttpDelete(this.BaseURI + resource);
response = this.Client.execute(httpdelete);
}
Integer serverCode = response.getStatusLine().getStatusCode();
if ( response.getEntity() != null ) {
json = this.convertStreamToString(response.getEntity().getContent()).replaceFirst("\\{", String.format("{ \"server_code\": %s, ", serverCode.toString()));
} else {
// dummy response
json = String.format("{\"message\":\"no response\",\"api_id\":\"unknown\", \"server_code\":%s}", serverCode.toString());
}
} catch (ClientProtocolException e) {
throw new PlivoException(e.getLocalizedMessage());
} catch (IOException e) {
throw new PlivoException(e.getLocalizedMessage());
} catch (IllegalStateException e) {
throw new PlivoException(e.getLocalizedMessage());
} finally {
this.Client.getConnectionManager().shutdown();
}
return json;
}
|
diff --git a/TFC_Shared/src/TFC/Handlers/CraftingHandler.java b/TFC_Shared/src/TFC/Handlers/CraftingHandler.java
index f40cc468e..27905f178 100644
--- a/TFC_Shared/src/TFC/Handlers/CraftingHandler.java
+++ b/TFC_Shared/src/TFC/Handlers/CraftingHandler.java
@@ -1,140 +1,140 @@
package TFC.Handlers;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import TFC.TFCBlocks;
import TFC.TFCItems;
import TFC.TerraFirmaCraft;
import TFC.Core.Recipes;
import TFC.Food.ItemTerraFood;
import cpw.mods.fml.common.ICraftingHandler;
public class CraftingHandler implements ICraftingHandler
{
@Override
public void onCrafting(EntityPlayer entityplayer, ItemStack itemstack, IInventory iinventory)
{
int index = 0;
- if(iinventory != null && !entityplayer.worldObj.isRemote)
+ if(iinventory != null)
{
if(itemstack.itemID == TFCItems.StoneBrick.itemID)
{
HandleItem(entityplayer, iinventory, Recipes.Chisels);
}
else if(itemstack.itemID == TFCItems.SinglePlank.itemID)
{
HandleItem(entityplayer, iinventory, Recipes.Axes);
HandleItem(entityplayer, iinventory, Recipes.Saws);
}
else if(itemstack.itemID == TFCBlocks.WoodSupportH.blockID || itemstack.itemID == TFCBlocks.WoodSupportV.blockID)
{
HandleItem(entityplayer, iinventory, Recipes.Saws);
HandleItem(entityplayer, iinventory, Recipes.Axes);
}
else if(itemstack.itemID == Item.bowlEmpty.itemID ||
itemstack.getItem() instanceof ItemTerraFood || itemstack.itemID == TFCItems.ScrapedHide.itemID
|| itemstack.itemID == TFCItems.Wool.itemID||itemstack.itemID == TFCItems.TerraLeather.itemID)
{
HandleItem(entityplayer, iinventory, Recipes.Knives);
- if(itemstack.itemID == TFCItems.Wool.itemID&& !entityplayer.worldObj.isRemote){
+ if (itemstack.itemID == TFCItems.Wool.itemID && !entityplayer.worldObj.isRemote){
entityplayer.dropItem(TFCItems.Hide.itemID, 1);
}
else if(itemstack.itemID == TFCItems.TerraLeather.itemID){
boolean openGui = false;
for(int i = 0; i < iinventory.getSizeInventory(); i++)
{
if(iinventory.getStackInSlot(i) == null)
{
continue;
}
if(true)//iinventory.getStackInSlot(i).itemID == TFCItems.TerraLeather.shiftedIndex)
{
if(iinventory.getStackInSlot(i).stackSize == 1)
iinventory.setInventorySlotContents(i, null);
else
{
ItemStack is = iinventory.getStackInSlot(i); is.stackSize-=1;
if(is.stackSize > 0)
iinventory.setInventorySlotContents(i, is);
}
openGui = true;
//itemstack.stackSize = -1;
}
}
if(openGui)
entityplayer.openGui(TerraFirmaCraft.instance, 36, entityplayer.worldObj, (int)entityplayer.posX, (int)entityplayer.posY, (int)entityplayer.posZ);
}
}
else if(itemstack.itemID == TFCItems.WoolYarn.itemID)
{
HandleItem(entityplayer,iinventory,Recipes.Spindle);
}
else if(itemstack.itemID == TFCItems.Flux.itemID)
{
HandleItem(entityplayer, iinventory, Recipes.Hammers);
}
else if(itemstack.itemID == TFCItems.Mortar.itemID)
{
for(int i = 0; i < iinventory.getSizeInventory(); i++)
{
if(iinventory.getStackInSlot(i) == null)
{
continue;
}
if(iinventory.getStackInSlot(i).itemID == TFCItems.WoodenBucketWater.itemID)
{
iinventory.getStackInSlot(i).itemID=TFCItems.Limewater.itemID;
}
}
}
}
}
public static void HandleItem(EntityPlayer entityplayer, IInventory iinventory, Item[] Items)
{
ItemStack item = null;
for(int i = 0; i < iinventory.getSizeInventory(); i++)
{
if(iinventory.getStackInSlot(i) == null)
{
continue;
}
for(int j = 0; j < Items.length; j++)
{
DamageItem(entityplayer,iinventory,i,Items[j].itemID);
}
}
}
public static void DamageItem(EntityPlayer entityplayer, IInventory iinventory, int i, int shiftedindex)
{
if(iinventory.getStackInSlot(i).itemID == shiftedindex)
{
int index = i;
ItemStack item = iinventory.getStackInSlot(index).copy();
if(item != null)
{
item.damageItem(1 , entityplayer);
if (item.getItemDamage() != 0 || entityplayer.capabilities.isCreativeMode)
{
iinventory.setInventorySlotContents(index, item);
iinventory.getStackInSlot(index).stackSize = iinventory.getStackInSlot(index).stackSize + 1;
if(iinventory.getStackInSlot(index).stackSize > 2)
iinventory.getStackInSlot(index).stackSize = 2;
}
}
}
}
@Override
public void onSmelting(EntityPlayer player, ItemStack item) {
// TODO Auto-generated method stub
}
}
| false | true | public void onCrafting(EntityPlayer entityplayer, ItemStack itemstack, IInventory iinventory)
{
int index = 0;
if(iinventory != null && !entityplayer.worldObj.isRemote)
{
if(itemstack.itemID == TFCItems.StoneBrick.itemID)
{
HandleItem(entityplayer, iinventory, Recipes.Chisels);
}
else if(itemstack.itemID == TFCItems.SinglePlank.itemID)
{
HandleItem(entityplayer, iinventory, Recipes.Axes);
HandleItem(entityplayer, iinventory, Recipes.Saws);
}
else if(itemstack.itemID == TFCBlocks.WoodSupportH.blockID || itemstack.itemID == TFCBlocks.WoodSupportV.blockID)
{
HandleItem(entityplayer, iinventory, Recipes.Saws);
HandleItem(entityplayer, iinventory, Recipes.Axes);
}
else if(itemstack.itemID == Item.bowlEmpty.itemID ||
itemstack.getItem() instanceof ItemTerraFood || itemstack.itemID == TFCItems.ScrapedHide.itemID
|| itemstack.itemID == TFCItems.Wool.itemID||itemstack.itemID == TFCItems.TerraLeather.itemID)
{
HandleItem(entityplayer, iinventory, Recipes.Knives);
if(itemstack.itemID == TFCItems.Wool.itemID&& !entityplayer.worldObj.isRemote){
entityplayer.dropItem(TFCItems.Hide.itemID, 1);
}
else if(itemstack.itemID == TFCItems.TerraLeather.itemID){
boolean openGui = false;
for(int i = 0; i < iinventory.getSizeInventory(); i++)
{
if(iinventory.getStackInSlot(i) == null)
{
continue;
}
if(true)//iinventory.getStackInSlot(i).itemID == TFCItems.TerraLeather.shiftedIndex)
{
if(iinventory.getStackInSlot(i).stackSize == 1)
iinventory.setInventorySlotContents(i, null);
else
{
ItemStack is = iinventory.getStackInSlot(i); is.stackSize-=1;
if(is.stackSize > 0)
iinventory.setInventorySlotContents(i, is);
}
openGui = true;
//itemstack.stackSize = -1;
}
}
if(openGui)
entityplayer.openGui(TerraFirmaCraft.instance, 36, entityplayer.worldObj, (int)entityplayer.posX, (int)entityplayer.posY, (int)entityplayer.posZ);
}
}
else if(itemstack.itemID == TFCItems.WoolYarn.itemID)
{
HandleItem(entityplayer,iinventory,Recipes.Spindle);
}
else if(itemstack.itemID == TFCItems.Flux.itemID)
{
HandleItem(entityplayer, iinventory, Recipes.Hammers);
}
else if(itemstack.itemID == TFCItems.Mortar.itemID)
{
for(int i = 0; i < iinventory.getSizeInventory(); i++)
{
if(iinventory.getStackInSlot(i) == null)
{
continue;
}
if(iinventory.getStackInSlot(i).itemID == TFCItems.WoodenBucketWater.itemID)
{
iinventory.getStackInSlot(i).itemID=TFCItems.Limewater.itemID;
}
}
}
}
}
| public void onCrafting(EntityPlayer entityplayer, ItemStack itemstack, IInventory iinventory)
{
int index = 0;
if(iinventory != null)
{
if(itemstack.itemID == TFCItems.StoneBrick.itemID)
{
HandleItem(entityplayer, iinventory, Recipes.Chisels);
}
else if(itemstack.itemID == TFCItems.SinglePlank.itemID)
{
HandleItem(entityplayer, iinventory, Recipes.Axes);
HandleItem(entityplayer, iinventory, Recipes.Saws);
}
else if(itemstack.itemID == TFCBlocks.WoodSupportH.blockID || itemstack.itemID == TFCBlocks.WoodSupportV.blockID)
{
HandleItem(entityplayer, iinventory, Recipes.Saws);
HandleItem(entityplayer, iinventory, Recipes.Axes);
}
else if(itemstack.itemID == Item.bowlEmpty.itemID ||
itemstack.getItem() instanceof ItemTerraFood || itemstack.itemID == TFCItems.ScrapedHide.itemID
|| itemstack.itemID == TFCItems.Wool.itemID||itemstack.itemID == TFCItems.TerraLeather.itemID)
{
HandleItem(entityplayer, iinventory, Recipes.Knives);
if (itemstack.itemID == TFCItems.Wool.itemID && !entityplayer.worldObj.isRemote){
entityplayer.dropItem(TFCItems.Hide.itemID, 1);
}
else if(itemstack.itemID == TFCItems.TerraLeather.itemID){
boolean openGui = false;
for(int i = 0; i < iinventory.getSizeInventory(); i++)
{
if(iinventory.getStackInSlot(i) == null)
{
continue;
}
if(true)//iinventory.getStackInSlot(i).itemID == TFCItems.TerraLeather.shiftedIndex)
{
if(iinventory.getStackInSlot(i).stackSize == 1)
iinventory.setInventorySlotContents(i, null);
else
{
ItemStack is = iinventory.getStackInSlot(i); is.stackSize-=1;
if(is.stackSize > 0)
iinventory.setInventorySlotContents(i, is);
}
openGui = true;
//itemstack.stackSize = -1;
}
}
if(openGui)
entityplayer.openGui(TerraFirmaCraft.instance, 36, entityplayer.worldObj, (int)entityplayer.posX, (int)entityplayer.posY, (int)entityplayer.posZ);
}
}
else if(itemstack.itemID == TFCItems.WoolYarn.itemID)
{
HandleItem(entityplayer,iinventory,Recipes.Spindle);
}
else if(itemstack.itemID == TFCItems.Flux.itemID)
{
HandleItem(entityplayer, iinventory, Recipes.Hammers);
}
else if(itemstack.itemID == TFCItems.Mortar.itemID)
{
for(int i = 0; i < iinventory.getSizeInventory(); i++)
{
if(iinventory.getStackInSlot(i) == null)
{
continue;
}
if(iinventory.getStackInSlot(i).itemID == TFCItems.WoodenBucketWater.itemID)
{
iinventory.getStackInSlot(i).itemID=TFCItems.Limewater.itemID;
}
}
}
}
}
|
diff --git a/src/main/java/me/tehbeard/vocalise/parser/VocalisedConversation.java b/src/main/java/me/tehbeard/vocalise/parser/VocalisedConversation.java
index 5f4cc70..c868a66 100644
--- a/src/main/java/me/tehbeard/vocalise/parser/VocalisedConversation.java
+++ b/src/main/java/me/tehbeard/vocalise/parser/VocalisedConversation.java
@@ -1,33 +1,34 @@
package me.tehbeard.vocalise.parser;
import java.util.Map;
import org.bukkit.conversations.*;
import org.bukkit.plugin.Plugin;
public class VocalisedConversation extends Conversation{
public VocalisedConversation(Plugin plugin, Conversable forWhom,
Prompt firstPrompt) {
super(plugin, forWhom, firstPrompt);
// TODO Auto-generated constructor stub
}
public VocalisedConversation(Plugin plugin, Conversable forWhom, Prompt firstPrompt, Map<Object, Object> initialSessionData) {
super(plugin,forWhom,firstPrompt,initialSessionData);
}
public void outputNextPrompt() {
if (currentPrompt == null) {
abandon(new ConversationAbandonedEvent(this));
} else {
- if(currentPrompt.getPromptText(context) != null){
- context.getForWhom().sendRawMessage(prefix.getPrefix(context) + currentPrompt.getPromptText(context));
+ String promptText = currentPrompt.getPromptText(context);
+ if(promptText != null){
+ context.getForWhom().sendRawMessage(prefix.getPrefix(context) + promptText);
}
if (!currentPrompt.blocksForInput(context)) {
currentPrompt = currentPrompt.acceptInput(context, null);
outputNextPrompt();
}
}
}
}
| true | true | public void outputNextPrompt() {
if (currentPrompt == null) {
abandon(new ConversationAbandonedEvent(this));
} else {
if(currentPrompt.getPromptText(context) != null){
context.getForWhom().sendRawMessage(prefix.getPrefix(context) + currentPrompt.getPromptText(context));
}
if (!currentPrompt.blocksForInput(context)) {
currentPrompt = currentPrompt.acceptInput(context, null);
outputNextPrompt();
}
}
}
| public void outputNextPrompt() {
if (currentPrompt == null) {
abandon(new ConversationAbandonedEvent(this));
} else {
String promptText = currentPrompt.getPromptText(context);
if(promptText != null){
context.getForWhom().sendRawMessage(prefix.getPrefix(context) + promptText);
}
if (!currentPrompt.blocksForInput(context)) {
currentPrompt = currentPrompt.acceptInput(context, null);
outputNextPrompt();
}
}
}
|
diff --git a/src/com/diycircuits/cangjie/CandidateSelect.java b/src/com/diycircuits/cangjie/CandidateSelect.java
index e419c08..6d12cce 100644
--- a/src/com/diycircuits/cangjie/CandidateSelect.java
+++ b/src/com/diycircuits/cangjie/CandidateSelect.java
@@ -1,292 +1,295 @@
package com.diycircuits.cangjie;
import android.content.Context;
import android.app.Activity;
import android.util.AttributeSet;
import android.view.*;
import android.widget.*;
import android.graphics.*;
import android.util.Log;
import android.os.Handler.Callback;
import android.os.Handler;
import android.os.Message;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewGroup.MarginLayoutParams;
public class CandidateSelect extends View implements Handler.Callback {
public static final int CHARACTER = 0;
private int width = 0;
private int height = 0;
private char match[] = null;
private int total = 0;
private Paint paint = null;
private float[] textWidth = new float[21529];
private int offset = 10;
private int charOffset = 0;
private int spacing = 17;
private float charWidth = 0;
private int topOffset = 0;
private int mFontSize = 0;
private Context context = null;
private PopupWindow mPopup = null;
private Handler mHandler = null;
private final static int SPACING = 4;
private final static int STARTING_FONT_SIZE = 12;
private final static int ENDING_FONT_SIZE = 128;
private CandidateListener listener = null;
public static interface CandidateListener {
void characterSelected(char c, int idx);
}
public CandidateSelect(Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
mFontSize = 50;
paint = new Paint();
paint.setColor(Color.BLACK);
paint.setAntiAlias(true);
paint.setTextSize(50);
paint.setStrokeWidth(0);
mHandler = new Handler(this);
}
public void setCandidateListener(CandidateListener listen) {
listener = listen;
}
private class CandidateItem {
}
public class CandidateAdapter extends ArrayAdapter<CandidateItem> {
private Context context = null;
private char[] match = null;
private int total = 0;
private int layoutRes = 0;
private int fontSize = 0;
private int topOffset = 0;
private int leftOffset = 0;
private int columnc = 0;
public CandidateAdapter(Context context, int layoutRes, CandidateItem[] row, char[] match, int columnc, int total, int fs, int to, int lo) {
super(context, layoutRes, row);
this.context = context;
this.match = match;
this.layoutRes = layoutRes;
this.match = match;
this.total = total;
this.fontSize = fs;
this.topOffset = to;
this.leftOffset = lo;
this.columnc = columnc;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
CandidateHolder holder = null;
if (row == null) {
LayoutInflater inflater = (LayoutInflater)
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(layoutRes, parent, false);
holder = new CandidateHolder();
holder.row = (CandidateRow) row.findViewById(R.id.candidateRow);
row.setTag(holder);
} else {
holder = (CandidateHolder) row.getTag();
}
holder.row.setHandler(mHandler);
holder.row.setFontSize(fontSize, topOffset, leftOffset);
holder.row.setMatch(match, position * columnc, total - (position * columnc) >= columnc ? columnc : (total - (position * columnc)), total);
return row;
}
class CandidateHolder {
CandidateRow row;
}
}
public void closePopup() {
if (mPopup == null) return;
mPopup.dismiss();
mPopup = null;
}
public boolean handleMessage(Message msg) {
if (msg.what == CHARACTER) {
closePopup();
if (listener != null && msg.arg1 != 0) listener.characterSelected((char) msg.arg1, msg.arg2);
}
return true;
}
public void showCandidatePopup(View mParent, int w, int h) {
if (total == 0) return;
if (mPopup == null) {
mPopup = new PopupWindow(context);
LayoutInflater inflate = (LayoutInflater)
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflate.inflate(R.layout.popup, null);
int measured = paint.getTextWidths(context.getString(R.string.cangjie), 0, 1, textWidth);
int columnc = (w / ((int) textWidth[0] + spacing));
int rowc = total / columnc;
if ((total % columnc) > 0) rowc++;
int leftOffset = (columnc * (int) textWidth[0]) +
((columnc - 1) * spacing);
leftOffset = (w - leftOffset) / 2;
CandidateItem[] row = new CandidateItem[rowc];
CandidateAdapter adapter = new CandidateAdapter(context, R.layout.candidate, row, match, columnc, total, mFontSize, topOffset, leftOffset);
- Button mButton = (Button) view.findViewById(R.id.cancelButton);
+ CloseButton mButton = (CloseButton) view.findViewById(R.id.cancelButton);
mButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
closePopup();
}
});
ScrollView sv = (ScrollView) view.findViewById(R.id.sv);
sv.setFillViewport(true);
ListView lv = (ListView) view.findViewById(R.id.candidateExpanded);
lv.setAdapter(adapter);
mPopup.setContentView(view);
+ mPopup.setWidth(w);
+ mPopup.setHeight(300);
+ mPopup.showAsDropDown(mParent, 0, -h);
+ } else {
+ mPopup.dismiss();
+ mPopup = null;
}
- mPopup.setWidth(w);
- mPopup.setHeight(300);
- mPopup.showAsDropDown(mParent, 0, -h);
}
public int fontSize() {
return mFontSize;
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
width = w;
height = h;
Rect rect = new Rect();
for (int fontsize = STARTING_FONT_SIZE; fontsize < ENDING_FONT_SIZE; fontsize += 2) {
paint.setTextSize(fontsize);
Paint.FontMetrics metrics = paint.getFontMetrics();
int totalHeight = (int) (metrics.bottom - metrics.top);
if (totalHeight > height) {
mFontSize = fontsize - 8;
paint.setTextSize(mFontSize);
paint.getTextBounds(context.getString(R.string.cangjie), 0, 1, rect);
topOffset = rect.height() - rect.bottom;
topOffset += (h - rect.height()) / 2;
break;
}
}
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (canvas == null) {
return;
}
paint.setColor(0xff282828);
canvas.drawRect(0, 0, width, height - 0, paint);
paint.setColor(0xff33B5E5);
if (match != null) {
int _width = total > textWidth.length ? textWidth.length : total;
int measured = paint.getTextWidths(match, 0, _width, textWidth);
int start = offset, index = charOffset;
while (start < width && index < total) {
canvas.drawText(match, index, 1, start, topOffset, paint);
start = start + (int) textWidth[index] + spacing;
index++;
}
}
}
@Override
public boolean onTouchEvent(MotionEvent me) {
int action = me.getAction();
int x = (int) me.getX();
int y = (int) me.getY();
int select = x - offset;
int left = offset;
char c = 0;
int idx = -1;
offset = 0;
for (int count = charOffset; count < textWidth.length - 1; count++) {
if (count >= total) continue;
if (select > left && select < left + textWidth[count]) {
c = match[count];
idx = count;
break;
}
left = left + (int) textWidth[count] + spacing;
}
switch (action) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_MOVE:
break;
case MotionEvent.ACTION_UP:
if (listener != null && c != 0) listener.characterSelected(c, idx);
break;
}
return true;
}
public void showNextPage() {
if (match == null) return;
if (total > 1 && charOffset < (total - 1)) {
charOffset++;
invalidate();
}
}
public void showPrevPage() {
if (match == null) return;
if (charOffset > 0) {
charOffset--;
invalidate();
}
}
public void updateMatch(char[] _match, int _total) {
match = _match;
total = _total;
charOffset = 0;
offset = 13;
invalidate();
}
}
| false | true | public void showCandidatePopup(View mParent, int w, int h) {
if (total == 0) return;
if (mPopup == null) {
mPopup = new PopupWindow(context);
LayoutInflater inflate = (LayoutInflater)
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflate.inflate(R.layout.popup, null);
int measured = paint.getTextWidths(context.getString(R.string.cangjie), 0, 1, textWidth);
int columnc = (w / ((int) textWidth[0] + spacing));
int rowc = total / columnc;
if ((total % columnc) > 0) rowc++;
int leftOffset = (columnc * (int) textWidth[0]) +
((columnc - 1) * spacing);
leftOffset = (w - leftOffset) / 2;
CandidateItem[] row = new CandidateItem[rowc];
CandidateAdapter adapter = new CandidateAdapter(context, R.layout.candidate, row, match, columnc, total, mFontSize, topOffset, leftOffset);
Button mButton = (Button) view.findViewById(R.id.cancelButton);
mButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
closePopup();
}
});
ScrollView sv = (ScrollView) view.findViewById(R.id.sv);
sv.setFillViewport(true);
ListView lv = (ListView) view.findViewById(R.id.candidateExpanded);
lv.setAdapter(adapter);
mPopup.setContentView(view);
}
mPopup.setWidth(w);
mPopup.setHeight(300);
mPopup.showAsDropDown(mParent, 0, -h);
}
| public void showCandidatePopup(View mParent, int w, int h) {
if (total == 0) return;
if (mPopup == null) {
mPopup = new PopupWindow(context);
LayoutInflater inflate = (LayoutInflater)
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflate.inflate(R.layout.popup, null);
int measured = paint.getTextWidths(context.getString(R.string.cangjie), 0, 1, textWidth);
int columnc = (w / ((int) textWidth[0] + spacing));
int rowc = total / columnc;
if ((total % columnc) > 0) rowc++;
int leftOffset = (columnc * (int) textWidth[0]) +
((columnc - 1) * spacing);
leftOffset = (w - leftOffset) / 2;
CandidateItem[] row = new CandidateItem[rowc];
CandidateAdapter adapter = new CandidateAdapter(context, R.layout.candidate, row, match, columnc, total, mFontSize, topOffset, leftOffset);
CloseButton mButton = (CloseButton) view.findViewById(R.id.cancelButton);
mButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
closePopup();
}
});
ScrollView sv = (ScrollView) view.findViewById(R.id.sv);
sv.setFillViewport(true);
ListView lv = (ListView) view.findViewById(R.id.candidateExpanded);
lv.setAdapter(adapter);
mPopup.setContentView(view);
mPopup.setWidth(w);
mPopup.setHeight(300);
mPopup.showAsDropDown(mParent, 0, -h);
} else {
mPopup.dismiss();
mPopup = null;
}
}
|
diff --git a/src/web/org/codehaus/groovy/grails/web/converters/xtream/DomainClassConverter.java b/src/web/org/codehaus/groovy/grails/web/converters/xtream/DomainClassConverter.java
index 559874096..720300d43 100644
--- a/src/web/org/codehaus/groovy/grails/web/converters/xtream/DomainClassConverter.java
+++ b/src/web/org/codehaus/groovy/grails/web/converters/xtream/DomainClassConverter.java
@@ -1,192 +1,190 @@
/* Copyright 2006-2007 Graeme Rocher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.codehaus.groovy.grails.web.converters.xtream;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import org.codehaus.groovy.grails.commons.GrailsDomainClass;
import org.codehaus.groovy.grails.commons.GrailsDomainClassProperty;
import org.codehaus.groovy.grails.web.converters.ConverterUtil;
import org.hibernate.collection.AbstractPersistentCollection;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import java.util.*;
/**
* An XStream converter for converting Grails domain classes to XML
*
* @author Siegfried Puchbauer
*/
public class DomainClassConverter implements Converter {
private boolean renderDomainClassRelations = false;
public boolean isRenderDomainClassRelations() {
return renderDomainClassRelations;
}
/**
* Configure wheter DomainClass Relations should be fully rendered or on the referenced ID's
*
* @param renderDomainClassRelations true to render nested DomainClass Instances, false to render their ID's
*/
public void setRenderDomainClassRelations(boolean renderDomainClassRelations) {
this.renderDomainClassRelations = renderDomainClassRelations;
}
public void marshal(Object value, HierarchicalStreamWriter writer,
MarshallingContext context) {
Class clazz = value.getClass();
GrailsDomainClass domainClass = ConverterUtil.getDomainClass(clazz.getName());
BeanWrapper beanWrapper = new BeanWrapperImpl(value);
GrailsDomainClassProperty id = domainClass.getIdentifier();
Object idValue = extractIdValue(value, id);
if (idValue != null) writer.addAttribute("id", String.valueOf(idValue));
GrailsDomainClassProperty[] properties = domainClass.getPersistentProperties();
for (int i = 0; i < properties.length; i++) {
GrailsDomainClassProperty property = properties[i];
writer.startNode(property.getName());
if (!property.isAssociation()) {
// Write non-relation property
Object val = beanWrapper.getPropertyValue(property.getName());
if (val == null) {
writer.startNode("null");
writer.endNode();
} else {
context.convertAnother(val);
}
} else {
Object referenceObject = beanWrapper.getPropertyValue(property.getName());
if (isRenderDomainClassRelations()) {
if (referenceObject == null) {
writer.startNode("null");
writer.endNode();
} else {
if (referenceObject instanceof AbstractPersistentCollection) {
// Force initialisation and get a non-persistent Collection Type
AbstractPersistentCollection acol = (AbstractPersistentCollection) referenceObject;
acol.forceInitialization();
if (referenceObject instanceof SortedMap) {
referenceObject = new TreeMap((SortedMap) referenceObject);
} else if (referenceObject instanceof SortedSet) {
referenceObject = new TreeSet((SortedSet) referenceObject);
} else if (referenceObject instanceof Set) {
referenceObject = new HashSet((Set) referenceObject);
} else if (referenceObject instanceof Map) {
referenceObject = new HashMap((Map) referenceObject);
} else {
referenceObject = new ArrayList((Collection) referenceObject);
}
}
context.convertAnother(referenceObject);
}
} else {
if (referenceObject == null) {
writer.startNode("null");
writer.endNode();
} else {
GrailsDomainClass referencedDomainClass = property.getReferencedDomainClass();
GrailsDomainClassProperty referencedIdProperty = referencedDomainClass.getIdentifier();
if (property.isOneToOne() || property.isManyToOne() || property.isEmbedded()) {
// Property contains 1 foreign Domain Object
- writer.startNode(referencedDomainClass.getPropertyName());
writer.addAttribute("id", String.valueOf(extractIdValue(referenceObject, referencedIdProperty)));
- writer.endNode();
} else {
String refPropertyName = referencedDomainClass.getPropertyName();
if (referenceObject instanceof Collection) {
Collection o = (Collection) referenceObject;
for (Iterator it = o.iterator(); it.hasNext();) {
Object el = (Object) it.next();
writer.startNode(refPropertyName);
writer.addAttribute("id", String.valueOf(extractIdValue(el, referencedIdProperty)));
writer.endNode();
}
} else if (referenceObject instanceof Map) {
Map map = (Map) referenceObject;
Iterator iterator = map.keySet().iterator();
while (iterator.hasNext()) {
String key = String.valueOf(iterator.next());
Object o = map.get(key);
writer.startNode("entry");
writer.startNode("string"); // key of map entry has to be a string
writer.setValue(key);
writer.endNode(); // end string
writer.startNode(refPropertyName);
writer.addAttribute("id", String.valueOf(extractIdValue(o, referencedIdProperty)));
writer.endNode(); // end refPropertyName
writer.endNode(); // end entry
}
}
}
}
}
}
writer.endNode();
}
}
public Object unmarshal(HierarchicalStreamReader reader,
UnmarshallingContext context) {
// Under development:
// try {
// Class clazz = context.getRequiredType();
// GrailsDomainClass domainClass = ConverterUtil.getDomainClass(clazz.getName());
// Object o = clazz.newInstance();
// BeanWrapper beanWrapper = new BeanWrapperImpl(o);
// //GroovyObject go = (GroovyObject) clazz.newInstance();
//
// while (reader.hasMoreChildren()) {
// reader.moveDown();
// String propertyName = reader.getNodeName();
// GrailsDomainClassProperty property = domainClass.getPropertyByName(propertyName);
//
// if (property.isAssociation()) {
// // TODO
// } else {
// Object value = context.convertAnother(o, property.getType());
// beanWrapper.setPropertyValue(property.getName(), value);
// }
// reader.moveUp();
// }
//
// return null;
// } catch (Exception e) {
// throw new UnhandledException(e);
// }
return null;
}
public boolean canConvert(Class clazz) {
return ConverterUtil.isDomainClass(clazz);
}
private Object extractIdValue(Object domainObject, GrailsDomainClassProperty idProperty) {
BeanWrapper beanWrapper = new BeanWrapperImpl(domainObject);
return beanWrapper.getPropertyValue(idProperty.getName());
}
}
| false | true | public void marshal(Object value, HierarchicalStreamWriter writer,
MarshallingContext context) {
Class clazz = value.getClass();
GrailsDomainClass domainClass = ConverterUtil.getDomainClass(clazz.getName());
BeanWrapper beanWrapper = new BeanWrapperImpl(value);
GrailsDomainClassProperty id = domainClass.getIdentifier();
Object idValue = extractIdValue(value, id);
if (idValue != null) writer.addAttribute("id", String.valueOf(idValue));
GrailsDomainClassProperty[] properties = domainClass.getPersistentProperties();
for (int i = 0; i < properties.length; i++) {
GrailsDomainClassProperty property = properties[i];
writer.startNode(property.getName());
if (!property.isAssociation()) {
// Write non-relation property
Object val = beanWrapper.getPropertyValue(property.getName());
if (val == null) {
writer.startNode("null");
writer.endNode();
} else {
context.convertAnother(val);
}
} else {
Object referenceObject = beanWrapper.getPropertyValue(property.getName());
if (isRenderDomainClassRelations()) {
if (referenceObject == null) {
writer.startNode("null");
writer.endNode();
} else {
if (referenceObject instanceof AbstractPersistentCollection) {
// Force initialisation and get a non-persistent Collection Type
AbstractPersistentCollection acol = (AbstractPersistentCollection) referenceObject;
acol.forceInitialization();
if (referenceObject instanceof SortedMap) {
referenceObject = new TreeMap((SortedMap) referenceObject);
} else if (referenceObject instanceof SortedSet) {
referenceObject = new TreeSet((SortedSet) referenceObject);
} else if (referenceObject instanceof Set) {
referenceObject = new HashSet((Set) referenceObject);
} else if (referenceObject instanceof Map) {
referenceObject = new HashMap((Map) referenceObject);
} else {
referenceObject = new ArrayList((Collection) referenceObject);
}
}
context.convertAnother(referenceObject);
}
} else {
if (referenceObject == null) {
writer.startNode("null");
writer.endNode();
} else {
GrailsDomainClass referencedDomainClass = property.getReferencedDomainClass();
GrailsDomainClassProperty referencedIdProperty = referencedDomainClass.getIdentifier();
if (property.isOneToOne() || property.isManyToOne() || property.isEmbedded()) {
// Property contains 1 foreign Domain Object
writer.startNode(referencedDomainClass.getPropertyName());
writer.addAttribute("id", String.valueOf(extractIdValue(referenceObject, referencedIdProperty)));
writer.endNode();
} else {
String refPropertyName = referencedDomainClass.getPropertyName();
if (referenceObject instanceof Collection) {
Collection o = (Collection) referenceObject;
for (Iterator it = o.iterator(); it.hasNext();) {
Object el = (Object) it.next();
writer.startNode(refPropertyName);
writer.addAttribute("id", String.valueOf(extractIdValue(el, referencedIdProperty)));
writer.endNode();
}
} else if (referenceObject instanceof Map) {
Map map = (Map) referenceObject;
Iterator iterator = map.keySet().iterator();
while (iterator.hasNext()) {
String key = String.valueOf(iterator.next());
Object o = map.get(key);
writer.startNode("entry");
writer.startNode("string"); // key of map entry has to be a string
writer.setValue(key);
writer.endNode(); // end string
writer.startNode(refPropertyName);
writer.addAttribute("id", String.valueOf(extractIdValue(o, referencedIdProperty)));
writer.endNode(); // end refPropertyName
writer.endNode(); // end entry
}
}
}
}
}
}
writer.endNode();
}
}
| public void marshal(Object value, HierarchicalStreamWriter writer,
MarshallingContext context) {
Class clazz = value.getClass();
GrailsDomainClass domainClass = ConverterUtil.getDomainClass(clazz.getName());
BeanWrapper beanWrapper = new BeanWrapperImpl(value);
GrailsDomainClassProperty id = domainClass.getIdentifier();
Object idValue = extractIdValue(value, id);
if (idValue != null) writer.addAttribute("id", String.valueOf(idValue));
GrailsDomainClassProperty[] properties = domainClass.getPersistentProperties();
for (int i = 0; i < properties.length; i++) {
GrailsDomainClassProperty property = properties[i];
writer.startNode(property.getName());
if (!property.isAssociation()) {
// Write non-relation property
Object val = beanWrapper.getPropertyValue(property.getName());
if (val == null) {
writer.startNode("null");
writer.endNode();
} else {
context.convertAnother(val);
}
} else {
Object referenceObject = beanWrapper.getPropertyValue(property.getName());
if (isRenderDomainClassRelations()) {
if (referenceObject == null) {
writer.startNode("null");
writer.endNode();
} else {
if (referenceObject instanceof AbstractPersistentCollection) {
// Force initialisation and get a non-persistent Collection Type
AbstractPersistentCollection acol = (AbstractPersistentCollection) referenceObject;
acol.forceInitialization();
if (referenceObject instanceof SortedMap) {
referenceObject = new TreeMap((SortedMap) referenceObject);
} else if (referenceObject instanceof SortedSet) {
referenceObject = new TreeSet((SortedSet) referenceObject);
} else if (referenceObject instanceof Set) {
referenceObject = new HashSet((Set) referenceObject);
} else if (referenceObject instanceof Map) {
referenceObject = new HashMap((Map) referenceObject);
} else {
referenceObject = new ArrayList((Collection) referenceObject);
}
}
context.convertAnother(referenceObject);
}
} else {
if (referenceObject == null) {
writer.startNode("null");
writer.endNode();
} else {
GrailsDomainClass referencedDomainClass = property.getReferencedDomainClass();
GrailsDomainClassProperty referencedIdProperty = referencedDomainClass.getIdentifier();
if (property.isOneToOne() || property.isManyToOne() || property.isEmbedded()) {
// Property contains 1 foreign Domain Object
writer.addAttribute("id", String.valueOf(extractIdValue(referenceObject, referencedIdProperty)));
} else {
String refPropertyName = referencedDomainClass.getPropertyName();
if (referenceObject instanceof Collection) {
Collection o = (Collection) referenceObject;
for (Iterator it = o.iterator(); it.hasNext();) {
Object el = (Object) it.next();
writer.startNode(refPropertyName);
writer.addAttribute("id", String.valueOf(extractIdValue(el, referencedIdProperty)));
writer.endNode();
}
} else if (referenceObject instanceof Map) {
Map map = (Map) referenceObject;
Iterator iterator = map.keySet().iterator();
while (iterator.hasNext()) {
String key = String.valueOf(iterator.next());
Object o = map.get(key);
writer.startNode("entry");
writer.startNode("string"); // key of map entry has to be a string
writer.setValue(key);
writer.endNode(); // end string
writer.startNode(refPropertyName);
writer.addAttribute("id", String.valueOf(extractIdValue(o, referencedIdProperty)));
writer.endNode(); // end refPropertyName
writer.endNode(); // end entry
}
}
}
}
}
}
writer.endNode();
}
}
|
diff --git a/galileo_openbook_cleaner/src/de/scrum_master/galileo/OpenbookCleaner.java b/galileo_openbook_cleaner/src/de/scrum_master/galileo/OpenbookCleaner.java
index 3dbb32b..57047ae 100644
--- a/galileo_openbook_cleaner/src/de/scrum_master/galileo/OpenbookCleaner.java
+++ b/galileo_openbook_cleaner/src/de/scrum_master/galileo/OpenbookCleaner.java
@@ -1,222 +1,222 @@
package de.scrum_master.galileo;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.io.PrintStream;
import org.xml.sax.SAXException;
import com.sun.org.apache.xalan.internal.xsltc.cmdline.getopt.GetOpt;
import de.scrum_master.galileo.filter.JTidyFilter;
import de.scrum_master.galileo.filter.PreJTidyFilter;
import de.scrum_master.galileo.filter.XOMUnclutterFilter;
import de.scrum_master.util.SimpleLogger;
public class OpenbookCleaner
{
private static File downloadDir;
private static BookInfo[] books;
private static boolean SINGLE_THREADED_WITH_INTERMEDIATE_FILES = false;
private final static FileFilter HTML_FILES = new FileFilter() {
public boolean accept(File file) {
String fileNameLC = file.getName().toLowerCase();
return fileNameLC.endsWith(".htm") || fileNameLC.endsWith(".html");
}
};
private final static String USAGE_TEXT =
"Usage: java " + OpenbookCleaner.class.getName() + " [-?] | [options] <download_dir> [<book_id>]*\n\n" +
"Options:\n"+
" -? Show this help text\n" +
" -a Download & clean *all* books\n" +
" -v Verbose output\n" +
" -d Debug output (implies -v)\n" +
" -s Single-threaded mode with intermediate files (for diagnostics)\n\n" +
"Parameters:\n"+
" download_dir Download directory for openbook archives (*.zip); must exist\n" +
" book_id Book ID; book will be unpacked to subdirectory <download_dir>/<book_id>.\n" +
" You can specify multiple book IDs separated by spaces.\n" +
" If -a is specified, the book_id list will be ignored.";
private static final String REGEX_TOC_RUBY = ".*ruby_on_rails_2.index.htm";
public static void main(String[] args) throws Exception
{
long startTimeTotal = System.currentTimeMillis();
processArgs(args);
for (BookInfo book : books) {
long startTime = System.currentTimeMillis();
SimpleLogger.echo("\nDownloading, verifying (MD5) and unpacking " + book.unpackDirectory + "...");
new Downloader(downloadDir, book).download();
SimpleLogger.echo("Processing " + book.unpackDirectory + "...");
for (File htmlFile : new File(downloadDir, book.unpackDirectory).listFiles(HTML_FILES))
cleanHTMLFile(htmlFile);
SimpleLogger.time("Duration for " + book.unpackDirectory, System.currentTimeMillis() - startTime);
}
SimpleLogger.time("\nTotal duration", System.currentTimeMillis() - startTimeTotal);
}
private static void processArgs(String[] args)
{
- if (args.length < 2)
+ if (args.length == 0)
displayUsageAndExit(0);
// TODO: GetOpt is poorly documented, hard to use and buggy (getCmdArgs falsely returns options
// if no non-option command-line agrument is given). There are plenty of better free command line
// parsing tools. If it was not for indepencence of yet another external library, I would not use
// JRE's GetOpt.
GetOpt options = new GetOpt(args, "?avds");
try {
int i = options.getNextOption();
while (i != -1) {
SimpleLogger.debug("Option parser: parameter = " + (char) i);
switch ((char) i) {
case '?' :
displayUsageAndExit(0);
break;
case 'a' :
books = BookInfo.values();
break;
case 'v' :
SimpleLogger.VERBOSE = true;
break;
case 'd' :
SimpleLogger.DEBUG = true;
SimpleLogger.VERBOSE = true;
break;
case 's' :
SINGLE_THREADED_WITH_INTERMEDIATE_FILES = true;
break;
}
i = options.getNextOption();
}
- if (options.getCmdArgs().length < 2)
- displayUsageAndExit(0);
+ if (options.getCmdArgs().length < 2 && books == null)
+ displayUsageAndExit(1, "missing argument(s) - please specify download_dir and either book_id or -a");
downloadDir = new File(options.getCmdArgs()[0]);
SimpleLogger.debug("Option parser: download_dir = " + downloadDir);
if (! downloadDir.isDirectory())
displayUsageAndExit(1, "download directory '" + downloadDir + "' not found\n");
if (books != null)
return;
int bookCount = options.getCmdArgs().length - 1;
books = new BookInfo[bookCount];
try {
for (i = 0; i < bookCount; i++)
books[i] = BookInfo.valueOf(options.getCmdArgs()[i + 1].toUpperCase());
}
catch (IllegalArgumentException e) {
displayUsageAndExit(1, "illegal book_id " + e.getMessage().replaceFirst(".*[.]", "").toLowerCase());
}
}
catch (Exception e) {
displayUsageAndExit(1);
}
}
private static void displayUsageAndExit(int exitCode)
{
displayUsageAndExit(exitCode, null);
}
private static void displayUsageAndExit(int exitCode, String errorMessage)
{
PrintStream out = (exitCode == 0) ? System.out : System.err;
out.println(
USAGE_TEXT + "\n\n" +
"List of legal book_id values (case-insensitive):"
);
for (BookInfo md : BookInfo.values())
out.println(" " + md.name().toLowerCase());
if (exitCode != 0 && errorMessage != null)
out.println("\nError: " + errorMessage);
System.exit(exitCode);
}
private static void cleanHTMLFile(File origFile) throws Exception
{
File backupFile = new File(origFile + ".bak");
SimpleLogger.verbose(" " + origFile.getName());
// Backups are useful if we want to re-run the application later
createBackupIfNotExists(origFile, backupFile);
doConversion(origFile, new FileInputStream(backupFile), new FileOutputStream(origFile));
}
private static void createBackupIfNotExists(File origFile, File backupFile)
throws IOException
{
if (!backupFile.exists())
origFile.renameTo(backupFile);
}
private static void doConversion(File origFile, InputStream rawInput, OutputStream finalOutput)
throws FileNotFoundException, SAXException, IOException
{
// Conversion steps for both modes (single-/multi-threaded):
// 1. Clean up raw HTML where necessary to make it parseable by JTidy
// 2. Convert raw HTML into valid XHTML using JTidy
// 3. Remove clutter (header, footer, navigation, ads) using XOM
// 4. Pretty-print XOM output again using JTidy (optional)
final boolean needsPreJTidy = origFile.getAbsolutePath().matches(REGEX_TOC_RUBY) ? true : false;
if (SINGLE_THREADED_WITH_INTERMEDIATE_FILES) {
// Single-threaded mode is slower (~40%), but good for diagnostic purposes:
// - It creates files for each intermediate processing step.
// - Log output is in (chrono)logical order.
// Set up intermediate files
File preJTidyFile = new File(origFile + ".pretidy");
File jTidyFile = new File(origFile + ".tidy");
File xomFile = new File(origFile + ".xom");
// Run conversion steps, using output of step (n) as input of step (n+1)
if (needsPreJTidy) {
new PreJTidyFilter(rawInput, new FileOutputStream(preJTidyFile), origFile).run();
new JTidyFilter(new FileInputStream(preJTidyFile), new FileOutputStream(jTidyFile), origFile).run();
}
else {
new JTidyFilter(rawInput, new FileOutputStream(jTidyFile), origFile).run();
}
new XOMUnclutterFilter(new FileInputStream(jTidyFile), new FileOutputStream(xomFile), origFile).run();
new JTidyFilter(new FileInputStream(xomFile), finalOutput, origFile).run();
}
else {
// Multi-threaded mode is faster, but not so good for diagnostic purposes:
// - There are no files for intermediate processing steps.
// - Log output is garbled because of multi-threading.
// Set up pipes
PipedOutputStream preJTidyOutput = new PipedOutputStream();
PipedInputStream preJTidyInput = new PipedInputStream(preJTidyOutput);
PipedOutputStream jTidyOutput = new PipedOutputStream();
PipedInputStream jTidyInput = new PipedInputStream(jTidyOutput);
PipedOutputStream unclutteredOutput = new PipedOutputStream();
PipedInputStream unclutteredInput = new PipedInputStream(unclutteredOutput);
// Run threads, piping output of thread (n) into input of thread (n+1)
if (needsPreJTidy) {
new Thread(new PreJTidyFilter(rawInput, preJTidyOutput, origFile)).start();
new Thread(new JTidyFilter(preJTidyInput, jTidyOutput, origFile)).start();
}
else {
new Thread(new JTidyFilter(rawInput, jTidyOutput, origFile)).start();
}
new Thread (new XOMUnclutterFilter(jTidyInput, unclutteredOutput, origFile)).start();
new Thread (new JTidyFilter(unclutteredInput, finalOutput, origFile)).start();
}
}
}
| false | true | private static void processArgs(String[] args)
{
if (args.length < 2)
displayUsageAndExit(0);
// TODO: GetOpt is poorly documented, hard to use and buggy (getCmdArgs falsely returns options
// if no non-option command-line agrument is given). There are plenty of better free command line
// parsing tools. If it was not for indepencence of yet another external library, I would not use
// JRE's GetOpt.
GetOpt options = new GetOpt(args, "?avds");
try {
int i = options.getNextOption();
while (i != -1) {
SimpleLogger.debug("Option parser: parameter = " + (char) i);
switch ((char) i) {
case '?' :
displayUsageAndExit(0);
break;
case 'a' :
books = BookInfo.values();
break;
case 'v' :
SimpleLogger.VERBOSE = true;
break;
case 'd' :
SimpleLogger.DEBUG = true;
SimpleLogger.VERBOSE = true;
break;
case 's' :
SINGLE_THREADED_WITH_INTERMEDIATE_FILES = true;
break;
}
i = options.getNextOption();
}
if (options.getCmdArgs().length < 2)
displayUsageAndExit(0);
downloadDir = new File(options.getCmdArgs()[0]);
SimpleLogger.debug("Option parser: download_dir = " + downloadDir);
if (! downloadDir.isDirectory())
displayUsageAndExit(1, "download directory '" + downloadDir + "' not found\n");
if (books != null)
return;
int bookCount = options.getCmdArgs().length - 1;
books = new BookInfo[bookCount];
try {
for (i = 0; i < bookCount; i++)
books[i] = BookInfo.valueOf(options.getCmdArgs()[i + 1].toUpperCase());
}
catch (IllegalArgumentException e) {
displayUsageAndExit(1, "illegal book_id " + e.getMessage().replaceFirst(".*[.]", "").toLowerCase());
}
}
catch (Exception e) {
displayUsageAndExit(1);
}
}
| private static void processArgs(String[] args)
{
if (args.length == 0)
displayUsageAndExit(0);
// TODO: GetOpt is poorly documented, hard to use and buggy (getCmdArgs falsely returns options
// if no non-option command-line agrument is given). There are plenty of better free command line
// parsing tools. If it was not for indepencence of yet another external library, I would not use
// JRE's GetOpt.
GetOpt options = new GetOpt(args, "?avds");
try {
int i = options.getNextOption();
while (i != -1) {
SimpleLogger.debug("Option parser: parameter = " + (char) i);
switch ((char) i) {
case '?' :
displayUsageAndExit(0);
break;
case 'a' :
books = BookInfo.values();
break;
case 'v' :
SimpleLogger.VERBOSE = true;
break;
case 'd' :
SimpleLogger.DEBUG = true;
SimpleLogger.VERBOSE = true;
break;
case 's' :
SINGLE_THREADED_WITH_INTERMEDIATE_FILES = true;
break;
}
i = options.getNextOption();
}
if (options.getCmdArgs().length < 2 && books == null)
displayUsageAndExit(1, "missing argument(s) - please specify download_dir and either book_id or -a");
downloadDir = new File(options.getCmdArgs()[0]);
SimpleLogger.debug("Option parser: download_dir = " + downloadDir);
if (! downloadDir.isDirectory())
displayUsageAndExit(1, "download directory '" + downloadDir + "' not found\n");
if (books != null)
return;
int bookCount = options.getCmdArgs().length - 1;
books = new BookInfo[bookCount];
try {
for (i = 0; i < bookCount; i++)
books[i] = BookInfo.valueOf(options.getCmdArgs()[i + 1].toUpperCase());
}
catch (IllegalArgumentException e) {
displayUsageAndExit(1, "illegal book_id " + e.getMessage().replaceFirst(".*[.]", "").toLowerCase());
}
}
catch (Exception e) {
displayUsageAndExit(1);
}
}
|
diff --git a/eol-globi-data-tool/src/main/java/org/eol/globi/service/TaxonPropertyEnricherFactory.java b/eol-globi-data-tool/src/main/java/org/eol/globi/service/TaxonPropertyEnricherFactory.java
index 2726355d..624d64e9 100644
--- a/eol-globi-data-tool/src/main/java/org/eol/globi/service/TaxonPropertyEnricherFactory.java
+++ b/eol-globi-data-tool/src/main/java/org/eol/globi/service/TaxonPropertyEnricherFactory.java
@@ -1,25 +1,25 @@
package org.eol.globi.service;
import org.neo4j.graphdb.GraphDatabaseService;
import java.util.ArrayList;
import java.util.List;
public class TaxonPropertyEnricherFactory {
public static TaxonPropertyEnricher createTaxonEnricher(GraphDatabaseService graphService) {
TaxonPropertyEnricherImpl taxonEnricher = new TaxonPropertyEnricherImpl(graphService);
List<TaxonPropertyLookupService> services = new ArrayList<TaxonPropertyLookupService>() {
{
- //add(new EOLOfflineService());
+ add(new EOLOfflineService());
add(new EOLService());
add(new WoRMSService());
add(new ITISService());
add(new GulfBaseService());
add(new NoMatchService());
}
};
taxonEnricher.setServices(services);
return taxonEnricher;
}
}
| true | true | public static TaxonPropertyEnricher createTaxonEnricher(GraphDatabaseService graphService) {
TaxonPropertyEnricherImpl taxonEnricher = new TaxonPropertyEnricherImpl(graphService);
List<TaxonPropertyLookupService> services = new ArrayList<TaxonPropertyLookupService>() {
{
//add(new EOLOfflineService());
add(new EOLService());
add(new WoRMSService());
add(new ITISService());
add(new GulfBaseService());
add(new NoMatchService());
}
};
taxonEnricher.setServices(services);
return taxonEnricher;
}
| public static TaxonPropertyEnricher createTaxonEnricher(GraphDatabaseService graphService) {
TaxonPropertyEnricherImpl taxonEnricher = new TaxonPropertyEnricherImpl(graphService);
List<TaxonPropertyLookupService> services = new ArrayList<TaxonPropertyLookupService>() {
{
add(new EOLOfflineService());
add(new EOLService());
add(new WoRMSService());
add(new ITISService());
add(new GulfBaseService());
add(new NoMatchService());
}
};
taxonEnricher.setServices(services);
return taxonEnricher;
}
|
diff --git a/ghana-national-core/src/test/java/org/motechproject/ghana/national/configuration/GhanaNationalCareSchedulesTest.java b/ghana-national-core/src/test/java/org/motechproject/ghana/national/configuration/GhanaNationalCareSchedulesTest.java
index b92f070b..7a35381b 100644
--- a/ghana-national-core/src/test/java/org/motechproject/ghana/national/configuration/GhanaNationalCareSchedulesTest.java
+++ b/ghana-national-core/src/test/java/org/motechproject/ghana/national/configuration/GhanaNationalCareSchedulesTest.java
@@ -1,64 +1,64 @@
package org.motechproject.ghana.national.configuration;
import org.joda.time.LocalDate;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.motechproject.model.RepeatingSchedulableJob;
import org.motechproject.model.Time;
import org.motechproject.scheduler.MotechSchedulerService;
import org.motechproject.scheduletracking.api.repository.AllEnrollments;
import org.motechproject.scheduletracking.api.repository.AllTrackedSchedules;
import org.motechproject.scheduletracking.api.service.EnrollmentRequest;
import org.motechproject.scheduletracking.api.service.EnrollmentService;
import org.motechproject.scheduletracking.api.service.ScheduleTrackingServiceImpl;
import org.motechproject.testing.utils.BaseUnitTest;
import org.motechproject.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.List;
import static junit.framework.Assert.assertEquals;
import static org.mockito.Mockito.*;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:/testApplicationContext-core.xml"})
public class GhanaNationalCareSchedulesTest extends BaseUnitTest {
@Autowired
AllTrackedSchedules allTrackedSchedules;
private Time preferredAlertTime;
@Before
public void setUp() {
preferredAlertTime = new Time(10, 10);
}
@Test
public void verifyPregnancySchedule() {
LocalDate today = DateUtil.newDate(2000, 1, 1);
mockCurrentDate(today);
LocalDate conceptionDate = today.minusWeeks(1);
AllEnrollments allEnrollments = mock(AllEnrollments.class);
MotechSchedulerService motechSchedulerService = mock(MotechSchedulerService.class);
- EnrollmentService enrollmentService = new EnrollmentService(allTrackedSchedules, motechSchedulerService);
+ EnrollmentService enrollmentService = new EnrollmentService(allTrackedSchedules, allEnrollments, null, null);
ScheduleTrackingServiceImpl scheduleTrackingService = new ScheduleTrackingServiceImpl(allTrackedSchedules, allEnrollments, enrollmentService);
EnrollmentRequest enrollmentRequest = new EnrollmentRequest("123", CareScheduleNames.DELIVERY, preferredAlertTime, conceptionDate);
scheduleTrackingService.enroll(enrollmentRequest);
ArgumentCaptor<RepeatingSchedulableJob> repeatingSchedulableJobArgumentCaptor = ArgumentCaptor.forClass(RepeatingSchedulableJob.class);
int numberOfScheduledJobs = 2;
verify(motechSchedulerService, times(numberOfScheduledJobs)).safeScheduleRepeatingJob(repeatingSchedulableJobArgumentCaptor.capture());
List<RepeatingSchedulableJob> schedulableJobs = repeatingSchedulableJobArgumentCaptor.getAllValues();
assertEquals(numberOfScheduledJobs, schedulableJobs.size());
assertEquals(DateUtil.newDate(schedulableJobs.get(0).getStartTime()), onDate(conceptionDate, 39));
assertEquals(DateUtil.newDate(schedulableJobs.get(1).getStartTime()), onDate(conceptionDate, 40));
}
private LocalDate onDate(LocalDate conceptionDate, int numberOfWeeks) {
return conceptionDate.plusWeeks(numberOfWeeks);
}
}
| true | true | public void verifyPregnancySchedule() {
LocalDate today = DateUtil.newDate(2000, 1, 1);
mockCurrentDate(today);
LocalDate conceptionDate = today.minusWeeks(1);
AllEnrollments allEnrollments = mock(AllEnrollments.class);
MotechSchedulerService motechSchedulerService = mock(MotechSchedulerService.class);
EnrollmentService enrollmentService = new EnrollmentService(allTrackedSchedules, motechSchedulerService);
ScheduleTrackingServiceImpl scheduleTrackingService = new ScheduleTrackingServiceImpl(allTrackedSchedules, allEnrollments, enrollmentService);
EnrollmentRequest enrollmentRequest = new EnrollmentRequest("123", CareScheduleNames.DELIVERY, preferredAlertTime, conceptionDate);
scheduleTrackingService.enroll(enrollmentRequest);
ArgumentCaptor<RepeatingSchedulableJob> repeatingSchedulableJobArgumentCaptor = ArgumentCaptor.forClass(RepeatingSchedulableJob.class);
int numberOfScheduledJobs = 2;
verify(motechSchedulerService, times(numberOfScheduledJobs)).safeScheduleRepeatingJob(repeatingSchedulableJobArgumentCaptor.capture());
List<RepeatingSchedulableJob> schedulableJobs = repeatingSchedulableJobArgumentCaptor.getAllValues();
assertEquals(numberOfScheduledJobs, schedulableJobs.size());
assertEquals(DateUtil.newDate(schedulableJobs.get(0).getStartTime()), onDate(conceptionDate, 39));
assertEquals(DateUtil.newDate(schedulableJobs.get(1).getStartTime()), onDate(conceptionDate, 40));
}
| public void verifyPregnancySchedule() {
LocalDate today = DateUtil.newDate(2000, 1, 1);
mockCurrentDate(today);
LocalDate conceptionDate = today.minusWeeks(1);
AllEnrollments allEnrollments = mock(AllEnrollments.class);
MotechSchedulerService motechSchedulerService = mock(MotechSchedulerService.class);
EnrollmentService enrollmentService = new EnrollmentService(allTrackedSchedules, allEnrollments, null, null);
ScheduleTrackingServiceImpl scheduleTrackingService = new ScheduleTrackingServiceImpl(allTrackedSchedules, allEnrollments, enrollmentService);
EnrollmentRequest enrollmentRequest = new EnrollmentRequest("123", CareScheduleNames.DELIVERY, preferredAlertTime, conceptionDate);
scheduleTrackingService.enroll(enrollmentRequest);
ArgumentCaptor<RepeatingSchedulableJob> repeatingSchedulableJobArgumentCaptor = ArgumentCaptor.forClass(RepeatingSchedulableJob.class);
int numberOfScheduledJobs = 2;
verify(motechSchedulerService, times(numberOfScheduledJobs)).safeScheduleRepeatingJob(repeatingSchedulableJobArgumentCaptor.capture());
List<RepeatingSchedulableJob> schedulableJobs = repeatingSchedulableJobArgumentCaptor.getAllValues();
assertEquals(numberOfScheduledJobs, schedulableJobs.size());
assertEquals(DateUtil.newDate(schedulableJobs.get(0).getStartTime()), onDate(conceptionDate, 39));
assertEquals(DateUtil.newDate(schedulableJobs.get(1).getStartTime()), onDate(conceptionDate, 40));
}
|
diff --git a/org.cloudsmith.geppetto.pp.dsl/src/org/cloudsmith/xtext/serializer/acceptor/HiddenTokenSequencer.java b/org.cloudsmith.geppetto.pp.dsl/src/org/cloudsmith/xtext/serializer/acceptor/HiddenTokenSequencer.java
index 156863b0..eb258741 100644
--- a/org.cloudsmith.geppetto.pp.dsl/src/org/cloudsmith/xtext/serializer/acceptor/HiddenTokenSequencer.java
+++ b/org.cloudsmith.geppetto.pp.dsl/src/org/cloudsmith/xtext/serializer/acceptor/HiddenTokenSequencer.java
@@ -1,434 +1,435 @@
/**
* Copyright (c) 2011, 2012 Cloudsmith Inc. and other contributors, as listed below.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* itemis AG (http://www.itemis.eu) - initial API and implementation
* Cloudsmith - adaption to DomModel and Contextual formatter
*
*/
package org.cloudsmith.xtext.serializer.acceptor;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import org.cloudsmith.xtext.dommodel.IDomNode;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.xtext.AbstractRule;
import org.eclipse.xtext.Action;
import org.eclipse.xtext.CrossReference;
import org.eclipse.xtext.Grammar;
import org.eclipse.xtext.GrammarUtil;
import org.eclipse.xtext.Keyword;
import org.eclipse.xtext.ParserRule;
import org.eclipse.xtext.RuleCall;
import org.eclipse.xtext.nodemodel.BidiTreeIterator;
import org.eclipse.xtext.nodemodel.ICompositeNode;
import org.eclipse.xtext.nodemodel.ILeafNode;
import org.eclipse.xtext.nodemodel.INode;
import org.eclipse.xtext.nodemodel.util.NodeModelUtils;
import org.eclipse.xtext.parsetree.reconstr.IHiddenTokenHelper;
import org.eclipse.xtext.parsetree.reconstr.impl.NodeIterator;
import org.eclipse.xtext.parsetree.reconstr.impl.TokenUtil;
import org.eclipse.xtext.serializer.acceptor.ISequenceAcceptor;
import org.eclipse.xtext.serializer.acceptor.ISyntacticSequenceAcceptor;
import org.eclipse.xtext.serializer.diagnostic.ISerializationDiagnostic.Acceptor;
import org.eclipse.xtext.serializer.sequencer.IHiddenTokenSequencer;
import org.eclipse.xtext.serializer.sequencer.ISyntacticSequencer;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.google.inject.Inject;
/**
* This is an adapted version of HiddenTokenSequencer that emits implicit white space where it is allowed.
* Implicit WS is emitted also when an INode model is not present.
*
*/
public class HiddenTokenSequencer implements IHiddenTokenSequencer, ISyntacticSequenceAcceptor {
@Inject
protected IHiddenTokenHelper hiddenTokenHelper;
@Inject
protected TokenUtil tokenUtil;
protected ISequenceAcceptor delegate;
protected INode lastNode;
protected INode rootNode;
protected ISyntacticSequencer sequencer;
/**
* List of 'tokens' that are currently hidden.
*/
protected List<AbstractRule> currentHidden;
/**
* Stack tracking the state of 'hidden tokens'
*/
protected List<List<AbstractRule>> hiddenStack = Lists.newArrayList();
protected List<RuleCall> stack = Lists.newArrayList();
/**
* When searching for hidden nodes between INodes 'from' and 'to', the {@link #hiddenInLastNode} describes
* the state of 'hidden' when 'from' was sequenced, and {@link #currentHidden} when 'to' is sequenced.
*/
protected List<AbstractRule> hiddenInLastNode;
@Override
public void acceptAssignedCrossRefDatatype(RuleCall rc, String tkn, EObject val, int index, ICompositeNode node) {
emitHiddenTokens(getHiddenNodesBetween(lastNode, node));
rememberNode(node);
delegate.acceptAssignedCrossRefDatatype(rc, tkn, val, index, node);
}
@Override
public void acceptAssignedCrossRefEnum(RuleCall rc, String token, EObject value, int index, ICompositeNode node) {
emitHiddenTokens(getHiddenNodesBetween(lastNode, node));
rememberLastLeaf(node);
delegate.acceptAssignedCrossRefEnum(rc, token, value, index, node);
}
@Override
public void acceptAssignedCrossRefKeyword(Keyword kw, String token, EObject value, int index, ILeafNode node) {
emitHiddenTokens(getHiddenNodesBetween(lastNode, node));
rememberLastLeaf(node);
delegate.acceptAssignedCrossRefKeyword(kw, token, value, index, node);
}
@Override
public void acceptAssignedCrossRefTerminal(RuleCall rc, String token, EObject value, int index, ILeafNode node) {
emitHiddenTokens(getHiddenNodesBetween(lastNode, node));
rememberNode(node);
delegate.acceptAssignedCrossRefTerminal(rc, token, value, index, node);
}
@Override
public void acceptAssignedDatatype(RuleCall rc, String token, Object value, int index, ICompositeNode node) {
emitHiddenTokens(getHiddenNodesBetween(lastNode, node));
rememberLastLeaf(node);
delegate.acceptAssignedDatatype(rc, token, value, index, node);
}
@Override
public void acceptAssignedEnum(RuleCall enumRC, String token, Object value, int index, ICompositeNode node) {
emitHiddenTokens(getHiddenNodesBetween(lastNode, node));
rememberLastLeaf(node);
delegate.acceptAssignedEnum(enumRC, token, value, index, node);
}
@Override
public void acceptAssignedKeyword(Keyword keyword, String token, Object value, int index, ILeafNode node) {
emitHiddenTokens(getHiddenNodesBetween(lastNode, node));
rememberNode(node);
delegate.acceptAssignedKeyword(keyword, token, value, index, node);
}
@Override
public void acceptAssignedTerminal(RuleCall terminalRC, String token, Object value, int index, ILeafNode node) {
emitHiddenTokens(getHiddenNodesBetween(lastNode, node));
rememberNode(node);
delegate.acceptAssignedTerminal(terminalRC, token, value, index, node);
}
@Override
public void acceptUnassignedAction(Action action) {
delegate.acceptUnassignedAction(action);
}
@Override
public void acceptUnassignedDatatype(RuleCall datatypeRC, String token, ICompositeNode node) {
emitHiddenTokens(getHiddenNodesBetween(lastNode, node));
rememberLastLeaf(node);
delegate.acceptUnassignedDatatype(datatypeRC, token, node);
}
@Override
public void acceptUnassignedEnum(RuleCall enumRC, String token, ICompositeNode node) {
emitHiddenTokens(getHiddenNodesBetween(lastNode, node));
rememberLastLeaf(node);
delegate.acceptUnassignedEnum(enumRC, token, node);
}
@Override
public void acceptUnassignedKeyword(Keyword keyword, String token, ILeafNode node) {
emitHiddenTokens(getHiddenNodesBetween(lastNode, node));
rememberNode(node);
delegate.acceptUnassignedKeyword(keyword, token, node);
}
@Override
public void acceptUnassignedTerminal(RuleCall terminalRC, String token, ILeafNode node) {
emitHiddenTokens(getHiddenNodesBetween(lastNode, node));
rememberNode(node);
delegate.acceptUnassignedTerminal(terminalRC, token, node);
}
protected void emitHiddenTokens(List<INode> hiddens /* Set<INode> comments, */) {
if(hiddens == null)
return;
boolean lastNonWhitespace = true;
AbstractRule ws = hiddenTokenHelper.getWhitespaceRuleFor(null, "");
for(INode node : hiddens)
if(tokenUtil.isCommentNode(node)) {
if(lastNonWhitespace)
delegate.acceptWhitespace(hiddenTokenHelper.getWhitespaceRuleFor(null, ""), "", null);
lastNonWhitespace = true;
// comments.remove(node);
delegate.acceptComment((AbstractRule) node.getGrammarElement(), node.getText(), (ILeafNode) node);
}
else {
delegate.acceptWhitespace((AbstractRule) node.getGrammarElement(), node.getText(), (ILeafNode) node);
lastNonWhitespace = false;
}
// NOTE: The original implementation has a FIX-ME note here that whitespace should be determined
// correctly. (Well, it did not work until a check was added if the ws was hidden or not).
// Longer explanation:
// When there is no WS between two elements and no node model the contextual serializer/formatter
// performs serialization by inserting an IMPLICIT WS.
// When the node model is created, empty ws nodes are skipped, and thus have to be created (this happens
// here). The created whitespace node should *NOT* be marked as implicit, since it by virtue of having been
// parsed is now the source text and should not be subject to formatting (like the IMPLICIT WS always is)
// when in "preserve whitespace" mode.
// Finally, what the fix below does is to also check if a missing WS should be emitted based on
// if whitespace is visible or not.
// THIS IS PROBABLY STILL NOT ENOUGH, as it may overrule the attempt to treat visible WS as eligible for formatting
// see isImpliedWhitespace and where it is called.
// if(lastNonWhitespace && currentHidden.contains(ws)) {
- if(lastNonWhitespace && hiddenInLastNode.contains(ws)) {
+ if(lastNonWhitespace && (hiddenInLastNode.contains(ws) || currentHidden.contains(ws))) {
+ // hiddenInLastNode.contains(ws)) {
delegate.acceptWhitespace(ws, "", null);
}
}
public boolean enterAssignedAction(Action action, EObject semanticChild, ICompositeNode node) {
return delegate.enterAssignedAction(action, semanticChild, node);
}
public boolean enterAssignedParserRuleCall(RuleCall rc, EObject semanticChild, ICompositeNode node) {
push(rc);
return delegate.enterAssignedParserRuleCall(rc, semanticChild, node);
}
public void enterUnassignedParserRuleCall(RuleCall rc) {
push(rc);
delegate.enterUnassignedParserRuleCall(rc);
}
public void finish() {
if(rootNode != null && rootNode == rootNode.getRootNode()) {
List<INode> hidden = getRemainingHiddenNodesInContainer(lastNode, rootNode);
if(!hidden.isEmpty()) {
emitHiddenTokens(hidden);
lastNode = rootNode;
}
}
delegate.finish();
}
protected Set<INode> getCommentsForEObject(EObject semanticObject, INode node) {
if(node == null)
return Collections.emptySet();
Set<INode> result = Sets.newHashSet();
BidiTreeIterator<INode> ti = node.getAsTreeIterable().iterator();
while(ti.hasNext()) {
INode next = ti.next();
if(next.getSemanticElement() != null && next.getSemanticElement() != semanticObject) {
ti.prune();
continue;
}
if(tokenUtil.isCommentNode(next))
result.add(next);
}
return result;
}
protected List<INode> getHiddenNodesBetween(INode from, INode to) {
List<INode> result = getHiddenNodesBetween2(from, to);
if(result == null) {
AbstractRule ws = hiddenTokenHelper.getWhitespaceRuleFor(null, "");
// only emit hidden whitespace, or visible whitespace where this is overridden using
// isImpliedWhitespace
// boolean implied = currentHidden != null && currentHidden.contains(ws);
boolean impliedFrom = hiddenInLastNode != null && hiddenInLastNode.contains(ws);
boolean impliedTo = currentHidden != null && currentHidden.contains(ws);
boolean implied = impliedFrom || impliedTo;
int sz = stack.size();
implied = isImpliedWhitespace(implied, sz == 0
? null
: stack.get(sz - 1), from, to);
if(implied) {
delegate.acceptWhitespace(ws, IDomNode.IMPLIED_EMPTY_WHITESPACE, null);
}
}
return result;
}
protected List<INode> getHiddenNodesBetween2(INode from, INode to) {
if(from == null || to == null)
return null;
List<INode> out = Lists.newArrayList();
NodeIterator ni = new NodeIterator(from);
while(ni.hasNext()) {
INode next = ni.next();
if(tokenUtil.isWhitespaceOrCommentNode(next)) {
out.add(next);
}
else if(next.equals(to)) {
if(next instanceof ICompositeNode &&
(GrammarUtil.isDatatypeRuleCall(next.getGrammarElement()) ||
GrammarUtil.isEnumRuleCall(next.getGrammarElement()) || next.getGrammarElement() instanceof CrossReference))
while(ni.hasNext()) {
INode next2 = ni.next();
if(tokenUtil.isWhitespaceOrCommentNode(next2)) {
out.add(next2);
}
else if(next2 instanceof ILeafNode)
return out;
}
else
return out;
}
else if(tokenUtil.isToken(next))
return null;
}
return out;
}
private INode getLastLeaf(INode node) {
while(node instanceof ICompositeNode)
node = ((ICompositeNode) node).getLastChild();
return node;
}
protected List<INode> getRemainingHiddenNodesInContainer(INode from, INode root) {
if(from == null || root == null)
return Collections.emptyList();
List<INode> out = Lists.newArrayList();
NodeIterator ni = new NodeIterator(from);
while(ni.hasNext()) {
INode next = ni.next();
if(next.getTotalOffset() > root.getTotalEndOffset())
return out;
else if(tokenUtil.isWhitespaceOrCommentNode(next)) {
out.add(next);
}
else if(tokenUtil.isToken(next))
return Collections.emptyList();
}
return out;
}
public void init(EObject context, EObject semanticObject, ISequenceAcceptor sequenceAcceptor, Acceptor errorAcceptor) {
this.delegate = sequenceAcceptor;
this.lastNode = NodeModelUtils.findActualNodeFor(semanticObject);
this.rootNode = lastNode;
initCurrentHidden(context);
}
protected void initCurrentHidden(EObject context) {
// when called for a specific parser rule, its hidden() spec (if any) is made current
// otherwise the hidden() spec of the grammar is made current.
// (There is no real way to calculate the calling chain to a particular starting parser rule)
//
if(context instanceof ParserRule) {
ParserRule pr = (ParserRule) context;
if(pr.isDefinesHiddenTokens())
currentHidden = pr.getHiddenTokens();
else {
Grammar grammar = GrammarUtil.getGrammar(context);
currentHidden = grammar.getHiddenTokens();
}
// TODO: Verify this is correct
hiddenInLastNode = currentHidden;
}
}
/**
* This method should be overridden in an implementation where certain visible whitespace
* rules should be subject to formatting.
*
* @param defaultResult
* - the result to return if the already made decision is ok
* @param rc
* - the {@link RuleCall} (or {@link Grammar}) in the call chain that determined what is hidden
* @param from
* - the node left of where the ws appears, or null if there is no node model
* @param to
* - the node right if where the ws appears, or null if there is no node model
* @return true if this WS should be eligible for formatting
*/
protected boolean isImpliedWhitespace(boolean defaultResult, EObject rc, INode from, INode to) {
return defaultResult;
}
public void leaveAssignedAction(Action action, EObject semanticChild) {
delegate.leaveAssignedAction(action, semanticChild);
}
public void leaveAssignedParserRuleCall(RuleCall rc, EObject semanticChild) {
delegate.leaveAssignedParserRuleCall(rc, semanticChild);
pop();
}
public void leaveUnssignedParserRuleCall(RuleCall rc) {
delegate.leaveUnssignedParserRuleCall(rc);
pop();
}
protected void pop() {
RuleCall top = stack.remove(stack.size() - 1);
// if the rule call on top defines hidden, it pushed on the hidden stack, and state needs to
// be restored
final AbstractRule r = top.getRule();
if(r instanceof ParserRule && ((ParserRule) r).isDefinesHiddenTokens()) {
currentHidden = hiddenStack.remove(hiddenStack.size() - 1);
}
}
protected void push(RuleCall rc) {
stack.add(rc);
// if rule defines hidden, remember previous hidden, and set the new as current
final AbstractRule r = rc.getRule();
if(r instanceof ParserRule && ((ParserRule) r).isDefinesHiddenTokens()) {
hiddenStack.add(currentHidden);
currentHidden = ((ParserRule) r).getHiddenTokens();
}
}
/**
* Remembers the last leaf of given node unless it is null.
*
* @param nodeToRemember
*/
private void rememberLastLeaf(INode node) {
if(node == null)
return;
lastNode = getLastLeaf(node);
hiddenInLastNode = currentHidden;
}
/**
* Remembers the given node unless it is null.
*
* @param nodeToRemember
*/
private void rememberNode(INode nodeToRemember) {
if(nodeToRemember == null)
return;
lastNode = nodeToRemember;
hiddenInLastNode = currentHidden;
}
}
| true | true | protected void emitHiddenTokens(List<INode> hiddens /* Set<INode> comments, */) {
if(hiddens == null)
return;
boolean lastNonWhitespace = true;
AbstractRule ws = hiddenTokenHelper.getWhitespaceRuleFor(null, "");
for(INode node : hiddens)
if(tokenUtil.isCommentNode(node)) {
if(lastNonWhitespace)
delegate.acceptWhitespace(hiddenTokenHelper.getWhitespaceRuleFor(null, ""), "", null);
lastNonWhitespace = true;
// comments.remove(node);
delegate.acceptComment((AbstractRule) node.getGrammarElement(), node.getText(), (ILeafNode) node);
}
else {
delegate.acceptWhitespace((AbstractRule) node.getGrammarElement(), node.getText(), (ILeafNode) node);
lastNonWhitespace = false;
}
// NOTE: The original implementation has a FIX-ME note here that whitespace should be determined
// correctly. (Well, it did not work until a check was added if the ws was hidden or not).
// Longer explanation:
// When there is no WS between two elements and no node model the contextual serializer/formatter
// performs serialization by inserting an IMPLICIT WS.
// When the node model is created, empty ws nodes are skipped, and thus have to be created (this happens
// here). The created whitespace node should *NOT* be marked as implicit, since it by virtue of having been
// parsed is now the source text and should not be subject to formatting (like the IMPLICIT WS always is)
// when in "preserve whitespace" mode.
// Finally, what the fix below does is to also check if a missing WS should be emitted based on
// if whitespace is visible or not.
// THIS IS PROBABLY STILL NOT ENOUGH, as it may overrule the attempt to treat visible WS as eligible for formatting
// see isImpliedWhitespace and where it is called.
// if(lastNonWhitespace && currentHidden.contains(ws)) {
if(lastNonWhitespace && hiddenInLastNode.contains(ws)) {
delegate.acceptWhitespace(ws, "", null);
}
}
| protected void emitHiddenTokens(List<INode> hiddens /* Set<INode> comments, */) {
if(hiddens == null)
return;
boolean lastNonWhitespace = true;
AbstractRule ws = hiddenTokenHelper.getWhitespaceRuleFor(null, "");
for(INode node : hiddens)
if(tokenUtil.isCommentNode(node)) {
if(lastNonWhitespace)
delegate.acceptWhitespace(hiddenTokenHelper.getWhitespaceRuleFor(null, ""), "", null);
lastNonWhitespace = true;
// comments.remove(node);
delegate.acceptComment((AbstractRule) node.getGrammarElement(), node.getText(), (ILeafNode) node);
}
else {
delegate.acceptWhitespace((AbstractRule) node.getGrammarElement(), node.getText(), (ILeafNode) node);
lastNonWhitespace = false;
}
// NOTE: The original implementation has a FIX-ME note here that whitespace should be determined
// correctly. (Well, it did not work until a check was added if the ws was hidden or not).
// Longer explanation:
// When there is no WS between two elements and no node model the contextual serializer/formatter
// performs serialization by inserting an IMPLICIT WS.
// When the node model is created, empty ws nodes are skipped, and thus have to be created (this happens
// here). The created whitespace node should *NOT* be marked as implicit, since it by virtue of having been
// parsed is now the source text and should not be subject to formatting (like the IMPLICIT WS always is)
// when in "preserve whitespace" mode.
// Finally, what the fix below does is to also check if a missing WS should be emitted based on
// if whitespace is visible or not.
// THIS IS PROBABLY STILL NOT ENOUGH, as it may overrule the attempt to treat visible WS as eligible for formatting
// see isImpliedWhitespace and where it is called.
// if(lastNonWhitespace && currentHidden.contains(ws)) {
if(lastNonWhitespace && (hiddenInLastNode.contains(ws) || currentHidden.contains(ws))) {
// hiddenInLastNode.contains(ws)) {
delegate.acceptWhitespace(ws, "", null);
}
}
|
diff --git a/core/cc.warlock.rcp/src/cc/warlock/rcp/application/WarlockPerspectiveFactory.java b/core/cc.warlock.rcp/src/cc/warlock/rcp/application/WarlockPerspectiveFactory.java
index d163e675..ad05bf42 100644
--- a/core/cc.warlock.rcp/src/cc/warlock/rcp/application/WarlockPerspectiveFactory.java
+++ b/core/cc.warlock.rcp/src/cc/warlock/rcp/application/WarlockPerspectiveFactory.java
@@ -1,91 +1,91 @@
/**
* Warlock, the open-source cross-platform game client
*
* Copyright 2008, Warlock LLC, and individual contributors as indicated
* by the @authors tag.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
/*
* Created on Dec 30, 2004
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
package cc.warlock.rcp.application;
import org.eclipse.ui.IFolderLayout;
import org.eclipse.ui.IPageLayout;
import org.eclipse.ui.IPerspectiveFactory;
import org.eclipse.ui.IPlaceholderFolderLayout;
import cc.warlock.rcp.views.ConnectionView;
/**
* @author Marshall
*/
public class WarlockPerspectiveFactory implements IPerspectiveFactory {
public static final String WARLOCK_PERSPECTIVE_ID = "cc.warlock.warlockPerspective";
public static final String BOTTOM_FOLDER_ID = "cc.warlock.bottomFolder";
public static final String TOP_FOLDER_ID = "cc.warlock.topFolder";
public static final String RIGHT_FOLDER_ID = "cc.warlock.rightFolder";
public static final String LEFT_FOLDER_ID = "cc.warlock.leftFolder";
public static final String MAIN_FOLDER_ID = "cc.warlock.mainFolder";
/* (non-Javadoc)
* @see org.eclipse.ui.IPerspectiveFactory#createInitialLayout(org.eclipse.ui.IPageLayout)
*/
public void createInitialLayout(IPageLayout layout) {
layout.setEditorAreaVisible(false);
IFolderLayout mainFolder = layout.createFolder(MAIN_FOLDER_ID, IPageLayout.BOTTOM, 0.15f, layout.getEditorArea());
mainFolder.addView(ConnectionView.VIEW_ID);
mainFolder.addPlaceholder("*GameView:*");
// layout.addStandaloneView(HandsView.VIEW_ID, false, IPageLayout.TOP, 0.05f, GameView.VIEW_ID);
// layout.addStandaloneView(StatusView.VIEW_ID, false, IPageLayout.RIGHT, .5f, HandsView.VIEW_ID);
IPlaceholderFolderLayout topFolder =
layout.createPlaceholderFolder(TOP_FOLDER_ID, IPageLayout.TOP, 0.15f, MAIN_FOLDER_ID);
topFolder.addPlaceholder("*topStream:*");
// topFolder.addPlaceholder(StreamView.DEATH_VIEW_ID);
// topFolder.addPlaceholder(StreamView.THOUGHTS_VIEW_ID);
IPlaceholderFolderLayout rightFolder =
layout.createPlaceholderFolder(RIGHT_FOLDER_ID, IPageLayout.RIGHT, 0.75f, MAIN_FOLDER_ID);
rightFolder.addPlaceholder("*rightStream:*");
IPlaceholderFolderLayout leftFolder =
- layout.createPlaceholderFolder(LEFT_FOLDER_ID, IPageLayout.LEFT, 0.75f, MAIN_FOLDER_ID);
+ layout.createPlaceholderFolder(LEFT_FOLDER_ID, IPageLayout.LEFT, 0.25f, MAIN_FOLDER_ID);
leftFolder.addPlaceholder("*leftStream:*");
// rightFolder.addPlaceholder(StreamView.INVENTORY_VIEW_ID);
rightFolder.addPlaceholder("*DebugView:*");
IPlaceholderFolderLayout bottomFolder =
layout.createPlaceholderFolder(BOTTOM_FOLDER_ID, IPageLayout.BOTTOM, 0.95f, MAIN_FOLDER_ID);
bottomFolder.addPlaceholder("*bottomStream*");
// IFolderLayout folder = layout.createFolder(BOTTOM_FOLDER_ID, IPageLayout.BOTTOM, 0.90f, GameView.VIEW_ID);
// layout.addStandaloneView(BarsView.VIEW_ID, false, IPageLayout.BOTTOM, 0.95f, GameView.VIEW_ID);
// folder.addView("org.eclipse.pde.runtime.LogView");
// layout.addView(CompassView.VIEW_ID, IPageLayout.RIGHT, 0.85f, BarsView.VIEW_ID);
}
}
| true | true | public void createInitialLayout(IPageLayout layout) {
layout.setEditorAreaVisible(false);
IFolderLayout mainFolder = layout.createFolder(MAIN_FOLDER_ID, IPageLayout.BOTTOM, 0.15f, layout.getEditorArea());
mainFolder.addView(ConnectionView.VIEW_ID);
mainFolder.addPlaceholder("*GameView:*");
// layout.addStandaloneView(HandsView.VIEW_ID, false, IPageLayout.TOP, 0.05f, GameView.VIEW_ID);
// layout.addStandaloneView(StatusView.VIEW_ID, false, IPageLayout.RIGHT, .5f, HandsView.VIEW_ID);
IPlaceholderFolderLayout topFolder =
layout.createPlaceholderFolder(TOP_FOLDER_ID, IPageLayout.TOP, 0.15f, MAIN_FOLDER_ID);
topFolder.addPlaceholder("*topStream:*");
// topFolder.addPlaceholder(StreamView.DEATH_VIEW_ID);
// topFolder.addPlaceholder(StreamView.THOUGHTS_VIEW_ID);
IPlaceholderFolderLayout rightFolder =
layout.createPlaceholderFolder(RIGHT_FOLDER_ID, IPageLayout.RIGHT, 0.75f, MAIN_FOLDER_ID);
rightFolder.addPlaceholder("*rightStream:*");
IPlaceholderFolderLayout leftFolder =
layout.createPlaceholderFolder(LEFT_FOLDER_ID, IPageLayout.LEFT, 0.75f, MAIN_FOLDER_ID);
leftFolder.addPlaceholder("*leftStream:*");
// rightFolder.addPlaceholder(StreamView.INVENTORY_VIEW_ID);
rightFolder.addPlaceholder("*DebugView:*");
IPlaceholderFolderLayout bottomFolder =
layout.createPlaceholderFolder(BOTTOM_FOLDER_ID, IPageLayout.BOTTOM, 0.95f, MAIN_FOLDER_ID);
bottomFolder.addPlaceholder("*bottomStream*");
// IFolderLayout folder = layout.createFolder(BOTTOM_FOLDER_ID, IPageLayout.BOTTOM, 0.90f, GameView.VIEW_ID);
// layout.addStandaloneView(BarsView.VIEW_ID, false, IPageLayout.BOTTOM, 0.95f, GameView.VIEW_ID);
// folder.addView("org.eclipse.pde.runtime.LogView");
// layout.addView(CompassView.VIEW_ID, IPageLayout.RIGHT, 0.85f, BarsView.VIEW_ID);
}
| public void createInitialLayout(IPageLayout layout) {
layout.setEditorAreaVisible(false);
IFolderLayout mainFolder = layout.createFolder(MAIN_FOLDER_ID, IPageLayout.BOTTOM, 0.15f, layout.getEditorArea());
mainFolder.addView(ConnectionView.VIEW_ID);
mainFolder.addPlaceholder("*GameView:*");
// layout.addStandaloneView(HandsView.VIEW_ID, false, IPageLayout.TOP, 0.05f, GameView.VIEW_ID);
// layout.addStandaloneView(StatusView.VIEW_ID, false, IPageLayout.RIGHT, .5f, HandsView.VIEW_ID);
IPlaceholderFolderLayout topFolder =
layout.createPlaceholderFolder(TOP_FOLDER_ID, IPageLayout.TOP, 0.15f, MAIN_FOLDER_ID);
topFolder.addPlaceholder("*topStream:*");
// topFolder.addPlaceholder(StreamView.DEATH_VIEW_ID);
// topFolder.addPlaceholder(StreamView.THOUGHTS_VIEW_ID);
IPlaceholderFolderLayout rightFolder =
layout.createPlaceholderFolder(RIGHT_FOLDER_ID, IPageLayout.RIGHT, 0.75f, MAIN_FOLDER_ID);
rightFolder.addPlaceholder("*rightStream:*");
IPlaceholderFolderLayout leftFolder =
layout.createPlaceholderFolder(LEFT_FOLDER_ID, IPageLayout.LEFT, 0.25f, MAIN_FOLDER_ID);
leftFolder.addPlaceholder("*leftStream:*");
// rightFolder.addPlaceholder(StreamView.INVENTORY_VIEW_ID);
rightFolder.addPlaceholder("*DebugView:*");
IPlaceholderFolderLayout bottomFolder =
layout.createPlaceholderFolder(BOTTOM_FOLDER_ID, IPageLayout.BOTTOM, 0.95f, MAIN_FOLDER_ID);
bottomFolder.addPlaceholder("*bottomStream*");
// IFolderLayout folder = layout.createFolder(BOTTOM_FOLDER_ID, IPageLayout.BOTTOM, 0.90f, GameView.VIEW_ID);
// layout.addStandaloneView(BarsView.VIEW_ID, false, IPageLayout.BOTTOM, 0.95f, GameView.VIEW_ID);
// folder.addView("org.eclipse.pde.runtime.LogView");
// layout.addView(CompassView.VIEW_ID, IPageLayout.RIGHT, 0.85f, BarsView.VIEW_ID);
}
|
diff --git a/plugins/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/impl/PreparedIVDataExtractionQuery.java b/plugins/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/impl/PreparedIVDataExtractionQuery.java
index 757d688e4..7243b0010 100644
--- a/plugins/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/impl/PreparedIVDataExtractionQuery.java
+++ b/plugins/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/impl/PreparedIVDataExtractionQuery.java
@@ -1,129 +1,129 @@
/*******************************************************************************
* Copyright (c) 2004, 2008 Actuate Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.birt.data.engine.impl;
import java.util.ArrayList;
import java.util.Map;
import org.eclipse.birt.core.data.ExpressionUtil;
import org.eclipse.birt.core.exception.BirtException;
import org.eclipse.birt.data.engine.api.IBaseQueryDefinition;
import org.eclipse.birt.data.engine.api.IBinding;
import org.eclipse.birt.data.engine.api.IQueryDefinition;
import org.eclipse.birt.data.engine.api.querydefn.Binding;
import org.eclipse.birt.data.engine.api.querydefn.QueryDefinition;
import org.eclipse.birt.data.engine.api.querydefn.ScriptExpression;
import org.eclipse.birt.data.engine.api.querydefn.SubqueryLocator;
import org.eclipse.birt.data.engine.core.DataException;
/**
*
*/
public class PreparedIVDataExtractionQuery extends PreparedIVQuerySourceQuery
{
PreparedIVDataExtractionQuery( DataEngineImpl dataEngine,
IQueryDefinition queryDefn, Map appContext, IQueryContextVisitor visitor ) throws DataException
{
super( dataEngine, queryDefn, appContext, visitor );
// TODO Auto-generated constructor stub
}
protected void prepareQuery( ) throws DataException
{
try
{
IBinding[] bindings = null;
if ( this.queryDefn.getSourceQuery( ) instanceof SubqueryLocator )
{
this.queryResults = engine.getQueryResults( getParentQueryResultsID( (SubqueryLocator) ( queryDefn.getSourceQuery( ) ) ) );
IQueryDefinition queryDefinition = queryResults.getPreparedQuery( )
.getReportQueryDefn( );
if ( queryDefn.getSourceQuery( ) instanceof SubqueryLocator )
{
ArrayList<IBinding> bindingList = new ArrayList<IBinding>( );
getSubQueryBindings( queryDefinition,
( (SubqueryLocator) queryDefn.getSourceQuery( ) ).getName( ), bindingList );
addQueryBindings( bindingList, queryDefinition.getBindings( ) );
bindings = bindingList.toArray( new IBinding[0] );
}
else
{
bindings = (IBinding[]) ( queryDefinition.getBindings( )
.values( ).toArray( new IBinding[0] ) );
}
}
else
{
if( ( (IQueryDefinition) queryDefn.getSourceQuery( ) ).getQueryResultsID( ) == null )
{
newPreDataEnige( );
this.queryResults = PreparedQueryUtil.newInstance( preDataEngine,
(IQueryDefinition) queryDefn.getSourceQuery( ),
this.appContext ).execute( null );
}
else
{
this.queryResults = PreparedQueryUtil.newInstance( engine,
(IQueryDefinition) queryDefn.getSourceQuery( ),
- null ).execute( null );
+ this.appContext ).execute( null );
}
if ( queryResults != null
&& queryResults.getPreparedQuery( ) != null )
{
IQueryDefinition queryDefinition = queryResults.getPreparedQuery( )
.getReportQueryDefn( );
bindings = (IBinding[]) queryDefinition.getBindings( )
.values( )
.toArray( new IBinding[0] );
}
else
{
bindings = new IBinding[0];
}
}
if ( !hasBinding )
{
for ( int i = 0; i < bindings.length; i++ )
{
IBinding binding = bindings[i];
if ( !this.queryDefn.getBindings( ).containsKey( binding.getBindingName( ) ))
this.queryDefn.addBinding( new Binding( binding.getBindingName( ),
new ScriptExpression( ExpressionUtil.createJSDataSetRowExpression( binding.getBindingName( ) ),
binding.getDataType( ) ) ) );
}
}
}
catch ( BirtException e )
{
throw DataException.wrap( e );
}
}
/**
*
* @param subqueryLocator
* @return
*/
private String getParentQueryResultsID( SubqueryLocator subqueryLocator )
{
IBaseQueryDefinition baseQueryDefinition = subqueryLocator.getParentQuery( );
while ( !( baseQueryDefinition instanceof QueryDefinition ) )
{
baseQueryDefinition = baseQueryDefinition.getParentQuery( );
}
return ( (QueryDefinition) baseQueryDefinition ).getQueryResultsID( );
}
}
| true | true | protected void prepareQuery( ) throws DataException
{
try
{
IBinding[] bindings = null;
if ( this.queryDefn.getSourceQuery( ) instanceof SubqueryLocator )
{
this.queryResults = engine.getQueryResults( getParentQueryResultsID( (SubqueryLocator) ( queryDefn.getSourceQuery( ) ) ) );
IQueryDefinition queryDefinition = queryResults.getPreparedQuery( )
.getReportQueryDefn( );
if ( queryDefn.getSourceQuery( ) instanceof SubqueryLocator )
{
ArrayList<IBinding> bindingList = new ArrayList<IBinding>( );
getSubQueryBindings( queryDefinition,
( (SubqueryLocator) queryDefn.getSourceQuery( ) ).getName( ), bindingList );
addQueryBindings( bindingList, queryDefinition.getBindings( ) );
bindings = bindingList.toArray( new IBinding[0] );
}
else
{
bindings = (IBinding[]) ( queryDefinition.getBindings( )
.values( ).toArray( new IBinding[0] ) );
}
}
else
{
if( ( (IQueryDefinition) queryDefn.getSourceQuery( ) ).getQueryResultsID( ) == null )
{
newPreDataEnige( );
this.queryResults = PreparedQueryUtil.newInstance( preDataEngine,
(IQueryDefinition) queryDefn.getSourceQuery( ),
this.appContext ).execute( null );
}
else
{
this.queryResults = PreparedQueryUtil.newInstance( engine,
(IQueryDefinition) queryDefn.getSourceQuery( ),
null ).execute( null );
}
if ( queryResults != null
&& queryResults.getPreparedQuery( ) != null )
{
IQueryDefinition queryDefinition = queryResults.getPreparedQuery( )
.getReportQueryDefn( );
bindings = (IBinding[]) queryDefinition.getBindings( )
.values( )
.toArray( new IBinding[0] );
}
else
{
bindings = new IBinding[0];
}
}
if ( !hasBinding )
{
for ( int i = 0; i < bindings.length; i++ )
{
IBinding binding = bindings[i];
if ( !this.queryDefn.getBindings( ).containsKey( binding.getBindingName( ) ))
this.queryDefn.addBinding( new Binding( binding.getBindingName( ),
new ScriptExpression( ExpressionUtil.createJSDataSetRowExpression( binding.getBindingName( ) ),
binding.getDataType( ) ) ) );
}
}
}
catch ( BirtException e )
{
throw DataException.wrap( e );
}
}
| protected void prepareQuery( ) throws DataException
{
try
{
IBinding[] bindings = null;
if ( this.queryDefn.getSourceQuery( ) instanceof SubqueryLocator )
{
this.queryResults = engine.getQueryResults( getParentQueryResultsID( (SubqueryLocator) ( queryDefn.getSourceQuery( ) ) ) );
IQueryDefinition queryDefinition = queryResults.getPreparedQuery( )
.getReportQueryDefn( );
if ( queryDefn.getSourceQuery( ) instanceof SubqueryLocator )
{
ArrayList<IBinding> bindingList = new ArrayList<IBinding>( );
getSubQueryBindings( queryDefinition,
( (SubqueryLocator) queryDefn.getSourceQuery( ) ).getName( ), bindingList );
addQueryBindings( bindingList, queryDefinition.getBindings( ) );
bindings = bindingList.toArray( new IBinding[0] );
}
else
{
bindings = (IBinding[]) ( queryDefinition.getBindings( )
.values( ).toArray( new IBinding[0] ) );
}
}
else
{
if( ( (IQueryDefinition) queryDefn.getSourceQuery( ) ).getQueryResultsID( ) == null )
{
newPreDataEnige( );
this.queryResults = PreparedQueryUtil.newInstance( preDataEngine,
(IQueryDefinition) queryDefn.getSourceQuery( ),
this.appContext ).execute( null );
}
else
{
this.queryResults = PreparedQueryUtil.newInstance( engine,
(IQueryDefinition) queryDefn.getSourceQuery( ),
this.appContext ).execute( null );
}
if ( queryResults != null
&& queryResults.getPreparedQuery( ) != null )
{
IQueryDefinition queryDefinition = queryResults.getPreparedQuery( )
.getReportQueryDefn( );
bindings = (IBinding[]) queryDefinition.getBindings( )
.values( )
.toArray( new IBinding[0] );
}
else
{
bindings = new IBinding[0];
}
}
if ( !hasBinding )
{
for ( int i = 0; i < bindings.length; i++ )
{
IBinding binding = bindings[i];
if ( !this.queryDefn.getBindings( ).containsKey( binding.getBindingName( ) ))
this.queryDefn.addBinding( new Binding( binding.getBindingName( ),
new ScriptExpression( ExpressionUtil.createJSDataSetRowExpression( binding.getBindingName( ) ),
binding.getDataType( ) ) ) );
}
}
}
catch ( BirtException e )
{
throw DataException.wrap( e );
}
}
|
diff --git a/src/org/hyperic/hq/hqapi1/test/ResourceUpdate_test.java b/src/org/hyperic/hq/hqapi1/test/ResourceUpdate_test.java
index f043e71..76c97dd 100644
--- a/src/org/hyperic/hq/hqapi1/test/ResourceUpdate_test.java
+++ b/src/org/hyperic/hq/hqapi1/test/ResourceUpdate_test.java
@@ -1,218 +1,224 @@
/*
*
* NOTE: This copyright does *not* cover user programs that use HQ
* program services by normal system calls through the application
* program interfaces provided as part of the Hyperic Plug-in Development
* Kit or the Hyperic Client Development Kit - this is merely considered
* normal use of the program, and does *not* fall under the heading of
* "derived work".
*
* Copyright (C) [2008, 2009], Hyperic, Inc.
* This file is part of HQ.
*
* HQ is free software; you can redistribute it and/or modify
* it under the terms version 2 of the GNU General Public License as
* published by the Free Software Foundation. This program is distributed
* in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA.
*
*/
package org.hyperic.hq.hqapi1.test;
import org.hyperic.hq.hqapi1.ResourceApi;
import org.hyperic.hq.hqapi1.types.Agent;
import org.hyperic.hq.hqapi1.types.Resource;
import org.hyperic.hq.hqapi1.types.ResourceConfig;
import org.hyperic.hq.hqapi1.types.ResourceProperty;
import org.hyperic.hq.hqapi1.types.ResourceResponse;
import org.hyperic.hq.hqapi1.types.ResourcesResponse;
import org.hyperic.hq.hqapi1.types.StatusResponse;
public class ResourceUpdate_test extends ResourceTestBase {
public ResourceUpdate_test(String name) {
super(name);
}
public void testUpdateFields() throws Exception {
Agent a = getRunningAgent();
ResourceApi api = getApi().getResourceApi();
ResourcesResponse resourcesResponse = api.getResources(a, false, false);
hqAssertSuccess(resourcesResponse);
Resource platform = resourcesResponse.getResource().get(0);
final String UPDATED_NAME = "Updated platform";
final String UPDATED_DESCRIPTION = "Updated description";
String origName = platform.getName();
String origDescription = platform.getDescription();
platform.setName(UPDATED_NAME);
platform.setDescription(UPDATED_DESCRIPTION);
StatusResponse updateResponse = api.updateResource(platform);
hqAssertSuccess(updateResponse);
ResourceResponse updatedResource = api.getResource(platform.getId(),
false, false);
hqAssertSuccess(updatedResource);
Resource updated = updatedResource.getResource();
assertEquals(updated.getName(), UPDATED_NAME);
assertEquals(updated.getDescription(), UPDATED_DESCRIPTION);
// Reset
updated.setName(origName);
updated.setDescription(origDescription);
updateResponse = api.updateResource(updated);
hqAssertSuccess(updateResponse);
}
public void testUpdateConfig() throws Exception {
ResourceApi api = getApi().getResourceApi();
Resource createdResource = createTestHTTPService();
final String UPDATED_HOSTNAME = "www.yahoo.com";
for (ResourceConfig c : createdResource.getResourceConfig()) {
if (c.getKey().equals("hostname")) {
c.setValue(UPDATED_HOSTNAME);
}
}
StatusResponse updateResponse = api.updateResource(createdResource);
hqAssertSuccess(updateResponse);
ResourceResponse getResponse = api.getResource(createdResource.getId(),
- false, false);
+ true, false);
hqAssertSuccess(getResponse);
Resource updatedResource = getResponse.getResource();
+ assertTrue("No configuration found for " + updatedResource.getName(),
+ updatedResource.getResourceConfig().size() > 0);
+ boolean foundHostname = false;
for (ResourceConfig c : updatedResource.getResourceConfig()) {
if (c.getKey().equals("hostname")) {
assertEquals(c.getValue(), UPDATED_HOSTNAME);
+ foundHostname = true;
}
}
+ assertTrue("Unable to find hostname configuration for " + updatedResource.getName(),
+ foundHostname);
// Cannot delete resources soon after modifying them..
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// Ignore
}
// Cleanup
StatusResponse deleteResponse = api.deleteResource(updatedResource.getId());
hqAssertSuccess(deleteResponse);
}
public void testUpdateProperties() throws Exception {
ResourceApi api = getApi().getResourceApi();
Resource platform = getLocalPlatformResource(true, false);
final String UPDATED_GW = "1.2.3.4";
String origGw = null;
for (ResourceProperty p : platform.getResourceProperty()) {
if (p.getKey().equals("defaultGateway")) {
origGw = p.getValue();
p.setValue(UPDATED_GW);
break;
}
}
assertNotNull("Unable to find default gateway property for resource " +
platform.getName() + origGw);
StatusResponse updateResponse = api.updateResource(platform);
hqAssertSuccess(updateResponse);
ResourceResponse getRequest = api.getResource(platform.getId(), false,
false);
hqAssertSuccess(getRequest);
for (ResourceProperty p : platform.getResourceProperty()) {
if (p.getKey().equals("defaultGateway")) {
assertEquals(p.getValue(), UPDATED_GW);
p.setValue(origGw);
break;
}
}
updateResponse = api.updateResource(platform);
hqAssertSuccess(updateResponse);
}
public void testUpdateInvalidResource() throws Exception {
ResourceApi api = getApi().getResourceApi();
Resource r = new Resource();
r.setId(Integer.MAX_VALUE);
r.setName("Invalid Resource");
StatusResponse updateResponse = api.updateResource(r);
hqAssertFailureObjectNotFound(updateResponse);
}
public void testUpdateInvalidChildResource() throws Exception {
Agent a = getRunningAgent();
ResourceApi api = getApi().getResourceApi();
ResourcesResponse resourcesResponse = api.getResources(a, false, false);
hqAssertSuccess(resourcesResponse);
Resource platform = resourcesResponse.getResource().get(0);
Resource r = new Resource();
r.setId(Integer.MAX_VALUE);
r.setName("Invalid child resource");
platform.getResource().add(r);
StatusResponse updateResponse = api.updateResource(platform);
hqAssertFailureObjectNotFound(updateResponse);
}
public void testUpdateInvalidDescription() throws Exception {
ResourceApi api = getApi().getResourceApi();
Resource createdResource = createTestHTTPService();
String longDescription = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" +
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" +
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" +
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" +
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" +
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" +
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
createdResource.setDescription(longDescription);
StatusResponse updateResponse = api.updateResource(createdResource);
hqAssertFailureInvalidParameters(updateResponse);
// Cannot delete resources soon after modifying them..
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// Ignore
}
// Cleanup
StatusResponse deleteResponse = api.deleteResource(createdResource.getId());
hqAssertSuccess(deleteResponse);
}
}
| false | true | public void testUpdateConfig() throws Exception {
ResourceApi api = getApi().getResourceApi();
Resource createdResource = createTestHTTPService();
final String UPDATED_HOSTNAME = "www.yahoo.com";
for (ResourceConfig c : createdResource.getResourceConfig()) {
if (c.getKey().equals("hostname")) {
c.setValue(UPDATED_HOSTNAME);
}
}
StatusResponse updateResponse = api.updateResource(createdResource);
hqAssertSuccess(updateResponse);
ResourceResponse getResponse = api.getResource(createdResource.getId(),
false, false);
hqAssertSuccess(getResponse);
Resource updatedResource = getResponse.getResource();
for (ResourceConfig c : updatedResource.getResourceConfig()) {
if (c.getKey().equals("hostname")) {
assertEquals(c.getValue(), UPDATED_HOSTNAME);
}
}
// Cannot delete resources soon after modifying them..
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// Ignore
}
// Cleanup
StatusResponse deleteResponse = api.deleteResource(updatedResource.getId());
hqAssertSuccess(deleteResponse);
}
| public void testUpdateConfig() throws Exception {
ResourceApi api = getApi().getResourceApi();
Resource createdResource = createTestHTTPService();
final String UPDATED_HOSTNAME = "www.yahoo.com";
for (ResourceConfig c : createdResource.getResourceConfig()) {
if (c.getKey().equals("hostname")) {
c.setValue(UPDATED_HOSTNAME);
}
}
StatusResponse updateResponse = api.updateResource(createdResource);
hqAssertSuccess(updateResponse);
ResourceResponse getResponse = api.getResource(createdResource.getId(),
true, false);
hqAssertSuccess(getResponse);
Resource updatedResource = getResponse.getResource();
assertTrue("No configuration found for " + updatedResource.getName(),
updatedResource.getResourceConfig().size() > 0);
boolean foundHostname = false;
for (ResourceConfig c : updatedResource.getResourceConfig()) {
if (c.getKey().equals("hostname")) {
assertEquals(c.getValue(), UPDATED_HOSTNAME);
foundHostname = true;
}
}
assertTrue("Unable to find hostname configuration for " + updatedResource.getName(),
foundHostname);
// Cannot delete resources soon after modifying them..
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// Ignore
}
// Cleanup
StatusResponse deleteResponse = api.deleteResource(updatedResource.getId());
hqAssertSuccess(deleteResponse);
}
|
diff --git a/openregistry-repository-jpa-impl/src/main/java/org/openregistry/core/repository/jpa/JpaPersonRepository.java b/openregistry-repository-jpa-impl/src/main/java/org/openregistry/core/repository/jpa/JpaPersonRepository.java
index 11d53198..0c695ebb 100644
--- a/openregistry-repository-jpa-impl/src/main/java/org/openregistry/core/repository/jpa/JpaPersonRepository.java
+++ b/openregistry-repository-jpa-impl/src/main/java/org/openregistry/core/repository/jpa/JpaPersonRepository.java
@@ -1,51 +1,51 @@
package org.openregistry.core.repository.jpa;
import java.util.List;
import org.openregistry.core.repository.PersonRepository;
import org.openregistry.core.repository.RepositoryAccessException;
import org.openregistry.core.domain.Person;
import org.openregistry.core.domain.sor.SorPerson;
import org.openregistry.core.domain.jpa.JpaPersonImpl;
import org.springframework.stereotype.Repository;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
/**
* Person repository implementation built on top of JPA.
*
* @author Dmitriy Kopylenko
* @version $Revision$ $Date$
* @since 1.0.0
*/
@Repository
public class JpaPersonRepository implements PersonRepository {
@PersistenceContext
private EntityManager entityManager;
public Person findByInternalId(final Long id) throws RepositoryAccessException {
return this.entityManager.find(JpaPersonImpl.class, id);
}
public List<Person> findByFamilyName(final String family) throws RepositoryAccessException {
- Query query = this.entityManager.createQuery("SELECT person FROM Person person WHERE person.officialName.family = :family");
+ Query query = this.entityManager.createQuery("SELECT p FROM person p WHERE p.officialName.family = :name");
query.setParameter("name", family);
return query.getResultList();
}
public Person savePerson(final Person person) throws RepositoryAccessException {
return this.entityManager.merge(person);
}
public SorPerson saveSorPerson(final SorPerson person) throws RepositoryAccessException {
return this.entityManager.merge(person);
}
public void addPerson(Person person) throws RepositoryAccessException {
this.entityManager.persist(person);
}
}
| true | true | public List<Person> findByFamilyName(final String family) throws RepositoryAccessException {
Query query = this.entityManager.createQuery("SELECT person FROM Person person WHERE person.officialName.family = :family");
query.setParameter("name", family);
return query.getResultList();
}
| public List<Person> findByFamilyName(final String family) throws RepositoryAccessException {
Query query = this.entityManager.createQuery("SELECT p FROM person p WHERE p.officialName.family = :name");
query.setParameter("name", family);
return query.getResultList();
}
|
diff --git a/libraries/javalib/java/util/AbstractList.java b/libraries/javalib/java/util/AbstractList.java
index 6b3c093c3..f6439bbae 100644
--- a/libraries/javalib/java/util/AbstractList.java
+++ b/libraries/javalib/java/util/AbstractList.java
@@ -1,227 +1,227 @@
/*
* Java core library component.
*
* Copyright (c) 1997, 1998
* Transvirtual Technologies, Inc. All rights reserved.
*
* See the file "license.terms" for information on usage and redistribution
* of this file.
*/
package java.util;
public abstract class AbstractList
extends AbstractCollection implements List {
protected int modCount;
protected AbstractList() {
}
public boolean add(Object o) {
add(size(), o);
return true;
}
public abstract Object get(int index);
public Object set(int index, Object element) {
throw new UnsupportedOperationException();
}
public void add(int index, Object element) {
throw new UnsupportedOperationException();
}
public Object remove(int index) {
throw new UnsupportedOperationException();
}
public int indexOf(Object o) {
ListIterator it = listIterator();
for (int idx = 0; it.hasNext(); idx++) {
Object next = it.next();
if (o == null ? next == null : o.equals(next)) {
return idx;
}
}
return -1;
}
public int lastIndexOf(Object o) {
ListIterator it = listIterator(size());
for (int idx = size() - 1; it.hasPrevious(); idx--) {
Object prev = it.previous();
if (o == null ? prev == null : o.equals(prev)) {
return (idx);
}
}
return (-1);
}
public void clear() {
removeRange(0, size());
}
public boolean addAll(int index, Collection c) {
for (Iterator i = c.iterator(); i.hasNext(); ) {
add(index++, i.next());
}
return c.size() != 0;
}
public Iterator iterator() {
return listIterator(0);
}
public ListIterator listIterator() {
return listIterator(0);
}
public ListIterator listIterator(int index) {
return new AbstractListIterator(this, index);
}
public List subList(final int fromIndex, final int toIndex) {
if (fromIndex < 0 || toIndex > size()) {
throw new IndexOutOfBoundsException();
}
if (fromIndex > toIndex) {
throw new IllegalArgumentException();
}
return new AbstractList() {
private final AbstractList list = AbstractList.this;
- private int modCount = AbstractList.this.modCount;
+ protected int modCount = AbstractList.this.modCount;
private final int off = fromIndex;
private int len = toIndex - fromIndex;
public int size() {
return len;
}
public Object get(int index) {
if (index < 0 || index >= len) {
throw new IndexOutOfBoundsException();
}
return list.get(off + index);
}
public Object set(int index, Object element) {
if (list.modCount != this.modCount) {
throw new ConcurrentModificationException();
}
if (index < 0 || index >= len) {
throw new IndexOutOfBoundsException();
}
return list.set(off + index, element);
}
public void add(int index, Object element) {
if (list.modCount != this.modCount) {
throw new ConcurrentModificationException();
}
if (index < 0 || index > len) {
throw new IndexOutOfBoundsException();
}
list.add(off + index, element);
modCount = AbstractList.this.modCount;
len++;
}
public Object remove(int index) {
if (list.modCount != this.modCount) {
throw new ConcurrentModificationException();
}
if (index < 0 || index >= len) {
throw new IndexOutOfBoundsException();
}
Object rtn = list.remove(off + index);
modCount = AbstractList.this.modCount;
len--;
return rtn;
}
public int indexOf(Object o) {
if (list.modCount != this.modCount) {
throw new ConcurrentModificationException();
}
final ListIterator it = list.listIterator(off);
for (int index = 0; index < len && it.hasNext(); index++) {
Object next = it.next();
if (o == null ? next == null : o.equals(next)) {
return index;
}
}
return -1;
}
public int lastIndexOf(Object o) {
if (list.modCount != this.modCount) {
throw new ConcurrentModificationException();
}
final ListIterator it = list.listIterator(off + len);
for (int index = len - 1; index >= 0 && it.hasPrevious(); index--) {
Object prev = it.previous();
if (o == null ? prev == null : o.equals(prev)) {
return index;
}
}
return -1;
}
protected void removeRange(int fromIndex0, int toIndex0) {
if (list.modCount != this.modCount) {
throw new ConcurrentModificationException();
}
if (fromIndex0 < 0 || toIndex0 > len) {
throw new IndexOutOfBoundsException();
}
list.removeRange(off + fromIndex0, off + toIndex0);
modCount = AbstractList.this.modCount;
len -= toIndex0 - fromIndex0;
}
};
}
public boolean equals(Object o) {
if (o == this) {
return (true);
}
if (!(o instanceof List)) {
return (false);
}
List other = (List)o;
if (size() != other.size()) {
return (false);
}
ListIterator mlist = listIterator();
ListIterator olist = other.listIterator();
while (mlist.hasNext()) {
final Object o1 = mlist.next();
final Object o2 = olist.next();
if (!(o1 == null ? o2 == null : o1.equals(o2))) {
return (false);
}
}
return (true);
}
public int hashCode() {
int hashCode = 1;
for (Iterator i = iterator(); i.hasNext(); ) {
final Object obj = i.next();
hashCode = 31*hashCode + (obj==null ? 0 : obj.hashCode());
}
return hashCode;
}
protected void removeRange(int fromIndex, int toIndex) {
final ListIterator i = listIterator(fromIndex);
while (fromIndex < toIndex && i.hasNext()) {
i.next();
i.remove();
fromIndex++;
}
}
}
| true | true | public List subList(final int fromIndex, final int toIndex) {
if (fromIndex < 0 || toIndex > size()) {
throw new IndexOutOfBoundsException();
}
if (fromIndex > toIndex) {
throw new IllegalArgumentException();
}
return new AbstractList() {
private final AbstractList list = AbstractList.this;
private int modCount = AbstractList.this.modCount;
private final int off = fromIndex;
private int len = toIndex - fromIndex;
public int size() {
return len;
}
public Object get(int index) {
if (index < 0 || index >= len) {
throw new IndexOutOfBoundsException();
}
return list.get(off + index);
}
public Object set(int index, Object element) {
if (list.modCount != this.modCount) {
throw new ConcurrentModificationException();
}
if (index < 0 || index >= len) {
throw new IndexOutOfBoundsException();
}
return list.set(off + index, element);
}
public void add(int index, Object element) {
if (list.modCount != this.modCount) {
throw new ConcurrentModificationException();
}
if (index < 0 || index > len) {
throw new IndexOutOfBoundsException();
}
list.add(off + index, element);
modCount = AbstractList.this.modCount;
len++;
}
public Object remove(int index) {
if (list.modCount != this.modCount) {
throw new ConcurrentModificationException();
}
if (index < 0 || index >= len) {
throw new IndexOutOfBoundsException();
}
Object rtn = list.remove(off + index);
modCount = AbstractList.this.modCount;
len--;
return rtn;
}
public int indexOf(Object o) {
if (list.modCount != this.modCount) {
throw new ConcurrentModificationException();
}
final ListIterator it = list.listIterator(off);
for (int index = 0; index < len && it.hasNext(); index++) {
Object next = it.next();
if (o == null ? next == null : o.equals(next)) {
return index;
}
}
return -1;
}
public int lastIndexOf(Object o) {
if (list.modCount != this.modCount) {
throw new ConcurrentModificationException();
}
final ListIterator it = list.listIterator(off + len);
for (int index = len - 1; index >= 0 && it.hasPrevious(); index--) {
Object prev = it.previous();
if (o == null ? prev == null : o.equals(prev)) {
return index;
}
}
return -1;
}
protected void removeRange(int fromIndex0, int toIndex0) {
if (list.modCount != this.modCount) {
throw new ConcurrentModificationException();
}
if (fromIndex0 < 0 || toIndex0 > len) {
throw new IndexOutOfBoundsException();
}
list.removeRange(off + fromIndex0, off + toIndex0);
modCount = AbstractList.this.modCount;
len -= toIndex0 - fromIndex0;
}
};
}
| public List subList(final int fromIndex, final int toIndex) {
if (fromIndex < 0 || toIndex > size()) {
throw new IndexOutOfBoundsException();
}
if (fromIndex > toIndex) {
throw new IllegalArgumentException();
}
return new AbstractList() {
private final AbstractList list = AbstractList.this;
protected int modCount = AbstractList.this.modCount;
private final int off = fromIndex;
private int len = toIndex - fromIndex;
public int size() {
return len;
}
public Object get(int index) {
if (index < 0 || index >= len) {
throw new IndexOutOfBoundsException();
}
return list.get(off + index);
}
public Object set(int index, Object element) {
if (list.modCount != this.modCount) {
throw new ConcurrentModificationException();
}
if (index < 0 || index >= len) {
throw new IndexOutOfBoundsException();
}
return list.set(off + index, element);
}
public void add(int index, Object element) {
if (list.modCount != this.modCount) {
throw new ConcurrentModificationException();
}
if (index < 0 || index > len) {
throw new IndexOutOfBoundsException();
}
list.add(off + index, element);
modCount = AbstractList.this.modCount;
len++;
}
public Object remove(int index) {
if (list.modCount != this.modCount) {
throw new ConcurrentModificationException();
}
if (index < 0 || index >= len) {
throw new IndexOutOfBoundsException();
}
Object rtn = list.remove(off + index);
modCount = AbstractList.this.modCount;
len--;
return rtn;
}
public int indexOf(Object o) {
if (list.modCount != this.modCount) {
throw new ConcurrentModificationException();
}
final ListIterator it = list.listIterator(off);
for (int index = 0; index < len && it.hasNext(); index++) {
Object next = it.next();
if (o == null ? next == null : o.equals(next)) {
return index;
}
}
return -1;
}
public int lastIndexOf(Object o) {
if (list.modCount != this.modCount) {
throw new ConcurrentModificationException();
}
final ListIterator it = list.listIterator(off + len);
for (int index = len - 1; index >= 0 && it.hasPrevious(); index--) {
Object prev = it.previous();
if (o == null ? prev == null : o.equals(prev)) {
return index;
}
}
return -1;
}
protected void removeRange(int fromIndex0, int toIndex0) {
if (list.modCount != this.modCount) {
throw new ConcurrentModificationException();
}
if (fromIndex0 < 0 || toIndex0 > len) {
throw new IndexOutOfBoundsException();
}
list.removeRange(off + fromIndex0, off + toIndex0);
modCount = AbstractList.this.modCount;
len -= toIndex0 - fromIndex0;
}
};
}
|
diff --git a/common-api/src/main/java/org/totalgrid/reef/clientapi/settings/util/PropertyReader.java b/common-api/src/main/java/org/totalgrid/reef/clientapi/settings/util/PropertyReader.java
index fa1a9cecc..871053b51 100644
--- a/common-api/src/main/java/org/totalgrid/reef/clientapi/settings/util/PropertyReader.java
+++ b/common-api/src/main/java/org/totalgrid/reef/clientapi/settings/util/PropertyReader.java
@@ -1,56 +1,58 @@
/**
* Copyright 2011 Green Energy Corp.
*
* Licensed to Green Energy Corp (www.greenenergycorp.com) under one or more
* contributor license agreements. See the NOTICE file distributed with this
* work for additional information regarding copyright ownership. Green Energy
* Corp licenses this file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.totalgrid.reef.clientapi.settings.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
/**
* Provides mechanisms for obtaining a Properties object
*/
public class PropertyReader
{
/**
* Read a properties objectg from a file
* @param fileName Absolute or relative file path
* @return Properties object
* @throws IOException
*/
public static Properties readFromFile( String fileName ) throws IOException
{
- File file = new File(fileName);
+ File file = new File( fileName );
- if(!file.canRead()) throw new IOException("Cannot find or access file: " + file.getAbsolutePath());
+ if ( !file.canRead() ){
+ throw new IOException( "Cannot find or access file: " + file.getAbsolutePath() );
+ }
FileInputStream fis = new FileInputStream( file );
Properties props = new Properties();
try
{
props.load( fis );
}
finally
{
fis.close();
}
return props;
}
}
| false | true | public static Properties readFromFile( String fileName ) throws IOException
{
File file = new File(fileName);
if(!file.canRead()) throw new IOException("Cannot find or access file: " + file.getAbsolutePath());
FileInputStream fis = new FileInputStream( file );
Properties props = new Properties();
try
{
props.load( fis );
}
finally
{
fis.close();
}
return props;
}
| public static Properties readFromFile( String fileName ) throws IOException
{
File file = new File( fileName );
if ( !file.canRead() ){
throw new IOException( "Cannot find or access file: " + file.getAbsolutePath() );
}
FileInputStream fis = new FileInputStream( file );
Properties props = new Properties();
try
{
props.load( fis );
}
finally
{
fis.close();
}
return props;
}
|
diff --git a/source/de/anomic/plasma/plasmaSnippetCache.java b/source/de/anomic/plasma/plasmaSnippetCache.java
index d5a80dcc3..64fa0dd16 100644
--- a/source/de/anomic/plasma/plasmaSnippetCache.java
+++ b/source/de/anomic/plasma/plasmaSnippetCache.java
@@ -1,365 +1,368 @@
// plasmaSnippetCache.java
// -----------------------
// part of YaCy
// (C) by Michael Peter Christen; [email protected]
// first published on http://www.anomic.de
// Frankfurt, Germany, 2005
// last major change: 07.06.2005
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// Using this software in any meaning (reading, learning, copying, compiling,
// running) means that you agree that the Author(s) is (are) not responsible
// for cost, loss of data or any harm that may be caused directly or indirectly
// by usage of this softare or this documentation. The usage of this software
// is on your own risk. The installation and usage (starting/running) of this
// software may allow other people or application to access your computer and
// any attached devices and is highly dependent on the configuration of the
// software which must be done by the user of the software; the author(s) is
// (are) also not responsible for proper configuration and usage of the
// software, even if provoked by documentation provided together with
// the software.
//
// Any changes to this file according to the GPL as documented in the file
// gpl.txt aside this file in the shipment you received can be done to the
// lines that follows this copyright notice here, but changes must not be
// done inside the copyright notive above. A re-distribution must contain
// the intact and unchanged copyright notice.
// Contributions and changes to the program code must be marked as such.
package de.anomic.plasma;
import java.util.*;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import de.anomic.htmlFilter.htmlFilterContentScraper;
import de.anomic.kelondro.kelondroMScoreCluster;
import de.anomic.server.serverFileUtils;
import de.anomic.server.logging.serverLog;
import de.anomic.http.httpHeader;
import de.anomic.yacy.yacySearch;
public class plasmaSnippetCache {
private static final int maxCache = 500;
public static final int SOURCE_CACHE = 0;
public static final int SOURCE_FILE = 1;
public static final int SOURCE_WEB = 2;
public static final int ERROR_NO_HASH_GIVEN = 11;
public static final int ERROR_SOURCE_LOADING = 12;
public static final int ERROR_RESOURCE_LOADING = 13;
public static final int ERROR_PARSER_FAILED = 14;
public static final int ERROR_PARSER_NO_LINES = 15;
public static final int ERROR_NO_MATCH = 16;
private int snippetsScoreCounter;
private kelondroMScoreCluster snippetsScore;
private HashMap snippetsCache;
private plasmaHTCache cacheManager;
private plasmaParser parser;
private serverLog log;
private String remoteProxyHost;
private int remoteProxyPort;
private boolean remoteProxyUse;
public plasmaSnippetCache(plasmaHTCache cacheManager, plasmaParser parser,
String remoteProxyHost, int remoteProxyPort, boolean remoteProxyUse,
serverLog log) {
this.cacheManager = cacheManager;
this.parser = parser;
this.log = log;
this.remoteProxyHost = remoteProxyHost;
this.remoteProxyPort = remoteProxyPort;
this.remoteProxyUse = remoteProxyUse;
this.snippetsScoreCounter = 0;
this.snippetsScore = new kelondroMScoreCluster();
this.snippetsCache = new HashMap();
}
public class result {
public String line;
public String error;
public int source;
public result(String line, int source, String errortext) {
this.line = line;
this.source = source;
this.error = errortext;
}
public String toString() {
return line;
}
}
public boolean existsInCache(URL url, Set queryhashes) {
String hashes = yacySearch.set2string(queryhashes);
return retrieveFromCache(hashes, plasmaURL.urlHash(url)) != null;
}
public result retrieve(URL url, Set queryhashes, boolean fetchOnline, int snippetMaxLength) {
// heise = "0OQUNU3JSs05"
if (queryhashes.size() == 0) {
//System.out.println("found no queryhashes for url retrieve " + url);
return new result(null, ERROR_NO_HASH_GIVEN, "no query hashes given");
}
String urlhash = plasmaURL.urlHash(url);
// try to get snippet from snippetCache
int source = SOURCE_CACHE;
String wordhashes = yacySearch.set2string(queryhashes);
String line = retrieveFromCache(wordhashes, urlhash);
if (line != null) {
//System.out.println("found snippet for url " + url + " in cache: " + line);
return new result(line, source, null);
}
// if the snippet is not in the cache, we can try to get it from the htcache
byte[] resource = null;
try {
resource = cacheManager.loadResource(url);
if ((fetchOnline) && (resource == null)) {
loadResourceFromWeb(url, 5000);
resource = cacheManager.loadResource(url);
source = SOURCE_WEB;
}
} catch (IOException e) {
return new result(null, ERROR_SOURCE_LOADING, "error loading resource from web: " + e.getMessage());
}
if (resource == null) {
//System.out.println("cannot load document for url " + url);
return new result(null, ERROR_RESOURCE_LOADING, "error loading resource from web, cacheManager returned NULL");
}
plasmaParserDocument document = parseDocument(url, resource);
if (document == null) return new result(null, ERROR_PARSER_FAILED, "parser error/failed"); // cannot be parsed
//System.out.println("loaded document for url " + url);
String[] sentences = document.getSentences();
//System.out.println("----" + url.toString()); for (int l = 0; l < sentences.length; l++) System.out.println(sentences[l]);
if ((sentences == null) || (sentences.length == 0)) {
//System.out.println("found no sentences in url " + url);
return new result(null, ERROR_PARSER_NO_LINES, "parser returned no sentences");
}
// we have found a parseable non-empty file: use the lines
line = computeSnippet(sentences, queryhashes, 8 + 6 * queryhashes.size(), snippetMaxLength);
//System.out.println("loaded snippet for url " + url + ": " + line);
if (line == null) return new result(null, ERROR_NO_MATCH, "no matching snippet found");
if (line.length() > snippetMaxLength) line = line.substring(0, snippetMaxLength);
// finally store this snippet in our own cache
storeToCache(wordhashes, urlhash, line);
return new result(line, source, null);
}
public synchronized void storeToCache(String wordhashes, String urlhash, String snippet) {
// generate key
String key = urlhash + wordhashes;
// do nothing if snippet is known
if (snippetsCache.containsKey(key)) return;
// learn new snippet
snippetsScore.addScore(key, snippetsScoreCounter++);
snippetsCache.put(key, snippet);
// care for counter
if (snippetsScoreCounter == java.lang.Integer.MAX_VALUE) {
snippetsScoreCounter = 0;
snippetsScore = new kelondroMScoreCluster();
snippetsCache = new HashMap();
}
// flush cache if cache is full
while (snippetsCache.size() > maxCache) {
key = (String) snippetsScore.getMinObject();
snippetsScore.deleteScore(key);
snippetsCache.remove(key);
}
}
private String retrieveFromCache(String wordhashes, String urlhash) {
// generate key
String key = urlhash + wordhashes;
return (String) snippetsCache.get(key);
}
private String computeSnippet(String[] sentences, Set queryhashes, int minLength, int maxLength) {
if ((sentences == null) || (sentences.length == 0)) return null;
if ((queryhashes == null) || (queryhashes.size() == 0)) return null;
kelondroMScoreCluster hitTable = new kelondroMScoreCluster();
Iterator j;
HashMap hs;
String hash;
for (int i = 0; i < sentences.length; i++) {
//System.out.println("Sentence " + i + ": " + sentences[i]);
if (sentences[i].length() > minLength) {
hs = hashSentence(sentences[i]);
j = queryhashes.iterator();
while (j.hasNext()) {
hash = (String) j.next();
if (hs.containsKey(hash)) {
//System.out.println("hash " + hash + " appears in line " + i);
hitTable.incScore(new Integer(i));
}
}
}
}
int score = hitTable.getMaxScore(); // best number of hits
if (score <= 0) return null;
// we found (a) line(s) that have <score> hits.
// now find the shortest line of these hits
int shortLineIndex = -1;
int shortLineLength = Integer.MAX_VALUE;
for (int i = 0; i < sentences.length; i++) {
if ((hitTable.getScore(new Integer(i)) == score) &&
(sentences[i].length() < shortLineLength)) {
shortLineIndex = i;
shortLineLength = sentences[i].length();
}
}
// find a first result
String result = sentences[shortLineIndex];
// remove all hashes that appear in the result
hs = hashSentence(result);
j = queryhashes.iterator();
Integer pos;
+ Set remaininghashes = new HashSet();
int p, minpos = result.length(), maxpos = -1;
while (j.hasNext()) {
- pos = (Integer) hs.get((String) j.next());
- if (pos != null) {
- j.remove();
+ hash = (String) j.next();
+ pos = (Integer) hs.get(hash);
+ if (pos == null) {
+ remaininghashes.add(hash);
+ } else {
p = pos.intValue();
if (p > maxpos) maxpos = p;
if (p < minpos) minpos = p;
}
}
// check result size
maxpos = maxpos + 10;
if (maxpos > result.length()) maxpos = result.length();
if (minpos < 0) minpos = 0;
// we have a result, but is it short enough?
if (maxpos - minpos + 10 > maxLength) {
// the string is too long, even if we cut at both ends
// so cut here in the middle of the string
int lenb = result.length();
result = result.substring(0, (minpos + 20 > result.length()) ? result.length() : minpos + 20).trim() +
" [..] " +
result.substring((maxpos + 26 > result.length()) ? result.length() : maxpos + 26).trim();
maxpos = maxpos + lenb - result.length() + 6;
}
if (maxpos > maxLength) {
// the string is too long, even if we cut it at the end
// so cut it here at both ends at once
int newlen = maxpos - minpos + 10;
int around = (maxLength - newlen) / 2;
- result = "[..] " + result.substring(minpos - around, maxpos + around).trim() + " [..]";
+ result = "[..] " + result.substring(minpos - around, ((maxpos + around) > result.length()) ? result.length() : (maxpos + around)).trim() + " [..]";
minpos = around;
maxpos = result.length() - around - 5;
}
if (result.length() > maxLength) {
// trim result, 1st step (cut at right side)
result = result.substring(0, maxpos).trim() + " [..]";
}
if (result.length() > maxLength) {
// trim result, 2nd step (cut at left side)
result = "[..] " + result.substring(minpos).trim();
}
if (result.length() > maxLength) {
// trim result, 3rd step (cut in the middle)
result = result.substring(6, 20).trim() + " [..] " + result.substring(result.length() - 26, result.length() - 6).trim();
}
if (queryhashes.size() == 0) return result;
// the result has not all words in it.
// find another sentence that represents the missing other words
// and find recursively more sentences
maxLength = maxLength - result.length();
if (maxLength < 20) maxLength = 20;
- String nextSnippet = computeSnippet(sentences, queryhashes, minLength, maxLength);
+ String nextSnippet = computeSnippet(sentences, remaininghashes, minLength, maxLength);
return result + ((nextSnippet == null) ? "" : (" / " + nextSnippet));
}
private HashMap hashSentence(String sentence) {
// generates a word-wordPos mapping
HashMap map = new HashMap();
Enumeration words = plasmaCondenser.wordTokenizer(sentence, 0);
int pos = 0;
String word;
while (words.hasMoreElements()) {
word = (String) words.nextElement();
map.put(plasmaWordIndexEntry.word2hash(word), new Integer(pos));
pos += word.length() + 1;
}
return map;
}
public plasmaParserDocument parseDocument(URL url, byte[] resource) {
if (resource == null) return null;
httpHeader header = null;
try {
header = cacheManager.getCachedResponse(plasmaURL.urlHash(url));
} catch (IOException e) {}
if (header == null) {
String filename = cacheManager.getCachePath(url).getName();
int p = filename.lastIndexOf('.');
if ((p < 0) ||
((p >= 0) && (plasmaParser.supportedFileExtContains(filename.substring(p + 1))))) {
return parser.parseSource(url, "text/html", resource);
} else {
return null;
}
} else {
if (plasmaParser.supportedMimeTypesContains(header.mime())) {
return parser.parseSource(url, header.mime(), resource);
} else {
return null;
}
}
}
public byte[] getResource(URL url, boolean fetchOnline) {
// load the url as resource from the web
try {
//return httpc.singleGET(url, 5000, null, null, remoteProxyHost, remoteProxyPort);
byte[] resource = cacheManager.loadResource(url);
if ((fetchOnline) && (resource == null)) {
loadResourceFromWeb(url, 5000);
resource = cacheManager.loadResource(url);
}
return resource;
} catch (IOException e) {
return null;
}
}
private void loadResourceFromWeb(URL url, int socketTimeout) throws IOException {
plasmaCrawlWorker.load(
url,
null,
null,
0,
null,
socketTimeout,
remoteProxyHost,
remoteProxyPort,
remoteProxyUse,
cacheManager,
log);
}
}
| false | true | private String computeSnippet(String[] sentences, Set queryhashes, int minLength, int maxLength) {
if ((sentences == null) || (sentences.length == 0)) return null;
if ((queryhashes == null) || (queryhashes.size() == 0)) return null;
kelondroMScoreCluster hitTable = new kelondroMScoreCluster();
Iterator j;
HashMap hs;
String hash;
for (int i = 0; i < sentences.length; i++) {
//System.out.println("Sentence " + i + ": " + sentences[i]);
if (sentences[i].length() > minLength) {
hs = hashSentence(sentences[i]);
j = queryhashes.iterator();
while (j.hasNext()) {
hash = (String) j.next();
if (hs.containsKey(hash)) {
//System.out.println("hash " + hash + " appears in line " + i);
hitTable.incScore(new Integer(i));
}
}
}
}
int score = hitTable.getMaxScore(); // best number of hits
if (score <= 0) return null;
// we found (a) line(s) that have <score> hits.
// now find the shortest line of these hits
int shortLineIndex = -1;
int shortLineLength = Integer.MAX_VALUE;
for (int i = 0; i < sentences.length; i++) {
if ((hitTable.getScore(new Integer(i)) == score) &&
(sentences[i].length() < shortLineLength)) {
shortLineIndex = i;
shortLineLength = sentences[i].length();
}
}
// find a first result
String result = sentences[shortLineIndex];
// remove all hashes that appear in the result
hs = hashSentence(result);
j = queryhashes.iterator();
Integer pos;
int p, minpos = result.length(), maxpos = -1;
while (j.hasNext()) {
pos = (Integer) hs.get((String) j.next());
if (pos != null) {
j.remove();
p = pos.intValue();
if (p > maxpos) maxpos = p;
if (p < minpos) minpos = p;
}
}
// check result size
maxpos = maxpos + 10;
if (maxpos > result.length()) maxpos = result.length();
if (minpos < 0) minpos = 0;
// we have a result, but is it short enough?
if (maxpos - minpos + 10 > maxLength) {
// the string is too long, even if we cut at both ends
// so cut here in the middle of the string
int lenb = result.length();
result = result.substring(0, (minpos + 20 > result.length()) ? result.length() : minpos + 20).trim() +
" [..] " +
result.substring((maxpos + 26 > result.length()) ? result.length() : maxpos + 26).trim();
maxpos = maxpos + lenb - result.length() + 6;
}
if (maxpos > maxLength) {
// the string is too long, even if we cut it at the end
// so cut it here at both ends at once
int newlen = maxpos - minpos + 10;
int around = (maxLength - newlen) / 2;
result = "[..] " + result.substring(minpos - around, maxpos + around).trim() + " [..]";
minpos = around;
maxpos = result.length() - around - 5;
}
if (result.length() > maxLength) {
// trim result, 1st step (cut at right side)
result = result.substring(0, maxpos).trim() + " [..]";
}
if (result.length() > maxLength) {
// trim result, 2nd step (cut at left side)
result = "[..] " + result.substring(minpos).trim();
}
if (result.length() > maxLength) {
// trim result, 3rd step (cut in the middle)
result = result.substring(6, 20).trim() + " [..] " + result.substring(result.length() - 26, result.length() - 6).trim();
}
if (queryhashes.size() == 0) return result;
// the result has not all words in it.
// find another sentence that represents the missing other words
// and find recursively more sentences
maxLength = maxLength - result.length();
if (maxLength < 20) maxLength = 20;
String nextSnippet = computeSnippet(sentences, queryhashes, minLength, maxLength);
return result + ((nextSnippet == null) ? "" : (" / " + nextSnippet));
}
| private String computeSnippet(String[] sentences, Set queryhashes, int minLength, int maxLength) {
if ((sentences == null) || (sentences.length == 0)) return null;
if ((queryhashes == null) || (queryhashes.size() == 0)) return null;
kelondroMScoreCluster hitTable = new kelondroMScoreCluster();
Iterator j;
HashMap hs;
String hash;
for (int i = 0; i < sentences.length; i++) {
//System.out.println("Sentence " + i + ": " + sentences[i]);
if (sentences[i].length() > minLength) {
hs = hashSentence(sentences[i]);
j = queryhashes.iterator();
while (j.hasNext()) {
hash = (String) j.next();
if (hs.containsKey(hash)) {
//System.out.println("hash " + hash + " appears in line " + i);
hitTable.incScore(new Integer(i));
}
}
}
}
int score = hitTable.getMaxScore(); // best number of hits
if (score <= 0) return null;
// we found (a) line(s) that have <score> hits.
// now find the shortest line of these hits
int shortLineIndex = -1;
int shortLineLength = Integer.MAX_VALUE;
for (int i = 0; i < sentences.length; i++) {
if ((hitTable.getScore(new Integer(i)) == score) &&
(sentences[i].length() < shortLineLength)) {
shortLineIndex = i;
shortLineLength = sentences[i].length();
}
}
// find a first result
String result = sentences[shortLineIndex];
// remove all hashes that appear in the result
hs = hashSentence(result);
j = queryhashes.iterator();
Integer pos;
Set remaininghashes = new HashSet();
int p, minpos = result.length(), maxpos = -1;
while (j.hasNext()) {
hash = (String) j.next();
pos = (Integer) hs.get(hash);
if (pos == null) {
remaininghashes.add(hash);
} else {
p = pos.intValue();
if (p > maxpos) maxpos = p;
if (p < minpos) minpos = p;
}
}
// check result size
maxpos = maxpos + 10;
if (maxpos > result.length()) maxpos = result.length();
if (minpos < 0) minpos = 0;
// we have a result, but is it short enough?
if (maxpos - minpos + 10 > maxLength) {
// the string is too long, even if we cut at both ends
// so cut here in the middle of the string
int lenb = result.length();
result = result.substring(0, (minpos + 20 > result.length()) ? result.length() : minpos + 20).trim() +
" [..] " +
result.substring((maxpos + 26 > result.length()) ? result.length() : maxpos + 26).trim();
maxpos = maxpos + lenb - result.length() + 6;
}
if (maxpos > maxLength) {
// the string is too long, even if we cut it at the end
// so cut it here at both ends at once
int newlen = maxpos - minpos + 10;
int around = (maxLength - newlen) / 2;
result = "[..] " + result.substring(minpos - around, ((maxpos + around) > result.length()) ? result.length() : (maxpos + around)).trim() + " [..]";
minpos = around;
maxpos = result.length() - around - 5;
}
if (result.length() > maxLength) {
// trim result, 1st step (cut at right side)
result = result.substring(0, maxpos).trim() + " [..]";
}
if (result.length() > maxLength) {
// trim result, 2nd step (cut at left side)
result = "[..] " + result.substring(minpos).trim();
}
if (result.length() > maxLength) {
// trim result, 3rd step (cut in the middle)
result = result.substring(6, 20).trim() + " [..] " + result.substring(result.length() - 26, result.length() - 6).trim();
}
if (queryhashes.size() == 0) return result;
// the result has not all words in it.
// find another sentence that represents the missing other words
// and find recursively more sentences
maxLength = maxLength - result.length();
if (maxLength < 20) maxLength = 20;
String nextSnippet = computeSnippet(sentences, remaininghashes, minLength, maxLength);
return result + ((nextSnippet == null) ? "" : (" / " + nextSnippet));
}
|
diff --git a/orbisgis-view/src/main/java/org/orbisgis/view/toc/actions/cui/legends/PnlRule.java b/orbisgis-view/src/main/java/org/orbisgis/view/toc/actions/cui/legends/PnlRule.java
index 5bd0cd4c5..407189450 100644
--- a/orbisgis-view/src/main/java/org/orbisgis/view/toc/actions/cui/legends/PnlRule.java
+++ b/orbisgis-view/src/main/java/org/orbisgis/view/toc/actions/cui/legends/PnlRule.java
@@ -1,314 +1,314 @@
/**
* OrbisGIS is a GIS application dedicated to scientific spatial simulation.
* This cross-platform GIS is developed at French IRSTV institute and is able to
* manipulate and create vector and raster spatial information.
*
* OrbisGIS is distributed under GPL 3 license. It is produced by the "Atelier SIG"
* team of the IRSTV Institute <http://www.irstv.fr/> CNRS FR 2488.
*
* Copyright (C) 2007-2012 IRSTV (FR CNRS 2488)
*
* This file is part of OrbisGIS.
*
* OrbisGIS is free software: you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later
* version.
*
* OrbisGIS is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* OrbisGIS. If not, see <http://www.gnu.org/licenses/>.
*
* For more information, please consult: <http://www.orbisgis.org/>
* or contact directly:
* info_at_ orbisgis.org
*/
package org.orbisgis.view.toc.actions.cui.legends;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusListener;
import java.awt.event.KeyListener;
import java.beans.EventHandler;
import javax.swing.*;
import org.orbisgis.core.map.MapTransform;
import org.orbisgis.core.renderer.se.Rule;
import org.orbisgis.view.toc.actions.cui.LegendContext;
import org.orbisgis.view.toc.actions.cui.legend.ISELegendPanel;
import org.xnap.commons.i18n.I18n;
import org.xnap.commons.i18n.I18nFactory;
/**
* Panel associated to {@code Rule} instances in the legend edition UI.
* @author Alexis Guéganno
*/
public class PnlRule extends JPanel implements ISELegendPanel {
private static final I18n I18N = I18nFactory.getI18n(PnlRule.class);
private JButton btnCurrentScaleToMin;
private JButton btnCurrentScaleToMax;
private JTextField txtMinScale;
private JTextField txtMaxScale;
private JTextField txtName;
private JTextArea txtDescription;
private Rule rule;
private LegendContext legendContext;
private String id;
/**
* Sets the Rule associated to this panel.
*
* @param r
*/
public void setRule(Rule r) {
rule = r;
}
/**
* Gets the Rule associated to this panel.
*
* @return
*/
public Rule getRule() {
return rule;
}
@Override
public Component getComponent() {
removeAll();
FlowLayout fl = new FlowLayout();
fl.setVgap(0);
this.setLayout(fl);
//We need the map transform to use the buttons
final MapTransform mt = legendContext.getCurrentMapTransform();
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
//We display the title
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.LINE_START;
panel.add(new JLabel(I18N.tr("Title : ")), gbc);
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.LINE_START;
txtName = new JTextField(rule.getName(), 10);
txtName.addFocusListener(EventHandler.create(FocusListener.class, this, "setTitle", "source.text", "focusLost"));
panel.add(txtName, gbc);
//We display the description
//Label
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 1;
gbc.anchor = GridBagConstraints.LINE_START;
panel.add(new JLabel("Description : "), gbc);
//Text field
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 1;
gbc.insets = new Insets(5, 5, 5, 5);
gbc.anchor = GridBagConstraints.LINE_START;
txtDescription = new JTextArea("");
txtDescription.setColumns(40);
txtDescription.setRows(6);
txtDescription.setLineWrap(true);
txtDescription.addFocusListener(EventHandler.create(
FocusListener.class, this, "setDescription", "source.text", "focusLost"));
JScrollPane jsp = new JScrollPane(txtDescription);
jsp.setPreferredSize(txtDescription.getPreferredSize());
panel.add(jsp, gbc);
//We display the minScale
KeyListener keyAdapter = EventHandler.create(KeyListener.class, this, "applyScales");
//Text
//We put the text field and the button in a single panel in order to
JPanel min = new JPanel();
FlowLayout flowMin = new FlowLayout();
flowMin.setHgap(5);
min.setLayout(flowMin);
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 2;
gbc.anchor = GridBagConstraints.LINE_START;
panel.add(new JLabel(I18N.tr("Min. scale :")), gbc);
//Text field
txtMinScale = new JTextField(10);
txtMinScale.addKeyListener(keyAdapter);
txtMinScale.setText(getMinscale());
min.add(txtMinScale);
//Button
btnCurrentScaleToMin = new JButton(I18N.tr("Current scale"));
btnCurrentScaleToMin.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
txtMinScale.setText(Integer.toString((int) mt.getScaleDenominator()));
applyScales();
}
});
min.add(btnCurrentScaleToMin);
//We add this dedicated panel to our GridBagLayout.
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 2;
gbc.anchor = GridBagConstraints.LINE_START;
panel.add(min, gbc);
//We display the maxScale
//Text
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 3;
gbc.anchor = GridBagConstraints.LINE_START;
panel.add(new JLabel(I18N.tr("Max. scale :")), gbc);
//We put the text field and the button in a single panel in order to
//improve the UI.
//Text field
JPanel max = new JPanel();
FlowLayout flowMax = new FlowLayout();
flowMax.setHgap(5);
max.setLayout(flowMax);
txtMaxScale = new JTextField(10);
txtMaxScale.addKeyListener(keyAdapter);
txtMaxScale.setText(getMaxscale());
max.add(txtMaxScale, gbc);
//Button
btnCurrentScaleToMax = new JButton(I18N.tr("Current scale"));
btnCurrentScaleToMax.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
txtMaxScale.setText(Integer.toString((int) mt.getScaleDenominator()));
applyScales();
}
});
max.add(btnCurrentScaleToMax);
//We add this dedicated panel to our GridBagLayout.
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 3;
gbc.anchor = GridBagConstraints.LINE_START;
panel.add(max, gbc);
this.add(panel);
this.setPreferredSize(new Dimension(200, 100));
- this.setBorder(BorderFactory.createTitledBorder(I18N.tr("Scale")));
+ this.setBorder(BorderFactory.createTitledBorder(I18N.tr("Rule Configuration")));
return this;
}
@Override
public void initialize(LegendContext lc) {
legendContext = lc;
getComponent();
}
@Override
public ISELegendPanel newInstance() {
return new PnlRule();
}
@Override
public String getId() {
return id;
}
@Override
public void setId(String id) {
this.id = id;
}
/**
* Apply to the Rule's name the text contained in the editor used to
* manage it.
*/
public void setTitle(String s) {
rule.setName(s);
}
/**
* Apply to the Rule's description the text contained in the editor used
* to manage it.
*/
public void setDescription(String s) {
rule.setDescription(null);
}
/**
* Apply the scales registered in the text fields of this panel to the
* underlying {@code Rule}.
*/
public void applyScales() {
String minScale = txtMinScale.getText();
if (minScale.trim().length() != 0) {
try {
Double min = Double.parseDouble(minScale);
rule.setMinScaleDenom(min);
} catch (NumberFormatException e1) {
}
} else {
rule.setMinScaleDenom(Double.NEGATIVE_INFINITY);
}
String maxScale = txtMaxScale.getText();
if (maxScale.trim().length() != 0) {
try {
Double max = Double.parseDouble(maxScale);
rule.setMaxScaleDenom(max);
} catch (NumberFormatException e1) {
}
} else {
rule.setMaxScaleDenom(Double.POSITIVE_INFINITY);
}
}
@Override
public String validateInput() {
String minScale = txtMinScale.getText();
String maxScale = txtMaxScale.getText();
StringBuilder stringBuilder = new StringBuilder();
if (minScale.trim().length() != 0) {
try {
Integer.parseInt(minScale);
} catch (NumberFormatException e) {
stringBuilder.append(I18N.tr("Min. scale is not a valid number"));
}
}
if (maxScale.trim().length() != 0) {
try {
Integer.parseInt(maxScale);
} catch (NumberFormatException e) {
stringBuilder.append("\n");
stringBuilder.append(I18N.tr("Max. scale is not a valid number"));
}
}
String res = stringBuilder.toString();
if (res != null && !res.isEmpty()) {
return res;
} else {
return null;
}
}
private String getMinscale() {
if (rule.getMinScaleDenom() != null && rule.getMinScaleDenom() > Double.NEGATIVE_INFINITY) {
Double d = rule.getMinScaleDenom();
Integer i = d.intValue();
return i.toString();
} else {
return "";
}
}
private String getMaxscale() {
if (rule.getMaxScaleDenom() != null && rule.getMaxScaleDenom() < Double.POSITIVE_INFINITY) {
Double d = rule.getMaxScaleDenom();
Integer i = d.intValue();
return i.toString();
} else {
return "";
}
}
}
| true | true | public Component getComponent() {
removeAll();
FlowLayout fl = new FlowLayout();
fl.setVgap(0);
this.setLayout(fl);
//We need the map transform to use the buttons
final MapTransform mt = legendContext.getCurrentMapTransform();
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
//We display the title
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.LINE_START;
panel.add(new JLabel(I18N.tr("Title : ")), gbc);
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.LINE_START;
txtName = new JTextField(rule.getName(), 10);
txtName.addFocusListener(EventHandler.create(FocusListener.class, this, "setTitle", "source.text", "focusLost"));
panel.add(txtName, gbc);
//We display the description
//Label
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 1;
gbc.anchor = GridBagConstraints.LINE_START;
panel.add(new JLabel("Description : "), gbc);
//Text field
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 1;
gbc.insets = new Insets(5, 5, 5, 5);
gbc.anchor = GridBagConstraints.LINE_START;
txtDescription = new JTextArea("");
txtDescription.setColumns(40);
txtDescription.setRows(6);
txtDescription.setLineWrap(true);
txtDescription.addFocusListener(EventHandler.create(
FocusListener.class, this, "setDescription", "source.text", "focusLost"));
JScrollPane jsp = new JScrollPane(txtDescription);
jsp.setPreferredSize(txtDescription.getPreferredSize());
panel.add(jsp, gbc);
//We display the minScale
KeyListener keyAdapter = EventHandler.create(KeyListener.class, this, "applyScales");
//Text
//We put the text field and the button in a single panel in order to
JPanel min = new JPanel();
FlowLayout flowMin = new FlowLayout();
flowMin.setHgap(5);
min.setLayout(flowMin);
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 2;
gbc.anchor = GridBagConstraints.LINE_START;
panel.add(new JLabel(I18N.tr("Min. scale :")), gbc);
//Text field
txtMinScale = new JTextField(10);
txtMinScale.addKeyListener(keyAdapter);
txtMinScale.setText(getMinscale());
min.add(txtMinScale);
//Button
btnCurrentScaleToMin = new JButton(I18N.tr("Current scale"));
btnCurrentScaleToMin.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
txtMinScale.setText(Integer.toString((int) mt.getScaleDenominator()));
applyScales();
}
});
min.add(btnCurrentScaleToMin);
//We add this dedicated panel to our GridBagLayout.
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 2;
gbc.anchor = GridBagConstraints.LINE_START;
panel.add(min, gbc);
//We display the maxScale
//Text
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 3;
gbc.anchor = GridBagConstraints.LINE_START;
panel.add(new JLabel(I18N.tr("Max. scale :")), gbc);
//We put the text field and the button in a single panel in order to
//improve the UI.
//Text field
JPanel max = new JPanel();
FlowLayout flowMax = new FlowLayout();
flowMax.setHgap(5);
max.setLayout(flowMax);
txtMaxScale = new JTextField(10);
txtMaxScale.addKeyListener(keyAdapter);
txtMaxScale.setText(getMaxscale());
max.add(txtMaxScale, gbc);
//Button
btnCurrentScaleToMax = new JButton(I18N.tr("Current scale"));
btnCurrentScaleToMax.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
txtMaxScale.setText(Integer.toString((int) mt.getScaleDenominator()));
applyScales();
}
});
max.add(btnCurrentScaleToMax);
//We add this dedicated panel to our GridBagLayout.
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 3;
gbc.anchor = GridBagConstraints.LINE_START;
panel.add(max, gbc);
this.add(panel);
this.setPreferredSize(new Dimension(200, 100));
this.setBorder(BorderFactory.createTitledBorder(I18N.tr("Scale")));
return this;
}
| public Component getComponent() {
removeAll();
FlowLayout fl = new FlowLayout();
fl.setVgap(0);
this.setLayout(fl);
//We need the map transform to use the buttons
final MapTransform mt = legendContext.getCurrentMapTransform();
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
//We display the title
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.LINE_START;
panel.add(new JLabel(I18N.tr("Title : ")), gbc);
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.LINE_START;
txtName = new JTextField(rule.getName(), 10);
txtName.addFocusListener(EventHandler.create(FocusListener.class, this, "setTitle", "source.text", "focusLost"));
panel.add(txtName, gbc);
//We display the description
//Label
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 1;
gbc.anchor = GridBagConstraints.LINE_START;
panel.add(new JLabel("Description : "), gbc);
//Text field
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 1;
gbc.insets = new Insets(5, 5, 5, 5);
gbc.anchor = GridBagConstraints.LINE_START;
txtDescription = new JTextArea("");
txtDescription.setColumns(40);
txtDescription.setRows(6);
txtDescription.setLineWrap(true);
txtDescription.addFocusListener(EventHandler.create(
FocusListener.class, this, "setDescription", "source.text", "focusLost"));
JScrollPane jsp = new JScrollPane(txtDescription);
jsp.setPreferredSize(txtDescription.getPreferredSize());
panel.add(jsp, gbc);
//We display the minScale
KeyListener keyAdapter = EventHandler.create(KeyListener.class, this, "applyScales");
//Text
//We put the text field and the button in a single panel in order to
JPanel min = new JPanel();
FlowLayout flowMin = new FlowLayout();
flowMin.setHgap(5);
min.setLayout(flowMin);
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 2;
gbc.anchor = GridBagConstraints.LINE_START;
panel.add(new JLabel(I18N.tr("Min. scale :")), gbc);
//Text field
txtMinScale = new JTextField(10);
txtMinScale.addKeyListener(keyAdapter);
txtMinScale.setText(getMinscale());
min.add(txtMinScale);
//Button
btnCurrentScaleToMin = new JButton(I18N.tr("Current scale"));
btnCurrentScaleToMin.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
txtMinScale.setText(Integer.toString((int) mt.getScaleDenominator()));
applyScales();
}
});
min.add(btnCurrentScaleToMin);
//We add this dedicated panel to our GridBagLayout.
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 2;
gbc.anchor = GridBagConstraints.LINE_START;
panel.add(min, gbc);
//We display the maxScale
//Text
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 3;
gbc.anchor = GridBagConstraints.LINE_START;
panel.add(new JLabel(I18N.tr("Max. scale :")), gbc);
//We put the text field and the button in a single panel in order to
//improve the UI.
//Text field
JPanel max = new JPanel();
FlowLayout flowMax = new FlowLayout();
flowMax.setHgap(5);
max.setLayout(flowMax);
txtMaxScale = new JTextField(10);
txtMaxScale.addKeyListener(keyAdapter);
txtMaxScale.setText(getMaxscale());
max.add(txtMaxScale, gbc);
//Button
btnCurrentScaleToMax = new JButton(I18N.tr("Current scale"));
btnCurrentScaleToMax.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
txtMaxScale.setText(Integer.toString((int) mt.getScaleDenominator()));
applyScales();
}
});
max.add(btnCurrentScaleToMax);
//We add this dedicated panel to our GridBagLayout.
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 3;
gbc.anchor = GridBagConstraints.LINE_START;
panel.add(max, gbc);
this.add(panel);
this.setPreferredSize(new Dimension(200, 100));
this.setBorder(BorderFactory.createTitledBorder(I18N.tr("Rule Configuration")));
return this;
}
|
diff --git a/nuxeo-platform-webapp-base/src/main/java/org/nuxeo/ecm/webapp/delegate/DocumentManagerBusinessDelegate.java b/nuxeo-platform-webapp-base/src/main/java/org/nuxeo/ecm/webapp/delegate/DocumentManagerBusinessDelegate.java
index 3b89a009..58bd8e90 100644
--- a/nuxeo-platform-webapp-base/src/main/java/org/nuxeo/ecm/webapp/delegate/DocumentManagerBusinessDelegate.java
+++ b/nuxeo-platform-webapp-base/src/main/java/org/nuxeo/ecm/webapp/delegate/DocumentManagerBusinessDelegate.java
@@ -1,174 +1,175 @@
/*
* (C) Copyright 2006-2008 Nuxeo SAS (http://nuxeo.com/) and contributors.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser General Public License
* (LGPL) version 2.1 which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl.html
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* Contributors:
* Razvan Caraghin
* Olivier Grisel
* Thierry Delprat
* Florent Guillaume
*/
package org.nuxeo.ecm.webapp.delegate;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import javax.annotation.security.PermitAll;
import javax.ejb.EJBAccessException;
import javax.security.auth.login.LoginContext;
import javax.security.auth.login.LoginException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jboss.seam.Component;
import org.jboss.seam.annotations.Destroy;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.annotations.Unwrap;
import org.jboss.seam.contexts.Lifecycle;
import org.jboss.seam.core.Manager;
import org.nuxeo.ecm.core.api.ClientException;
import org.nuxeo.ecm.core.api.CoreSession;
import org.nuxeo.ecm.core.api.repository.Repository;
import org.nuxeo.ecm.core.api.repository.RepositoryManager;
import org.nuxeo.ecm.platform.util.RepositoryLocation;
import org.nuxeo.runtime.api.Framework;
import static org.jboss.seam.ScopeType.CONVERSATION;
/**
* Acquires a {@link CoreSession} connection.
*
* @author Razvan Caraghin
* @author Olivier Grisel
* @author Thierry Delprat
* @author Florent Guillaume
*/
@Name("documentManager")
@Scope(CONVERSATION)
public class DocumentManagerBusinessDelegate implements Serializable {
private static final long serialVersionUID = 1L;
private static final Log log = LogFactory.getLog(DocumentManagerBusinessDelegate.class);
@In(value = "org.jboss.seam.core.manager")
public transient Manager conversationManager;
/**
* Map holding the open session for each repository location.
*/
protected final Map<RepositoryLocation, CoreSession> sessions = new HashMap<RepositoryLocation, CoreSession>();
public void initialize() {
log.debug("Seam component initialized...");
}
@Unwrap
public CoreSession getDocumentManager() throws ClientException {
/*
* Explicit lookup, as this method is the only user of the Seam
* component. Also, in some cases (Seam remoting), it seems that the
* injection is not done correctly.
*/
RepositoryLocation currentServerLocation = (RepositoryLocation) Component.getInstance("currentServerLocation");
return getDocumentManager(currentServerLocation);
}
public CoreSession getDocumentManager(RepositoryLocation serverLocation)
throws ClientException {
if (serverLocation == null) {
if (Framework.getProperty("org.nuxeo.conversation.error.log") != null) {
String errorMessage = String.format(
"serverLocation is null. Current ConversationId: %s; LongRunningConversation: %b",
conversationManager.getCurrentConversationId(),
conversationManager.isLongRunningConversation());
log.error(errorMessage);
- log.error(Thread.currentThread().getStackTrace());
+ Exception e = new Exception("serverLocation is null");
+ log.error(e, e);
}
/*
* currentServerLocation (factory in ServerContextBean) is set
* through navigationContext, which itself injects documentManager,
* so it will be null the first time.
*/
return null;
}
CoreSession session = sessions.get(serverLocation);
if (session == null) {
if (Lifecycle.isDestroying()) {
/*
* During Seam component destroy phases, we don't want to
* recreate a core session just for injection. This happens
* during logout when the session context is destroyed; we don't
* want to cause EJB calls in this case as the authentication
* wouldn't work.
*/
return null;
}
String serverName = serverLocation.getName();
try {
RepositoryManager repositoryManager = Framework.getService(RepositoryManager.class);
Repository repository = repositoryManager.getRepository(serverName);
session = repository.open();
log.debug("Opened session for repository " + serverName);
} catch (Exception e) {
throw new ClientException(
"Error opening session for repository " + serverName, e);
}
sessions.put(serverLocation, session);
}
return session;
}
@Destroy
@PermitAll
public void remove() {
for (Entry<RepositoryLocation, CoreSession> entry : sessions.entrySet()) {
String serverName = entry.getKey().getName();
CoreSession session = entry.getValue();
try {
Repository.close(session);
log.debug("Closed session for repository " + serverName);
} catch (EJBAccessException e) {
log.debug("EJBAccessException while closing session for repository "
+ serverName);
LoginContext lc = null;
try {
lc = Framework.login();
Repository.close(session);
} catch (LoginException le) {
log.error("Unable to login as System", le);
} finally {
if (lc != null) {
try {
lc.logout();
} catch (LoginException lo) {
log.error("Error when loggin out", lo);
}
}
}
} catch (Exception e) {
log.error("Error closing session for repository " + serverName,
e);
}
}
sessions.clear();
}
}
| true | true | public CoreSession getDocumentManager(RepositoryLocation serverLocation)
throws ClientException {
if (serverLocation == null) {
if (Framework.getProperty("org.nuxeo.conversation.error.log") != null) {
String errorMessage = String.format(
"serverLocation is null. Current ConversationId: %s; LongRunningConversation: %b",
conversationManager.getCurrentConversationId(),
conversationManager.isLongRunningConversation());
log.error(errorMessage);
log.error(Thread.currentThread().getStackTrace());
}
/*
* currentServerLocation (factory in ServerContextBean) is set
* through navigationContext, which itself injects documentManager,
* so it will be null the first time.
*/
return null;
}
CoreSession session = sessions.get(serverLocation);
if (session == null) {
if (Lifecycle.isDestroying()) {
/*
* During Seam component destroy phases, we don't want to
* recreate a core session just for injection. This happens
* during logout when the session context is destroyed; we don't
* want to cause EJB calls in this case as the authentication
* wouldn't work.
*/
return null;
}
String serverName = serverLocation.getName();
try {
RepositoryManager repositoryManager = Framework.getService(RepositoryManager.class);
Repository repository = repositoryManager.getRepository(serverName);
session = repository.open();
log.debug("Opened session for repository " + serverName);
} catch (Exception e) {
throw new ClientException(
"Error opening session for repository " + serverName, e);
}
sessions.put(serverLocation, session);
}
return session;
}
| public CoreSession getDocumentManager(RepositoryLocation serverLocation)
throws ClientException {
if (serverLocation == null) {
if (Framework.getProperty("org.nuxeo.conversation.error.log") != null) {
String errorMessage = String.format(
"serverLocation is null. Current ConversationId: %s; LongRunningConversation: %b",
conversationManager.getCurrentConversationId(),
conversationManager.isLongRunningConversation());
log.error(errorMessage);
Exception e = new Exception("serverLocation is null");
log.error(e, e);
}
/*
* currentServerLocation (factory in ServerContextBean) is set
* through navigationContext, which itself injects documentManager,
* so it will be null the first time.
*/
return null;
}
CoreSession session = sessions.get(serverLocation);
if (session == null) {
if (Lifecycle.isDestroying()) {
/*
* During Seam component destroy phases, we don't want to
* recreate a core session just for injection. This happens
* during logout when the session context is destroyed; we don't
* want to cause EJB calls in this case as the authentication
* wouldn't work.
*/
return null;
}
String serverName = serverLocation.getName();
try {
RepositoryManager repositoryManager = Framework.getService(RepositoryManager.class);
Repository repository = repositoryManager.getRepository(serverName);
session = repository.open();
log.debug("Opened session for repository " + serverName);
} catch (Exception e) {
throw new ClientException(
"Error opening session for repository " + serverName, e);
}
sessions.put(serverLocation, session);
}
return session;
}
|
diff --git a/Toolbox/src/biz/shadowservices/DegreesToolbox/DataFetcher.java b/Toolbox/src/biz/shadowservices/DegreesToolbox/DataFetcher.java
index c856127..f259f15 100644
--- a/Toolbox/src/biz/shadowservices/DegreesToolbox/DataFetcher.java
+++ b/Toolbox/src/biz/shadowservices/DegreesToolbox/DataFetcher.java
@@ -1,436 +1,436 @@
/*******************************************************************************
* Copyright (c) 2011 Jordan Thoms.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
package biz.shadowservices.DegreesToolbox;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.message.BasicNameValuePair;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import de.quist.app.errorreporter.ExceptionReporter;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.preference.PreferenceManager;
import android.util.Log;
public class DataFetcher {
// This class handles the actual fetching of the data from 2Degrees.
public double result;
public static final String LASTMONTHCHARGES = "Your last month's charges";
private static String TAG = "2DegreesDataFetcher";
private ExceptionReporter exceptionReporter;
public enum FetchResult {
SUCCESS,
NOTONLINE,
LOGINFAILED,
USERNAMEPASSWORDNOTSET,
NETWORKERROR,
NOTALLOWED
}
public DataFetcher(ExceptionReporter e) {
exceptionReporter = e;
}
public boolean isOnline(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
if (info == null) {
return false;
} else {
return info.isConnected();
}
}
public boolean isWifi(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (info == null) {
return false;
} else {
return info.isConnected();
}
}
public boolean isRoaming(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (info == null) {
return false;
} else {
return info.isRoaming();
}
}
public boolean isBackgroundDataEnabled(Context context) {
ConnectivityManager mgr = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
return(mgr.getBackgroundDataSetting());
}
public boolean isAutoSyncEnabled() {
// Get the autosync setting, if on a phone which has one.
// There are better ways of doing this than reflection, but it's easy in this case
// since then we can keep linking against the 1.6 SDK.
if (android.os.Build.VERSION.SDK_INT >= 5) {
Class<ContentResolver> contentResolverClass = ContentResolver.class;
try {
Method m = contentResolverClass.getMethod("getMasterSyncAutomatically", null);
Log.d(TAG, m.toString());
Log.d(TAG, m.invoke(null, null).toString());
boolean bool = ((Boolean)m.invoke(null, null)).booleanValue();
return bool;
} catch (Exception e) {
Log.d(TAG, "could not determine if autosync is enabled, assuming yes");
return true;
}
} else {
return true;
}
}
public FetchResult updateData(Context context, boolean force) {
//Open database
DBOpenHelper dbhelper = new DBOpenHelper(context);
SQLiteDatabase db = dbhelper.getWritableDatabase();
// check for internet connectivity
try {
if (!isOnline(context)) {
Log.d(TAG, "We do not seem to be online. Skipping Update.");
return FetchResult.NOTONLINE;
}
} catch (Exception e) {
exceptionReporter.reportException(Thread.currentThread(), e, "Exception during isOnline()");
}
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
if (!force) {
try {
if (sp.getBoolean("loginFailed", false) == true) {
Log.d(TAG, "Previous login failed. Skipping Update.");
DBLog.insertMessage(context, "i", TAG, "Previous login failed. Skipping Update.");
return FetchResult.LOGINFAILED;
}
if(sp.getBoolean("autoupdates", true) == false) {
Log.d(TAG, "Automatic updates not enabled. Skipping Update.");
DBLog.insertMessage(context, "i", TAG, "Automatic updates not enabled. Skipping Update.");
return FetchResult.NOTALLOWED;
}
if (!isBackgroundDataEnabled(context) && sp.getBoolean("obeyBackgroundData", true)) {
Log.d(TAG, "Background data not enabled. Skipping Update.");
DBLog.insertMessage(context, "i", TAG, "Background data not enabled. Skipping Update.");
return FetchResult.NOTALLOWED;
}
if (!isAutoSyncEnabled() && sp.getBoolean("obeyAutoSync", true) && sp.getBoolean("obeyBackgroundData", true)) {
Log.d(TAG, "Auto sync not enabled. Skipping Update.");
DBLog.insertMessage(context, "i", TAG, "Auto sync not enabled. Skipping Update.");
return FetchResult.NOTALLOWED;
}
if (isWifi(context) && !sp.getBoolean("wifiUpdates", true)) {
Log.d(TAG, "On wifi, and wifi auto updates not allowed. Skipping Update");
DBLog.insertMessage(context, "i", TAG, "On wifi, and wifi auto updates not allowed. Skipping Update");
return FetchResult.NOTALLOWED;
} else if (!isWifi(context)){
Log.d(TAG, "We are not on wifi.");
if (!isRoaming(context) && !sp.getBoolean("2DData", true)) {
Log.d(TAG, "Automatic updates on 2Degrees data not enabled. Skipping Update.");
DBLog.insertMessage(context, "i", TAG, "Automatic updates on 2Degrees data not enabled. Skipping Update.");
return FetchResult.NOTALLOWED;
} else if (isRoaming(context) && !sp.getBoolean("roamingData", false)) {
Log.d(TAG, "Automatic updates on roaming mobile data not enabled. Skipping Update.");
DBLog.insertMessage(context, "i", TAG, "Automatic updates on roaming mobile data not enabled. Skipping Update.");
return FetchResult.NOTALLOWED;
}
}
} catch (Exception e) {
exceptionReporter.reportException(Thread.currentThread(), e, "Exception while finding if to update.");
}
} else {
Log.d(TAG, "Update Forced");
}
try {
String username = sp.getString("username", null);
String password = sp.getString("password", null);
if(username == null || password == null) {
DBLog.insertMessage(context, "i", TAG, "Username or password not set.");
return FetchResult.USERNAMEPASSWORDNOTSET;
}
// Find the URL of the page to send login data to.
Log.d(TAG, "Finding Action. ");
HttpGetter loginPageGet = new HttpGetter("https://secure.2degreesmobile.co.nz/web/ip/login");
String loginPageString = loginPageGet.execute();
if (loginPageString != null) {
Document loginPage = Jsoup.parse(loginPageString, "https://secure.2degreesmobile.co.nz/web/ip/login");
Element loginForm = loginPage.getElementsByAttributeValue("name", "loginFrm").first();
String loginAction = loginForm.attr("action");
// Send login form
List<NameValuePair> loginValues = new ArrayList <NameValuePair>();
loginValues.add(new BasicNameValuePair("externalURLRedirect", ""));
- loginValues.add(new BasicNameValuePair("hdnAction", "login"));
+ loginValues.add(new BasicNameValuePair("hdnAction", "login_userlogin"));
loginValues.add(new BasicNameValuePair("hdnAuthenticationType", "M"));
loginValues.add(new BasicNameValuePair("hdnlocale", ""));
loginValues.add(new BasicNameValuePair("userid", username));
loginValues.add(new BasicNameValuePair("password", password));
Log.d(TAG, "Sending Login ");
HttpPoster sendLoginPoster = new HttpPoster(loginAction, loginValues);
// Parse result
Document homePage = Jsoup.parse(sendLoginPoster.execute());
// Determine if this is a pre-pay or post-paid account.
boolean postPaid;
if (homePage.getElementById("p_p_id_PostPaidHomePage_WAR_Homepage_") == null) {
Log.d(TAG, "Pre-pay account or no account.");
postPaid = false;
} else {
Log.d(TAG, "Post-paid account.");
postPaid = true;
}
Element accountSummary = homePage.getElementById("accountSummary");
if (accountSummary == null) {
Log.d(TAG, "Login failed.");
return FetchResult.LOGINFAILED;
}
db.delete("cache", "", null);
/* This code fetched some extra details for postpaid users, but on reflection they aren't that useful.
* Might reconsider this.
*
if (postPaid) {
Element accountBalanceSummaryTable = accountSummary.getElementsByClass("tableBillSummary").first();
Elements rows = accountBalanceSummaryTable.getElementsByTag("tr");
int rowno = 0;
for (Element row : rows) {
if (rowno > 1) {
break;
}
//Log.d(TAG, "Starting row");
//Log.d(TAG, row.html());
Double value;
try {
Element amount = row.getElementsByClass("tableBillamount").first();
String amountHTML = amount.html();
Log.d(TAG, amountHTML.substring(1));
value = Double.parseDouble(amountHTML.substring(1));
} catch (Exception e) {
Log.d(TAG, "Failed to parse amount from row.");
value = null;
}
String expiresDetails = "";
String expiresDate = null;
String name = null;
try {
Element details = row.getElementsByClass("tableBilldetail").first();
name = details.ownText();
Element expires = details.getElementsByTag("em").first();
if (expires != null) {
expiresDetails = expires.text();
}
Log.d(TAG, expiresDetails);
Pattern pattern;
pattern = Pattern.compile("\\(payment is due (.*)\\)");
Matcher matcher = pattern.matcher(expiresDetails);
if (matcher.find()) {
/*Log.d(TAG, "matched expires");
Log.d(TAG, "group 0:" + matcher.group(0));
Log.d(TAG, "group 1:" + matcher.group(1));
Log.d(TAG, "group 2:" + matcher.group(2)); *
String expiresDateString = matcher.group(1);
Date expiresDateObj;
if (expiresDateString != null) {
if (expiresDateString.length() > 0) {
try {
expiresDateObj = DateFormatters.EXPIRESDATE.parse(expiresDateString);
expiresDate = DateFormatters.ISO8601DATEONLYFORMAT.format(expiresDateObj);
} catch (java.text.ParseException e) {
Log.d(TAG, "Could not parse date: " + expiresDateString);
}
}
}
}
} catch (Exception e) {
Log.d(TAG, "Failed to parse details from row.");
}
String expirev = null;
ContentValues values = new ContentValues();
values.put("name", name);
values.put("value", value);
values.put("units", "$NZ");
values.put("expires_value", expirev );
values.put("expires_date", expiresDate);
db.insert("cache", "value", values );
rowno++;
}
} */
Element accountSummaryTable = accountSummary.getElementsByClass("tableAccountSummary").first();
Elements rows = accountSummaryTable.getElementsByTag("tr");
for (Element row : rows) {
// We are now looking at each of the rows in the data table.
//Log.d(TAG, "Starting row");
//Log.d(TAG, row.html());
Double value;
String units;
try {
Element amount = row.getElementsByClass("tableBillamount").first();
String amountHTML = amount.html();
//Log.d(TAG, amountHTML);
String[] amountParts = amountHTML.split(" ", 2);
//Log.d(TAG, amountParts[0]);
//Log.d(TAG, amountParts[1]);
if (amountParts[0].contains("Included") || amountParts[0].equals("All You Need")) {
value = Values.INCLUDED;
} else {
try {
value = Double.parseDouble(amountParts[0]);
} catch (NumberFormatException e) {
exceptionReporter.reportException(Thread.currentThread(), e, "Decoding value.");
value = 0.0;
}
}
units = amountParts[1];
} catch (NullPointerException e) {
//Log.d(TAG, "Failed to parse amount from row.");
value = null;
units = null;
}
Element details = row.getElementsByClass("tableBilldetail").first();
String name = details.getElementsByTag("strong").first().text();
Element expires = details.getElementsByTag("em").first();
String expiresDetails = "";
if (expires != null) {
expiresDetails = expires.text();
}
Log.d(TAG, expiresDetails);
Pattern pattern;
if (postPaid == false) {
pattern = Pattern.compile("\\(([\\d\\.]*) ?\\w*? ?expiring on (.*)\\)");
} else {
pattern = Pattern.compile("\\(([\\d\\.]*) ?\\w*? ?will expire on (.*)\\)");
}
Matcher matcher = pattern.matcher(expiresDetails);
Double expiresValue = null;
String expiresDate = null;
if (matcher.find()) {
/*Log.d(TAG, "matched expires");
Log.d(TAG, "group 0:" + matcher.group(0));
Log.d(TAG, "group 1:" + matcher.group(1));
Log.d(TAG, "group 2:" + matcher.group(2)); */
try {
expiresValue = Double.parseDouble(matcher.group(1));
} catch (NumberFormatException e) {
expiresValue = null;
}
String expiresDateString = matcher.group(2);
Date expiresDateObj;
if (expiresDateString != null) {
if (expiresDateString.length() > 0) {
try {
expiresDateObj = DateFormatters.EXPIRESDATE.parse(expiresDateString);
expiresDate = DateFormatters.ISO8601DATEONLYFORMAT.format(expiresDateObj);
} catch (java.text.ParseException e) {
Log.d(TAG, "Could not parse date: " + expiresDateString);
}
}
}
}
ContentValues values = new ContentValues();
values.put("name", name);
values.put("value", value);
values.put("units", units);
values.put("expires_value", expiresValue);
values.put("expires_date", expiresDate);
db.insert("cache", "value", values );
}
if(postPaid == false) {
Log.d(TAG, "Getting Value packs...");
// Find value packs
HttpGetter valuePacksPageGet = new HttpGetter("https://secure.2degreesmobile.co.nz/group/ip/prevaluepack");
String valuePacksPageString = valuePacksPageGet.execute();
//DBLog.insertMessage(context, "d", "", valuePacksPageString);
if(valuePacksPageString != null) {
Document valuePacksPage = Jsoup.parse(valuePacksPageString);
Elements enabledPacks = valuePacksPage.getElementsByClass("yellow");
for (Element enabledPack : enabledPacks) {
Element offerNameElemt = enabledPack.getElementsByAttributeValueStarting("name", "offername").first();
String offerName = offerNameElemt.val();
DBLog.insertMessage(context, "d", "", "Got element: " + offerName);
ValuePack[] packs = Values.valuePacks.get(offerName);
if (packs == null) {
DBLog.insertMessage(context, "d", "", "Offer name: " + offerName + " not matched.");
} else {
for (ValuePack pack: packs) {
// Cursor csr = db.query("cache", null, "name = '" + pack.type.id + "'", null, null, null, null);
// if (csr.getCount() == 1) {
// csr.moveToFirst();
ContentValues values = new ContentValues();
// Not sure why adding on the previous value?
//values.put("plan_startamount", csr.getDouble(4) + pack.value);
//DBLog.insertMessage(context, "d", "", "Pack " + pack.type.id + " start value set to " + csr.getDouble(4) + pack.value);
values.put("plan_startamount", pack.value);
values.put("plan_name", offerName);
DBLog.insertMessage(context, "d", "", "Pack " + pack.type.id + " start value set to " + pack.value);
db.update("cache", values, "name = '" + pack.type.id + "'", null);
// } else {
// DBLog.insertMessage(context, "d", "", "Pack " + pack.type.id + " Couldn't find item to add to");
// }
// csr.close();
}
}
}
}
}
SharedPreferences.Editor prefedit = sp.edit();
Date now = new Date();
prefedit.putString("updateDate", DateFormatters.ISO8601FORMAT.format(now));
prefedit.putBoolean("loginFailed", false);
prefedit.putBoolean("networkError", false);
prefedit.commit();
DBLog.insertMessage(context, "i", TAG, "Update Successful");
return FetchResult.SUCCESS;
}
} catch (ClientProtocolException e) {
DBLog.insertMessage(context, "w", TAG, "Network error: " + e.getMessage());
return FetchResult.NETWORKERROR;
} catch (IOException e) {
DBLog.insertMessage(context, "w", TAG, "Network error: " + e.getMessage());
return FetchResult.NETWORKERROR;
}
finally {
db.close();
}
return null;
}
}
| true | true | public FetchResult updateData(Context context, boolean force) {
//Open database
DBOpenHelper dbhelper = new DBOpenHelper(context);
SQLiteDatabase db = dbhelper.getWritableDatabase();
// check for internet connectivity
try {
if (!isOnline(context)) {
Log.d(TAG, "We do not seem to be online. Skipping Update.");
return FetchResult.NOTONLINE;
}
} catch (Exception e) {
exceptionReporter.reportException(Thread.currentThread(), e, "Exception during isOnline()");
}
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
if (!force) {
try {
if (sp.getBoolean("loginFailed", false) == true) {
Log.d(TAG, "Previous login failed. Skipping Update.");
DBLog.insertMessage(context, "i", TAG, "Previous login failed. Skipping Update.");
return FetchResult.LOGINFAILED;
}
if(sp.getBoolean("autoupdates", true) == false) {
Log.d(TAG, "Automatic updates not enabled. Skipping Update.");
DBLog.insertMessage(context, "i", TAG, "Automatic updates not enabled. Skipping Update.");
return FetchResult.NOTALLOWED;
}
if (!isBackgroundDataEnabled(context) && sp.getBoolean("obeyBackgroundData", true)) {
Log.d(TAG, "Background data not enabled. Skipping Update.");
DBLog.insertMessage(context, "i", TAG, "Background data not enabled. Skipping Update.");
return FetchResult.NOTALLOWED;
}
if (!isAutoSyncEnabled() && sp.getBoolean("obeyAutoSync", true) && sp.getBoolean("obeyBackgroundData", true)) {
Log.d(TAG, "Auto sync not enabled. Skipping Update.");
DBLog.insertMessage(context, "i", TAG, "Auto sync not enabled. Skipping Update.");
return FetchResult.NOTALLOWED;
}
if (isWifi(context) && !sp.getBoolean("wifiUpdates", true)) {
Log.d(TAG, "On wifi, and wifi auto updates not allowed. Skipping Update");
DBLog.insertMessage(context, "i", TAG, "On wifi, and wifi auto updates not allowed. Skipping Update");
return FetchResult.NOTALLOWED;
} else if (!isWifi(context)){
Log.d(TAG, "We are not on wifi.");
if (!isRoaming(context) && !sp.getBoolean("2DData", true)) {
Log.d(TAG, "Automatic updates on 2Degrees data not enabled. Skipping Update.");
DBLog.insertMessage(context, "i", TAG, "Automatic updates on 2Degrees data not enabled. Skipping Update.");
return FetchResult.NOTALLOWED;
} else if (isRoaming(context) && !sp.getBoolean("roamingData", false)) {
Log.d(TAG, "Automatic updates on roaming mobile data not enabled. Skipping Update.");
DBLog.insertMessage(context, "i", TAG, "Automatic updates on roaming mobile data not enabled. Skipping Update.");
return FetchResult.NOTALLOWED;
}
}
} catch (Exception e) {
exceptionReporter.reportException(Thread.currentThread(), e, "Exception while finding if to update.");
}
} else {
Log.d(TAG, "Update Forced");
}
try {
String username = sp.getString("username", null);
String password = sp.getString("password", null);
if(username == null || password == null) {
DBLog.insertMessage(context, "i", TAG, "Username or password not set.");
return FetchResult.USERNAMEPASSWORDNOTSET;
}
// Find the URL of the page to send login data to.
Log.d(TAG, "Finding Action. ");
HttpGetter loginPageGet = new HttpGetter("https://secure.2degreesmobile.co.nz/web/ip/login");
String loginPageString = loginPageGet.execute();
if (loginPageString != null) {
Document loginPage = Jsoup.parse(loginPageString, "https://secure.2degreesmobile.co.nz/web/ip/login");
Element loginForm = loginPage.getElementsByAttributeValue("name", "loginFrm").first();
String loginAction = loginForm.attr("action");
// Send login form
List<NameValuePair> loginValues = new ArrayList <NameValuePair>();
loginValues.add(new BasicNameValuePair("externalURLRedirect", ""));
loginValues.add(new BasicNameValuePair("hdnAction", "login"));
loginValues.add(new BasicNameValuePair("hdnAuthenticationType", "M"));
loginValues.add(new BasicNameValuePair("hdnlocale", ""));
loginValues.add(new BasicNameValuePair("userid", username));
loginValues.add(new BasicNameValuePair("password", password));
Log.d(TAG, "Sending Login ");
HttpPoster sendLoginPoster = new HttpPoster(loginAction, loginValues);
// Parse result
Document homePage = Jsoup.parse(sendLoginPoster.execute());
// Determine if this is a pre-pay or post-paid account.
boolean postPaid;
if (homePage.getElementById("p_p_id_PostPaidHomePage_WAR_Homepage_") == null) {
Log.d(TAG, "Pre-pay account or no account.");
postPaid = false;
} else {
Log.d(TAG, "Post-paid account.");
postPaid = true;
}
Element accountSummary = homePage.getElementById("accountSummary");
if (accountSummary == null) {
Log.d(TAG, "Login failed.");
return FetchResult.LOGINFAILED;
}
db.delete("cache", "", null);
/* This code fetched some extra details for postpaid users, but on reflection they aren't that useful.
* Might reconsider this.
*
if (postPaid) {
Element accountBalanceSummaryTable = accountSummary.getElementsByClass("tableBillSummary").first();
Elements rows = accountBalanceSummaryTable.getElementsByTag("tr");
int rowno = 0;
for (Element row : rows) {
if (rowno > 1) {
break;
}
//Log.d(TAG, "Starting row");
//Log.d(TAG, row.html());
Double value;
try {
Element amount = row.getElementsByClass("tableBillamount").first();
String amountHTML = amount.html();
Log.d(TAG, amountHTML.substring(1));
value = Double.parseDouble(amountHTML.substring(1));
} catch (Exception e) {
Log.d(TAG, "Failed to parse amount from row.");
value = null;
}
String expiresDetails = "";
String expiresDate = null;
String name = null;
try {
Element details = row.getElementsByClass("tableBilldetail").first();
name = details.ownText();
Element expires = details.getElementsByTag("em").first();
if (expires != null) {
expiresDetails = expires.text();
}
Log.d(TAG, expiresDetails);
Pattern pattern;
pattern = Pattern.compile("\\(payment is due (.*)\\)");
Matcher matcher = pattern.matcher(expiresDetails);
if (matcher.find()) {
/*Log.d(TAG, "matched expires");
Log.d(TAG, "group 0:" + matcher.group(0));
Log.d(TAG, "group 1:" + matcher.group(1));
Log.d(TAG, "group 2:" + matcher.group(2)); *
String expiresDateString = matcher.group(1);
Date expiresDateObj;
if (expiresDateString != null) {
if (expiresDateString.length() > 0) {
try {
expiresDateObj = DateFormatters.EXPIRESDATE.parse(expiresDateString);
expiresDate = DateFormatters.ISO8601DATEONLYFORMAT.format(expiresDateObj);
} catch (java.text.ParseException e) {
Log.d(TAG, "Could not parse date: " + expiresDateString);
}
}
}
}
} catch (Exception e) {
Log.d(TAG, "Failed to parse details from row.");
}
String expirev = null;
ContentValues values = new ContentValues();
values.put("name", name);
values.put("value", value);
values.put("units", "$NZ");
values.put("expires_value", expirev );
values.put("expires_date", expiresDate);
db.insert("cache", "value", values );
rowno++;
}
} */
Element accountSummaryTable = accountSummary.getElementsByClass("tableAccountSummary").first();
Elements rows = accountSummaryTable.getElementsByTag("tr");
for (Element row : rows) {
// We are now looking at each of the rows in the data table.
//Log.d(TAG, "Starting row");
//Log.d(TAG, row.html());
Double value;
String units;
try {
Element amount = row.getElementsByClass("tableBillamount").first();
String amountHTML = amount.html();
//Log.d(TAG, amountHTML);
String[] amountParts = amountHTML.split(" ", 2);
//Log.d(TAG, amountParts[0]);
//Log.d(TAG, amountParts[1]);
if (amountParts[0].contains("Included") || amountParts[0].equals("All You Need")) {
value = Values.INCLUDED;
} else {
try {
value = Double.parseDouble(amountParts[0]);
} catch (NumberFormatException e) {
exceptionReporter.reportException(Thread.currentThread(), e, "Decoding value.");
value = 0.0;
}
}
units = amountParts[1];
} catch (NullPointerException e) {
//Log.d(TAG, "Failed to parse amount from row.");
value = null;
units = null;
}
Element details = row.getElementsByClass("tableBilldetail").first();
String name = details.getElementsByTag("strong").first().text();
Element expires = details.getElementsByTag("em").first();
String expiresDetails = "";
if (expires != null) {
expiresDetails = expires.text();
}
Log.d(TAG, expiresDetails);
Pattern pattern;
if (postPaid == false) {
pattern = Pattern.compile("\\(([\\d\\.]*) ?\\w*? ?expiring on (.*)\\)");
} else {
pattern = Pattern.compile("\\(([\\d\\.]*) ?\\w*? ?will expire on (.*)\\)");
}
Matcher matcher = pattern.matcher(expiresDetails);
Double expiresValue = null;
String expiresDate = null;
if (matcher.find()) {
/*Log.d(TAG, "matched expires");
Log.d(TAG, "group 0:" + matcher.group(0));
Log.d(TAG, "group 1:" + matcher.group(1));
Log.d(TAG, "group 2:" + matcher.group(2)); */
try {
expiresValue = Double.parseDouble(matcher.group(1));
} catch (NumberFormatException e) {
expiresValue = null;
}
String expiresDateString = matcher.group(2);
Date expiresDateObj;
if (expiresDateString != null) {
if (expiresDateString.length() > 0) {
try {
expiresDateObj = DateFormatters.EXPIRESDATE.parse(expiresDateString);
expiresDate = DateFormatters.ISO8601DATEONLYFORMAT.format(expiresDateObj);
} catch (java.text.ParseException e) {
Log.d(TAG, "Could not parse date: " + expiresDateString);
}
}
}
}
ContentValues values = new ContentValues();
values.put("name", name);
values.put("value", value);
values.put("units", units);
values.put("expires_value", expiresValue);
values.put("expires_date", expiresDate);
db.insert("cache", "value", values );
}
if(postPaid == false) {
Log.d(TAG, "Getting Value packs...");
// Find value packs
HttpGetter valuePacksPageGet = new HttpGetter("https://secure.2degreesmobile.co.nz/group/ip/prevaluepack");
String valuePacksPageString = valuePacksPageGet.execute();
//DBLog.insertMessage(context, "d", "", valuePacksPageString);
if(valuePacksPageString != null) {
Document valuePacksPage = Jsoup.parse(valuePacksPageString);
Elements enabledPacks = valuePacksPage.getElementsByClass("yellow");
for (Element enabledPack : enabledPacks) {
Element offerNameElemt = enabledPack.getElementsByAttributeValueStarting("name", "offername").first();
String offerName = offerNameElemt.val();
DBLog.insertMessage(context, "d", "", "Got element: " + offerName);
ValuePack[] packs = Values.valuePacks.get(offerName);
if (packs == null) {
DBLog.insertMessage(context, "d", "", "Offer name: " + offerName + " not matched.");
} else {
for (ValuePack pack: packs) {
// Cursor csr = db.query("cache", null, "name = '" + pack.type.id + "'", null, null, null, null);
// if (csr.getCount() == 1) {
// csr.moveToFirst();
ContentValues values = new ContentValues();
// Not sure why adding on the previous value?
//values.put("plan_startamount", csr.getDouble(4) + pack.value);
//DBLog.insertMessage(context, "d", "", "Pack " + pack.type.id + " start value set to " + csr.getDouble(4) + pack.value);
values.put("plan_startamount", pack.value);
values.put("plan_name", offerName);
DBLog.insertMessage(context, "d", "", "Pack " + pack.type.id + " start value set to " + pack.value);
db.update("cache", values, "name = '" + pack.type.id + "'", null);
// } else {
// DBLog.insertMessage(context, "d", "", "Pack " + pack.type.id + " Couldn't find item to add to");
// }
// csr.close();
}
}
}
}
}
SharedPreferences.Editor prefedit = sp.edit();
Date now = new Date();
prefedit.putString("updateDate", DateFormatters.ISO8601FORMAT.format(now));
prefedit.putBoolean("loginFailed", false);
prefedit.putBoolean("networkError", false);
prefedit.commit();
DBLog.insertMessage(context, "i", TAG, "Update Successful");
return FetchResult.SUCCESS;
}
} catch (ClientProtocolException e) {
DBLog.insertMessage(context, "w", TAG, "Network error: " + e.getMessage());
return FetchResult.NETWORKERROR;
} catch (IOException e) {
DBLog.insertMessage(context, "w", TAG, "Network error: " + e.getMessage());
return FetchResult.NETWORKERROR;
}
finally {
db.close();
}
return null;
}
| public FetchResult updateData(Context context, boolean force) {
//Open database
DBOpenHelper dbhelper = new DBOpenHelper(context);
SQLiteDatabase db = dbhelper.getWritableDatabase();
// check for internet connectivity
try {
if (!isOnline(context)) {
Log.d(TAG, "We do not seem to be online. Skipping Update.");
return FetchResult.NOTONLINE;
}
} catch (Exception e) {
exceptionReporter.reportException(Thread.currentThread(), e, "Exception during isOnline()");
}
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
if (!force) {
try {
if (sp.getBoolean("loginFailed", false) == true) {
Log.d(TAG, "Previous login failed. Skipping Update.");
DBLog.insertMessage(context, "i", TAG, "Previous login failed. Skipping Update.");
return FetchResult.LOGINFAILED;
}
if(sp.getBoolean("autoupdates", true) == false) {
Log.d(TAG, "Automatic updates not enabled. Skipping Update.");
DBLog.insertMessage(context, "i", TAG, "Automatic updates not enabled. Skipping Update.");
return FetchResult.NOTALLOWED;
}
if (!isBackgroundDataEnabled(context) && sp.getBoolean("obeyBackgroundData", true)) {
Log.d(TAG, "Background data not enabled. Skipping Update.");
DBLog.insertMessage(context, "i", TAG, "Background data not enabled. Skipping Update.");
return FetchResult.NOTALLOWED;
}
if (!isAutoSyncEnabled() && sp.getBoolean("obeyAutoSync", true) && sp.getBoolean("obeyBackgroundData", true)) {
Log.d(TAG, "Auto sync not enabled. Skipping Update.");
DBLog.insertMessage(context, "i", TAG, "Auto sync not enabled. Skipping Update.");
return FetchResult.NOTALLOWED;
}
if (isWifi(context) && !sp.getBoolean("wifiUpdates", true)) {
Log.d(TAG, "On wifi, and wifi auto updates not allowed. Skipping Update");
DBLog.insertMessage(context, "i", TAG, "On wifi, and wifi auto updates not allowed. Skipping Update");
return FetchResult.NOTALLOWED;
} else if (!isWifi(context)){
Log.d(TAG, "We are not on wifi.");
if (!isRoaming(context) && !sp.getBoolean("2DData", true)) {
Log.d(TAG, "Automatic updates on 2Degrees data not enabled. Skipping Update.");
DBLog.insertMessage(context, "i", TAG, "Automatic updates on 2Degrees data not enabled. Skipping Update.");
return FetchResult.NOTALLOWED;
} else if (isRoaming(context) && !sp.getBoolean("roamingData", false)) {
Log.d(TAG, "Automatic updates on roaming mobile data not enabled. Skipping Update.");
DBLog.insertMessage(context, "i", TAG, "Automatic updates on roaming mobile data not enabled. Skipping Update.");
return FetchResult.NOTALLOWED;
}
}
} catch (Exception e) {
exceptionReporter.reportException(Thread.currentThread(), e, "Exception while finding if to update.");
}
} else {
Log.d(TAG, "Update Forced");
}
try {
String username = sp.getString("username", null);
String password = sp.getString("password", null);
if(username == null || password == null) {
DBLog.insertMessage(context, "i", TAG, "Username or password not set.");
return FetchResult.USERNAMEPASSWORDNOTSET;
}
// Find the URL of the page to send login data to.
Log.d(TAG, "Finding Action. ");
HttpGetter loginPageGet = new HttpGetter("https://secure.2degreesmobile.co.nz/web/ip/login");
String loginPageString = loginPageGet.execute();
if (loginPageString != null) {
Document loginPage = Jsoup.parse(loginPageString, "https://secure.2degreesmobile.co.nz/web/ip/login");
Element loginForm = loginPage.getElementsByAttributeValue("name", "loginFrm").first();
String loginAction = loginForm.attr("action");
// Send login form
List<NameValuePair> loginValues = new ArrayList <NameValuePair>();
loginValues.add(new BasicNameValuePair("externalURLRedirect", ""));
loginValues.add(new BasicNameValuePair("hdnAction", "login_userlogin"));
loginValues.add(new BasicNameValuePair("hdnAuthenticationType", "M"));
loginValues.add(new BasicNameValuePair("hdnlocale", ""));
loginValues.add(new BasicNameValuePair("userid", username));
loginValues.add(new BasicNameValuePair("password", password));
Log.d(TAG, "Sending Login ");
HttpPoster sendLoginPoster = new HttpPoster(loginAction, loginValues);
// Parse result
Document homePage = Jsoup.parse(sendLoginPoster.execute());
// Determine if this is a pre-pay or post-paid account.
boolean postPaid;
if (homePage.getElementById("p_p_id_PostPaidHomePage_WAR_Homepage_") == null) {
Log.d(TAG, "Pre-pay account or no account.");
postPaid = false;
} else {
Log.d(TAG, "Post-paid account.");
postPaid = true;
}
Element accountSummary = homePage.getElementById("accountSummary");
if (accountSummary == null) {
Log.d(TAG, "Login failed.");
return FetchResult.LOGINFAILED;
}
db.delete("cache", "", null);
/* This code fetched some extra details for postpaid users, but on reflection they aren't that useful.
* Might reconsider this.
*
if (postPaid) {
Element accountBalanceSummaryTable = accountSummary.getElementsByClass("tableBillSummary").first();
Elements rows = accountBalanceSummaryTable.getElementsByTag("tr");
int rowno = 0;
for (Element row : rows) {
if (rowno > 1) {
break;
}
//Log.d(TAG, "Starting row");
//Log.d(TAG, row.html());
Double value;
try {
Element amount = row.getElementsByClass("tableBillamount").first();
String amountHTML = amount.html();
Log.d(TAG, amountHTML.substring(1));
value = Double.parseDouble(amountHTML.substring(1));
} catch (Exception e) {
Log.d(TAG, "Failed to parse amount from row.");
value = null;
}
String expiresDetails = "";
String expiresDate = null;
String name = null;
try {
Element details = row.getElementsByClass("tableBilldetail").first();
name = details.ownText();
Element expires = details.getElementsByTag("em").first();
if (expires != null) {
expiresDetails = expires.text();
}
Log.d(TAG, expiresDetails);
Pattern pattern;
pattern = Pattern.compile("\\(payment is due (.*)\\)");
Matcher matcher = pattern.matcher(expiresDetails);
if (matcher.find()) {
/*Log.d(TAG, "matched expires");
Log.d(TAG, "group 0:" + matcher.group(0));
Log.d(TAG, "group 1:" + matcher.group(1));
Log.d(TAG, "group 2:" + matcher.group(2)); *
String expiresDateString = matcher.group(1);
Date expiresDateObj;
if (expiresDateString != null) {
if (expiresDateString.length() > 0) {
try {
expiresDateObj = DateFormatters.EXPIRESDATE.parse(expiresDateString);
expiresDate = DateFormatters.ISO8601DATEONLYFORMAT.format(expiresDateObj);
} catch (java.text.ParseException e) {
Log.d(TAG, "Could not parse date: " + expiresDateString);
}
}
}
}
} catch (Exception e) {
Log.d(TAG, "Failed to parse details from row.");
}
String expirev = null;
ContentValues values = new ContentValues();
values.put("name", name);
values.put("value", value);
values.put("units", "$NZ");
values.put("expires_value", expirev );
values.put("expires_date", expiresDate);
db.insert("cache", "value", values );
rowno++;
}
} */
Element accountSummaryTable = accountSummary.getElementsByClass("tableAccountSummary").first();
Elements rows = accountSummaryTable.getElementsByTag("tr");
for (Element row : rows) {
// We are now looking at each of the rows in the data table.
//Log.d(TAG, "Starting row");
//Log.d(TAG, row.html());
Double value;
String units;
try {
Element amount = row.getElementsByClass("tableBillamount").first();
String amountHTML = amount.html();
//Log.d(TAG, amountHTML);
String[] amountParts = amountHTML.split(" ", 2);
//Log.d(TAG, amountParts[0]);
//Log.d(TAG, amountParts[1]);
if (amountParts[0].contains("Included") || amountParts[0].equals("All You Need")) {
value = Values.INCLUDED;
} else {
try {
value = Double.parseDouble(amountParts[0]);
} catch (NumberFormatException e) {
exceptionReporter.reportException(Thread.currentThread(), e, "Decoding value.");
value = 0.0;
}
}
units = amountParts[1];
} catch (NullPointerException e) {
//Log.d(TAG, "Failed to parse amount from row.");
value = null;
units = null;
}
Element details = row.getElementsByClass("tableBilldetail").first();
String name = details.getElementsByTag("strong").first().text();
Element expires = details.getElementsByTag("em").first();
String expiresDetails = "";
if (expires != null) {
expiresDetails = expires.text();
}
Log.d(TAG, expiresDetails);
Pattern pattern;
if (postPaid == false) {
pattern = Pattern.compile("\\(([\\d\\.]*) ?\\w*? ?expiring on (.*)\\)");
} else {
pattern = Pattern.compile("\\(([\\d\\.]*) ?\\w*? ?will expire on (.*)\\)");
}
Matcher matcher = pattern.matcher(expiresDetails);
Double expiresValue = null;
String expiresDate = null;
if (matcher.find()) {
/*Log.d(TAG, "matched expires");
Log.d(TAG, "group 0:" + matcher.group(0));
Log.d(TAG, "group 1:" + matcher.group(1));
Log.d(TAG, "group 2:" + matcher.group(2)); */
try {
expiresValue = Double.parseDouble(matcher.group(1));
} catch (NumberFormatException e) {
expiresValue = null;
}
String expiresDateString = matcher.group(2);
Date expiresDateObj;
if (expiresDateString != null) {
if (expiresDateString.length() > 0) {
try {
expiresDateObj = DateFormatters.EXPIRESDATE.parse(expiresDateString);
expiresDate = DateFormatters.ISO8601DATEONLYFORMAT.format(expiresDateObj);
} catch (java.text.ParseException e) {
Log.d(TAG, "Could not parse date: " + expiresDateString);
}
}
}
}
ContentValues values = new ContentValues();
values.put("name", name);
values.put("value", value);
values.put("units", units);
values.put("expires_value", expiresValue);
values.put("expires_date", expiresDate);
db.insert("cache", "value", values );
}
if(postPaid == false) {
Log.d(TAG, "Getting Value packs...");
// Find value packs
HttpGetter valuePacksPageGet = new HttpGetter("https://secure.2degreesmobile.co.nz/group/ip/prevaluepack");
String valuePacksPageString = valuePacksPageGet.execute();
//DBLog.insertMessage(context, "d", "", valuePacksPageString);
if(valuePacksPageString != null) {
Document valuePacksPage = Jsoup.parse(valuePacksPageString);
Elements enabledPacks = valuePacksPage.getElementsByClass("yellow");
for (Element enabledPack : enabledPacks) {
Element offerNameElemt = enabledPack.getElementsByAttributeValueStarting("name", "offername").first();
String offerName = offerNameElemt.val();
DBLog.insertMessage(context, "d", "", "Got element: " + offerName);
ValuePack[] packs = Values.valuePacks.get(offerName);
if (packs == null) {
DBLog.insertMessage(context, "d", "", "Offer name: " + offerName + " not matched.");
} else {
for (ValuePack pack: packs) {
// Cursor csr = db.query("cache", null, "name = '" + pack.type.id + "'", null, null, null, null);
// if (csr.getCount() == 1) {
// csr.moveToFirst();
ContentValues values = new ContentValues();
// Not sure why adding on the previous value?
//values.put("plan_startamount", csr.getDouble(4) + pack.value);
//DBLog.insertMessage(context, "d", "", "Pack " + pack.type.id + " start value set to " + csr.getDouble(4) + pack.value);
values.put("plan_startamount", pack.value);
values.put("plan_name", offerName);
DBLog.insertMessage(context, "d", "", "Pack " + pack.type.id + " start value set to " + pack.value);
db.update("cache", values, "name = '" + pack.type.id + "'", null);
// } else {
// DBLog.insertMessage(context, "d", "", "Pack " + pack.type.id + " Couldn't find item to add to");
// }
// csr.close();
}
}
}
}
}
SharedPreferences.Editor prefedit = sp.edit();
Date now = new Date();
prefedit.putString("updateDate", DateFormatters.ISO8601FORMAT.format(now));
prefedit.putBoolean("loginFailed", false);
prefedit.putBoolean("networkError", false);
prefedit.commit();
DBLog.insertMessage(context, "i", TAG, "Update Successful");
return FetchResult.SUCCESS;
}
} catch (ClientProtocolException e) {
DBLog.insertMessage(context, "w", TAG, "Network error: " + e.getMessage());
return FetchResult.NETWORKERROR;
} catch (IOException e) {
DBLog.insertMessage(context, "w", TAG, "Network error: " + e.getMessage());
return FetchResult.NETWORKERROR;
}
finally {
db.close();
}
return null;
}
|
diff --git a/rain/src/com/follett/mywebapp/server/TreeBuilderServiceImpl.java b/rain/src/com/follett/mywebapp/server/TreeBuilderServiceImpl.java
index 20fd3cb..45cf261 100644
--- a/rain/src/com/follett/mywebapp/server/TreeBuilderServiceImpl.java
+++ b/rain/src/com/follett/mywebapp/server/TreeBuilderServiceImpl.java
@@ -1,112 +1,113 @@
package com.follett.mywebapp.server;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import com.follett.mywebapp.util.ValidationTreeDataItem;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
/**
* The server side implementation of the RPC service.
*/
public class TreeBuilderServiceImpl extends RemoteServiceServlet implements TreeBuilderService {
private static final long serialVersionUID = 1L;
/**
* Implement the connection to the server and gather the necessary data
* */
@Override
public HashMap<String, ArrayList<ValidationTreeDataItem>> getTreeItems() {
HashMap<String, ArrayList<ValidationTreeDataItem>> returnable = new HashMap<String, ArrayList<ValidationTreeDataItem>>();
+ ArrayList<ValidationTreeDataItem> exception = new ArrayList<ValidationTreeDataItem>();
+ exception.add(new ValidationTreeDataItem("","root","Exception", Integer.valueOf(0)));
try {
Class.forName(DatabaseParameters.getTDSDriver()).newInstance();
- // TODO get tree items and build them into the tree
String url = DatabaseParameters.getDatabaseURL();
Connection conn = DriverManager.getConnection(url, DatabaseParameters.getConnectionProperties());
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM dbo.TreeItems ORDER BY parentTagID");
String tagID;
String parentTagID;
String description;
Integer fields;
String fieldDescriptions;
while(rs.next()) {
tagID = rs.getString("tagID");
parentTagID = rs.getString("parentTagID");
description = rs.getString("label");
fields = Integer.valueOf(rs.getInt("textfields"));
fieldDescriptions = rs.getString("fieldDescriptions");
ValidationTreeDataItem item = new ValidationTreeDataItem(tagID, parentTagID, description, fields);
item.addDescriptions(fieldDescriptions);
ArrayList<ValidationTreeDataItem> currentList;
if(returnable.containsKey(parentTagID)) {
currentList = returnable.get(parentTagID);
} else {
currentList = new ArrayList<ValidationTreeDataItem>();
}
currentList.add(item);
returnable.put(parentTagID, currentList);
}
conn.close();
} catch (SQLException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
+ exception.get(0).setDescription(e.toString());
+ returnable.put("root", exception);
} catch (ClassNotFoundException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (InstantiationException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (IllegalAccessException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
+ exception.get(0).setDescription(e.toString());
+ returnable.put("root", exception);
+ } catch (InstantiationException e) {
+ exception.get(0).setDescription(e.toString());
+ returnable.put("root", exception);
+ } catch (IllegalAccessException e) {
+ exception.get(0).setDescription(e.toString());
+ returnable.put("root", exception);
+ }
return returnable;
}
public Boolean saveTreeItems(ArrayList<ValidationTreeDataItem> nodes) {
Boolean exception = Boolean.FALSE;
try {
Class.forName(DatabaseParameters.getTDSDriver()).newInstance();
String url = DatabaseParameters.getDatabaseURL();
Connection conn = DriverManager.getConnection(url, DatabaseParameters.getConnectionProperties());
Statement stmt = conn.createStatement();
String sql = "";
for (ValidationTreeDataItem item : nodes) {
sql = "UPDATE dbo.TreeItems SET " +
"parentTagID = '" + item.getParentTagID() + "', " +
"description = '" + item.getDescription() + "', " +
"fields = '" + item.getFields() + "', " +
"fieldDescriptions = '" + item.getDescriptionsToString() + "' " +
"WHERE tagID = '" + item.getTagID() + "'";
int success = stmt.executeUpdate(sql);
if(success == 0) {
sql = "INSERT INTO dbo.TreeItems " +
"(tagID, parentTagID, description, fields, fieldDescriptions) values (" +
"'" + item.getTagID() + "', " +
"'" + item.getParentTagID() + "', " +
"'" + item.getDescription() + "', " +
"'" + item.getFields() + "', " +
"'" + item.getDescriptionsToString() + "') ";
success = stmt.executeUpdate(sql);
}
}
conn.close();
} catch (InstantiationException e) {
exception = Boolean.TRUE;
} catch (IllegalAccessException e) {
exception = Boolean.TRUE;
} catch (ClassNotFoundException e) {
exception = Boolean.TRUE;
} catch (SQLException e) {
exception = Boolean.TRUE;
}
return exception;
}
}
| false | true | public HashMap<String, ArrayList<ValidationTreeDataItem>> getTreeItems() {
HashMap<String, ArrayList<ValidationTreeDataItem>> returnable = new HashMap<String, ArrayList<ValidationTreeDataItem>>();
try {
Class.forName(DatabaseParameters.getTDSDriver()).newInstance();
// TODO get tree items and build them into the tree
String url = DatabaseParameters.getDatabaseURL();
Connection conn = DriverManager.getConnection(url, DatabaseParameters.getConnectionProperties());
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM dbo.TreeItems ORDER BY parentTagID");
String tagID;
String parentTagID;
String description;
Integer fields;
String fieldDescriptions;
while(rs.next()) {
tagID = rs.getString("tagID");
parentTagID = rs.getString("parentTagID");
description = rs.getString("label");
fields = Integer.valueOf(rs.getInt("textfields"));
fieldDescriptions = rs.getString("fieldDescriptions");
ValidationTreeDataItem item = new ValidationTreeDataItem(tagID, parentTagID, description, fields);
item.addDescriptions(fieldDescriptions);
ArrayList<ValidationTreeDataItem> currentList;
if(returnable.containsKey(parentTagID)) {
currentList = returnable.get(parentTagID);
} else {
currentList = new ArrayList<ValidationTreeDataItem>();
}
currentList.add(item);
returnable.put(parentTagID, currentList);
}
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return returnable;
}
| public HashMap<String, ArrayList<ValidationTreeDataItem>> getTreeItems() {
HashMap<String, ArrayList<ValidationTreeDataItem>> returnable = new HashMap<String, ArrayList<ValidationTreeDataItem>>();
ArrayList<ValidationTreeDataItem> exception = new ArrayList<ValidationTreeDataItem>();
exception.add(new ValidationTreeDataItem("","root","Exception", Integer.valueOf(0)));
try {
Class.forName(DatabaseParameters.getTDSDriver()).newInstance();
String url = DatabaseParameters.getDatabaseURL();
Connection conn = DriverManager.getConnection(url, DatabaseParameters.getConnectionProperties());
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM dbo.TreeItems ORDER BY parentTagID");
String tagID;
String parentTagID;
String description;
Integer fields;
String fieldDescriptions;
while(rs.next()) {
tagID = rs.getString("tagID");
parentTagID = rs.getString("parentTagID");
description = rs.getString("label");
fields = Integer.valueOf(rs.getInt("textfields"));
fieldDescriptions = rs.getString("fieldDescriptions");
ValidationTreeDataItem item = new ValidationTreeDataItem(tagID, parentTagID, description, fields);
item.addDescriptions(fieldDescriptions);
ArrayList<ValidationTreeDataItem> currentList;
if(returnable.containsKey(parentTagID)) {
currentList = returnable.get(parentTagID);
} else {
currentList = new ArrayList<ValidationTreeDataItem>();
}
currentList.add(item);
returnable.put(parentTagID, currentList);
}
conn.close();
} catch (SQLException e) {
exception.get(0).setDescription(e.toString());
returnable.put("root", exception);
} catch (ClassNotFoundException e) {
exception.get(0).setDescription(e.toString());
returnable.put("root", exception);
} catch (InstantiationException e) {
exception.get(0).setDescription(e.toString());
returnable.put("root", exception);
} catch (IllegalAccessException e) {
exception.get(0).setDescription(e.toString());
returnable.put("root", exception);
}
return returnable;
}
|
diff --git a/data/hibernate/src/test/java/org/appfuse/dao/GenericDaoTest.java b/data/hibernate/src/test/java/org/appfuse/dao/GenericDaoTest.java
index 1b7bb566..7949befe 100644
--- a/data/hibernate/src/test/java/org/appfuse/dao/GenericDaoTest.java
+++ b/data/hibernate/src/test/java/org/appfuse/dao/GenericDaoTest.java
@@ -1,65 +1,65 @@
package org.appfuse.dao;
import org.appfuse.model.User;
import org.springframework.dao.InvalidDataAccessApiUsageException;
import org.springframework.orm.ObjectRetrievalFailureException;
/**
* This class tests the generic Dao and BaseDao implementation.
*/
public class GenericDaoTest extends BaseDaoTestCase {
protected Dao dao;
/**
* This method is used instead of setDao b/c setDao uses autowire byType
* <code>setPopulateProtectedVariables(true)</code> can also be used, but it's
* a little bit slower.
*/
public void onSetUpBeforeTransaction() throws Exception {
dao = (Dao) applicationContext.getBean("dao");
}
public void onTearDownAfterTransaction() throws Exception {
dao = null;
}
/**
* Simple test to verify BaseDao works.
*/
public void testCRUD() {
User user = new User();
// set required fields
user.setUsername("foo");
user.setPassword("bar");
user.setFirstName("first");
user.setLastName("last");
user.getAddress().setCity("Denver");
user.getAddress().setPostalCode("80465");
user.setEmail("[email protected]");
// create
dao.saveObject(user);
assertNotNull(user.getId());
// retrieve
user = (User) dao.getObject(User.class, user.getId());
assertNotNull(user);
assertEquals(user.getLastName(), "last");
// update
user.getAddress().setCountry("USA");
dao.saveObject(user);
assertEquals(user.getAddress().getCountry(), "USA");
// delete
dao.removeObject(User.class, user.getId());
try {
dao.getObject(User.class, user.getId());
fail("User 'foo' found in database");
} catch (ObjectRetrievalFailureException e) {
assertNotNull(e.getMessage());
- } catch (InvalidDataAccessApiUsageException e) { // hibernate 3.2.0.cr2 throws this one
+ } catch (InvalidDataAccessApiUsageException e) { // Spring 2.0 throws this one
assertNotNull(e.getMessage());
}
}
}
| true | true | public void testCRUD() {
User user = new User();
// set required fields
user.setUsername("foo");
user.setPassword("bar");
user.setFirstName("first");
user.setLastName("last");
user.getAddress().setCity("Denver");
user.getAddress().setPostalCode("80465");
user.setEmail("[email protected]");
// create
dao.saveObject(user);
assertNotNull(user.getId());
// retrieve
user = (User) dao.getObject(User.class, user.getId());
assertNotNull(user);
assertEquals(user.getLastName(), "last");
// update
user.getAddress().setCountry("USA");
dao.saveObject(user);
assertEquals(user.getAddress().getCountry(), "USA");
// delete
dao.removeObject(User.class, user.getId());
try {
dao.getObject(User.class, user.getId());
fail("User 'foo' found in database");
} catch (ObjectRetrievalFailureException e) {
assertNotNull(e.getMessage());
} catch (InvalidDataAccessApiUsageException e) { // hibernate 3.2.0.cr2 throws this one
assertNotNull(e.getMessage());
}
}
| public void testCRUD() {
User user = new User();
// set required fields
user.setUsername("foo");
user.setPassword("bar");
user.setFirstName("first");
user.setLastName("last");
user.getAddress().setCity("Denver");
user.getAddress().setPostalCode("80465");
user.setEmail("[email protected]");
// create
dao.saveObject(user);
assertNotNull(user.getId());
// retrieve
user = (User) dao.getObject(User.class, user.getId());
assertNotNull(user);
assertEquals(user.getLastName(), "last");
// update
user.getAddress().setCountry("USA");
dao.saveObject(user);
assertEquals(user.getAddress().getCountry(), "USA");
// delete
dao.removeObject(User.class, user.getId());
try {
dao.getObject(User.class, user.getId());
fail("User 'foo' found in database");
} catch (ObjectRetrievalFailureException e) {
assertNotNull(e.getMessage());
} catch (InvalidDataAccessApiUsageException e) { // Spring 2.0 throws this one
assertNotNull(e.getMessage());
}
}
|
diff --git a/obex/javax/obex/PrivateOutputStream.java b/obex/javax/obex/PrivateOutputStream.java
index ea01ab4c..06dd55e2 100644
--- a/obex/javax/obex/PrivateOutputStream.java
+++ b/obex/javax/obex/PrivateOutputStream.java
@@ -1,163 +1,166 @@
/*
* Copyright (c) 2008-2009, Motorola, Inc.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* - Neither the name of the Motorola, Inc. nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package javax.obex;
import java.io.IOException;
import java.io.OutputStream;
/**
* This object provides an output stream to the Operation objects used in this
* package.
* @hide
*/
public final class PrivateOutputStream extends OutputStream {
private BaseStream mParent;
private ObexByteBuffer mBuffer;
private boolean mOpen;
private int mMaxPacketSize;
/**
* Creates an empty <code>PrivateOutputStream</code> to write to.
* @param p the connection that this stream runs over
*/
public PrivateOutputStream(BaseStream p, int maxSize) {
mParent = p;
mBuffer = new ObexByteBuffer(32);
mMaxPacketSize = maxSize;
mOpen = true;
}
/**
* Determines how many bytes have been written to the output stream.
* @return the number of bytes written to the output stream
*/
public int size() {
return mBuffer.getLength();
}
/**
* Writes the specified byte to this output stream. The general contract for
* write is that one byte is written to the output stream. The byte to be
* written is the eight low-order bits of the argument b. The 24 high-order
* bits of b are ignored.
* @param b the byte to write
* @throws IOException if an I/O error occurs
*/
@Override
public synchronized void write(int b) throws IOException {
ensureOpen();
mParent.ensureNotDone();
mBuffer.write((byte)b);
if (mBuffer.getLength() == mMaxPacketSize) {
mParent.continueOperation(true, false);
}
}
@Override
public void write(byte[] buffer) throws IOException {
write(buffer, 0, buffer.length);
}
@Override
public synchronized void write(byte[] buffer, int offset, int count) throws IOException {
int offset1 = offset;
int remainLength = count;
if (buffer == null) {
throw new IOException("buffer is null");
}
if ((offset | count) < 0 || count > buffer.length - offset) {
throw new IndexOutOfBoundsException("index outof bound");
}
ensureOpen();
mParent.ensureNotDone();
- while ((mArray.size() + remainLength) >= mMaxPacketSize) {
- int bufferLeft = mMaxPacketSize - mArray.size();
- mArray.write(buffer, offset1, bufferLeft);
- offset1 += bufferLeft;
- remainLength -= bufferLeft;
- mParent.continueOperation(true, false);
- }
- if (remainLength > 0) {
- mArray.write(buffer, offset1, remainLength);
+ if (count < mMaxPacketSize) {
+ mBuffer.write(buffer, offset, count);
+ } else {
+ while (remainLength >= mMaxPacketSize) {
+ mBuffer.write(buffer, offset1, mMaxPacketSize);
+ offset1 += mMaxPacketSize;
+ remainLength = count - offset1;
+ mParent.continueOperation(true, false);
+ }
+ if (remainLength > 0) {
+ mBuffer.write(buffer, offset1, remainLength);
+ }
}
}
/**
* Write some of the bytes that have been written to this stream to
* an ObexByteBuffer.
*
* @param dest the stream to write to
* @param start where to write in the byte array
* @param size the number of bytes to write to the byte array
*/
public synchronized void writeTo(ObexByteBuffer dest, int size) throws IOException {
mBuffer.read(dest, size);
}
/**
* Verifies that this stream is open
* @throws IOException if the stream is not open
*/
private void ensureOpen() throws IOException {
mParent.ensureOpen();
if (!mOpen) {
throw new IOException("Output stream is closed");
}
}
/**
* Closes the output stream. If the input stream is already closed, do
* nothing.
* @throws IOException this will never happen
*/
@Override
public void close() throws IOException {
mOpen = false;
mParent.streamClosed(false);
}
/**
* Determines if the connection is closed
* @return <code>true</code> if the connection is closed; <code>false</code>
* if the connection is open
*/
public boolean isClosed() {
return !mOpen;
}
}
| true | true | public synchronized void write(byte[] buffer, int offset, int count) throws IOException {
int offset1 = offset;
int remainLength = count;
if (buffer == null) {
throw new IOException("buffer is null");
}
if ((offset | count) < 0 || count > buffer.length - offset) {
throw new IndexOutOfBoundsException("index outof bound");
}
ensureOpen();
mParent.ensureNotDone();
while ((mArray.size() + remainLength) >= mMaxPacketSize) {
int bufferLeft = mMaxPacketSize - mArray.size();
mArray.write(buffer, offset1, bufferLeft);
offset1 += bufferLeft;
remainLength -= bufferLeft;
mParent.continueOperation(true, false);
}
if (remainLength > 0) {
mArray.write(buffer, offset1, remainLength);
}
}
| public synchronized void write(byte[] buffer, int offset, int count) throws IOException {
int offset1 = offset;
int remainLength = count;
if (buffer == null) {
throw new IOException("buffer is null");
}
if ((offset | count) < 0 || count > buffer.length - offset) {
throw new IndexOutOfBoundsException("index outof bound");
}
ensureOpen();
mParent.ensureNotDone();
if (count < mMaxPacketSize) {
mBuffer.write(buffer, offset, count);
} else {
while (remainLength >= mMaxPacketSize) {
mBuffer.write(buffer, offset1, mMaxPacketSize);
offset1 += mMaxPacketSize;
remainLength = count - offset1;
mParent.continueOperation(true, false);
}
if (remainLength > 0) {
mBuffer.write(buffer, offset1, remainLength);
}
}
}
|
diff --git a/modules/resin/src/com/caucho/jstl/rt/XmlParseTag.java b/modules/resin/src/com/caucho/jstl/rt/XmlParseTag.java
index 37501761b..02463ad5c 100644
--- a/modules/resin/src/com/caucho/jstl/rt/XmlParseTag.java
+++ b/modules/resin/src/com/caucho/jstl/rt/XmlParseTag.java
@@ -1,237 +1,236 @@
/*
* Copyright (c) 1998-2008 Caucho Technology -- all rights reserved
*
* This file is part of Resin(R) Open Source
*
* Each copy or derived work must preserve the copyright notice and this
* notice unmodified.
*
* Resin Open Source is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* Resin Open Source is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty
* of NON-INFRINGEMENT. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with Resin Open Source; if not, write to the
*
* Free Software Foundation, Inc.
* 59 Temple Place, Suite 330
* Boston, MA 02111-1307 USA
*
* @author Scott Ferguson
*/
package com.caucho.jstl.rt;
import com.caucho.jsp.BodyContentImpl;
import com.caucho.jsp.PageContextImpl;
import com.caucho.util.L10N;
import com.caucho.vfs.*;
import com.caucho.xml.Xml;
import com.caucho.xml.XmlParser;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.*;
import javax.xml.parsers.*;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.dom.DOMResult;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;
import java.io.Reader;
public class XmlParseTag extends BodyTagSupport {
private static L10N L = new L10N(XmlParseTag.class);
private Object _xml;
private String _systemId;
private Object _filter;
private XMLReader _saxReader;
private String _var;
private String _scope;
private String _varDom;
private String _scopeDom;
/**
* Sets the xml
*/
public void setXml(Object xml)
{
_xml = xml;
}
/**
* Sets the xml
*/
public void setDoc(Object xml)
{
setXml(xml);
}
/**
* Sets the system id
*/
public void setSystemId(String systemId)
{
_systemId = systemId;
}
/**
* Sets the filter
*/
public void setFilter(Object filter)
{
_filter = filter;
}
/**
* Sets the sax reader
*/
public void setSaxReader(XMLReader reader)
{
_saxReader = reader;
}
/**
* Sets the variable
*/
public void setVar(String var)
{
_var = var;
}
/**
* Sets the scope
*/
public void setScope(String scope)
{
_scope = scope;
}
/**
* Sets the variable
*/
public void setVarDom(String var)
{
_varDom = var;
}
/**
* Sets the scope
*/
public void setScopeDom(String scope)
{
_scopeDom = scope;
}
public int doEndTag() throws JspException
{
try {
PageContextImpl pageContext = (PageContextImpl) this.pageContext;
BodyContentImpl body = (BodyContentImpl) getBodyContent();
Reader reader;
if (_xml != null) {
Object obj = _xml;
if (obj instanceof Reader)
reader = (Reader) obj;
else if (obj instanceof String)
reader = Vfs.openString((String) obj).getReader();
else
throw new JspException(L.l("xml must be Reader or String at `{0}'",
obj));
}
else if (body != null) {
TempCharReader tempReader = (TempCharReader) body.getReader();
int ch;
while (Character.isWhitespace((ch = tempReader.read()))) {
}
if (ch >= 0)
tempReader.unread();
reader = tempReader;
}
else
- throw new JspException(L.l("doc attribute must be a Reader or String at `{0}'",
- null));
+ throw new JspException(L.l("No XML document supplied via a doc attribute or inside the body of <x:parse> tag."));
InputSource is = new InputSource(reader);
if (_systemId != null)
is.setSystemId(_systemId);
Document doc = null;
XMLFilter filter = (XMLFilter) _filter;
if (_filter != null) {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
XMLReader parser = saxParser.getXMLReader();
filter.setParent(parser);
if (_var != null || _varDom != null) {
TransformerFactory saxTrFactory = SAXTransformerFactory.newInstance();
Transformer transformer = saxTrFactory.newTransformer();
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
doc = dbFactory.newDocumentBuilder().newDocument();
DOMResult result = new DOMResult(doc);
transformer.transform(new SAXSource(filter, is), result);
if (_var != null)
CoreSetTag.setValue(pageContext, _var, _scope, doc);
if (_varDom != null)
CoreSetTag.setValue(pageContext, _varDom, _scope, doc);
}
else {
filter.parse(is);
}
reader.close();
}
else {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder parser = factory.newDocumentBuilder();
doc = parser.parse(is);
reader.close();
if (_var != null)
CoreSetTag.setValue(pageContext, _var, _scope, doc);
else if (_varDom != null)
CoreSetTag.setValue(pageContext, _varDom, _scopeDom, doc);
else
throw new JspException(L.l("x:parse needs either var or varDom"));
}
} catch (JspException e) {
throw e;
} catch (Exception e) {
throw new JspException(e);
}
return EVAL_PAGE;
}
}
| true | true | public int doEndTag() throws JspException
{
try {
PageContextImpl pageContext = (PageContextImpl) this.pageContext;
BodyContentImpl body = (BodyContentImpl) getBodyContent();
Reader reader;
if (_xml != null) {
Object obj = _xml;
if (obj instanceof Reader)
reader = (Reader) obj;
else if (obj instanceof String)
reader = Vfs.openString((String) obj).getReader();
else
throw new JspException(L.l("xml must be Reader or String at `{0}'",
obj));
}
else if (body != null) {
TempCharReader tempReader = (TempCharReader) body.getReader();
int ch;
while (Character.isWhitespace((ch = tempReader.read()))) {
}
if (ch >= 0)
tempReader.unread();
reader = tempReader;
}
else
throw new JspException(L.l("doc attribute must be a Reader or String at `{0}'",
null));
InputSource is = new InputSource(reader);
if (_systemId != null)
is.setSystemId(_systemId);
Document doc = null;
XMLFilter filter = (XMLFilter) _filter;
if (_filter != null) {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
XMLReader parser = saxParser.getXMLReader();
filter.setParent(parser);
if (_var != null || _varDom != null) {
TransformerFactory saxTrFactory = SAXTransformerFactory.newInstance();
Transformer transformer = saxTrFactory.newTransformer();
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
doc = dbFactory.newDocumentBuilder().newDocument();
DOMResult result = new DOMResult(doc);
transformer.transform(new SAXSource(filter, is), result);
if (_var != null)
CoreSetTag.setValue(pageContext, _var, _scope, doc);
if (_varDom != null)
CoreSetTag.setValue(pageContext, _varDom, _scope, doc);
}
else {
filter.parse(is);
}
reader.close();
}
else {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder parser = factory.newDocumentBuilder();
doc = parser.parse(is);
reader.close();
if (_var != null)
CoreSetTag.setValue(pageContext, _var, _scope, doc);
else if (_varDom != null)
CoreSetTag.setValue(pageContext, _varDom, _scopeDom, doc);
else
throw new JspException(L.l("x:parse needs either var or varDom"));
}
} catch (JspException e) {
throw e;
} catch (Exception e) {
throw new JspException(e);
}
return EVAL_PAGE;
}
| public int doEndTag() throws JspException
{
try {
PageContextImpl pageContext = (PageContextImpl) this.pageContext;
BodyContentImpl body = (BodyContentImpl) getBodyContent();
Reader reader;
if (_xml != null) {
Object obj = _xml;
if (obj instanceof Reader)
reader = (Reader) obj;
else if (obj instanceof String)
reader = Vfs.openString((String) obj).getReader();
else
throw new JspException(L.l("xml must be Reader or String at `{0}'",
obj));
}
else if (body != null) {
TempCharReader tempReader = (TempCharReader) body.getReader();
int ch;
while (Character.isWhitespace((ch = tempReader.read()))) {
}
if (ch >= 0)
tempReader.unread();
reader = tempReader;
}
else
throw new JspException(L.l("No XML document supplied via a doc attribute or inside the body of <x:parse> tag."));
InputSource is = new InputSource(reader);
if (_systemId != null)
is.setSystemId(_systemId);
Document doc = null;
XMLFilter filter = (XMLFilter) _filter;
if (_filter != null) {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
XMLReader parser = saxParser.getXMLReader();
filter.setParent(parser);
if (_var != null || _varDom != null) {
TransformerFactory saxTrFactory = SAXTransformerFactory.newInstance();
Transformer transformer = saxTrFactory.newTransformer();
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
doc = dbFactory.newDocumentBuilder().newDocument();
DOMResult result = new DOMResult(doc);
transformer.transform(new SAXSource(filter, is), result);
if (_var != null)
CoreSetTag.setValue(pageContext, _var, _scope, doc);
if (_varDom != null)
CoreSetTag.setValue(pageContext, _varDom, _scope, doc);
}
else {
filter.parse(is);
}
reader.close();
}
else {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder parser = factory.newDocumentBuilder();
doc = parser.parse(is);
reader.close();
if (_var != null)
CoreSetTag.setValue(pageContext, _var, _scope, doc);
else if (_varDom != null)
CoreSetTag.setValue(pageContext, _varDom, _scopeDom, doc);
else
throw new JspException(L.l("x:parse needs either var or varDom"));
}
} catch (JspException e) {
throw e;
} catch (Exception e) {
throw new JspException(e);
}
return EVAL_PAGE;
}
|
diff --git a/plugins/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/layout/pdf/PDFLayoutManagerFactory.java b/plugins/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/layout/pdf/PDFLayoutManagerFactory.java
index a07ccbb90..887ecd48c 100644
--- a/plugins/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/layout/pdf/PDFLayoutManagerFactory.java
+++ b/plugins/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/layout/pdf/PDFLayoutManagerFactory.java
@@ -1,272 +1,277 @@
package org.eclipse.birt.report.engine.layout.pdf;
/***********************************************************************
* Copyright (c) 2004 Actuate Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - initial API and implementation
***********************************************************************/
import org.eclipse.birt.core.format.NumberFormatter;
import org.eclipse.birt.report.engine.content.IAutoTextContent;
import org.eclipse.birt.report.engine.content.ICellContent;
import org.eclipse.birt.report.engine.content.IContainerContent;
import org.eclipse.birt.report.engine.content.IContent;
import org.eclipse.birt.report.engine.content.IContentVisitor;
import org.eclipse.birt.report.engine.content.IDataContent;
import org.eclipse.birt.report.engine.content.IForeignContent;
import org.eclipse.birt.report.engine.content.IGroupContent;
import org.eclipse.birt.report.engine.content.IImageContent;
import org.eclipse.birt.report.engine.content.ILabelContent;
import org.eclipse.birt.report.engine.content.IListBandContent;
import org.eclipse.birt.report.engine.content.IListContent;
import org.eclipse.birt.report.engine.content.IListGroupContent;
import org.eclipse.birt.report.engine.content.IPageContent;
import org.eclipse.birt.report.engine.content.IRowContent;
import org.eclipse.birt.report.engine.content.ITableBandContent;
import org.eclipse.birt.report.engine.content.ITableContent;
import org.eclipse.birt.report.engine.content.ITableGroupContent;
import org.eclipse.birt.report.engine.content.ITextContent;
import org.eclipse.birt.report.engine.content.impl.LabelContent;
import org.eclipse.birt.report.engine.emitter.IContentEmitter;
import org.eclipse.birt.report.engine.executor.IReportItemExecutor;
import org.eclipse.birt.report.engine.internal.executor.dom.DOMReportItemExecutor;
import org.eclipse.birt.report.engine.ir.DimensionType;
import org.eclipse.birt.report.engine.layout.content.LineStackingExecutor;
import org.eclipse.birt.report.engine.layout.pdf.util.HTML2Content;
import org.eclipse.birt.report.engine.layout.pdf.util.PropertyUtil;
public class PDFLayoutManagerFactory
{
private ContentVisitor visitor = new ContentVisitor( );
PDFAbstractLM layoutManager = null;
PDFStackingLM parent = null;
private PDFLayoutEngineContext context = null;
protected HTML2Content converter = null;
protected IContentEmitter emitter;
protected IReportItemExecutor executor;
public PDFLayoutManagerFactory( PDFLayoutEngineContext context )
{
this.context = context;
}
public PDFAbstractLM createLayoutManager( PDFStackingLM parent,
IContent content, IContentEmitter emitter,
IReportItemExecutor executor )
{
this.parent = parent;
this.emitter = emitter;
this.executor = executor;
if ( executor instanceof LineStackingExecutor )
{
return new PDFLineAreaLM( context, parent, emitter, executor );
}
if ( content != null )
{
return (PDFAbstractLM) content.accept( visitor, null );
}
assert ( false );
return null;
}
private class ContentVisitor implements IContentVisitor
{
public Object visit( IContent content, Object value )
{
return visitContent( content, value );
}
public Object visitContent( IContent content, Object value )
{
boolean isInline = PropertyUtil.isInlineElement( content );
if ( isInline )
{
return new PDFTextInlineBlockLM( context, parent, content,
emitter, executor );
}
else
{
return new PDFBlockContainerLM( context, parent, content,
emitter, executor );
}
}
public Object visitPage( IPageContent page, Object value )
{
assert ( false );
return null;
}
public Object visitContainer( IContainerContent container, Object value )
{
return visitContent( container, value );
}
public Object visitTable( ITableContent table, Object value )
{
return new PDFTableLM( context, parent, table, emitter, executor );
}
public Object visitTableBand( ITableBandContent tableBand, Object value )
{
return new PDFTableBandLM( context, parent, tableBand, emitter,
executor );
}
public Object visitRow( IRowContent row, Object value )
{
return new PDFRowLM( context, parent, row, emitter, executor );
}
public Object visitCell( ICellContent cell, Object value )
{
return new PDFCellLM( context, parent, cell, emitter, executor );
}
public Object visitText( ITextContent text, Object value )
{
// FIXME
return handleText( text );
}
public Object visitLabel( ILabelContent label, Object value )
{
return handleText( label );
}
public Object visitData( IDataContent data, Object value )
{
return handleText( data );
}
public Object visitImage( IImageContent image, Object value )
{
boolean isInline = parent instanceof PDFLineAreaLM;
if ( isInline )
{
assert ( parent instanceof PDFLineAreaLM );
return new PDFImageLM( context, parent, image, emitter,
executor );
}
else
{
return new PDFImageBlockContainerLM( context, parent, image,
emitter, executor );
}
}
public Object visitForeign( IForeignContent foreign, Object value )
{
if ( IForeignContent.HTML_TYPE.equals( foreign.getRawType( ) ) )
{
if ( converter == null )
{
converter = new HTML2Content( foreign.getReportContent( )
.getDesign( ).getBasePath( ) );
}
// build content DOM tree for HTML text
converter.html2Content( foreign );
executor = new DOMReportItemExecutor( foreign );
executor.execute( );
return visitContent( foreign, value );
}
LabelContent label = new LabelContent( foreign );
label.setText( (String) foreign.getRawValue( ) );
return handleText( label );
}
public Object visitAutoText( IAutoTextContent autoText, Object value )
{
if ( IAutoTextContent.PAGE_NUMBER == autoText.getType( ) )
{
String originalPageNumber = autoText.getText( );
NumberFormatter nf = new NumberFormatter( );
String patternStr = autoText.getComputedStyle( )
.getNumberFormat( );
nf.applyPattern( patternStr );
autoText.setText( nf.format( Integer
.parseInt( originalPageNumber ) ) );
return handleText( autoText );
}
return new PDFTemplateLM( context, parent, autoText, emitter,
executor );
}
private Object handleText( ITextContent content )
{
boolean isInline = parent instanceof PDFLineAreaLM;
if ( isInline )
{
assert ( parent instanceof PDFLineAreaLM );
DimensionType width = content.getWidth( );
// if text contains line break or width is specified, this text
// will be regard as a inline-block area
if ( width != null /* || text.indexOf( '\n' )>=0 */)
{
return new PDFTextInlineBlockLM( context, parent, content,
emitter, executor );
}
else
{
return new PDFTextLM( context, parent, content, emitter,
executor );
}
}
else
{
+ String text = content.getText( );
+ if(text==null || "".equals( text ))
+ {
+ content.setText( " " );
+ }
return new PDFTextBlockContainerLM( context, parent, content,
emitter, executor );
}
}
public Object visitList( IListContent list, Object value )
{
return new PDFListLM( context, parent, list, emitter, executor );
}
public Object visitListBand( IListBandContent listBand, Object value )
{
assert ( false );
return null;
// return new PDFListBandLM(context, parent, listBand, emitter,
// executor);
}
public Object visitListGroup( IListGroupContent group, Object value )
{
return new PDFListGroupLM( context, parent, group, emitter,
executor );
}
public Object visitTableGroup( ITableGroupContent group, Object value )
{
return new PDFTableGroupLM( context, parent, group, emitter,
executor );
}
public Object visitGroup( IGroupContent group, Object value )
{
return new PDFListGroupLM( context, parent, group, emitter,
executor );
}
}
}
| true | true | private Object handleText( ITextContent content )
{
boolean isInline = parent instanceof PDFLineAreaLM;
if ( isInline )
{
assert ( parent instanceof PDFLineAreaLM );
DimensionType width = content.getWidth( );
// if text contains line break or width is specified, this text
// will be regard as a inline-block area
if ( width != null /* || text.indexOf( '\n' )>=0 */)
{
return new PDFTextInlineBlockLM( context, parent, content,
emitter, executor );
}
else
{
return new PDFTextLM( context, parent, content, emitter,
executor );
}
}
else
{
return new PDFTextBlockContainerLM( context, parent, content,
emitter, executor );
}
}
| private Object handleText( ITextContent content )
{
boolean isInline = parent instanceof PDFLineAreaLM;
if ( isInline )
{
assert ( parent instanceof PDFLineAreaLM );
DimensionType width = content.getWidth( );
// if text contains line break or width is specified, this text
// will be regard as a inline-block area
if ( width != null /* || text.indexOf( '\n' )>=0 */)
{
return new PDFTextInlineBlockLM( context, parent, content,
emitter, executor );
}
else
{
return new PDFTextLM( context, parent, content, emitter,
executor );
}
}
else
{
String text = content.getText( );
if(text==null || "".equals( text ))
{
content.setText( " " );
}
return new PDFTextBlockContainerLM( context, parent, content,
emitter, executor );
}
}
|
diff --git a/PacketHandler.java b/PacketHandler.java
index 436b676..5aca56b 100644
--- a/PacketHandler.java
+++ b/PacketHandler.java
@@ -1,86 +1,86 @@
package assets.recipehandler;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.inventory.ContainerPlayer;
import net.minecraft.inventory.ContainerWorkbench;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.network.INetworkManager;
import net.minecraft.network.packet.Packet;
import net.minecraft.network.packet.Packet250CustomPayload;
import cpw.mods.fml.common.network.IPacketHandler;
import cpw.mods.fml.common.network.PacketDispatcher;
import cpw.mods.fml.common.network.Player;
public class PacketHandler implements IPacketHandler{
@Override
public void onPacketData(INetworkManager manager, Packet250CustomPayload packet, Player player)
{
if(packet.channel.equals(Constants.CHANNEL))
{
handle(packet, (EntityPlayer)player);
}
}
private void handle(Packet250CustomPayload packet, EntityPlayer player)
{
DataInputStream inStream = new DataInputStream(new ByteArrayInputStream(packet.data));
int[] data = new int[4];
try {
for(int id = 0; id < data.length; id++)
data[id] = inStream.readInt();
} catch (IOException e) {
e.printStackTrace();
return;
}
IInventory result = null;
- if(player.entityId==data[3])
+ if(player.entityId==data[0])
{
if(player.openContainer instanceof ContainerPlayer)
{
result = ((ContainerPlayer)player.openContainer).craftResult;
}
else if(player.openContainer instanceof ContainerWorkbench)
{
result = ((ContainerWorkbench)player.openContainer).craftResult;
}
}
if(result != null)
{
- result.setInventorySlotContents(0, new ItemStack(data[0],data[1],data[2]));
+ result.setInventorySlotContents(0, new ItemStack(data[1],data[2],data[3]));
if(player instanceof EntityPlayerMP)
{
((EntityPlayerMP)player).playerNetServerHandler.sendPacketToPlayer(packet);
}
}
}
public static Packet getPacket(int... data)
{
ByteArrayOutputStream bos = new ByteArrayOutputStream(4*data.length);
DataOutputStream outputStream = new DataOutputStream(bos);
try
{
for(int d:data)
outputStream.writeInt(d);
}
catch (IOException ex)
{
ex.printStackTrace();
}
Packet250CustomPayload packet = new Packet250CustomPayload();
packet.channel = Constants.CHANNEL;
packet.data = bos.toByteArray();
packet.length = bos.size();
return packet;
}
}
| false | true | private void handle(Packet250CustomPayload packet, EntityPlayer player)
{
DataInputStream inStream = new DataInputStream(new ByteArrayInputStream(packet.data));
int[] data = new int[4];
try {
for(int id = 0; id < data.length; id++)
data[id] = inStream.readInt();
} catch (IOException e) {
e.printStackTrace();
return;
}
IInventory result = null;
if(player.entityId==data[3])
{
if(player.openContainer instanceof ContainerPlayer)
{
result = ((ContainerPlayer)player.openContainer).craftResult;
}
else if(player.openContainer instanceof ContainerWorkbench)
{
result = ((ContainerWorkbench)player.openContainer).craftResult;
}
}
if(result != null)
{
result.setInventorySlotContents(0, new ItemStack(data[0],data[1],data[2]));
if(player instanceof EntityPlayerMP)
{
((EntityPlayerMP)player).playerNetServerHandler.sendPacketToPlayer(packet);
}
}
}
| private void handle(Packet250CustomPayload packet, EntityPlayer player)
{
DataInputStream inStream = new DataInputStream(new ByteArrayInputStream(packet.data));
int[] data = new int[4];
try {
for(int id = 0; id < data.length; id++)
data[id] = inStream.readInt();
} catch (IOException e) {
e.printStackTrace();
return;
}
IInventory result = null;
if(player.entityId==data[0])
{
if(player.openContainer instanceof ContainerPlayer)
{
result = ((ContainerPlayer)player.openContainer).craftResult;
}
else if(player.openContainer instanceof ContainerWorkbench)
{
result = ((ContainerWorkbench)player.openContainer).craftResult;
}
}
if(result != null)
{
result.setInventorySlotContents(0, new ItemStack(data[1],data[2],data[3]));
if(player instanceof EntityPlayerMP)
{
((EntityPlayerMP)player).playerNetServerHandler.sendPacketToPlayer(packet);
}
}
}
|
diff --git a/mcp/src/minecraft/sammko/quantumCraft/client/ClientTickHandler.java b/mcp/src/minecraft/sammko/quantumCraft/client/ClientTickHandler.java
index d41ca8c..63abe48 100755
--- a/mcp/src/minecraft/sammko/quantumCraft/client/ClientTickHandler.java
+++ b/mcp/src/minecraft/sammko/quantumCraft/client/ClientTickHandler.java
@@ -1,74 +1,74 @@
package sammko.quantumCraft.client;
import cpw.mods.fml.common.ITickHandler;
import cpw.mods.fml.common.TickType;
import java.util.EnumSet;
import sammko.quantumCraft.core.QuantumCraftSettings;
import sammko.quantumCraft.items.ItemInitializator;
import net.minecraft.client.Minecraft;
import net.minecraft.client.entity.EntityClientPlayerMP;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.GuiIngame;
import net.minecraft.client.gui.ScaledResolution;
import net.minecraft.client.settings.GameSettings;
import net.minecraft.client.settings.KeyBinding;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.entity.player.PlayerCapabilities;
import net.minecraft.item.ItemStack;
import net.minecraft.src.ModLoader;
public class ClientTickHandler implements ITickHandler {
public static Minecraft mc = ModLoader.getMinecraftInstance();
public EnumSet ticks() {
return EnumSet.of(TickType.WORLD, TickType.WORLDLOAD, TickType.CLIENT,
TickType.RENDER);
}
public String getItemDamage(ItemStack item) {
if (mc.inGameHasFocus == true && mc.thePlayer.inventory.getCurrentItem() != null && mc.thePlayer.inventory.getCurrentItem().itemID == QuantumCraftSettings.CrystalPickaxeID + 256 ) {
final int damage = item.getItemDamageForDisplay();
final int damageLeft = 500-damage;
String damageString = null;
if (damageLeft >= 300){
- damageString = "�a" + damageLeft + "/500";
+ damageString = "§a" + damageLeft + "/500";
}
else if (damageLeft >= 100){
- damageString = "�e" + damageLeft + "/500";
+ damageString = "§e" + damageLeft + "/500";
}
else if (damageLeft >= 50){
- damageString = "�5" + damageLeft + "/500";
+ damageString = "§5" + damageLeft + "/500";
}
return damageString;
}else{
return "";
}
}
@Override
public void tickStart(EnumSet<TickType> type, Object... tickData) {
}
@Override
public void tickEnd(EnumSet<TickType> type, Object... tickData) {
if (mc.inGameHasFocus == true) {
ItemStack itemstack = mc.thePlayer.inventory.getCurrentItem();
mc.fontRenderer.drawString(getItemDamage(itemstack), 1, 1, 1);
//mc.fontRenderer.drawString("test", 1, 1, 1);
}
}
@Override
public String getLabel() {
// TODO Auto-generated method stub
return null;
}
}
| false | true | public String getItemDamage(ItemStack item) {
if (mc.inGameHasFocus == true && mc.thePlayer.inventory.getCurrentItem() != null && mc.thePlayer.inventory.getCurrentItem().itemID == QuantumCraftSettings.CrystalPickaxeID + 256 ) {
final int damage = item.getItemDamageForDisplay();
final int damageLeft = 500-damage;
String damageString = null;
if (damageLeft >= 300){
damageString = "�a" + damageLeft + "/500";
}
else if (damageLeft >= 100){
damageString = "�e" + damageLeft + "/500";
}
else if (damageLeft >= 50){
damageString = "�5" + damageLeft + "/500";
}
return damageString;
}else{
return "";
}
}
| public String getItemDamage(ItemStack item) {
if (mc.inGameHasFocus == true && mc.thePlayer.inventory.getCurrentItem() != null && mc.thePlayer.inventory.getCurrentItem().itemID == QuantumCraftSettings.CrystalPickaxeID + 256 ) {
final int damage = item.getItemDamageForDisplay();
final int damageLeft = 500-damage;
String damageString = null;
if (damageLeft >= 300){
damageString = "§a" + damageLeft + "/500";
}
else if (damageLeft >= 100){
damageString = "§e" + damageLeft + "/500";
}
else if (damageLeft >= 50){
damageString = "§5" + damageLeft + "/500";
}
return damageString;
}else{
return "";
}
}
|
diff --git a/src-standard/test/java/javax/time/chrono/TestISODate.java b/src-standard/test/java/javax/time/chrono/TestISODate.java
index adb30538..5f4e2ab1 100644
--- a/src-standard/test/java/javax/time/chrono/TestISODate.java
+++ b/src-standard/test/java/javax/time/chrono/TestISODate.java
@@ -1,417 +1,417 @@
/*
* Copyright (c) 2008-2012, Stephen Colebourne & Michael Nascimento Santos
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of JSR-310 nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package javax.time.chrono;
import static javax.time.calendrical.LocalDateTimeField.DAY_OF_MONTH;
import static javax.time.calendrical.LocalDateTimeField.MONTH_OF_YEAR;
import static javax.time.calendrical.LocalDateTimeField.YEAR;
import static javax.time.calendrical.LocalPeriodUnit.DAYS;
import static javax.time.calendrical.LocalPeriodUnit.MONTHS;
import static javax.time.calendrical.LocalPeriodUnit.WEEKS;
import static javax.time.calendrical.LocalPeriodUnit.YEARS;
import static javax.time.chrono.ISOEra.ISO_BCE;
import static javax.time.chrono.ISOEra.ISO_CE;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertNull;
import static org.testng.Assert.assertTrue;
import java.math.BigDecimal;
import javax.time.Instant;
import javax.time.LocalDate;
import javax.time.LocalDateTime;
import javax.time.LocalTime;
import javax.time.OffsetDate;
import javax.time.OffsetDateTime;
import javax.time.OffsetTime;
import javax.time.Period;
import javax.time.ZoneId;
import javax.time.ZoneOffset;
import javax.time.ZonedDateTime;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class TestISODate {
private ChronoDate TEST_2007_07_15;
private ChronoDate TEST_2007_07_16;
private LocalDate TEST_LOCAL_2007_07_15;
@BeforeMethod(groups="tck")
public void setUp() {
TEST_2007_07_15 = ISOChronology.INSTANCE.date(2007, 7, 15);
TEST_2007_07_16 = ISOChronology.INSTANCE.date(2007, 7, 16);
TEST_LOCAL_2007_07_15 = LocalDate.of(2007, 7, 15);
}
//-----------------------------------------------------------------
@Test(expectedExceptions=NullPointerException.class, groups="implementation")
public void testFromFactory_null() {
ISODate.from(null);
}
//-----------------------------------------------------------------------
// extract(Class)
//-----------------------------------------------------------------------
@Test(groups={"tck"})
public void test_extract_Class() {
ChronoDate test = TEST_2007_07_15;
assertEquals(test.extract(LocalDate.class), test.toLocalDate());
assertEquals(test.extract(LocalTime.class), null);
assertEquals(test.extract(LocalDateTime.class), null);
assertEquals(test.extract(OffsetDate.class), null);
assertEquals(test.extract(OffsetTime.class), null);
assertEquals(test.extract(OffsetDateTime.class), null);
- assertEquals(test.extract(ZonedDateTime.class), test);
+ assertEquals(test.extract(ZonedDateTime.class), null);
assertEquals(test.extract(ZoneOffset.class), null);
assertEquals(test.extract(ZoneId.class), null);
assertEquals(test.extract(Instant.class), null);
assertEquals(test.extract(Chronology.class), test.getChronology());
assertEquals(test.extract(String.class), null);
assertEquals(test.extract(BigDecimal.class), null);
assertEquals(test.extract(null), null);
}
//-----------------------------------------------------------------
// extract()
//-----------------------------------------------------------------
@Test(groups="tck")
public void test_extract_LocalDate() {
assertEquals(TEST_2007_07_15.extract(LocalDate.class), TEST_LOCAL_2007_07_15);
}
@Test(groups="tck")
public void test_extract_Chrono() {
assertEquals(TEST_2007_07_15.extract(Chronology.class), ISOChronology.INSTANCE);
}
@Test(groups="tck")
public void test_extract_null() {
assertNull(TEST_2007_07_15.extract(null));
}
//-----------------------------------------------------------------
@Test(groups="tck")
public void test_Getters() {
check(TEST_2007_07_15, 2007, 7, 15);
}
//-----------------------------------------------------------------
// get()
//-----------------------------------------------------------------
@Test(groups="tck")
public void testFieldGetters() {
assertEquals(TEST_2007_07_15.get(YEAR), 2007);
assertEquals(TEST_2007_07_15.get(MONTH_OF_YEAR), 7);
assertEquals(TEST_2007_07_15.get(DAY_OF_MONTH), 15);
}
@Test(expectedExceptions=NullPointerException.class, groups="tck")
public void testFieldGetters_null() {
TEST_2007_07_15.get(null);
}
//-----------------------------------------------------------------
// getChronology()
//-----------------------------------------------------------------
@Test(groups="tck")
public void test_getChronology() {
assertEquals(TEST_2007_07_15.getChronology(), ISOChronology.INSTANCE);
}
//-----------------------------------------------------------------
// isAfter()
//-----------------------------------------------------------------
@Test(groups="tck")
public void test_IsAfter() {
assertTrue(TEST_2007_07_16.isAfter(TEST_2007_07_15));
assertFalse(TEST_2007_07_15.isAfter(TEST_2007_07_16));
assertFalse(TEST_2007_07_15.isAfter(TEST_2007_07_15));
}
@Test(expectedExceptions=NullPointerException.class, groups="tck")
public void test_IsAfter_null() {
TEST_2007_07_15.isAfter(null);
}
//-----------------------------------------------------------------
// isBefore()
//-----------------------------------------------------------------
@Test(groups="tck")
public void test_IsBefore() {
assertTrue(TEST_2007_07_15.isBefore(TEST_2007_07_16));
assertFalse(TEST_2007_07_16.isBefore(TEST_2007_07_15));
assertFalse(TEST_2007_07_15.isBefore(TEST_2007_07_15));
}
@Test(expectedExceptions=NullPointerException.class, groups="tck")
public void test_IsBefore_null() {
TEST_2007_07_15.isBefore(null);
}
//-----------------------------------------------------------------
// isLeapYear()
//-----------------------------------------------------------------
@DataProvider(name="leapYears")
Object[][] leapYearInformation() {
return new Object[][] {
{2000, true},
{1996, true},
{1600, true},
{1900, false},
{2100, false},
};
}
@Test(dataProvider="leapYears", groups="tck")
public void testIsLeapYear(int year, boolean isLeapYear) {
assertEquals(TEST_2007_07_15.withYearOfEra(year).isLeapYear(), isLeapYear);
}
//-----------------------------------------------------------------
// lengthOfMonth()
//-----------------------------------------------------------------
@DataProvider(name="monthLengths")
Object[][] monthLengths() {
return new Object[][] {
{2000, 4, 30},
{2001, 4, 30},
{2000, 2, 29},
{2001, 2, 28},
{2000, 5, 31},
{2001, 5, 31},
};
}
@Test(dataProvider="monthLengths", groups="tck")
public void test_lengthOfMonth(int year, int monthOfYear, int daysInMonth) {
ChronoDate date = ISOChronology.INSTANCE.date(year, monthOfYear, 1);
assertEquals(date.lengthOfMonth(), daysInMonth);
}
//-----------------------------------------------------------------
// lengthOfYear()
//-----------------------------------------------------------------
@Test(dataProvider="leapYears", groups="tck")
public void test_lengthOfYear(int year, boolean isLeapYear) {
int lengthOfYear = isLeapYear ? 366 : 365;
assertEquals(TEST_2007_07_15.withYearOfEra(year).lengthOfYear(), lengthOfYear);
}
//-----------------------------------------------------------------
// minusDays()
//-----------------------------------------------------------------
@DataProvider(name="minusDays")
Object[][] minusDays() {
return new Object[][] {
{1, 2007, 7, 14},
{14, 2007, 7, 1},
{15, 2007, 6, 30},
{365, 2006, 7, 15},
};
}
@Test(dataProvider="minusDays", groups="tck")
public void test_minusDays(long daysToSubtract, int year, int month, int dayOfMonth) {
ChronoDate newDate = TEST_2007_07_15.minusDays(daysToSubtract);
check(newDate, year, month, dayOfMonth);
}
//-----------------------------------------------------------------
// minusWeeks()
//-----------------------------------------------------------------
@DataProvider(name="minusWeeks")
Object[][] minusWeeks() {
return new Object[][] {
{1, 2007, 7, 8},
{3, 2007, 6, 24},
{52, 2006, 7, 16},
};
}
@Test(dataProvider="minusWeeks", groups="tck")
public void test_minusWeeks(long weeksToSubtract, int year, int month, int dayOfMonth) {
ChronoDate newDate = TEST_2007_07_15.minusWeeks(weeksToSubtract);
check(newDate, year, month, dayOfMonth);
}
//-----------------------------------------------------------------
// minusMonths()
//-----------------------------------------------------------------
@DataProvider(name="minusMonths")
Object[][] minusMonths() {
return new Object[][] {
{1, 2007, 6, 15},
{7, 2006, 12, 15},
{12, 2006, 7, 15},
{24, 2005, 7, 15},
};
}
@Test(dataProvider="minusMonths", groups="tck")
public void test_minusMonths(long monthsToSubtract, int year, int month, int dayOfMonth) {
ChronoDate newDate = TEST_2007_07_15.minusMonths(monthsToSubtract);
check(newDate, year, month, dayOfMonth);
}
@Test(groups="tck")
public void test_minusMonths_missingDay() {
ChronoDate newDate = ISOChronology.INSTANCE.date(2012, 3, 31).minusMonths(1);
check(newDate, 2012, 2, 29);
}
//-----------------------------------------------------------------
// minusYears()
//-----------------------------------------------------------------
@DataProvider(name="minusYears")
Object[][] minusYears() {
return new Object[][] {
{1, 2006, 7, 15},
{8, 1999, 7, 15},
{2007, 0, 7, 15},
{2008, -1, 7, 15},
};
}
@Test(dataProvider="minusYears", groups="tck")
public void test_minusYears(long yearsToSubtract, int year, int month, int dayOfMonth) {
ChronoDate newDate = TEST_2007_07_15.minusYears(yearsToSubtract);
System.out.println(newDate);
check(newDate, year, month, dayOfMonth);
if (year > 0) {
assertEquals(newDate.getYearOfEra(), year);
assertEquals(newDate.getEra(), ISO_CE);
} else {
assertEquals(newDate.getYearOfEra(), 1 + (-1 * year));
assertEquals(newDate.getEra(), ISO_BCE);
}
}
@Test(groups="tck")
public void test_minusYears_missingDay() {
ChronoDate newDate = ISOChronology.INSTANCE.date(2012, 2, 29).minusYears(1);
check(newDate, 2011, 2, 28);
}
//-----------------------------------------------------------------
// minus(long, PeriodUnit)
//-----------------------------------------------------------------
@Test(dataProvider="minusDays", groups="tck")
public void test_minus_daysPeriod(long daysToSubtract, int year, int month, int dayOfMonth) {
ChronoDate newDate = TEST_2007_07_15.minus(daysToSubtract, DAYS);
check(newDate, year, month, dayOfMonth);
}
@Test(dataProvider="minusWeeks", groups="tck")
public void test_minus_weeksPeriod(long weeksToSubtract, int year, int month, int dayOfMonth) {
ChronoDate newDate = TEST_2007_07_15.minus(weeksToSubtract, WEEKS);
check(newDate, year, month, dayOfMonth);
}
@Test(dataProvider="minusMonths", groups="tck")
public void test_minus_monthsPeriod(long monthsToSubtract, int year, int month, int dayOfMonth) {
ChronoDate newDate = TEST_2007_07_15.minus(monthsToSubtract, MONTHS);
check(newDate, year, month, dayOfMonth);
}
@Test(dataProvider="minusYears", groups="tck")
public void test_minus_yearsPeriod(long yearsToSubtract, int year, int month, int dayOfMonth) {
ChronoDate newDate = TEST_2007_07_15.minus(yearsToSubtract, YEARS);
check(newDate, year, month, dayOfMonth);
}
@Test(groups="tck")
public void test_minus_monthsPeriod_missingDay() {
ChronoDate newDate = ISOChronology.INSTANCE.date(2012, 3, 31).minus(1, MONTHS);
check(newDate, 2012, 2, 29);
}
@Test(expectedExceptions=NullPointerException.class, groups="tck")
public void test_minus_null() {
TEST_2007_07_15.minus(1, null);
}
//-----------------------------------------------------------------
// minus(Period)
//-----------------------------------------------------------------
@Test(dataProvider="minusDays", groups="tck")
public void test_minusPeriod_daysPeriod(long daysToSubtract, int year, int month, int dayOfMonth) {
ChronoDate newDate = TEST_2007_07_15.minus(Period.of(daysToSubtract, DAYS));
check(newDate, year, month, dayOfMonth);
}
@Test(dataProvider="minusWeeks", groups="tck")
public void test_minusPeriod_weeksPeriod(long weeksToSubtract, int year, int month, int dayOfMonth) {
ChronoDate newDate = TEST_2007_07_15.minus(Period.of(weeksToSubtract, WEEKS));
check(newDate, year, month, dayOfMonth);
}
@Test(dataProvider="minusMonths", groups="tck")
public void test_minusPeriod_monthsPeriod(long monthsToSubtract, int year, int month, int dayOfMonth) {
ChronoDate newDate = TEST_2007_07_15.minus(Period.of(monthsToSubtract, MONTHS));
check(newDate, year, month, dayOfMonth);
}
@Test(dataProvider="minusYears", groups="tck")
public void test_minusPeriod_yearsPeriod(long yearsToSubtract, int year, int month, int dayOfMonth) {
ChronoDate newDate = TEST_2007_07_15.minus(Period.of(yearsToSubtract, YEARS));
check(newDate, year, month, dayOfMonth);
}
@Test(groups="tck")
public void test_minusPeriod_monthsPeriod_missingDay() {
ChronoDate newDate = ISOChronology.INSTANCE.date(2012, 3, 31).minus(Period.of(1, MONTHS));
check(newDate, 2012, 2, 29);
}
@Test(expectedExceptions=NullPointerException.class, groups="tck")
public void test_minusPeriod_null() {
TEST_2007_07_15.minus(null);
}
//-----------------------------------------------------------------
// TODO: with and plus methods
//-----------------------------------------------------------------
private void check(ChronoDate date, int prolepticYear, int month, int dayOfMonth) {
assertEquals(date.getProlepticYear(), prolepticYear);
assertEquals(date.getMonth(), month);
assertEquals(date.getDayOfMonth(), dayOfMonth);
}
}
| true | true | public void test_extract_Class() {
ChronoDate test = TEST_2007_07_15;
assertEquals(test.extract(LocalDate.class), test.toLocalDate());
assertEquals(test.extract(LocalTime.class), null);
assertEquals(test.extract(LocalDateTime.class), null);
assertEquals(test.extract(OffsetDate.class), null);
assertEquals(test.extract(OffsetTime.class), null);
assertEquals(test.extract(OffsetDateTime.class), null);
assertEquals(test.extract(ZonedDateTime.class), test);
assertEquals(test.extract(ZoneOffset.class), null);
assertEquals(test.extract(ZoneId.class), null);
assertEquals(test.extract(Instant.class), null);
assertEquals(test.extract(Chronology.class), test.getChronology());
assertEquals(test.extract(String.class), null);
assertEquals(test.extract(BigDecimal.class), null);
assertEquals(test.extract(null), null);
}
| public void test_extract_Class() {
ChronoDate test = TEST_2007_07_15;
assertEquals(test.extract(LocalDate.class), test.toLocalDate());
assertEquals(test.extract(LocalTime.class), null);
assertEquals(test.extract(LocalDateTime.class), null);
assertEquals(test.extract(OffsetDate.class), null);
assertEquals(test.extract(OffsetTime.class), null);
assertEquals(test.extract(OffsetDateTime.class), null);
assertEquals(test.extract(ZonedDateTime.class), null);
assertEquals(test.extract(ZoneOffset.class), null);
assertEquals(test.extract(ZoneId.class), null);
assertEquals(test.extract(Instant.class), null);
assertEquals(test.extract(Chronology.class), test.getChronology());
assertEquals(test.extract(String.class), null);
assertEquals(test.extract(BigDecimal.class), null);
assertEquals(test.extract(null), null);
}
|
diff --git a/impl/logic/src/java/org/sakaiproject/evaluation/logic/impl/EvalResponsesLogicImpl.java b/impl/logic/src/java/org/sakaiproject/evaluation/logic/impl/EvalResponsesLogicImpl.java
index aa467ecd..36e9f526 100644
--- a/impl/logic/src/java/org/sakaiproject/evaluation/logic/impl/EvalResponsesLogicImpl.java
+++ b/impl/logic/src/java/org/sakaiproject/evaluation/logic/impl/EvalResponsesLogicImpl.java
@@ -1,408 +1,409 @@
/******************************************************************************
* EvalResponsesLogicImpl.java - created by [email protected]
*****************************************************************************/
package org.sakaiproject.evaluation.logic.impl;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.sakaiproject.evaluation.dao.EvaluationDao;
import org.sakaiproject.evaluation.logic.EvalEvaluationsLogic;
import org.sakaiproject.evaluation.logic.EvalExternalLogic;
import org.sakaiproject.evaluation.logic.EvalItemsLogic;
import org.sakaiproject.evaluation.logic.EvalResponsesLogic;
import org.sakaiproject.evaluation.logic.EvalSettings;
import org.sakaiproject.evaluation.logic.model.EvalGroup;
import org.sakaiproject.evaluation.logic.utils.EvalUtils;
import org.sakaiproject.evaluation.logic.utils.TemplateItemUtils;
import org.sakaiproject.evaluation.model.EvalAnswer;
import org.sakaiproject.evaluation.model.EvalEvaluation;
import org.sakaiproject.evaluation.model.EvalItem;
import org.sakaiproject.evaluation.model.EvalResponse;
import org.sakaiproject.evaluation.model.EvalTemplateItem;
import org.sakaiproject.evaluation.model.constant.EvalConstants;
import org.sakaiproject.genericdao.api.finders.ByPropsFinder;
/**
* Implementation for EvalResponsesLogic
*
* @author Aaron Zeckoski ([email protected])
*/
public class EvalResponsesLogicImpl implements EvalResponsesLogic {
private static Log log = LogFactory.getLog(EvalResponsesLogicImpl.class);
private EvaluationDao dao;
public void setDao(EvaluationDao dao) {
this.dao = dao;
}
private EvalExternalLogic external;
public void setExternalLogic(EvalExternalLogic external) {
this.external = external;
}
// requires access to evaluations logic to check if user can take the evaluation
private EvalEvaluationsLogic evaluationsLogic;
public void setEvaluationsLogic(EvalEvaluationsLogic evaluationsLogic) {
this.evaluationsLogic = evaluationsLogic;
}
private EvalItemsLogic itemsLogic;
public void setItemsLogic(EvalItemsLogic itemsLogic) {
this.itemsLogic = itemsLogic;
}
private EvalSettings evalSettings;
public void setEvalSettings(EvalSettings evalSettings) {
this.evalSettings = evalSettings;
}
// INIT method
public void init() {
log.debug("Init");
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.evaluation.logic.EvalResponsesLogic#getNonResponders(java.lang.Long)
*/
public Set<String> getNonResponders(Long evaluationId, EvalGroup group) {
Long[] evaluationIds = { evaluationId };
Set<String> userIds = new HashSet<String>();
// get everyone permitted to take the evaluation
Set<String> ids = external.getUserIdsForEvalGroup(group.evalGroupId, EvalConstants.PERM_TAKE_EVALUATION);
for (Iterator<String> i = ids.iterator(); i.hasNext();) {
String userId = i.next();
// if this user hasn't submitted a response, add the user's id
if (getEvaluationResponses(userId, evaluationIds).isEmpty()) {
userIds.add(userId);
}
}
return userIds;
}
public EvalResponse getResponseById(Long responseId) {
log.debug("responseId: " + responseId);
// get the response by passing in id
return (EvalResponse) dao.findById(EvalResponse.class, responseId);
}
@SuppressWarnings("unchecked")
public List<EvalResponse> getEvaluationResponses(String userId, Long[] evaluationIds) {
log.debug("userId: " + userId + ", evaluationIds: " + evaluationIds);
if (evaluationIds.length <= 0) {
throw new IllegalArgumentException("evaluationIds cannot be empty");
}
// check that the ids are actually valid
int count = dao.countByProperties(EvalEvaluation.class, new String[] { "id" }, new Object[] { evaluationIds });
if (count != evaluationIds.length) {
throw new IllegalArgumentException("One or more invalid evaluation ids in evaluationIds: " + evaluationIds);
}
if (external.isUserAdmin(userId)) {
// if user is admin then return all matching responses for this evaluation
return dao.findByProperties(EvalResponse.class, new String[] { "evaluation.id" },
new Object[] { evaluationIds }, new int[] { ByPropsFinder.EQUALS }, new String[] { "id" });
} else {
// not admin, only return the responses for this user
return dao.findByProperties(EvalResponse.class, new String[] { "owner", "evaluation.id" }, new Object[] {
userId, evaluationIds }, new int[] { ByPropsFinder.EQUALS, ByPropsFinder.EQUALS },
new String[] { "id" });
}
}
public int countResponses(Long evaluationId, String evalGroupId) {
log.debug("evaluationId: " + evaluationId + ", evalGroupId: " + evalGroupId);
if (dao.countByProperties(EvalEvaluation.class, new String[] { "id" }, new Object[] { evaluationId }) <= 0) {
throw new IllegalArgumentException("Could not find evaluation with id: " + evaluationId);
}
if (evalGroupId == null) {
// returns count of all responses in all eval groups if evalGroupId
// is null
return dao.countByProperties(EvalResponse.class, new String[] { "evaluation.id" },
new Object[] { evaluationId });
} else {
// returns count of responses in this evalGroupId only if set
return dao.countByProperties(EvalResponse.class, new String[] { "evaluation.id", "evalGroupId" },
new Object[] { evaluationId, evalGroupId });
}
}
public List<EvalAnswer> getEvalAnswers(Long itemId, Long evaluationId, String[] evalGroupIds) {
log.debug("itemId: " + itemId + ", evaluationId: " + evaluationId);
if (dao.countByProperties(EvalItem.class, new String[] { "id" }, new Object[] { itemId }) <= 0) {
throw new IllegalArgumentException("Could not find item with id: " + itemId);
}
if (dao.countByProperties(EvalEvaluation.class, new String[] { "id" }, new Object[] { evaluationId }) <= 0) {
throw new IllegalArgumentException("Could not find evaluation with id: " + evaluationId);
}
return dao.getAnswers(itemId, evaluationId, evalGroupIds);
}
public List<Long> getEvalResponseIds(Long evaluationId, String[] evalGroupIds) {
log.debug("evaluationId: " + evaluationId);
if (dao.countByProperties(EvalEvaluation.class, new String[] { "id" }, new Object[] { evaluationId }) <= 0) {
throw new IllegalArgumentException("Could not find evaluation with id: " + evaluationId);
}
return dao.getResponseIds(evaluationId, evalGroupIds);
}
@SuppressWarnings("unchecked")
public void saveResponse(EvalResponse response, String userId) {
log.debug("userId: " + userId + ", response: " + response.getId() + ", evalGroupId: " + response.getEvalGroupId());
// set the date modified
response.setLastModified(new Date());
if (response.getId() != null) {
// TODO - existing response, don't allow change to any setting
// except starttime, endtime, and answers
}
// fill in any default values and nulls here
// check perms and evaluation state
if (checkUserModifyResponse(userId, response)) {
// make sure the user can take this evalaution
Long evaluationId = response.getEvaluation().getId();
String context = response.getEvalGroupId();
if (!evaluationsLogic.canTakeEvaluation(userId, evaluationId, context)) {
throw new IllegalStateException("User (" + userId + ") cannot take this evaluation (" + evaluationId
+ ") in this evalGroupId (" + context + ") right now");
}
// check to make sure answers are valid for this evaluation
if (response.getAnswers() != null && !response.getAnswers().isEmpty()) {
checkAnswersValidForEval(response);
} else {
if (response.getEndTime() != null) {
// the response is complete (submission of an evaluation) and not just creating the empty response
// check if answers are required to be filled in
Boolean unansweredAllowed = (Boolean)evalSettings.get(EvalSettings.STUDENT_ALLOWED_LEAVE_UNANSWERED);
if (unansweredAllowed == null) {
unansweredAllowed = response.getEvaluation().getBlankResponsesAllowed();
}
if (unansweredAllowed.booleanValue() == false) {
// all items must be completed so die if they are not
throw new IllegalStateException("User submitted a blank response and there are required answers");
}
}
response.setAnswers(new HashSet());
}
// save everything in one transaction
// response has to be saved first
Set<EvalResponse> responseSet = new HashSet<EvalResponse>();
responseSet.add(response);
Set<EvalAnswer> answersSet = response.getAnswers();
dao.saveMixedSet(new Set[] {responseSet, answersSet});
if (response.getEndTime() != null) {
// the response is complete (submission of an evaluation) and not just creating the empty response
// so lock evaluation
log.info("Locking evaluation (" + response.getEvaluation().getId() + ") and associated entities");
dao.lockEvaluation(response.getEvaluation());
}
int answerCount = response.getAnswers() == null ? 0 : response.getAnswers().size();
log.info("User (" + userId + ") saved response (" + response.getId() + "), evalGroupId ("
+ response.getEvalGroupId() + ") and " + answerCount + " answers");
return;
}
// should not get here so die if we do
throw new RuntimeException("User (" + userId + ") could NOT save response (" + response.getId()
+ "), evalGroupId: " + response.getEvalGroupId());
}
// PERMISSIONS
public boolean canModifyResponse(String userId, Long responseId) {
log.debug("userId: " + userId + ", responseId: " + responseId);
// get the response by id
EvalResponse response = (EvalResponse) dao.findById(EvalResponse.class, responseId);
if (response == null) {
throw new IllegalArgumentException("Cannot find response with id: " + responseId);
}
// valid state, check perms and locked
try {
return checkUserModifyResponse(userId, response);
} catch (RuntimeException e) {
log.info(e.getMessage());
}
return false;
}
// INTERNAL METHODS
/**
* Check if user has permission to modify this response
*
* @param userId
* @param response
* @return true if they do, exception otherwise
*/
protected boolean checkUserModifyResponse(String userId, EvalResponse response) {
log.debug("evalGroupId: " + response.getEvalGroupId() + ", userId: " + userId);
String state = EvalUtils.getEvaluationState(response.getEvaluation());
if (EvalConstants.EVALUATION_STATE_ACTIVE.equals(state) || EvalConstants.EVALUATION_STATE_ACTIVE.equals(state)) {
// admin CAN save responses -AZ
// // check admin (admins can never save responses)
// if (external.isUserAdmin(userId)) {
// throw new IllegalArgumentException("Admin user (" + userId + ") cannot create response ("
// + response.getId() + "), admins can never save responses");
// }
// check ownership
if (response.getOwner().equals(userId)) {
return true;
} else {
throw new SecurityException("User (" + userId + ") cannot modify response (" + response.getId()
+ ") without permissions");
}
} else {
throw new IllegalStateException("Evaluation state (" + state + ") not valid for modifying responses");
}
}
/**
* Checks the answers in the response for validity<br/>
*
* @param response
* @return true if all answers valid, exception otherwise
*/
protected boolean checkAnswersValidForEval(EvalResponse response) {
// get a list of the valid templateItems for this evaluation
EvalEvaluation eval = response.getEvaluation();
Long evalId = eval.getId();
- List<EvalTemplateItem> allTemplateItems = itemsLogic.getTemplateItemsForEvaluation(evalId, null, null, null);
+ // TODO - make this more efficient by limiting the nodes, instructors, and groups
+ List<EvalTemplateItem> allTemplateItems = itemsLogic.getTemplateItemsForEvaluation(evalId, new String[] {}, new String[] {}, new String[] {});
// OLD - this should use a method elsewhere -AZ
// EvalEvaluation eval = response.getEvaluation();
// Long templateId = eval.getTemplate().getId();
// List<EvalTemplateItem> allTemplateItems =
// dao.findByProperties(EvalTemplateItem.class,
// new String[] { "template.id" },
// new Object[] { templateId });
List<EvalTemplateItem> templateItems = TemplateItemUtils.getAnswerableTemplateItems(allTemplateItems);
// put all templateItemIds into a set for easy comparison
Set<Long> templateItemIds = new HashSet<Long>();
for (int i = 0; i < templateItems.size(); i++) {
templateItemIds.add(((EvalTemplateItem) templateItems.get(i)).getId());
}
// check the answers
Set<Long> answeredTemplateItemIds = new HashSet<Long>();
for (Iterator<EvalAnswer> iter = response.getAnswers().iterator(); iter.hasNext();) {
EvalAnswer answer = (EvalAnswer) iter.next();
if (answer.getNumeric() == null && answer.getText() == null) {
throw new IllegalArgumentException("Cannot save blank answers: answer for templateItem: "
+ answer.getTemplateItem().getId());
}
// make sure the item and template item are available for this answer
if (answer.getTemplateItem() == null || answer.getTemplateItem().getItem() == null) {
throw new IllegalArgumentException("NULL templateItem or templateItem.item for answer: " +
"Answers must have the templateItem set, and that must have the item set");
}
// verify the base state of new answers
if (answer.getId() == null) {
// force the item to be set correctly
answer.setItem(answer.getTemplateItem().getItem());
// check that the associated id is filled in for associated items
if (EvalConstants.ITEM_CATEGORY_COURSE.equals(answer.getTemplateItem().getItemCategory())) {
if (answer.getAssociatedId() != null) {
log.warn("Course answers should have the associated id field blank, for templateItem: "
+ answer.getTemplateItem().getId());
}
answer.setAssociatedId(null);
answer.setAssociatedType(null);
} else if (EvalConstants.ITEM_CATEGORY_INSTRUCTOR.equals(answer.getTemplateItem().getItemCategory())) {
if (answer.getAssociatedId() == null) {
throw new IllegalArgumentException(
"Instructor answers must have the associated field filled in with the instructor userId, for templateItem: "
+ answer.getTemplateItem().getId());
}
answer.setAssociatedType(EvalConstants.ITEM_CATEGORY_INSTRUCTOR);
} else if (EvalConstants.ITEM_CATEGORY_ENVIRONMENT.equals(answer.getTemplateItem().getItemCategory())) {
if (answer.getAssociatedId() == null) {
throw new IllegalArgumentException(
"Environment answers must have the associated field filled in with the unique environment id, for templateItem: "
+ answer.getTemplateItem().getId());
}
answer.setAssociatedType(EvalConstants.ITEM_CATEGORY_ENVIRONMENT);
} else {
throw new IllegalArgumentException("Do not know how to handle a templateItem category of ("
+ answer.getTemplateItem().getItemCategory() + ") for templateItem: "
+ answer.getTemplateItem().getId());
}
// make sure answer is associated with a valid templateItem for this evaluation
if (! templateItemIds.contains(answer.getTemplateItem().getId())) {
throw new IllegalArgumentException("This answer templateItem (" + answer.getTemplateItem().getId()
+ ") is not part of this evaluation (" + response.getEvaluation().getTitle() + ")");
}
}
// TODO - check if numerical answers are valid?
// add to the answered items set
answeredTemplateItemIds.add(answer.getTemplateItem().getId());
}
// check if required answers are filled in
Boolean unansweredAllowed = (Boolean)evalSettings.get(EvalSettings.STUDENT_ALLOWED_LEAVE_UNANSWERED);
if (unansweredAllowed == null) {
unansweredAllowed = eval.getBlankResponsesAllowed();
}
if (unansweredAllowed.booleanValue() == false) {
// all items must be completed so die if they are not
List<EvalTemplateItem> requiredTemplateItems = TemplateItemUtils.getRequiredTemplateItems(templateItems);
int missingRequired = 0;
for (EvalTemplateItem templateItem : requiredTemplateItems) {
if (! answeredTemplateItemIds.contains(templateItem.getId())) {
missingRequired++;
}
}
if (missingRequired > 0) {
throw new IllegalStateException("Missing " + missingRequired + " required items for this evaluation response: " + response.getId());
}
}
return true;
}
}
| true | true | protected boolean checkAnswersValidForEval(EvalResponse response) {
// get a list of the valid templateItems for this evaluation
EvalEvaluation eval = response.getEvaluation();
Long evalId = eval.getId();
List<EvalTemplateItem> allTemplateItems = itemsLogic.getTemplateItemsForEvaluation(evalId, null, null, null);
// OLD - this should use a method elsewhere -AZ
// EvalEvaluation eval = response.getEvaluation();
// Long templateId = eval.getTemplate().getId();
// List<EvalTemplateItem> allTemplateItems =
// dao.findByProperties(EvalTemplateItem.class,
// new String[] { "template.id" },
// new Object[] { templateId });
List<EvalTemplateItem> templateItems = TemplateItemUtils.getAnswerableTemplateItems(allTemplateItems);
// put all templateItemIds into a set for easy comparison
Set<Long> templateItemIds = new HashSet<Long>();
for (int i = 0; i < templateItems.size(); i++) {
templateItemIds.add(((EvalTemplateItem) templateItems.get(i)).getId());
}
// check the answers
Set<Long> answeredTemplateItemIds = new HashSet<Long>();
for (Iterator<EvalAnswer> iter = response.getAnswers().iterator(); iter.hasNext();) {
EvalAnswer answer = (EvalAnswer) iter.next();
if (answer.getNumeric() == null && answer.getText() == null) {
throw new IllegalArgumentException("Cannot save blank answers: answer for templateItem: "
+ answer.getTemplateItem().getId());
}
// make sure the item and template item are available for this answer
if (answer.getTemplateItem() == null || answer.getTemplateItem().getItem() == null) {
throw new IllegalArgumentException("NULL templateItem or templateItem.item for answer: " +
"Answers must have the templateItem set, and that must have the item set");
}
// verify the base state of new answers
if (answer.getId() == null) {
// force the item to be set correctly
answer.setItem(answer.getTemplateItem().getItem());
// check that the associated id is filled in for associated items
if (EvalConstants.ITEM_CATEGORY_COURSE.equals(answer.getTemplateItem().getItemCategory())) {
if (answer.getAssociatedId() != null) {
log.warn("Course answers should have the associated id field blank, for templateItem: "
+ answer.getTemplateItem().getId());
}
answer.setAssociatedId(null);
answer.setAssociatedType(null);
} else if (EvalConstants.ITEM_CATEGORY_INSTRUCTOR.equals(answer.getTemplateItem().getItemCategory())) {
if (answer.getAssociatedId() == null) {
throw new IllegalArgumentException(
"Instructor answers must have the associated field filled in with the instructor userId, for templateItem: "
+ answer.getTemplateItem().getId());
}
answer.setAssociatedType(EvalConstants.ITEM_CATEGORY_INSTRUCTOR);
} else if (EvalConstants.ITEM_CATEGORY_ENVIRONMENT.equals(answer.getTemplateItem().getItemCategory())) {
if (answer.getAssociatedId() == null) {
throw new IllegalArgumentException(
"Environment answers must have the associated field filled in with the unique environment id, for templateItem: "
+ answer.getTemplateItem().getId());
}
answer.setAssociatedType(EvalConstants.ITEM_CATEGORY_ENVIRONMENT);
} else {
throw new IllegalArgumentException("Do not know how to handle a templateItem category of ("
+ answer.getTemplateItem().getItemCategory() + ") for templateItem: "
+ answer.getTemplateItem().getId());
}
// make sure answer is associated with a valid templateItem for this evaluation
if (! templateItemIds.contains(answer.getTemplateItem().getId())) {
throw new IllegalArgumentException("This answer templateItem (" + answer.getTemplateItem().getId()
+ ") is not part of this evaluation (" + response.getEvaluation().getTitle() + ")");
}
}
// TODO - check if numerical answers are valid?
// add to the answered items set
answeredTemplateItemIds.add(answer.getTemplateItem().getId());
}
// check if required answers are filled in
Boolean unansweredAllowed = (Boolean)evalSettings.get(EvalSettings.STUDENT_ALLOWED_LEAVE_UNANSWERED);
if (unansweredAllowed == null) {
unansweredAllowed = eval.getBlankResponsesAllowed();
}
if (unansweredAllowed.booleanValue() == false) {
// all items must be completed so die if they are not
List<EvalTemplateItem> requiredTemplateItems = TemplateItemUtils.getRequiredTemplateItems(templateItems);
int missingRequired = 0;
for (EvalTemplateItem templateItem : requiredTemplateItems) {
if (! answeredTemplateItemIds.contains(templateItem.getId())) {
missingRequired++;
}
}
if (missingRequired > 0) {
throw new IllegalStateException("Missing " + missingRequired + " required items for this evaluation response: " + response.getId());
}
}
return true;
}
| protected boolean checkAnswersValidForEval(EvalResponse response) {
// get a list of the valid templateItems for this evaluation
EvalEvaluation eval = response.getEvaluation();
Long evalId = eval.getId();
// TODO - make this more efficient by limiting the nodes, instructors, and groups
List<EvalTemplateItem> allTemplateItems = itemsLogic.getTemplateItemsForEvaluation(evalId, new String[] {}, new String[] {}, new String[] {});
// OLD - this should use a method elsewhere -AZ
// EvalEvaluation eval = response.getEvaluation();
// Long templateId = eval.getTemplate().getId();
// List<EvalTemplateItem> allTemplateItems =
// dao.findByProperties(EvalTemplateItem.class,
// new String[] { "template.id" },
// new Object[] { templateId });
List<EvalTemplateItem> templateItems = TemplateItemUtils.getAnswerableTemplateItems(allTemplateItems);
// put all templateItemIds into a set for easy comparison
Set<Long> templateItemIds = new HashSet<Long>();
for (int i = 0; i < templateItems.size(); i++) {
templateItemIds.add(((EvalTemplateItem) templateItems.get(i)).getId());
}
// check the answers
Set<Long> answeredTemplateItemIds = new HashSet<Long>();
for (Iterator<EvalAnswer> iter = response.getAnswers().iterator(); iter.hasNext();) {
EvalAnswer answer = (EvalAnswer) iter.next();
if (answer.getNumeric() == null && answer.getText() == null) {
throw new IllegalArgumentException("Cannot save blank answers: answer for templateItem: "
+ answer.getTemplateItem().getId());
}
// make sure the item and template item are available for this answer
if (answer.getTemplateItem() == null || answer.getTemplateItem().getItem() == null) {
throw new IllegalArgumentException("NULL templateItem or templateItem.item for answer: " +
"Answers must have the templateItem set, and that must have the item set");
}
// verify the base state of new answers
if (answer.getId() == null) {
// force the item to be set correctly
answer.setItem(answer.getTemplateItem().getItem());
// check that the associated id is filled in for associated items
if (EvalConstants.ITEM_CATEGORY_COURSE.equals(answer.getTemplateItem().getItemCategory())) {
if (answer.getAssociatedId() != null) {
log.warn("Course answers should have the associated id field blank, for templateItem: "
+ answer.getTemplateItem().getId());
}
answer.setAssociatedId(null);
answer.setAssociatedType(null);
} else if (EvalConstants.ITEM_CATEGORY_INSTRUCTOR.equals(answer.getTemplateItem().getItemCategory())) {
if (answer.getAssociatedId() == null) {
throw new IllegalArgumentException(
"Instructor answers must have the associated field filled in with the instructor userId, for templateItem: "
+ answer.getTemplateItem().getId());
}
answer.setAssociatedType(EvalConstants.ITEM_CATEGORY_INSTRUCTOR);
} else if (EvalConstants.ITEM_CATEGORY_ENVIRONMENT.equals(answer.getTemplateItem().getItemCategory())) {
if (answer.getAssociatedId() == null) {
throw new IllegalArgumentException(
"Environment answers must have the associated field filled in with the unique environment id, for templateItem: "
+ answer.getTemplateItem().getId());
}
answer.setAssociatedType(EvalConstants.ITEM_CATEGORY_ENVIRONMENT);
} else {
throw new IllegalArgumentException("Do not know how to handle a templateItem category of ("
+ answer.getTemplateItem().getItemCategory() + ") for templateItem: "
+ answer.getTemplateItem().getId());
}
// make sure answer is associated with a valid templateItem for this evaluation
if (! templateItemIds.contains(answer.getTemplateItem().getId())) {
throw new IllegalArgumentException("This answer templateItem (" + answer.getTemplateItem().getId()
+ ") is not part of this evaluation (" + response.getEvaluation().getTitle() + ")");
}
}
// TODO - check if numerical answers are valid?
// add to the answered items set
answeredTemplateItemIds.add(answer.getTemplateItem().getId());
}
// check if required answers are filled in
Boolean unansweredAllowed = (Boolean)evalSettings.get(EvalSettings.STUDENT_ALLOWED_LEAVE_UNANSWERED);
if (unansweredAllowed == null) {
unansweredAllowed = eval.getBlankResponsesAllowed();
}
if (unansweredAllowed.booleanValue() == false) {
// all items must be completed so die if they are not
List<EvalTemplateItem> requiredTemplateItems = TemplateItemUtils.getRequiredTemplateItems(templateItems);
int missingRequired = 0;
for (EvalTemplateItem templateItem : requiredTemplateItems) {
if (! answeredTemplateItemIds.contains(templateItem.getId())) {
missingRequired++;
}
}
if (missingRequired > 0) {
throw new IllegalStateException("Missing " + missingRequired + " required items for this evaluation response: " + response.getId());
}
}
return true;
}
|
diff --git a/src-terminal/com/jediterm/terminal/TerminalKeyEncoder.java b/src-terminal/com/jediterm/terminal/TerminalKeyEncoder.java
index 2c75321..3e65bce 100644
--- a/src-terminal/com/jediterm/terminal/TerminalKeyEncoder.java
+++ b/src-terminal/com/jediterm/terminal/TerminalKeyEncoder.java
@@ -1,94 +1,94 @@
package com.jediterm.terminal;
import com.google.common.base.Ascii;
import java.util.HashMap;
import java.util.Map;
import static java.awt.event.KeyEvent.*;
/**
* @author traff
*/
public class TerminalKeyEncoder {
public static final int ESC = Ascii.ESC;
public static final int DEL = Ascii.DEL;
private final Map<Integer, byte[]> myKeyCodes = new HashMap<Integer, byte[]>();
public TerminalKeyEncoder() {
putCode(VK_ENTER, Ascii.CR);
arrowKeysApplicationSequences();
keypadApplicationSequences();
putCode(VK_F1, ESC, 'O', 'P');
putCode(VK_F2, ESC, 'O', 'Q');
putCode(VK_F3, ESC, 'O', 'R');
putCode(VK_F4, ESC, 'O', 'S');
putCode(VK_F5, ESC, 'O', 't');
putCode(VK_F6, ESC, '[', '1', '7', '~');
putCode(VK_F7, ESC, '[', '1', '8', '~');
putCode(VK_F8, ESC, '[', '1', '9', '~');
putCode(VK_F9, ESC, '[', '2', '0', '~');
putCode(VK_F10, ESC, '[', '2', '1', '~');
putCode(VK_F11, ESC, '[', '2', '3', '~', ESC);
putCode(VK_F12, ESC, '[', '2', '4', '~', Ascii.BS);
putCode(VK_INSERT, ESC, '[', '2', '~');
- putCode(VK_DELETE, ESC, '[', '1', '~');
+ putCode(VK_DELETE, ESC, '[', '3', '~');
putCode(VK_PAGE_UP, ESC, '[', '5', '~');
putCode(VK_PAGE_DOWN, ESC, '[', '6', '~');
putCode(VK_HOME, ESC, '[', 'H');
putCode(VK_END, ESC, '[', 'F');
}
public void arrowKeysApplicationSequences() {
putCode(VK_UP, ESC, 'O', 'A');
putCode(VK_DOWN, ESC, 'O', 'B');
putCode(VK_RIGHT, ESC, 'O', 'C');
putCode(VK_LEFT, ESC, 'O', 'D');
}
public void arrowKeysAnsiCursorSequences() {
putCode(VK_UP, ESC, '[', 'A');
putCode(VK_DOWN, ESC, '[', 'B');
putCode(VK_RIGHT, ESC, '[', 'C');
putCode(VK_LEFT, ESC, '[', 'D');
}
void putCode(final int code, final int... bytesAsInt) {
myKeyCodes.put(code, CharacterUtils.makeCode(bytesAsInt));
}
public byte[] getCode(final int key) {
return myKeyCodes.get(key);
}
public void keypadApplicationSequences() {
//0
//1
putCode(VK_KP_DOWN, ESC, 'O', 'r'); //2
//3
putCode(VK_KP_LEFT, ESC, 'O', 't'); //4
//5
putCode(VK_KP_RIGHT, ESC, 'O', 'v'); //6
//7
putCode(VK_KP_UP, ESC, 'O', 'x'); //8
//9
}
public void normalKeypad() {
//0
//1
putCode(VK_KP_DOWN, 2); //2
//3
putCode(VK_KP_LEFT, 4); //4
//5
putCode(VK_KP_RIGHT, 6); //6
//7
putCode(VK_KP_UP, 8); //8
//9
}
}
| true | true | public TerminalKeyEncoder() {
putCode(VK_ENTER, Ascii.CR);
arrowKeysApplicationSequences();
keypadApplicationSequences();
putCode(VK_F1, ESC, 'O', 'P');
putCode(VK_F2, ESC, 'O', 'Q');
putCode(VK_F3, ESC, 'O', 'R');
putCode(VK_F4, ESC, 'O', 'S');
putCode(VK_F5, ESC, 'O', 't');
putCode(VK_F6, ESC, '[', '1', '7', '~');
putCode(VK_F7, ESC, '[', '1', '8', '~');
putCode(VK_F8, ESC, '[', '1', '9', '~');
putCode(VK_F9, ESC, '[', '2', '0', '~');
putCode(VK_F10, ESC, '[', '2', '1', '~');
putCode(VK_F11, ESC, '[', '2', '3', '~', ESC);
putCode(VK_F12, ESC, '[', '2', '4', '~', Ascii.BS);
putCode(VK_INSERT, ESC, '[', '2', '~');
putCode(VK_DELETE, ESC, '[', '1', '~');
putCode(VK_PAGE_UP, ESC, '[', '5', '~');
putCode(VK_PAGE_DOWN, ESC, '[', '6', '~');
putCode(VK_HOME, ESC, '[', 'H');
putCode(VK_END, ESC, '[', 'F');
}
| public TerminalKeyEncoder() {
putCode(VK_ENTER, Ascii.CR);
arrowKeysApplicationSequences();
keypadApplicationSequences();
putCode(VK_F1, ESC, 'O', 'P');
putCode(VK_F2, ESC, 'O', 'Q');
putCode(VK_F3, ESC, 'O', 'R');
putCode(VK_F4, ESC, 'O', 'S');
putCode(VK_F5, ESC, 'O', 't');
putCode(VK_F6, ESC, '[', '1', '7', '~');
putCode(VK_F7, ESC, '[', '1', '8', '~');
putCode(VK_F8, ESC, '[', '1', '9', '~');
putCode(VK_F9, ESC, '[', '2', '0', '~');
putCode(VK_F10, ESC, '[', '2', '1', '~');
putCode(VK_F11, ESC, '[', '2', '3', '~', ESC);
putCode(VK_F12, ESC, '[', '2', '4', '~', Ascii.BS);
putCode(VK_INSERT, ESC, '[', '2', '~');
putCode(VK_DELETE, ESC, '[', '3', '~');
putCode(VK_PAGE_UP, ESC, '[', '5', '~');
putCode(VK_PAGE_DOWN, ESC, '[', '6', '~');
putCode(VK_HOME, ESC, '[', 'H');
putCode(VK_END, ESC, '[', 'F');
}
|
diff --git a/core/src/main/java/brooklyn/util/internal/ssh/sshj/SshjTool.java b/core/src/main/java/brooklyn/util/internal/ssh/sshj/SshjTool.java
index 61563aefb..5c8ebee55 100644
--- a/core/src/main/java/brooklyn/util/internal/ssh/sshj/SshjTool.java
+++ b/core/src/main/java/brooklyn/util/internal/ssh/sshj/SshjTool.java
@@ -1,789 +1,792 @@
package brooklyn.util.internal.ssh.sshj;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Throwables.getCausalChain;
import static com.google.common.collect.Iterables.any;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import net.schmizz.sshj.connection.ConnectionException;
import net.schmizz.sshj.connection.channel.direct.PTYMode;
import net.schmizz.sshj.connection.channel.direct.Session;
import net.schmizz.sshj.connection.channel.direct.Session.Command;
import net.schmizz.sshj.connection.channel.direct.Session.Shell;
import net.schmizz.sshj.connection.channel.direct.SessionChannel;
import net.schmizz.sshj.sftp.FileAttributes;
import net.schmizz.sshj.sftp.SFTPClient;
import net.schmizz.sshj.transport.TransportException;
import net.schmizz.sshj.xfer.InMemorySourceFile;
import org.apache.commons.io.input.ProxyInputStream;
import org.bouncycastle.util.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import brooklyn.util.Time;
import brooklyn.util.exceptions.Exceptions;
import brooklyn.util.internal.StreamGobbler;
import brooklyn.util.internal.ssh.BackoffLimitedRetryHandler;
import brooklyn.util.internal.ssh.SshAbstractTool;
import brooklyn.util.internal.ssh.SshTool;
import brooklyn.util.stream.InputStreamSupplier;
import brooklyn.util.stream.KnownSizeInputStream;
import brooklyn.util.text.Identifiers;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Joiner;
import com.google.common.base.Predicate;
import com.google.common.base.Stopwatch;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.io.Closeables;
import com.google.common.io.Files;
import com.google.common.net.HostAndPort;
import com.google.common.primitives.Ints;
/**
* For ssh and scp-style commands, using the sshj library.
* <p>
* The implementation is based on a combination of the existing brooklyn SshJschTool,
* and the jclouds SshjSshClient.
* <p>
* Not thread-safe. Use a different SshjTool for each concurrent thread.
* If passing from one thread to another, ensure code goes through a synchronized block.
*/
public class SshjTool extends SshAbstractTool implements SshTool {
private static final Logger LOG = LoggerFactory.getLogger(SshjTool.class);
protected final int sshTriesTimeout;
protected final int sshTries;
protected final BackoffLimitedRetryHandler backoffLimitedRetryHandler;
private class CloseFtpChannelOnCloseInputStream extends ProxyInputStream {
private final SFTPClient sftp;
private CloseFtpChannelOnCloseInputStream(InputStream proxy, SFTPClient sftp) {
super(proxy);
this.sftp = sftp;
}
@Override
public void close() throws IOException {
super.close();
closeWhispering(sftp, this);
}
}
private final SshjClientConnection sshClientConnection;
public static Builder<SshjTool,?> builder() {
return new ConcreteBuilder();
}
private static class ConcreteBuilder extends Builder<SshjTool, ConcreteBuilder> {
}
public static class Builder<T extends SshjTool, B extends Builder<T,B>> extends AbstractToolBuilder<T,B> {
protected int connectTimeout;
protected int sessionTimeout;
protected int sshTries = 4; //allow 4 tries by default, much safer
protected int sshTriesTimeout = 2*60*1000; //allow 2 minutesby default (so if too slow trying sshTries times, abort anyway)
protected long sshRetryDelay = 50L;
public B from(Map<String,?> props) {
super.from(props);
sshTries = getOptionalVal(props, PROP_SSH_TRIES);
sshTriesTimeout = getOptionalVal(props, PROP_SSH_TRIES_TIMEOUT);
sshRetryDelay = getOptionalVal(props, PROP_SSH_RETRY_DELAY);
connectTimeout = getOptionalVal(props, PROP_CONNECT_TIMEOUT);
sessionTimeout = getOptionalVal(props, PROP_SESSION_TIMEOUT);
return self();
}
public B connectTimeout(int val) {
this.connectTimeout = val; return self();
}
public B sessionTimeout(int val) {
this.sessionTimeout = val; return self();
}
public B sshRetries(int val) {
this.sshTries = val; return self();
}
public B sshRetriesTimeout(int val) {
this.sshTriesTimeout = val; return self();
}
public B sshRetryDelay(long val) {
this.sshRetryDelay = val; return self();
}
@SuppressWarnings("unchecked")
public T build() {
return (T) new SshjTool(this);
}
}
public SshjTool(Map<String,?> map) {
this(builder().from(map));
}
protected SshjTool(Builder<?,?> builder) {
super(builder);
sshTries = builder.sshTries;
sshTriesTimeout = builder.sshTriesTimeout;
backoffLimitedRetryHandler = new BackoffLimitedRetryHandler(sshTries, builder.sshRetryDelay);
sshClientConnection = SshjClientConnection.builder()
.hostAndPort(HostAndPort.fromParts(host, port))
.username(user)
.password(password)
.privateKeyPassphrase(privateKeyPassphrase)
.privateKeyData(privateKeyData)
.privateKeyFile(privateKeyFile)
.strictHostKeyChecking(strictHostKeyChecking)
.connectTimeout(builder.connectTimeout)
.sessionTimeout(builder.sessionTimeout)
.build();
if (LOG.isTraceEnabled()) LOG.trace("Created SshTool {} ({})", this, System.identityHashCode(this));
}
@Override
public void connect() {
try {
if (LOG.isTraceEnabled()) LOG.trace("Connecting SshjTool {} ({})", this, System.identityHashCode(this));
acquire(sshClientConnection);
} catch (Exception e) {
if (LOG.isDebugEnabled()) LOG.debug(toString()+" failed to connect (rethrowing)", e);
throw propagate(e, "failed to connect");
}
}
@Override
public void connect(int maxAttempts) {
connect(); // FIXME Should callers instead configure sshTries? But that would apply to all ssh attempts
}
@Override
public void disconnect() {
if (LOG.isTraceEnabled()) LOG.trace("Disconnecting SshjTool {} ({})", this, System.identityHashCode(this));
try {
sshClientConnection.clear();
} catch (Exception e) {
throw Throwables.propagate(e);
}
}
@Override
public boolean isConnected() {
return sshClientConnection.isConnected() && sshClientConnection.isAuthenticated();
}
@Override
public int copyToServer(java.util.Map<String,?> props, byte[] contents, String pathAndFileOnRemoteServer) {
return copyToServer(props, new ByteArrayInputStream(contents), contents.length, pathAndFileOnRemoteServer);
}
@Override
public int copyToServer(Map<String,?> props, InputStream contents, String pathAndFileOnRemoteServer) {
if (contents instanceof KnownSizeInputStream)
return copyToServer(props, contents, ((KnownSizeInputStream)contents).length(), pathAndFileOnRemoteServer);
/* sshj needs to know the length of the InputStream to copy the file to perform copy;
* for now, write it to a file if we come here with something other than a KnownSizeInputStream.
* (we could have a switch where we hold it in memory if less than some max size,
* but most the routines should supply a string or byte array or similar,
* so we probably don't come here too often.)
*/
File tempFile = writeTempFile(contents);
try {
return copyToServer(props, tempFile, pathAndFileOnRemoteServer);
} finally {
tempFile.delete();
}
}
@Override
public int copyToServer(Map<String,?> props, File localFile, String pathAndFileOnRemoteServer) {
try {
return copyToServer(props, new FileInputStream(localFile), (int)localFile.length(), pathAndFileOnRemoteServer);
} catch (FileNotFoundException e) {
throw Exceptions.propagate(e);
}
}
@Override
public int transferFileTo(Map<String,?> props, InputStream input, String pathAndFileOnRemoteServer) {
return copyToServer(props, input, pathAndFileOnRemoteServer);
}
@Override
public int createFile(Map<String,?> props, String pathAndFileOnRemoteServer, InputStream input, long size) {
return copyToServer(props, input, (int)size, pathAndFileOnRemoteServer);
}
@Override
public int createFile(Map<String,?> props, String pathAndFileOnRemoteServer, String contents) {
return copyToServer(props, contents.getBytes(), pathAndFileOnRemoteServer);
}
@Override
public int createFile(Map<String,?> props, String pathAndFileOnRemoteServer, byte[] contents) {
return copyToServer(props, contents, pathAndFileOnRemoteServer);
}
private int copyToServer(Map<String,?> props, InputStream contents, long length, String pathAndFileOnRemoteServer) {
acquire(new PutFileAction(props, pathAndFileOnRemoteServer, contents, length));
return 0; // TODO Can we assume put will have thrown exception if failed? Rather than exit code != 0?
}
@Override
public int transferFileFrom(Map<String,?> props, String pathAndFileOnRemoteServer, String pathAndFileOnLocalServer) {
return copyFromServer(props, pathAndFileOnRemoteServer, new File(pathAndFileOnLocalServer));
}
@Override
public int copyFromServer(Map<String,?> props, String pathAndFileOnRemoteServer, File localFile) {
InputStream contents = acquire(new GetFileAction(pathAndFileOnRemoteServer));
try {
Files.copy(new InputStreamSupplier(contents), localFile);
return 0; // TODO Can we assume put will have thrown exception if failed? Rather than exit code != 0?
} catch (IOException e) {
throw Throwables.propagate(e);
}
}
public int execShell(Map<String,?> props, List<String> commands) {
return execScript(props, commands, Collections.<String,Object>emptyMap());
}
public int execShell(Map<String,?> props, List<String> commands, Map<String,?> env) {
return execScript(props, commands, env);
}
@Override
public int execScript(Map<String,?> props, List<String> commands) {
return execScript(props, commands, Collections.<String,Object>emptyMap());
}
/**
* This creates a script containing the user's commands, copies it to the remote server, and
* executes the script. The script is then deleted.
* <p>
* Executing commands directly is fraught with dangers! Here are other options, and their problems:
* <ul>
* <li>Use execCommands, rather than shell.
* The user's environment will not be setup normally (e.g. ~/.bash_profile will not have been sourced)
* so things like wget may not be on the PATH.
* <li>Send the stream of commands to the shell.
* But characters being sent can be lost.
* Try the following (e.g. in an OS X terminal):
* - sleep 5
* - <paste a command that is 1000s of characters long>
* Only the first 1024 characters appear. The rest are lost.
* If sending a stream of commands, you need to be careful not send the next (big) command while the
* previous one is still executing.
* <li>Send a stream to the shell, but spot when the previous command has completed.
* e.g. by looking for the prompt (but what if the commands being executed change the prompt?)
* e.g. by putting every second command as "echo <uid>", and waiting for the stdout.
* This gets fiddly...
* </ul>
*
* So on balance, the script-based approach seems most reliable, even if there is an overhead
* of separate message(s) for copying the file!
*/
@Override
public int execScript(Map<String,?> props, List<String> commands, Map<String,?> env) {
OutputStream out = getOptionalVal(props, PROP_OUT_STREAM);
OutputStream err = getOptionalVal(props, PROP_ERR_STREAM);
String scriptDir = getOptionalVal(props, PROP_SCRIPT_DIR);
String scriptPath = scriptDir+"/brooklyn-"+System.currentTimeMillis()+"-"+Identifiers.makeRandomId(8)+".sh";
String scriptContents = toScript(props, commands, env);
if (LOG.isTraceEnabled()) LOG.trace("Running shell command at {} as script: {}", host, scriptContents);
copyToServer(ImmutableMap.of("permissions", "0700"), scriptContents.getBytes(), scriptPath);
// use "-f" because some systems have "rm" aliased to "rm -i"; use "< /dev/null" to guarantee doesn't hang
List<String> cmds = ImmutableList.of(
scriptPath+" < /dev/null",
"RESULT=$?",
"echo \"Executed "+scriptPath+", result $RESULT\"",
"rm -f "+scriptPath+" < /dev/null",
"exit $RESULT");
Integer result = acquire(new ShellAction(cmds, out, err));
return result != null ? result : -1;
}
public int execShellDirect(Map<String,?> props, List<String> commands, Map<String,?> env) {
OutputStream out = getOptionalVal(props, PROP_OUT_STREAM);
OutputStream err = getOptionalVal(props, PROP_ERR_STREAM);
List<String> cmdSequence = toCommandSequence(commands, env);
List<String> allcmds = ImmutableList.<String>builder()
.add(getOptionalVal(props, PROP_DIRECT_HEADER))
.addAll(cmdSequence)
.add("exit $?")
.build();
if (LOG.isTraceEnabled()) LOG.trace("Running shell command at {}: {}", host, allcmds);
Integer result = acquire(new ShellAction(allcmds, out, err));
if (LOG.isTraceEnabled()) LOG.trace("Running shell command at {} completed: return status {}", host, result);
return result != null ? result : -1;
}
@Override
public int execCommands(Map<String,?> props, List<String> commands) {
return execCommands(props, commands, Collections.<String,Object>emptyMap());
}
@Override
public int execCommands(Map<String,?> props, List<String> commands, Map<String,?> env) {
if (props.containsKey("blocks") && props.get("blocks") == Boolean.FALSE) {
throw new IllegalArgumentException("Cannot exec non-blocking: command="+commands);
}
OutputStream out = getOptionalVal(props, PROP_OUT_STREAM);
OutputStream err = getOptionalVal(props, PROP_ERR_STREAM);
String separator = getOptionalVal(props, PROP_SEPARATOR);
List<String> allcmds = toCommandSequence(commands, env);
String singlecmd = Joiner.on(separator).join(allcmds);
if (LOG.isTraceEnabled()) LOG.trace("Running command at {}: {}", host, singlecmd);
Command result = acquire(new ExecAction(singlecmd, out, err));
if (LOG.isTraceEnabled()) LOG.trace("Running command at {} completed: exit code {}", host, result.getExitStatus());
// FIXME this can NPE if no exit status is received (observed on kill `ps aux | grep thing-to-grep-for | awk {print $2}`
return result.getExitStatus();
}
protected void checkConnected() {
if (!isConnected()) {
throw new IllegalStateException(String.format("(%s) ssh not connected!", toString()));
}
}
protected void backoffForAttempt(int retryAttempt, String message) {
backoffLimitedRetryHandler.imposeBackoffExponentialDelay(retryAttempt, message);
}
protected <T, C extends SshAction<T>> T acquire(C connection) {
Stopwatch stopwatch = new Stopwatch().start();
for (int i = 0; i < sshTries; i++) {
try {
connection.clear();
if (LOG.isTraceEnabled()) LOG.trace(">> ({}) acquiring {}", toString(), connection);
T returnVal = connection.create();
if (LOG.isTraceEnabled()) LOG.trace("<< ({}) acquired {}", toString(), returnVal);
return returnVal;
} catch (Exception e) {
String errorMessage = String.format("(%s) error acquiring %s", toString(), connection);
String fullMessage = String.format("%s (attempt %s/%s, in time %s/%s)",
errorMessage, (i+1), sshTries, Time.makeTimeString(stopwatch.elapsedMillis()),
(sshTriesTimeout > 0 ? Time.makeTimeString(sshTriesTimeout) : "unlimited"));
try {
disconnect();
} catch (Exception e2) {
LOG.warn("<< ("+toString()+") error closing connection: "+e+" / "+e2, e);
}
if (i + 1 == sshTries) {
LOG.warn("<< {}: {}", fullMessage, e.getMessage());
throw propagate(e, fullMessage + "; out of retries");
} else if (sshTriesTimeout > 0 && stopwatch.elapsedMillis() > sshTriesTimeout) {
LOG.warn("<< {}: {}", fullMessage, e.getMessage());
throw propagate(e, fullMessage + "; out of time");
} else {
if (LOG.isDebugEnabled()) LOG.debug("<< {}: {}", fullMessage, e.getMessage());
backoffForAttempt(i + 1, errorMessage + ": " + e.getMessage());
if (connection != sshClientConnection)
connect();
continue;
}
}
}
assert false : "should not reach here";
return null;
}
private final SshAction<SFTPClient> sftpConnection = new SshAction<SFTPClient>() {
private SFTPClient sftp;
@Override
public void clear() {
closeWhispering(sftp, this);
sftp = null;
}
@Override
public SFTPClient create() throws IOException {
checkConnected();
sftp = sshClientConnection.ssh.newSFTPClient();
return sftp;
}
@Override
public String toString() {
return "SFTPClient()";
}
};
private class GetFileAction implements SshAction<InputStream> {
private final String path;
private SFTPClient sftp;
GetFileAction(String path) {
this.path = checkNotNull(path, "path");
}
@Override
public void clear() throws IOException {
closeWhispering(sftp, this);
sftp = null;
}
@Override
public InputStream create() throws Exception {
sftp = acquire(sftpConnection);
return new CloseFtpChannelOnCloseInputStream(
sftp.getSFTPEngine().open(path).getInputStream(), sftp);
}
@Override
public String toString() {
return "Payload(path=[" + path + "])";
}
};
private class PutFileAction implements SshAction<Void> {
// TODO See SshJschTool.createFile: it does whacky stuff when copying; do we need that here as well?
// TODO support backup as a property?
private final String path;
private SFTPClient sftp;
private int permissionsMask;
private long lastModificationDate;
private long lastAccessDate;
private InputStream contents;
private Integer length;
PutFileAction(Map<String,?> props, String path, InputStream contents, long length) {
String permissions = getOptionalVal(props, PROP_PERMISSIONS, "0644");
permissionsMask = Integer.parseInt(permissions, 8);
lastModificationDate = getOptionalVal(props, PROP_LAST_MODIFICATION_DATE, 0L);
lastAccessDate = getOptionalVal(props, PROP_LAST_ACCESS_DATE, 0L);
if (lastAccessDate <= 0 ^ lastModificationDate <= 0) {
lastAccessDate = Math.max(lastAccessDate, lastModificationDate);
lastModificationDate = Math.max(lastAccessDate, lastModificationDate);
}
this.path = checkNotNull(path, "path");
this.contents = checkNotNull(contents, "contents");
this.length = Ints.checkedCast(checkNotNull((long)length, "size"));
}
@Override
public void clear() {
closeWhispering(sftp, this);
sftp = null;
}
@Override
public Void create() throws Exception {
sftp = acquire(sftpConnection);
try {
sftp.put(new InMemorySourceFile() {
@Override public String getName() {
return path;
}
@Override public long getLength() {
return length;
}
@Override public InputStream getInputStream() throws IOException {
return contents;
}
}, path);
sftp.chmod(path, permissionsMask);
if (lastAccessDate > 0) {
sftp.setattr(path, new FileAttributes.Builder()
.withAtimeMtime(lastAccessDate, lastModificationDate)
.build());
}
} finally {
Closeables.closeQuietly(contents);
}
return null;
}
@Override
public String toString() {
return "Put(path=[" + path + " "+length+"])";
}
};
@VisibleForTesting
Predicate<String> causalChainHasMessageContaining(final Exception from) {
return new Predicate<String>() {
@Override
public boolean apply(final String input) {
return any(getCausalChain(from), new Predicate<Throwable>() {
@Override
public boolean apply(Throwable arg0) {
return (arg0.toString().indexOf(input) != -1)
|| (arg0.getMessage() != null && arg0.getMessage().indexOf(input) != -1);
}
});
}
};
}
protected void allocatePTY(Session s) throws ConnectionException, TransportException {
// this was set as the default, but it makes output harder to read
// and causes stderr to be sent to stdout;
// but some systems requiretty for sudoing
if (allocatePTY)
s.allocatePTY("vt100", 80, 24, 0, 0, Collections.<PTYMode, Integer> emptyMap());
// s.allocatePTY("dumb", 80, 24, 0, 0, Collections.<PTYMode, Integer> emptyMap());
}
protected SshAction<Session> newSessionAction() {
return new SshAction<Session>() {
private Session session = null;
@Override
public void clear() throws TransportException, ConnectionException {
closeWhispering(session, this);
session = null;
}
@Override
public Session create() throws Exception {
checkConnected();
session = sshClientConnection.ssh.startSession();
allocatePTY(session);
return session;
}
@Override
public String toString() {
return "Session()";
}
};
}
class ExecAction implements SshAction<Command> {
private final String command;
private Session session;
private Shell shell;
private StreamGobbler outgobbler;
private StreamGobbler errgobbler;
private OutputStream out;
private OutputStream err;
ExecAction(String command, OutputStream out, OutputStream err) {
this.command = checkNotNull(command, "command");
this.out = out;
this.err = err;
}
@Override
public void clear() throws TransportException, ConnectionException {
closeWhispering(session, this);
closeWhispering(shell, this);
closeWhispering(outgobbler, this);
closeWhispering(errgobbler, this);
session = null;
shell = null;
}
@Override
public Command create() throws Exception {
try {
session = acquire(newSessionAction());
Command output = session.exec(checkNotNull(command, "command"));
if (out != null) {
outgobbler = new StreamGobbler(output.getInputStream(), out, (Logger)null);
outgobbler.start();
}
if (err != null) {
errgobbler = new StreamGobbler(output.getErrorStream(), err, (Logger)null);
errgobbler.start();
}
try {
output.join(sshClientConnection.getSessionTimeout(), TimeUnit.MILLISECONDS);
return output;
} finally {
// wait for all stdout/stderr to have been re-directed
try {
if (outgobbler != null) outgobbler.join();
if (errgobbler != null) errgobbler.join();
} catch (InterruptedException e) {
LOG.warn("Interrupted gobbling streams from ssh: "+command, e);
Thread.currentThread().interrupt();
}
}
} finally {
clear();
}
}
@Override
public String toString() {
return "Exec(command=[" + command + "])";
}
}
class ShellAction implements SshAction<Integer> {
private final List<String> commands;
private Session session;
private Shell shell;
private StreamGobbler outgobbler;
private StreamGobbler errgobbler;
private OutputStream out;
private OutputStream err;
ShellAction(List<String> commands, OutputStream out, OutputStream err) {
this.commands = checkNotNull(commands, "commands");
this.out = out;
this.err = err;
}
@Override
public void clear() throws TransportException, ConnectionException {
closeWhispering(session, this);
closeWhispering(shell, this);
closeWhispering(outgobbler, this);
closeWhispering(errgobbler, this);
session = null;
shell = null;
}
@Override
public Integer create() throws Exception {
try {
session = acquire(newSessionAction());
shell = session.startShell();
if (out != null) {
InputStream outstream = shell.getInputStream();
outgobbler = new StreamGobbler(outstream, out, (Logger)null);
outgobbler.start();
}
if (err != null) {
InputStream errstream = shell.getErrorStream();
errgobbler = new StreamGobbler(errstream, err, (Logger)null);
errgobbler.start();
}
OutputStream output = shell.getOutputStream();
for (CharSequence cmd : commands) {
try {
output.write(Strings.toUTF8ByteArray(cmd+"\n"));
output.flush();
} catch (ConnectionException e) {
if (!shell.isOpen()) {
// shell is closed; presumably the user command did `exit`
if (LOG.isDebugEnabled()) LOG.debug("Shell closed to {} when executing {}", SshjTool.this.toString(), commands);
break;
} else {
throw e;
}
}
}
- shell.sendEOF();
+ // workaround attempt for SSHJ deadlock - https://github.com/shikhar/sshj/issues/105
+ synchronized (shell.getOutputStream()) {
+ shell.sendEOF();
+ }
closeWhispering(output, this);
try {
int timeout = sshClientConnection.getSessionTimeout();
long timeoutEnd = System.currentTimeMillis() + timeout;
Exception last = null;
do {
if (!shell.isOpen() && ((SessionChannel)session).getExitStatus()!=null)
// shell closed, and exit status returned
break;
boolean endBecauseReturned =
// if either condition is satisfied, then wait 1s in hopes the other does, then return
(!shell.isOpen() || ((SessionChannel)session).getExitStatus()!=null);
try {
shell.join(1000, TimeUnit.MILLISECONDS);
} catch (ConnectionException e) { last = e; }
if (endBecauseReturned)
// shell is still open, ie some process is running
// but we have a result code, so main shell is finished
// we waited one second extra to allow any background process
// which is nohupped to really be in the background (#162)
// now let's bail out
break;
} while (timeout<=0 || System.currentTimeMillis() < timeoutEnd);
if (shell.isOpen() && ((SessionChannel)session).getExitStatus()==null) {
LOG.debug("Timeout ({}) in SSH shell to {}", sshClientConnection.getSessionTimeout(), this);
// we timed out, or other problem -- reproduce the error
throw last;
}
return ((SessionChannel)session).getExitStatus();
} finally {
// wait for all stdout/stderr to have been re-directed
closeWhispering(shell, this);
shell = null;
try {
if (outgobbler != null) outgobbler.join();
if (errgobbler != null) errgobbler.join();
} catch (InterruptedException e) {
LOG.warn("Interrupted gobbling streams from ssh: "+commands, e);
Thread.currentThread().interrupt();
}
}
} finally {
clear();
}
}
@Override
public String toString() {
return "Shell(command=[" + commands + "])";
}
}
// protected Payload toPayload(byte[] input) {
// return new ByteArrayPayload(input);
// }
//
// protected Payload toPayload(File input) {
// return new FilePayload(input);
// }
//
// protected Payload toPayload(InputStream input, long length) {
// InputStreamPayload payload = new InputStreamPayload(new LimitInputStream(input, length));
// payload.getContentMetadata().setContentLength(length);
// return payload;
// }
}
| true | true | public Integer create() throws Exception {
try {
session = acquire(newSessionAction());
shell = session.startShell();
if (out != null) {
InputStream outstream = shell.getInputStream();
outgobbler = new StreamGobbler(outstream, out, (Logger)null);
outgobbler.start();
}
if (err != null) {
InputStream errstream = shell.getErrorStream();
errgobbler = new StreamGobbler(errstream, err, (Logger)null);
errgobbler.start();
}
OutputStream output = shell.getOutputStream();
for (CharSequence cmd : commands) {
try {
output.write(Strings.toUTF8ByteArray(cmd+"\n"));
output.flush();
} catch (ConnectionException e) {
if (!shell.isOpen()) {
// shell is closed; presumably the user command did `exit`
if (LOG.isDebugEnabled()) LOG.debug("Shell closed to {} when executing {}", SshjTool.this.toString(), commands);
break;
} else {
throw e;
}
}
}
shell.sendEOF();
closeWhispering(output, this);
try {
int timeout = sshClientConnection.getSessionTimeout();
long timeoutEnd = System.currentTimeMillis() + timeout;
Exception last = null;
do {
if (!shell.isOpen() && ((SessionChannel)session).getExitStatus()!=null)
// shell closed, and exit status returned
break;
boolean endBecauseReturned =
// if either condition is satisfied, then wait 1s in hopes the other does, then return
(!shell.isOpen() || ((SessionChannel)session).getExitStatus()!=null);
try {
shell.join(1000, TimeUnit.MILLISECONDS);
} catch (ConnectionException e) { last = e; }
if (endBecauseReturned)
// shell is still open, ie some process is running
// but we have a result code, so main shell is finished
// we waited one second extra to allow any background process
// which is nohupped to really be in the background (#162)
// now let's bail out
break;
} while (timeout<=0 || System.currentTimeMillis() < timeoutEnd);
if (shell.isOpen() && ((SessionChannel)session).getExitStatus()==null) {
LOG.debug("Timeout ({}) in SSH shell to {}", sshClientConnection.getSessionTimeout(), this);
// we timed out, or other problem -- reproduce the error
throw last;
}
return ((SessionChannel)session).getExitStatus();
} finally {
// wait for all stdout/stderr to have been re-directed
closeWhispering(shell, this);
shell = null;
try {
if (outgobbler != null) outgobbler.join();
if (errgobbler != null) errgobbler.join();
} catch (InterruptedException e) {
LOG.warn("Interrupted gobbling streams from ssh: "+commands, e);
Thread.currentThread().interrupt();
}
}
} finally {
clear();
}
}
| public Integer create() throws Exception {
try {
session = acquire(newSessionAction());
shell = session.startShell();
if (out != null) {
InputStream outstream = shell.getInputStream();
outgobbler = new StreamGobbler(outstream, out, (Logger)null);
outgobbler.start();
}
if (err != null) {
InputStream errstream = shell.getErrorStream();
errgobbler = new StreamGobbler(errstream, err, (Logger)null);
errgobbler.start();
}
OutputStream output = shell.getOutputStream();
for (CharSequence cmd : commands) {
try {
output.write(Strings.toUTF8ByteArray(cmd+"\n"));
output.flush();
} catch (ConnectionException e) {
if (!shell.isOpen()) {
// shell is closed; presumably the user command did `exit`
if (LOG.isDebugEnabled()) LOG.debug("Shell closed to {} when executing {}", SshjTool.this.toString(), commands);
break;
} else {
throw e;
}
}
}
// workaround attempt for SSHJ deadlock - https://github.com/shikhar/sshj/issues/105
synchronized (shell.getOutputStream()) {
shell.sendEOF();
}
closeWhispering(output, this);
try {
int timeout = sshClientConnection.getSessionTimeout();
long timeoutEnd = System.currentTimeMillis() + timeout;
Exception last = null;
do {
if (!shell.isOpen() && ((SessionChannel)session).getExitStatus()!=null)
// shell closed, and exit status returned
break;
boolean endBecauseReturned =
// if either condition is satisfied, then wait 1s in hopes the other does, then return
(!shell.isOpen() || ((SessionChannel)session).getExitStatus()!=null);
try {
shell.join(1000, TimeUnit.MILLISECONDS);
} catch (ConnectionException e) { last = e; }
if (endBecauseReturned)
// shell is still open, ie some process is running
// but we have a result code, so main shell is finished
// we waited one second extra to allow any background process
// which is nohupped to really be in the background (#162)
// now let's bail out
break;
} while (timeout<=0 || System.currentTimeMillis() < timeoutEnd);
if (shell.isOpen() && ((SessionChannel)session).getExitStatus()==null) {
LOG.debug("Timeout ({}) in SSH shell to {}", sshClientConnection.getSessionTimeout(), this);
// we timed out, or other problem -- reproduce the error
throw last;
}
return ((SessionChannel)session).getExitStatus();
} finally {
// wait for all stdout/stderr to have been re-directed
closeWhispering(shell, this);
shell = null;
try {
if (outgobbler != null) outgobbler.join();
if (errgobbler != null) errgobbler.join();
} catch (InterruptedException e) {
LOG.warn("Interrupted gobbling streams from ssh: "+commands, e);
Thread.currentThread().interrupt();
}
}
} finally {
clear();
}
}
|
diff --git a/h2/src/main/org/h2/server/web/DbContextRule.java b/h2/src/main/org/h2/server/web/DbContextRule.java
index 91e9f24e0..8221c7319 100644
--- a/h2/src/main/org/h2/server/web/DbContextRule.java
+++ b/h2/src/main/org/h2/server/web/DbContextRule.java
@@ -1,492 +1,492 @@
/*
* Copyright 2004-2008 H2 Group. Multiple-Licensed under the H2 License,
* Version 1.0, and under the Eclipse Public License, Version 1.0
* (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.server.web;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import org.h2.bnf.Bnf;
import org.h2.bnf.Rule;
import org.h2.bnf.Sentence;
import org.h2.command.Parser;
import org.h2.message.Message;
import org.h2.util.StringUtils;
/**
* A BNF terminal rule that is linked to the database context information.
* This class is used by the H2 Console, to support auto-complete.
*/
public class DbContextRule implements Rule {
static final int COLUMN = 0, TABLE = 1, TABLE_ALIAS = 2;
static final int NEW_TABLE_ALIAS = 3;
static final int COLUMN_ALIAS = 4, SCHEMA = 5;
private static final boolean SUGGEST_TABLE_ALIAS = false;
private DbContents contents;
private int type;
DbContextRule(DbContents contents, int type) {
this.contents = contents;
this.type = type;
}
public String toString() {
switch (type) {
case SCHEMA:
return "schema";
case TABLE:
return "table";
case NEW_TABLE_ALIAS:
return "nt";
case TABLE_ALIAS:
return "t";
case COLUMN_ALIAS:
return "c";
case COLUMN:
return "column";
default:
return "?";
}
}
public String name() {
return null;
}
public String random(Bnf config, int level) {
return null;
}
public Rule last() {
return this;
}
public void setLinks(HashMap ruleMap) {
// nothing to do
}
public void addNextTokenList(Sentence sentence) {
switch (type) {
case SCHEMA:
addSchema(sentence);
break;
case TABLE:
addTable(sentence);
break;
case NEW_TABLE_ALIAS:
addNewTableAlias(sentence);
break;
case TABLE_ALIAS:
addTableAlias(sentence);
break;
case COLUMN_ALIAS:
// addColumnAlias(query, sentence);
// break;
case COLUMN:
addColumn(sentence);
break;
default:
}
}
private void addTableAlias(Sentence sentence) {
String query = sentence.getQuery();
String q = StringUtils.toUpperEnglish(query.trim());
HashMap map = sentence.getAliases();
HashSet set = new HashSet();
if (map != null) {
for (Iterator it = map.entrySet().iterator(); it.hasNext();) {
Map.Entry entry = (Entry) it.next();
String alias = (String) entry.getKey();
DbTableOrView table = (DbTableOrView) entry.getValue();
set.add(StringUtils.toUpperEnglish(table.name));
if (q.length() == 0 || alias.startsWith(q)) {
if (q.length() < alias.length()) {
sentence.add(alias + ".", alias.substring(q.length()) + ".", Sentence.CONTEXT);
}
}
}
}
HashSet tables = sentence.getTables();
if (tables != null) {
for (Iterator it = tables.iterator(); it.hasNext();) {
DbTableOrView table = (DbTableOrView) it.next();
String tableName = StringUtils.toUpperEnglish(table.name);
//DbTableOrView[] tables = contents.defaultSchema.tables;
//for(int i=0; i<tables.length; i++) {
// DbTableOrView table = tables[i];
// String tableName = StringUtils.toUpperEnglish(table.name);
if (!set.contains(tableName)) {
if (q.length() == 0 || tableName.startsWith(q)) {
if (q.length() < tableName.length()) {
sentence.add(tableName + ".", tableName.substring(q.length()) + ".", Sentence.CONTEXT);
}
}
}
}
}
}
private void addNewTableAlias(Sentence sentence) {
String query = sentence.getQuery();
if (SUGGEST_TABLE_ALIAS) {
// good when testing!
if (query.length() > 3) {
return;
}
String lastTableName = StringUtils.toUpperEnglish(sentence.getLastTable().name);
if (lastTableName == null) {
return;
}
HashMap map = sentence.getAliases();
String shortName = lastTableName.substring(0, 1);
if (map != null && map.containsKey(shortName)) {
int result = 0;
for (int i = 1;; i++) {
if (!map.containsKey(shortName + i)) {
result = i;
break;
}
}
shortName += result;
}
String q = StringUtils.toUpperEnglish(query.trim());
if (q.length() == 0 || StringUtils.toUpperEnglish(shortName).startsWith(q)) {
if (q.length() < shortName.length()) {
sentence.add(shortName, shortName.substring(q.length()), Sentence.CONTEXT);
}
}
}
}
// private boolean startWithIgnoreCase(String a, String b) {
// if(a.length() < b.length()) {
// return false;
// }
// for(int i=0; i<b.length(); i++) {
// if(Character.toUpperCase(a.charAt(i))
// != Character.toUpperCase(b.charAt(i))) {
// return false;
// }
// }
// return true;
// }
private void addSchema(Sentence sentence) {
String query = sentence.getQuery();
String q = StringUtils.toUpperEnglish(query);
if (q.trim().length() == 0) {
q = q.trim();
}
DbSchema[] schemas = contents.schemas;
for (int i = 0; i < schemas.length; i++) {
DbSchema schema = schemas[i];
if (schema == contents.defaultSchema) {
continue;
}
if (q.length() == 0 || StringUtils.toUpperEnglish(schema.name).startsWith(q)) {
if (q.length() < schema.quotedName.length()) {
sentence.add(schema.quotedName + ".", schema.quotedName.substring(q.length()) + ".", Sentence.CONTEXT);
}
}
}
}
private void addTable(Sentence sentence) {
String query = sentence.getQuery();
DbSchema schema = sentence.getLastMatchedSchema();
if (schema == null) {
schema = contents.defaultSchema;
}
String q = StringUtils.toUpperEnglish(query);
if (q.trim().length() == 0) {
q = q.trim();
}
DbTableOrView[] tables = schema.tables;
for (int i = 0; i < tables.length; i++) {
DbTableOrView table = tables[i];
if (q.length() == 0 || StringUtils.toUpperEnglish(table.name).startsWith(q)) {
if (q.length() < table.quotedName.length()) {
sentence.add(table.quotedName, table.quotedName.substring(q.length()), Sentence.CONTEXT);
}
}
}
}
private void addColumn(Sentence sentence) {
String query = sentence.getQuery();
String tableName = query;
String columnPattern = "";
if (query.trim().length() == 0) {
tableName = null;
} else {
tableName = StringUtils.toUpperEnglish(query.trim());
if (tableName.endsWith(".")) {
tableName = tableName.substring(0, tableName.length() - 1);
} else {
columnPattern = StringUtils.toUpperEnglish(query.trim());
tableName = null;
}
}
HashSet set = null;
HashMap aliases = sentence.getAliases();
if (tableName == null && sentence.getTables() != null) {
set = sentence.getTables();
}
DbTableOrView table = null;
if (tableName != null && aliases != null && aliases.get(tableName) != null) {
table = (DbTableOrView) aliases.get(tableName);
tableName = StringUtils.toUpperEnglish(table.name);
}
if (tableName == null) {
if (set == null && aliases == null) {
return;
}
if ((set != null && set.size() > 1) || (aliases != null && aliases.size() > 1)) {
return;
}
}
if (table == null) {
DbTableOrView[] tables = contents.defaultSchema.tables;
for (int i = 0; i < tables.length; i++) {
DbTableOrView tab = tables[i];
String t = StringUtils.toUpperEnglish(tab.name);
if (tableName != null && !tableName.equals(t)) {
continue;
}
if (set != null && !set.contains(tab)) {
continue;
}
table = tab;
break;
}
}
- if (table != null) {
+ if (table != null && table.columns != null) {
for (int j = 0; j < table.columns.length; j++) {
String columnName = table.columns[j].name;
if (!StringUtils.toUpperEnglish(columnName).startsWith(columnPattern)) {
continue;
}
if (columnPattern.length() < columnName.length()) {
sentence.add(columnName, columnName.substring(columnPattern.length()), Sentence.CONTEXT);
}
}
}
}
public boolean matchRemove(Sentence sentence) {
if (sentence.getQuery().length() == 0) {
return false;
}
String s;
switch (type) {
case SCHEMA:
s = matchSchema(sentence);
break;
case TABLE:
s = matchTable(sentence);
break;
case NEW_TABLE_ALIAS:
s = matchTableAlias(sentence, true);
break;
case TABLE_ALIAS:
s = matchTableAlias(sentence, false);
break;
case COLUMN_ALIAS:
s = matchColumnAlias(sentence);
break;
case COLUMN:
s = matchColumn(sentence);
break;
default:
throw Message.getInternalError("type=" + type);
}
if (s == null) {
return false;
}
sentence.setQuery(s);
return true;
}
private String matchSchema(Sentence sentence) {
String query = sentence.getQuery();
String up = sentence.getQueryUpper();
DbSchema[] schemas = contents.schemas;
String best = null;
DbSchema bestSchema = null;
for (int i = 0; i < schemas.length; i++) {
DbSchema schema = schemas[i];
String schemaName = StringUtils.toUpperEnglish(schema.name);
if (up.startsWith(schemaName)) {
if (best == null || schemaName.length() > best.length()) {
best = schemaName;
bestSchema = schema;
}
}
}
sentence.setLastMatchedSchema(bestSchema);
if (best == null) {
return null;
}
query = query.substring(best.length());
// while(query.length()>0 && Character.isWhitespace(query.charAt(0))) {
// query = query.substring(1);
// }
return query;
}
private String matchTable(Sentence sentence) {
String query = sentence.getQuery();
String up = sentence.getQueryUpper();
DbSchema schema = sentence.getLastMatchedSchema();
if (schema == null) {
schema = contents.defaultSchema;
}
DbTableOrView[] tables = schema.tables;
String best = null;
DbTableOrView bestTable = null;
for (int i = 0; i < tables.length; i++) {
DbTableOrView table = tables[i];
String tableName = StringUtils.toUpperEnglish(table.name);
if (up.startsWith(tableName)) {
if (best == null || tableName.length() > best.length()) {
best = tableName;
bestTable = table;
}
}
}
if (best == null) {
return null;
}
sentence.addTable(bestTable);
query = query.substring(best.length());
// while(query.length()>0 && Character.isWhitespace(query.charAt(0))) {
// query = query.substring(1);
// }
return query;
}
private String matchColumnAlias(Sentence sentence) {
String query = sentence.getQuery();
String up = sentence.getQueryUpper();
int i = 0;
if (query.indexOf(' ') < 0) {
return null;
}
for (; i < up.length(); i++) {
char ch = up.charAt(i);
if (ch != '_' && !Character.isLetterOrDigit(ch)) {
break;
}
}
if (i == 0) {
return null;
}
String alias = up.substring(0, i);
if (Parser.isKeyword(alias, true)) {
return null;
}
return query.substring(alias.length());
}
private String matchTableAlias(Sentence sentence, boolean add) {
String query = sentence.getQuery();
String up = sentence.getQueryUpper();
int i = 0;
if (query.indexOf(' ') < 0) {
return null;
}
for (; i < up.length(); i++) {
char ch = up.charAt(i);
if (ch != '_' && !Character.isLetterOrDigit(ch)) {
break;
}
}
if (i == 0) {
return null;
}
String alias = up.substring(0, i);
if (Parser.isKeyword(alias, true)) {
return null;
}
if (add) {
sentence.addAlias(alias, sentence.getLastTable());
}
HashMap map = sentence.getAliases();
if ((map != null && map.containsKey(alias)) || (sentence.getLastTable() == null)) {
if (add && query.length() == alias.length()) {
return query;
}
query = query.substring(alias.length());
return query;
}
HashSet tables = sentence.getTables();
if (tables != null) {
String best = null;
for (Iterator it = tables.iterator(); it.hasNext();) {
DbTableOrView table = (DbTableOrView) it.next();
String tableName = StringUtils.toUpperEnglish(table.name);
//DbTableOrView[] tables = contents.defaultSchema.tables;
//for(int i=0; i<tables.length; i++) {
// DbTableOrView table = tables[i];
// String tableName = StringUtils.toUpperEnglish(table.name);
if (alias.startsWith(tableName) && (best == null || tableName.length() > best.length())) {
sentence.setLastMatchedTable(table);
best = tableName;
}
}
if (best != null) {
query = query.substring(best.length());
return query;
}
}
return null;
}
private String matchColumn(Sentence sentence) {
String query = sentence.getQuery();
String up = sentence.getQueryUpper();
HashSet set = sentence.getTables();
String best = null;
DbTableOrView last = sentence.getLastMatchedTable();
if (last != null && last.columns != null) {
for (int j = 0; j < last.columns.length; j++) {
String name = StringUtils.toUpperEnglish(last.columns[j].name);
if (up.startsWith(name)) {
String b = query.substring(name.length());
if (best == null || b.length() < best.length()) {
best = b;
}
}
}
}
DbTableOrView[] tables = contents.defaultSchema.tables;
for (int i = 0; i < tables.length; i++) {
DbTableOrView table = tables[i];
if (table != last && set != null && !set.contains(table)) {
continue;
}
if (table == null || table.columns == null) {
continue;
}
for (int j = 0; j < table.columns.length; j++) {
String name = StringUtils.toUpperEnglish(table.columns[j].name);
if (up.startsWith(name)) {
String b = query.substring(name.length());
if (best == null || b.length() < best.length()) {
best = b;
}
}
}
}
return best;
}
}
| true | true | private void addColumn(Sentence sentence) {
String query = sentence.getQuery();
String tableName = query;
String columnPattern = "";
if (query.trim().length() == 0) {
tableName = null;
} else {
tableName = StringUtils.toUpperEnglish(query.trim());
if (tableName.endsWith(".")) {
tableName = tableName.substring(0, tableName.length() - 1);
} else {
columnPattern = StringUtils.toUpperEnglish(query.trim());
tableName = null;
}
}
HashSet set = null;
HashMap aliases = sentence.getAliases();
if (tableName == null && sentence.getTables() != null) {
set = sentence.getTables();
}
DbTableOrView table = null;
if (tableName != null && aliases != null && aliases.get(tableName) != null) {
table = (DbTableOrView) aliases.get(tableName);
tableName = StringUtils.toUpperEnglish(table.name);
}
if (tableName == null) {
if (set == null && aliases == null) {
return;
}
if ((set != null && set.size() > 1) || (aliases != null && aliases.size() > 1)) {
return;
}
}
if (table == null) {
DbTableOrView[] tables = contents.defaultSchema.tables;
for (int i = 0; i < tables.length; i++) {
DbTableOrView tab = tables[i];
String t = StringUtils.toUpperEnglish(tab.name);
if (tableName != null && !tableName.equals(t)) {
continue;
}
if (set != null && !set.contains(tab)) {
continue;
}
table = tab;
break;
}
}
if (table != null) {
for (int j = 0; j < table.columns.length; j++) {
String columnName = table.columns[j].name;
if (!StringUtils.toUpperEnglish(columnName).startsWith(columnPattern)) {
continue;
}
if (columnPattern.length() < columnName.length()) {
sentence.add(columnName, columnName.substring(columnPattern.length()), Sentence.CONTEXT);
}
}
}
}
| private void addColumn(Sentence sentence) {
String query = sentence.getQuery();
String tableName = query;
String columnPattern = "";
if (query.trim().length() == 0) {
tableName = null;
} else {
tableName = StringUtils.toUpperEnglish(query.trim());
if (tableName.endsWith(".")) {
tableName = tableName.substring(0, tableName.length() - 1);
} else {
columnPattern = StringUtils.toUpperEnglish(query.trim());
tableName = null;
}
}
HashSet set = null;
HashMap aliases = sentence.getAliases();
if (tableName == null && sentence.getTables() != null) {
set = sentence.getTables();
}
DbTableOrView table = null;
if (tableName != null && aliases != null && aliases.get(tableName) != null) {
table = (DbTableOrView) aliases.get(tableName);
tableName = StringUtils.toUpperEnglish(table.name);
}
if (tableName == null) {
if (set == null && aliases == null) {
return;
}
if ((set != null && set.size() > 1) || (aliases != null && aliases.size() > 1)) {
return;
}
}
if (table == null) {
DbTableOrView[] tables = contents.defaultSchema.tables;
for (int i = 0; i < tables.length; i++) {
DbTableOrView tab = tables[i];
String t = StringUtils.toUpperEnglish(tab.name);
if (tableName != null && !tableName.equals(t)) {
continue;
}
if (set != null && !set.contains(tab)) {
continue;
}
table = tab;
break;
}
}
if (table != null && table.columns != null) {
for (int j = 0; j < table.columns.length; j++) {
String columnName = table.columns[j].name;
if (!StringUtils.toUpperEnglish(columnName).startsWith(columnPattern)) {
continue;
}
if (columnPattern.length() < columnName.length()) {
sentence.add(columnName, columnName.substring(columnPattern.length()), Sentence.CONTEXT);
}
}
}
}
|
diff --git a/java-buzz-client/src/main/java/com/google/buzz/model/BuzzComment.java b/java-buzz-client/src/main/java/com/google/buzz/model/BuzzComment.java
index 28f1e74..edb3052 100644
--- a/java-buzz-client/src/main/java/com/google/buzz/model/BuzzComment.java
+++ b/java-buzz-client/src/main/java/com/google/buzz/model/BuzzComment.java
@@ -1,211 +1,219 @@
package com.google.buzz.model;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class BuzzComment
{
/**
* The object type of the activity.
*/
private String activityObjectType;
/**
* The comment id.
*/
private String id;
/**
* The published date
*/
private Date published;
/**
* The comment author
*/
private BuzzAuthor author;
/**
* The comment content
*/
private BuzzContent content;
/**
* The comment original content
*/
private BuzzContent originalContent;
/**
* The comment links
*/
private List<BuzzLink> links = new ArrayList<BuzzLink>( 0 );
/**
* The comment reply
*/
private BuzzReply reply;
/**
* @return the activityObjectType
*/
public String getActivityObjectType()
{
return activityObjectType;
}
/**
* @param activityObjectType the activityObjectType to set
*/
public void setActivityObjectType( String activityObjectType )
{
this.activityObjectType = activityObjectType;
}
/**
* @return the id
*/
public String getId()
{
return id;
}
/**
* @param id the id to set
*/
public void setId( String id )
{
this.id = id;
}
/**
* @return the published
*/
public Date getPublished()
{
return published;
}
/**
* @param published the published to set
*/
public void setPublished( Date published )
{
this.published = published;
}
/**
* @return the author
*/
public BuzzAuthor getAuthor()
{
return author;
}
/**
* @param author the author to set
*/
public void setAuthor( BuzzAuthor author )
{
this.author = author;
}
/**
* @return the content
*/
public BuzzContent getContent()
{
return content;
}
/**
* @param content the content to set
*/
public void setContent( BuzzContent content )
{
this.content = content;
}
/**
* @return the originalContent
*/
public BuzzContent getOriginalContent()
{
return originalContent;
}
/**
* @param originalContent the originalContent to set
*/
public void setOriginalContent( BuzzContent originalContent )
{
this.originalContent = originalContent;
}
/**
* @return the links
*/
public List<BuzzLink> getLinks()
{
return links;
}
/**
* @param links the links to set
*/
public void setLinks( List<BuzzLink> links )
{
this.links = links;
}
/**
* @return the reply
*/
public BuzzReply getReply()
{
return reply;
}
/**
* @param reply the reply to set
*/
public void setReply( BuzzReply reply )
{
this.reply = reply;
}
/**
* Overwrite the default toString method
*
* @return the string representation of the object
*/
public String toString()
{
return toString( "\n" );
}
/**
* Print the object in a pretty way.
*
* @param indent to print the attributes
* @return a formatted string representation of the object
*/
public String toString( String indent )
{
StringBuilder sb = new StringBuilder();
String newIndent = indent + "\t";
sb.append( indent + "BuzzComment:" );
sb.append( newIndent + "Activity Object Type: " + activityObjectType );
sb.append( newIndent + "Published: " + published );
sb.append( newIndent + "Id: " + id );
sb.append( newIndent + "Author: " + author.toString( newIndent + "\t" ) );
- sb.append( newIndent + "Content: " + content.toString( newIndent + "\t" ) );
- sb.append( newIndent + "Original Content: " + originalContent.toString( newIndent + "\t" ) );
+ if (content!=null) {
+ sb.append( newIndent + "Content: " + content.toString( newIndent + "\t" ) );
+ } else {
+ sb.append( newIndent + "Content: null" );
+ }
+ if (originalContent!=null) {
+ sb.append( newIndent + "Original Content: " + originalContent.toString( newIndent + "\t" ) );
+ } else {
+ sb.append( newIndent + "OriginalContent: null" );
+ }
for ( int i = 0; i < links.size(); i++ )
{
sb.append( links.get( i ).toString( newIndent + "\t" ) );
}
sb.append( newIndent + "Reply: " + reply.toString( newIndent + "\t" ) );
return sb.toString();
}
}
| true | true | public String toString( String indent )
{
StringBuilder sb = new StringBuilder();
String newIndent = indent + "\t";
sb.append( indent + "BuzzComment:" );
sb.append( newIndent + "Activity Object Type: " + activityObjectType );
sb.append( newIndent + "Published: " + published );
sb.append( newIndent + "Id: " + id );
sb.append( newIndent + "Author: " + author.toString( newIndent + "\t" ) );
sb.append( newIndent + "Content: " + content.toString( newIndent + "\t" ) );
sb.append( newIndent + "Original Content: " + originalContent.toString( newIndent + "\t" ) );
for ( int i = 0; i < links.size(); i++ )
{
sb.append( links.get( i ).toString( newIndent + "\t" ) );
}
sb.append( newIndent + "Reply: " + reply.toString( newIndent + "\t" ) );
return sb.toString();
}
| public String toString( String indent )
{
StringBuilder sb = new StringBuilder();
String newIndent = indent + "\t";
sb.append( indent + "BuzzComment:" );
sb.append( newIndent + "Activity Object Type: " + activityObjectType );
sb.append( newIndent + "Published: " + published );
sb.append( newIndent + "Id: " + id );
sb.append( newIndent + "Author: " + author.toString( newIndent + "\t" ) );
if (content!=null) {
sb.append( newIndent + "Content: " + content.toString( newIndent + "\t" ) );
} else {
sb.append( newIndent + "Content: null" );
}
if (originalContent!=null) {
sb.append( newIndent + "Original Content: " + originalContent.toString( newIndent + "\t" ) );
} else {
sb.append( newIndent + "OriginalContent: null" );
}
for ( int i = 0; i < links.size(); i++ )
{
sb.append( links.get( i ).toString( newIndent + "\t" ) );
}
sb.append( newIndent + "Reply: " + reply.toString( newIndent + "\t" ) );
return sb.toString();
}
|
diff --git a/src/java/com/opensymphony/module/sitemesh/servlets/PathologicalServlet.java b/src/java/com/opensymphony/module/sitemesh/servlets/PathologicalServlet.java
index 577273a..737a663 100644
--- a/src/java/com/opensymphony/module/sitemesh/servlets/PathologicalServlet.java
+++ b/src/java/com/opensymphony/module/sitemesh/servlets/PathologicalServlet.java
@@ -1,36 +1,36 @@
package com.opensymphony.module.sitemesh.servlets;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
/**
* Created by IntelliJ IDEA.
* User: joeo
* Date: Jun 5, 2004
* Time: 3:36:11 AM
* To change this template use File | Settings | File Templates.
*/
public class PathologicalServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String mode = request.getParameter("out");
PrintWriter pw = null;
- if (mode.equals("writer")) {
+ if (mode.equals("stream")) {
OutputStreamWriter osw = new OutputStreamWriter(response.getOutputStream());
pw = new PrintWriter(osw);
}
if (pw == null) {
pw = response.getWriter();
}
response.setContentType("text/html");
pw.println("<html><head><title>Servlet using " + mode + "</title></head>");
pw.println("<body>This is a servlet using " + mode + " to output</body></html>");
pw.flush();
}
}
| true | true | protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String mode = request.getParameter("out");
PrintWriter pw = null;
if (mode.equals("writer")) {
OutputStreamWriter osw = new OutputStreamWriter(response.getOutputStream());
pw = new PrintWriter(osw);
}
if (pw == null) {
pw = response.getWriter();
}
response.setContentType("text/html");
pw.println("<html><head><title>Servlet using " + mode + "</title></head>");
pw.println("<body>This is a servlet using " + mode + " to output</body></html>");
pw.flush();
}
| protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String mode = request.getParameter("out");
PrintWriter pw = null;
if (mode.equals("stream")) {
OutputStreamWriter osw = new OutputStreamWriter(response.getOutputStream());
pw = new PrintWriter(osw);
}
if (pw == null) {
pw = response.getWriter();
}
response.setContentType("text/html");
pw.println("<html><head><title>Servlet using " + mode + "</title></head>");
pw.println("<body>This is a servlet using " + mode + " to output</body></html>");
pw.flush();
}
|
diff --git a/weblets-api/src/main/java/net/java/dev/weblets/FacesWebletUtils.java b/weblets-api/src/main/java/net/java/dev/weblets/FacesWebletUtils.java
index 7242332..9684a23 100644
--- a/weblets-api/src/main/java/net/java/dev/weblets/FacesWebletUtils.java
+++ b/weblets-api/src/main/java/net/java/dev/weblets/FacesWebletUtils.java
@@ -1,75 +1,75 @@
package net.java.dev.weblets;
import javax.faces.context.FacesContext;
/**
* @author Werner Punz Weblet Utils class which gives the interfaces for the JSF part of weblets
*/
public class FacesWebletUtils {
/**
* returns the absolute url with the context path
*
* @param context the current faces context
* @param weblet the weblet name
* @param pathInfo the path info
* @return a url with the current web-app context path to the weblet
*/
public static String getURL(FacesContext context, String weblet, String pathInfo) {
- return WebletUtils.getResource(weblet, pathInfo);
+ return WebletUtils.getURL(weblet, pathInfo);
}
/**
* internal api which can be used by component
* sets to suppress double includes
* for jsf components!
*
* @param context
* @param weblet
* @param pathInfo
* @param suppressDoubleIncludes
* @return
*/
public static String getURL(FacesContext context, String weblet, String pathInfo, boolean suppressDoubleIncludes) {
return WebletUtils.getURL(context.getExternalContext().getRequest(), weblet, pathInfo, suppressDoubleIncludes);
}
/**
* getResource which also suppresses double includes
* for internal handling
* comes in handy with the subbundles which always deliver the bundle id as resource!
*
* @param context
* @param weblet
* @param pathInfo
* @param suppressDoubleIncludes
* @return
*/
public static String getResource(FacesContext context, String weblet, String pathInfo, boolean suppressDoubleIncludes) {
return WebletUtils.getResource(context.getExternalContext(), weblet, pathInfo, suppressDoubleIncludes);
}
/**
* returns the relative url without the context path
*
* @param context the current faces context
* @param weblet the weblet name
* @param pathInfo the path info to the resource
* @return a url with the current web-app context path to the weblet
*/
public static String getResource(FacesContext context, String weblet, String pathInfo) {
return WebletUtils.getResource(weblet, pathInfo);
}
/**
* isResourceLoaded check
*
* @param context the current facesContext
* @param weblet the weblet
* @param pathInfo the pathInfo
* @return
*/
public static boolean isResourceLoaded(FacesContext context, String weblet, String pathInfo) {
return WebletUtils.isResourceLoaded(context.getExternalContext().getRequest(), weblet, pathInfo);
}
}
| true | true | public static String getURL(FacesContext context, String weblet, String pathInfo) {
return WebletUtils.getResource(weblet, pathInfo);
}
| public static String getURL(FacesContext context, String weblet, String pathInfo) {
return WebletUtils.getURL(weblet, pathInfo);
}
|
diff --git a/src/org/servalproject/servald/BundleKey.java b/src/org/servalproject/servald/BundleKey.java
index 65d746b2..0a949079 100644
--- a/src/org/servalproject/servald/BundleKey.java
+++ b/src/org/servalproject/servald/BundleKey.java
@@ -1,44 +1,44 @@
/**
* Copyright (C) 2011 The Serval Project
*
* This file is part of Serval Software (http://www.servalproject.org)
*
* Serval Software is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This source code is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this source code; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.servalproject.servald;
import java.nio.BufferUnderflowException;
import java.nio.ByteBuffer;
public class BundleKey extends AbstractId {
public int getBinarySize() {
- return 64;
+ return 32;
}
public BundleKey(String hex) throws InvalidHexException {
super(hex);
}
public BundleKey(ByteBuffer b) throws InvalidBinaryException {
super(b);
}
public BundleKey(byte[] binary) throws InvalidBinaryException {
super(binary);
}
}
| true | true | public int getBinarySize() {
return 64;
}
| public int getBinarySize() {
return 32;
}
|
diff --git a/openejb/tomee/tomee-loader/src/test/java/org/apache/tomee/loader/test/UserSessionTest.java b/openejb/tomee/tomee-loader/src/test/java/org/apache/tomee/loader/test/UserSessionTest.java
index 1f1123a30..2c16ad6a7 100644
--- a/openejb/tomee/tomee-loader/src/test/java/org/apache/tomee/loader/test/UserSessionTest.java
+++ b/openejb/tomee/tomee-loader/src/test/java/org/apache/tomee/loader/test/UserSessionTest.java
@@ -1,122 +1,120 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.tomee.loader.test;
import org.apache.tomee.loader.service.ServiceContext;
import org.apache.tomee.loader.service.ServiceContextImpl;
import org.junit.Test;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
public class UserSessionTest {
@Test()
public void test() throws Exception {
{
final Properties properties = new Properties();
properties.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.openejb.core.LocalInitialContextFactory");
properties.put("openejb.loader", "embed");
try {
new InitialContext(properties);
} catch (NamingException e) {
throw new RuntimeException(e);
}
}
final ServiceContext service = new ServiceContextImpl();
final Map<String, Object> result = service.getJndiHelper().getJndi();
org.junit.Assert.assertNotNull(result);
org.junit.Assert.assertFalse(result.isEmpty());
final List<String> names = new ArrayList<String>();
mountPathsList(names, new ArrayList<String>(), result);
System.out.println("*******************************************");
System.out.println(result);
System.out.println("*******************************************");
for (String name : names) {
- System.out.println(name);
- }
- System.out.println("*******************************************");
- for (String name : names) {
Object srv = null;
try {
srv = service.getOpenEJBHelper().lookup(name);
} catch (NamingException e) {
- System.out.println(name + " (NOT FOUND) ");
+ //not found
}
if (DummyEjb.class.isInstance(srv)) {
final DummyEjb dummyEjb = DummyEjb.class.cast(srv);
- System.out.println(name + " -> " + dummyEjb.sayHi());
+ System.out.println(name + " -> dummyEjb.sayHi() -> " + dummyEjb.sayHi());
} else {
- if (srv != null) {
+ if (srv == null) {
+ System.out.println(name + " (NOT FOUND) ");
+ } else {
System.out.println(name);
}
}
}
System.out.println("*******************************************");
}
private void mountPathsList(final List<String> names, final List<String> path, final Map<String, Object> jndiEntry) {
if ("module".equals(jndiEntry.get("type"))) {
return;
}
final List<String> innerPath = new ArrayList<String>(path);
if ("context".equals(jndiEntry.get("type"))) {
innerPath.add((String) jndiEntry.get("path"));
} else if ("leaf".equals(jndiEntry.get("type"))) {
if ("/AppName".equals(jndiEntry.get("path"))
|| "/ModuleName".equals(jndiEntry.get("path"))) {
return;
}
String[] entryPaths = ((String) jndiEntry.get("path")).split("/");
String leafName = entryPaths[entryPaths.length - 1];
StringBuffer resultingPath = new StringBuffer();
for (String pathEntry : path) {
resultingPath.append(pathEntry);
resultingPath.append("/");
}
resultingPath.append(leafName);
names.add(resultingPath.toString());
return;
}
List<Map<String, Object>> jndiEntries = (List<Map<String, Object>>) jndiEntry.get("children");
if (jndiEntries != null && !jndiEntries.isEmpty()) {
for (Map<String, Object> child : jndiEntries) {
mountPathsList(names, innerPath, child);
}
}
}
}
| false | true | public void test() throws Exception {
{
final Properties properties = new Properties();
properties.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.openejb.core.LocalInitialContextFactory");
properties.put("openejb.loader", "embed");
try {
new InitialContext(properties);
} catch (NamingException e) {
throw new RuntimeException(e);
}
}
final ServiceContext service = new ServiceContextImpl();
final Map<String, Object> result = service.getJndiHelper().getJndi();
org.junit.Assert.assertNotNull(result);
org.junit.Assert.assertFalse(result.isEmpty());
final List<String> names = new ArrayList<String>();
mountPathsList(names, new ArrayList<String>(), result);
System.out.println("*******************************************");
System.out.println(result);
System.out.println("*******************************************");
for (String name : names) {
System.out.println(name);
}
System.out.println("*******************************************");
for (String name : names) {
Object srv = null;
try {
srv = service.getOpenEJBHelper().lookup(name);
} catch (NamingException e) {
System.out.println(name + " (NOT FOUND) ");
}
if (DummyEjb.class.isInstance(srv)) {
final DummyEjb dummyEjb = DummyEjb.class.cast(srv);
System.out.println(name + " -> " + dummyEjb.sayHi());
} else {
if (srv != null) {
System.out.println(name);
}
}
}
System.out.println("*******************************************");
}
| public void test() throws Exception {
{
final Properties properties = new Properties();
properties.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.openejb.core.LocalInitialContextFactory");
properties.put("openejb.loader", "embed");
try {
new InitialContext(properties);
} catch (NamingException e) {
throw new RuntimeException(e);
}
}
final ServiceContext service = new ServiceContextImpl();
final Map<String, Object> result = service.getJndiHelper().getJndi();
org.junit.Assert.assertNotNull(result);
org.junit.Assert.assertFalse(result.isEmpty());
final List<String> names = new ArrayList<String>();
mountPathsList(names, new ArrayList<String>(), result);
System.out.println("*******************************************");
System.out.println(result);
System.out.println("*******************************************");
for (String name : names) {
Object srv = null;
try {
srv = service.getOpenEJBHelper().lookup(name);
} catch (NamingException e) {
//not found
}
if (DummyEjb.class.isInstance(srv)) {
final DummyEjb dummyEjb = DummyEjb.class.cast(srv);
System.out.println(name + " -> dummyEjb.sayHi() -> " + dummyEjb.sayHi());
} else {
if (srv == null) {
System.out.println(name + " (NOT FOUND) ");
} else {
System.out.println(name);
}
}
}
System.out.println("*******************************************");
}
|
diff --git a/src/main/java/com/jin/tpdb/persistence/DAO.java b/src/main/java/com/jin/tpdb/persistence/DAO.java
index b6f0cd8..b4bdfbc 100755
--- a/src/main/java/com/jin/tpdb/persistence/DAO.java
+++ b/src/main/java/com/jin/tpdb/persistence/DAO.java
@@ -1,115 +1,115 @@
package com.jin.tpdb.persistence;
import java.util.List;
import javax.persistence.*;
import javax.persistence.criteria.*;
import com.jin.tpdb.entities.*;
public class DAO {
protected static EntityManagerFactory factory;
protected EntityManager em;
public DAO() {
if(DAO.getManagerFactory() == null) {
factory = Persistence.createEntityManagerFactory("jin");
DAO.setManagerFactory(factory);
} else {
factory = DAO.getManagerFactory();
}
}
protected static void setManagerFactory(EntityManagerFactory f){
factory = f;
}
protected static EntityManagerFactory getManagerFactory() {
return factory;
}
public void open() {
try {
em = factory.createEntityManager();
em.getTransaction().begin();
} catch(Exception e) {
e.printStackTrace();
}
}
public void close() {
try {
em.getTransaction().commit();
em.close();
} catch(Exception e) {
e.printStackTrace();
}
}
public void save(Object o) {
em.persist(o);
}
public void rollback() {
em.getTransaction().rollback();
}
public static <T> T load(Class c, int i) {
DAO dao = new DAO();
dao.open();
T result = dao.get(c, i);
dao.close();
return result;
}
public static <T> List<T> getList(Class c) {
DAO dao = new DAO();
dao.open();
List<T> results = dao.list(c);
dao.close();
return results;
}
public <T> T get(Class c, int i) {
return (T)em.find(c, i);
}
protected <T> List<T> list(Class entity) {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<T> query = cb.createQuery(entity);
TypedQuery<T> typedQuery = em.createQuery(
query.select(
query.from(entity)
)
);
return typedQuery.getResultList();
}
public int getAlbumTotalComments(int id) {
/*$albums_query = "SELECT users.username, albums.album_id, albums.uploader_user_id, albums.album_name,
albums.upload_date, albums.cover, albums.description, artists.artist_name,
(SELECT COUNT( comment_id ) FROM comments WHERE comments.album_id = albums.album_id) AS total_comments
FROM albums, artists, users
WHERE artists.artist_id = albums.artist_id AND users.user_id
*/
String qs = "SELECT COUNT(ac) FROM AlbumComment ac";
TypedQuery<Integer> query = em.createQuery(qs, Integer.class);
- return query.getSingleResult();
+ return (int)query.getSingleResult();
/*Root<AlbumComment> root = cq.from(AlbumComment.class);
cq.select(qb.count(root));
Predicate predicate = qb.equal(root.get("album_id"), id);
cq.where(predicate);
return em.createQuery(cq).getSingleResult();*/
}
public static int countAlbumComments(int id) {
DAO dao = new DAO();
dao.open();
int count = dao.getAlbumTotalComments(id);
dao.close();
return count;
}
}
| true | true | public int getAlbumTotalComments(int id) {
/*$albums_query = "SELECT users.username, albums.album_id, albums.uploader_user_id, albums.album_name,
albums.upload_date, albums.cover, albums.description, artists.artist_name,
(SELECT COUNT( comment_id ) FROM comments WHERE comments.album_id = albums.album_id) AS total_comments
FROM albums, artists, users
WHERE artists.artist_id = albums.artist_id AND users.user_id
*/
String qs = "SELECT COUNT(ac) FROM AlbumComment ac";
TypedQuery<Integer> query = em.createQuery(qs, Integer.class);
return query.getSingleResult();
/*Root<AlbumComment> root = cq.from(AlbumComment.class);
cq.select(qb.count(root));
Predicate predicate = qb.equal(root.get("album_id"), id);
cq.where(predicate);
return em.createQuery(cq).getSingleResult();*/
}
| public int getAlbumTotalComments(int id) {
/*$albums_query = "SELECT users.username, albums.album_id, albums.uploader_user_id, albums.album_name,
albums.upload_date, albums.cover, albums.description, artists.artist_name,
(SELECT COUNT( comment_id ) FROM comments WHERE comments.album_id = albums.album_id) AS total_comments
FROM albums, artists, users
WHERE artists.artist_id = albums.artist_id AND users.user_id
*/
String qs = "SELECT COUNT(ac) FROM AlbumComment ac";
TypedQuery<Integer> query = em.createQuery(qs, Integer.class);
return (int)query.getSingleResult();
/*Root<AlbumComment> root = cq.from(AlbumComment.class);
cq.select(qb.count(root));
Predicate predicate = qb.equal(root.get("album_id"), id);
cq.where(predicate);
return em.createQuery(cq).getSingleResult();*/
}
|
diff --git a/src/tests/java/net/sf/picard/sam/MergeSamFilesTest.java b/src/tests/java/net/sf/picard/sam/MergeSamFilesTest.java
index a9c98a12..0fcaba30 100644
--- a/src/tests/java/net/sf/picard/sam/MergeSamFilesTest.java
+++ b/src/tests/java/net/sf/picard/sam/MergeSamFilesTest.java
@@ -1,60 +1,58 @@
/*
* The MIT License
*
* Copyright (c) 2011 The Broad Institute
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package net.sf.picard.sam;
import net.sf.samtools.SAMFileHeader;
import net.sf.samtools.SAMFileReader;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.io.File;
public class MergeSamFilesTest {
private static File TEST_DATA_DIR = new File("testdata/net/sf/picard/sam/MergeSamFiles");
/**
* Confirm that unsorted input can result in coordinate sorted output, with index created.
*/
@Test
public void unsortedInputSortedOutputTest() throws Exception {
File unsortedInputTestDataDir = new File(TEST_DATA_DIR, "unsorted_input");
File mergedOutput = File.createTempFile("unsortedInputSortedOutputTest.", ".bam");
mergedOutput.deleteOnExit();
String[] args = {
"I=" + new File(unsortedInputTestDataDir, "1.sam").getAbsolutePath(),
"I=" + new File(unsortedInputTestDataDir, "2.sam").getAbsolutePath(),
"O=" + mergedOutput.getAbsolutePath(),
- "SO=coordinate",
- "CREATE_INDEX=True"
+ "SO=coordinate"
};
final int mergeExitStatus = new MergeSamFiles().instanceMain(args);
Assert.assertEquals(mergeExitStatus, 0);
final SAMFileReader reader = new SAMFileReader(mergedOutput);
Assert.assertEquals(reader.getFileHeader().getSortOrder(), SAMFileHeader.SortOrder.coordinate);
- Assert.assertTrue(reader.hasIndex());
final int validateExitStatus = new ValidateSamFile().instanceMain(new String[] {"I=" + mergedOutput.getAbsolutePath()});
Assert.assertEquals(validateExitStatus, 0);
}
}
| false | true | public void unsortedInputSortedOutputTest() throws Exception {
File unsortedInputTestDataDir = new File(TEST_DATA_DIR, "unsorted_input");
File mergedOutput = File.createTempFile("unsortedInputSortedOutputTest.", ".bam");
mergedOutput.deleteOnExit();
String[] args = {
"I=" + new File(unsortedInputTestDataDir, "1.sam").getAbsolutePath(),
"I=" + new File(unsortedInputTestDataDir, "2.sam").getAbsolutePath(),
"O=" + mergedOutput.getAbsolutePath(),
"SO=coordinate",
"CREATE_INDEX=True"
};
final int mergeExitStatus = new MergeSamFiles().instanceMain(args);
Assert.assertEquals(mergeExitStatus, 0);
final SAMFileReader reader = new SAMFileReader(mergedOutput);
Assert.assertEquals(reader.getFileHeader().getSortOrder(), SAMFileHeader.SortOrder.coordinate);
Assert.assertTrue(reader.hasIndex());
final int validateExitStatus = new ValidateSamFile().instanceMain(new String[] {"I=" + mergedOutput.getAbsolutePath()});
Assert.assertEquals(validateExitStatus, 0);
}
| public void unsortedInputSortedOutputTest() throws Exception {
File unsortedInputTestDataDir = new File(TEST_DATA_DIR, "unsorted_input");
File mergedOutput = File.createTempFile("unsortedInputSortedOutputTest.", ".bam");
mergedOutput.deleteOnExit();
String[] args = {
"I=" + new File(unsortedInputTestDataDir, "1.sam").getAbsolutePath(),
"I=" + new File(unsortedInputTestDataDir, "2.sam").getAbsolutePath(),
"O=" + mergedOutput.getAbsolutePath(),
"SO=coordinate"
};
final int mergeExitStatus = new MergeSamFiles().instanceMain(args);
Assert.assertEquals(mergeExitStatus, 0);
final SAMFileReader reader = new SAMFileReader(mergedOutput);
Assert.assertEquals(reader.getFileHeader().getSortOrder(), SAMFileHeader.SortOrder.coordinate);
final int validateExitStatus = new ValidateSamFile().instanceMain(new String[] {"I=" + mergedOutput.getAbsolutePath()});
Assert.assertEquals(validateExitStatus, 0);
}
|
diff --git a/same/src/main/java/com/orbekk/net/MyJsonRpcHttpClient.java b/same/src/main/java/com/orbekk/net/MyJsonRpcHttpClient.java
index b610a2f..d5e30d7 100644
--- a/same/src/main/java/com/orbekk/net/MyJsonRpcHttpClient.java
+++ b/same/src/main/java/com/orbekk/net/MyJsonRpcHttpClient.java
@@ -1,76 +1,76 @@
package com.orbekk.net;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Type;
import java.net.URL;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentProducer;
import org.apache.http.entity.EntityTemplate;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.googlecode.jsonrpc4j.JsonRpcClient;
import com.googlecode.jsonrpc4j.JsonRpcHttpClient;
/**
* This class is horrible. :S
*
* We extend JsonRpcHttpClient but try to override everything it does.
*/
public class MyJsonRpcHttpClient extends JsonRpcHttpClient {
Logger logger = LoggerFactory.getLogger(getClass());
private URL serviceUrl;
private JsonRpcClient rpcClient;
private HttpClient httpClient;
public MyJsonRpcHttpClient(URL serviceUrl, int connectionTimeout,
int readTimeout) {
super(null);
httpClient = new DefaultHttpClient();
HttpParams params = httpClient.getParams();
HttpConnectionParams.setConnectionTimeout(params, connectionTimeout);
HttpConnectionParams.setSoTimeout(params, readTimeout);
rpcClient = new JsonRpcClient();
this.serviceUrl = serviceUrl;
}
@Override
public synchronized Object invoke(
final String methodName, final Object[] arguments, Type returnType,
Map<String, String> extraHeaders)
throws Exception {
EntityTemplate entity = new EntityTemplate(new ContentProducer() {
@Override
public void writeTo(OutputStream out) throws IOException {
try {
rpcClient.invoke(methodName, arguments, out);
} catch (Exception e) {
- throw new IOException(e.fillInStackTrace());
+ throw new IOException("RPC Failed: " + e.getMessage());
}
}
});
entity.setContentType("application/json-rpc");
HttpPost post = new HttpPost(serviceUrl.toString());
for (Map.Entry<String, String> entry : extraHeaders.entrySet()) {
post.addHeader(entry.getKey(), entry.getValue());
}
post.setEntity(entity);
HttpResponse response = httpClient.execute(post);
HttpEntity responseEntity = response.getEntity();
return super.readResponse(returnType, responseEntity.getContent());
}
}
| true | true | public synchronized Object invoke(
final String methodName, final Object[] arguments, Type returnType,
Map<String, String> extraHeaders)
throws Exception {
EntityTemplate entity = new EntityTemplate(new ContentProducer() {
@Override
public void writeTo(OutputStream out) throws IOException {
try {
rpcClient.invoke(methodName, arguments, out);
} catch (Exception e) {
throw new IOException(e.fillInStackTrace());
}
}
});
entity.setContentType("application/json-rpc");
HttpPost post = new HttpPost(serviceUrl.toString());
for (Map.Entry<String, String> entry : extraHeaders.entrySet()) {
post.addHeader(entry.getKey(), entry.getValue());
}
post.setEntity(entity);
HttpResponse response = httpClient.execute(post);
HttpEntity responseEntity = response.getEntity();
return super.readResponse(returnType, responseEntity.getContent());
}
| public synchronized Object invoke(
final String methodName, final Object[] arguments, Type returnType,
Map<String, String> extraHeaders)
throws Exception {
EntityTemplate entity = new EntityTemplate(new ContentProducer() {
@Override
public void writeTo(OutputStream out) throws IOException {
try {
rpcClient.invoke(methodName, arguments, out);
} catch (Exception e) {
throw new IOException("RPC Failed: " + e.getMessage());
}
}
});
entity.setContentType("application/json-rpc");
HttpPost post = new HttpPost(serviceUrl.toString());
for (Map.Entry<String, String> entry : extraHeaders.entrySet()) {
post.addHeader(entry.getKey(), entry.getValue());
}
post.setEntity(entity);
HttpResponse response = httpClient.execute(post);
HttpEntity responseEntity = response.getEntity();
return super.readResponse(returnType, responseEntity.getContent());
}
|
diff --git a/flexmojos-maven-plugin/src/main/java/org/sonatype/flexmojos/plugin/air/SignAirMojo.java b/flexmojos-maven-plugin/src/main/java/org/sonatype/flexmojos/plugin/air/SignAirMojo.java
index bcf56d311..71be8ca1f 100644
--- a/flexmojos-maven-plugin/src/main/java/org/sonatype/flexmojos/plugin/air/SignAirMojo.java
+++ b/flexmojos-maven-plugin/src/main/java/org/sonatype/flexmojos/plugin/air/SignAirMojo.java
@@ -1,439 +1,443 @@
/**
* Flexmojos is a set of maven goals to allow maven users to compile, optimize and test Flex SWF, Flex SWC, Air SWF and Air SWC.
* Copyright (C) 2008-2012 Marvin Froeder <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.sonatype.flexmojos.plugin.air;
import static org.sonatype.flexmojos.plugin.common.FlexExtension.AIR;
import static org.sonatype.flexmojos.plugin.common.FlexExtension.SWC;
import static org.sonatype.flexmojos.plugin.common.FlexExtension.SWF;
import static org.sonatype.flexmojos.util.PathUtil.file;
import static org.sonatype.flexmojos.util.PathUtil.path;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.cert.Certificate;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.model.FileSet;
import org.apache.maven.model.Resource;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.project.MavenProject;
import org.apache.maven.project.MavenProjectHelper;
import org.codehaus.plexus.util.DirectoryScanner;
import org.codehaus.plexus.util.FileUtils;
import org.sonatype.flexmojos.plugin.AbstractMavenMojo;
import org.sonatype.flexmojos.plugin.air.packager.FlexmojosAIRPackager;
import org.sonatype.flexmojos.plugin.utilities.FileInterpolationUtil;
import org.sonatype.flexmojos.util.PathUtil;
import com.adobe.air.Listener;
import com.adobe.air.Message;
/**
* @goal sign-air
* @phase package
* @requiresDependencyResolution compile
* @author Marvin Froeder
*/
public class SignAirMojo
extends AbstractMavenMojo
{
private static String TIMESTAMP_NONE = "none";
/**
* @parameter default-value="${project.build.directory}/air"
*/
private File airOutput;
/**
* Classifier to add to the artifact generated. If given, the artifact will be an attachment instead.
*
* @parameter expression="${flexmojos.classifier}"
*/
private String classifier;
/**
* @parameter default-value="${basedir}/src/main/resources/descriptor.xml"
* @required
*/
private File descriptorTemplate;
/**
* Ideally Adobe would have used some parseable token, not a huge pass-phrase on the descriptor output. They did
* prefer to reinvent wheel, so more work to all of us.
*
* @parameter expression="${flexmojos.flexbuilderCompatibility}"
*/
private boolean flexBuilderCompatibility;
/**
* Include specified files in AIR package.
*
* @parameter
*/
private List<String> includeFiles;
/**
* Include specified files or directories in AIR package.
*
* @parameter
*/
private FileSet[] includeFileSets;
/**
* @parameter default-value="${basedir}/src/main/resources/sign.p12"
*/
private File keystore;
/**
* @parameter expression="${project}"
*/
private MavenProject project;
/**
* @component
* @required
* @readonly
*/
protected MavenProjectHelper projectHelper;
/**
* @parameter
* @required
*/
private String storepass;
/**
* The type of keystore, determined by the keystore implementation.
*
* @parameter default-value="pkcs12"
*/
private String storetype;
/**
* Strip artifact version during copy of dependencies.
*
* @parameter default-value="false"
*/
private boolean stripVersion;
/**
* The URL for the timestamp server. If 'none', no timestamp will be used.
*
* @parameter
*/
private String timestampURL;
private void addSourceWithPath( FlexmojosAIRPackager packager, File directory, String includePath )
throws MojoFailureException
{
if ( includePath == null )
{
throw new MojoFailureException( "Cannot include a null file" );
}
// get file from output directory to allow filtered resources
File includeFile = new File( directory, includePath );
if ( !includeFile.isFile() )
{
throw new MojoFailureException( "Include files only accept files as parameters: " + includePath );
}
// don't include the app descriptor or the cert
if ( path( includeFile ).equals( path( this.descriptorTemplate ) )
|| path( includeFile ).equals( path( this.keystore ) ) )
{
return;
}
getLog().debug( " adding source " + includeFile + " with path " + includePath );
packager.addSourceWithPath( includeFile, includePath );
}
private void appendArtifacts( FlexmojosAIRPackager packager, Collection<Artifact> deps )
{
for ( Artifact artifact : deps )
{
if ( SWF.equals( artifact.getType() ) )
{
File source = artifact.getFile();
String path = source.getName();
if ( stripVersion && path.contains( artifact.getVersion() ) )
{
path = path.replace( "-" + artifact.getVersion(), "" );
}
getLog().debug( " adding source " + source + " with path " + path );
packager.addSourceWithPath( source, path );
}
}
}
protected void doPackage( String packagerName, FlexmojosAIRPackager packager )
throws MojoExecutionException
{
try
{
KeyStore keyStore = KeyStore.getInstance( storetype );
keyStore.load( new FileInputStream( keystore.getAbsolutePath() ), storepass.toCharArray() );
String alias = keyStore.aliases().nextElement();
PrivateKey key = (PrivateKey) keyStore.getKey( alias, storepass.toCharArray() );
packager.setPrivateKey( key );
String c = this.classifier == null ? "" : "-" + this.classifier;
File output =
new File( project.getBuild().getDirectory(), project.getBuild().getFinalName() + c + "." + packagerName );
packager.setOutput( output );
packager.setDescriptor( getAirDescriptor() );
Certificate certificate = keyStore.getCertificate( alias );
packager.setSignerCertificate( certificate );
Certificate[] certificateChain = keyStore.getCertificateChain( alias );
packager.setCertificateChain( certificateChain );
if ( this.timestampURL != null )
{
packager.setTimestampURL( TIMESTAMP_NONE.equals( this.timestampURL ) ? null : this.timestampURL );
}
String packaging = project.getPackaging();
if ( AIR.equals( packaging ) )
{
appendArtifacts( packager, project.getDependencyArtifacts() );
appendArtifacts( packager, project.getAttachedArtifacts() );
}
else if ( SWF.equals( packaging ) )
{
File source = project.getArtifact().getFile();
String path = source.getName();
getLog().debug( " adding source " + source + " with path " + path );
packager.addSourceWithPath( source, path );
}
else
{
throw new MojoFailureException( "Unexpected project packaging " + packaging );
}
if ( includeFiles == null && includeFileSets == null )
{
includeFileSets = resources.toArray( new FileSet[0] );
}
if ( includeFiles != null )
{
for ( final String includePath : includeFiles )
{
File directory = file( project.getBuild().getOutputDirectory() );
addSourceWithPath( packager, directory, includePath );
}
}
if ( includeFileSets != null )
{
for ( FileSet set : includeFileSets )
{
DirectoryScanner scanner;
if ( set instanceof Resource )
{
scanner = scan( (Resource) set );
}
else
{
scanner = scan( set );
}
File directory = file( set.getDirectory(), project.getBasedir() );
String[] files = scanner.getIncludedFiles();
for ( String path : files )
{
addSourceWithPath( packager, directory, path );
}
}
}
if ( classifier != null )
{
projectHelper.attachArtifact( project, packagerName, classifier, output );
}
else if ( SWF.equals( packaging ) )
{
projectHelper.attachArtifact( project, packagerName, output );
}
else
{
if ( AIR.equals( packagerName ) && AIR.equals( packaging ) )
{
project.getArtifact().setFile( output );
}
else
{
projectHelper.attachArtifact( project, packagerName, output );
}
}
final List<Message> messages = new ArrayList<Message>();
try
{
packager.setListener( new Listener()
{
public void message( final Message message )
{
messages.add( message );
}
public void progress( final int soFar, final int total )
{
getLog().info( " completed " + soFar + " of " + total );
}
} );
}
catch ( NullPointerException e )
{
// this is a ridiculous workaround, but I have no means to prevent the NPE nor to check if it will
// happen on AIR 2.5
if ( getLog().isDebugEnabled() )
{
getLog().error( e.getMessage() );
}
}
packager.createPackage();
if ( messages.size() > 0 )
{
for ( final Message message : messages )
{
getLog().error( " " + message.errorDescription );
}
throw new MojoExecutionException( "Error creating AIR application" );
}
else
{
getLog().info( " AIR package created: " + output.getAbsolutePath() );
}
}
catch ( MojoExecutionException e )
{
// do not handle
throw e;
}
catch ( Exception e )
{
+ if ( getLog().isDebugEnabled() )
+ {
+ getLog().error( e.getMessage(), e );
+ }
throw new MojoExecutionException( "Error invoking AIR api", e );
}
finally
{
packager.close();
}
}
public void execute()
throws MojoExecutionException, MojoFailureException
{
doPackage( AIR, new FlexmojosAIRPackager() );
}
private File getAirDescriptor()
throws MojoExecutionException
{
File output = getOutput();
String version;
if ( project.getArtifact().isSnapshot() )
{
version =
project.getVersion().replace( "SNAPSHOT", new SimpleDateFormat( "yyyyMMdd.HHmmss" ).format( new Date() ) );
}
else
{
version = project.getVersion();
}
File dest = new File( airOutput, project.getBuild().getFinalName() + "-descriptor.xml" );
try
{
Map<String, String> props = new HashMap<String, String>();
props.put( "output", output.getName() );
props.put( "version", version );
FileInterpolationUtil.copyFile( descriptorTemplate, dest, props );
if ( flexBuilderCompatibility )
{
// Workaround Flexbuilder/Flashbuilder weirdness
String str = FileUtils.fileRead( dest );
str =
str.replace( "[This value will be overwritten by Flex Builder in the output app.xml]",
output.getName() );
str =
str.replace( "[This value will be overwritten by Flash Builder in the output app.xml]",
output.getName() );
FileUtils.fileWrite( PathUtil.path( dest ), str );
}
}
catch ( IOException e )
{
throw new MojoExecutionException( "Failed to copy air template", e );
}
return dest;
}
private File getOutput()
{
File output = null;
if ( project.getPackaging().equals( AIR ) )
{
List<Artifact> attach = project.getAttachedArtifacts();
for ( Artifact artifact : attach )
{
if ( SWF.equals( artifact.getType() ) || SWC.equals( artifact.getType() ) )
{
return artifact.getFile();
}
}
Set<Artifact> deps = project.getDependencyArtifacts();
for ( Artifact artifact : deps )
{
if ( SWF.equals( artifact.getType() ) || SWC.equals( artifact.getType() ) )
{
return artifact.getFile();
}
}
}
else
{
output = project.getArtifact().getFile();
}
return output;
}
}
| true | true | protected void doPackage( String packagerName, FlexmojosAIRPackager packager )
throws MojoExecutionException
{
try
{
KeyStore keyStore = KeyStore.getInstance( storetype );
keyStore.load( new FileInputStream( keystore.getAbsolutePath() ), storepass.toCharArray() );
String alias = keyStore.aliases().nextElement();
PrivateKey key = (PrivateKey) keyStore.getKey( alias, storepass.toCharArray() );
packager.setPrivateKey( key );
String c = this.classifier == null ? "" : "-" + this.classifier;
File output =
new File( project.getBuild().getDirectory(), project.getBuild().getFinalName() + c + "." + packagerName );
packager.setOutput( output );
packager.setDescriptor( getAirDescriptor() );
Certificate certificate = keyStore.getCertificate( alias );
packager.setSignerCertificate( certificate );
Certificate[] certificateChain = keyStore.getCertificateChain( alias );
packager.setCertificateChain( certificateChain );
if ( this.timestampURL != null )
{
packager.setTimestampURL( TIMESTAMP_NONE.equals( this.timestampURL ) ? null : this.timestampURL );
}
String packaging = project.getPackaging();
if ( AIR.equals( packaging ) )
{
appendArtifacts( packager, project.getDependencyArtifacts() );
appendArtifacts( packager, project.getAttachedArtifacts() );
}
else if ( SWF.equals( packaging ) )
{
File source = project.getArtifact().getFile();
String path = source.getName();
getLog().debug( " adding source " + source + " with path " + path );
packager.addSourceWithPath( source, path );
}
else
{
throw new MojoFailureException( "Unexpected project packaging " + packaging );
}
if ( includeFiles == null && includeFileSets == null )
{
includeFileSets = resources.toArray( new FileSet[0] );
}
if ( includeFiles != null )
{
for ( final String includePath : includeFiles )
{
File directory = file( project.getBuild().getOutputDirectory() );
addSourceWithPath( packager, directory, includePath );
}
}
if ( includeFileSets != null )
{
for ( FileSet set : includeFileSets )
{
DirectoryScanner scanner;
if ( set instanceof Resource )
{
scanner = scan( (Resource) set );
}
else
{
scanner = scan( set );
}
File directory = file( set.getDirectory(), project.getBasedir() );
String[] files = scanner.getIncludedFiles();
for ( String path : files )
{
addSourceWithPath( packager, directory, path );
}
}
}
if ( classifier != null )
{
projectHelper.attachArtifact( project, packagerName, classifier, output );
}
else if ( SWF.equals( packaging ) )
{
projectHelper.attachArtifact( project, packagerName, output );
}
else
{
if ( AIR.equals( packagerName ) && AIR.equals( packaging ) )
{
project.getArtifact().setFile( output );
}
else
{
projectHelper.attachArtifact( project, packagerName, output );
}
}
final List<Message> messages = new ArrayList<Message>();
try
{
packager.setListener( new Listener()
{
public void message( final Message message )
{
messages.add( message );
}
public void progress( final int soFar, final int total )
{
getLog().info( " completed " + soFar + " of " + total );
}
} );
}
catch ( NullPointerException e )
{
// this is a ridiculous workaround, but I have no means to prevent the NPE nor to check if it will
// happen on AIR 2.5
if ( getLog().isDebugEnabled() )
{
getLog().error( e.getMessage() );
}
}
packager.createPackage();
if ( messages.size() > 0 )
{
for ( final Message message : messages )
{
getLog().error( " " + message.errorDescription );
}
throw new MojoExecutionException( "Error creating AIR application" );
}
else
{
getLog().info( " AIR package created: " + output.getAbsolutePath() );
}
}
catch ( MojoExecutionException e )
{
// do not handle
throw e;
}
catch ( Exception e )
{
throw new MojoExecutionException( "Error invoking AIR api", e );
}
finally
{
packager.close();
}
}
| protected void doPackage( String packagerName, FlexmojosAIRPackager packager )
throws MojoExecutionException
{
try
{
KeyStore keyStore = KeyStore.getInstance( storetype );
keyStore.load( new FileInputStream( keystore.getAbsolutePath() ), storepass.toCharArray() );
String alias = keyStore.aliases().nextElement();
PrivateKey key = (PrivateKey) keyStore.getKey( alias, storepass.toCharArray() );
packager.setPrivateKey( key );
String c = this.classifier == null ? "" : "-" + this.classifier;
File output =
new File( project.getBuild().getDirectory(), project.getBuild().getFinalName() + c + "." + packagerName );
packager.setOutput( output );
packager.setDescriptor( getAirDescriptor() );
Certificate certificate = keyStore.getCertificate( alias );
packager.setSignerCertificate( certificate );
Certificate[] certificateChain = keyStore.getCertificateChain( alias );
packager.setCertificateChain( certificateChain );
if ( this.timestampURL != null )
{
packager.setTimestampURL( TIMESTAMP_NONE.equals( this.timestampURL ) ? null : this.timestampURL );
}
String packaging = project.getPackaging();
if ( AIR.equals( packaging ) )
{
appendArtifacts( packager, project.getDependencyArtifacts() );
appendArtifacts( packager, project.getAttachedArtifacts() );
}
else if ( SWF.equals( packaging ) )
{
File source = project.getArtifact().getFile();
String path = source.getName();
getLog().debug( " adding source " + source + " with path " + path );
packager.addSourceWithPath( source, path );
}
else
{
throw new MojoFailureException( "Unexpected project packaging " + packaging );
}
if ( includeFiles == null && includeFileSets == null )
{
includeFileSets = resources.toArray( new FileSet[0] );
}
if ( includeFiles != null )
{
for ( final String includePath : includeFiles )
{
File directory = file( project.getBuild().getOutputDirectory() );
addSourceWithPath( packager, directory, includePath );
}
}
if ( includeFileSets != null )
{
for ( FileSet set : includeFileSets )
{
DirectoryScanner scanner;
if ( set instanceof Resource )
{
scanner = scan( (Resource) set );
}
else
{
scanner = scan( set );
}
File directory = file( set.getDirectory(), project.getBasedir() );
String[] files = scanner.getIncludedFiles();
for ( String path : files )
{
addSourceWithPath( packager, directory, path );
}
}
}
if ( classifier != null )
{
projectHelper.attachArtifact( project, packagerName, classifier, output );
}
else if ( SWF.equals( packaging ) )
{
projectHelper.attachArtifact( project, packagerName, output );
}
else
{
if ( AIR.equals( packagerName ) && AIR.equals( packaging ) )
{
project.getArtifact().setFile( output );
}
else
{
projectHelper.attachArtifact( project, packagerName, output );
}
}
final List<Message> messages = new ArrayList<Message>();
try
{
packager.setListener( new Listener()
{
public void message( final Message message )
{
messages.add( message );
}
public void progress( final int soFar, final int total )
{
getLog().info( " completed " + soFar + " of " + total );
}
} );
}
catch ( NullPointerException e )
{
// this is a ridiculous workaround, but I have no means to prevent the NPE nor to check if it will
// happen on AIR 2.5
if ( getLog().isDebugEnabled() )
{
getLog().error( e.getMessage() );
}
}
packager.createPackage();
if ( messages.size() > 0 )
{
for ( final Message message : messages )
{
getLog().error( " " + message.errorDescription );
}
throw new MojoExecutionException( "Error creating AIR application" );
}
else
{
getLog().info( " AIR package created: " + output.getAbsolutePath() );
}
}
catch ( MojoExecutionException e )
{
// do not handle
throw e;
}
catch ( Exception e )
{
if ( getLog().isDebugEnabled() )
{
getLog().error( e.getMessage(), e );
}
throw new MojoExecutionException( "Error invoking AIR api", e );
}
finally
{
packager.close();
}
}
|
diff --git a/src/main/java/com/minecraftdimensions/bungeesuitechat/listeners/MessageListener.java b/src/main/java/com/minecraftdimensions/bungeesuitechat/listeners/MessageListener.java
index ec2c52a..bc4fba5 100644
--- a/src/main/java/com/minecraftdimensions/bungeesuitechat/listeners/MessageListener.java
+++ b/src/main/java/com/minecraftdimensions/bungeesuitechat/listeners/MessageListener.java
@@ -1,137 +1,141 @@
package com.minecraftdimensions.bungeesuitechat.listeners;
import com.minecraftdimensions.bungeesuitechat.BungeeSuiteChat;
import com.minecraftdimensions.bungeesuitechat.managers.ChannelManager;
import com.minecraftdimensions.bungeesuitechat.managers.PlayerManager;
import com.minecraftdimensions.bungeesuitechat.managers.PrefixSuffixManager;
import com.minecraftdimensions.bungeesuitechat.objects.BSPlayer;
import com.minecraftdimensions.bungeesuitechat.objects.ServerData;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.permissions.Permission;
import org.bukkit.permissions.PermissionDefault;
import org.bukkit.plugin.messaging.PluginMessageListener;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.util.ArrayList;
public class MessageListener implements PluginMessageListener {
@Override
public void onPluginMessageReceived( String pluginChannel, Player receiver, byte[] message ) {
if ( !pluginChannel.equalsIgnoreCase( BungeeSuiteChat.INCOMING_PLUGIN_CHANNEL ) )
return;
DataInputStream in = new DataInputStream( new ByteArrayInputStream( message ) );
String channel = null;
try {
channel = in.readUTF();
} catch ( IOException e ) {
e.printStackTrace();
}
if ( channel.equals( "SendGlobalChat" ) ) {
try {
ChannelManager.getGlobalChat( in.readUTF(), in.readUTF() );
} catch ( IOException e ) {
e.printStackTrace();
}
return;
}
if ( channel.equals( "SendAdminChat" ) ) {
try {
ChannelManager.getAdminlChat( in.readUTF() );
} catch ( IOException e ) {
e.printStackTrace();
}
return;
}
if ( channel.equals( "SendPlayer" ) ) {
try {
PlayerManager.addPlayer( new BSPlayer( in.readUTF() ) );
} catch ( IOException e ) {
e.printStackTrace();
}
return;
}
if ( channel.equals( "SendChannel" ) ) {
if(!ChannelManager.receivedChannels){
ChannelManager.receivedChannels = true;
}
try {
ChannelManager.addChannel( in.readUTF() );
} catch ( IOException e ) {
e.printStackTrace();
}
return;
}
if ( channel.equals( "SendServerData" ) ) {
try {
ServerData.deserialise( in.readUTF() );
} catch ( IOException e ) {
e.printStackTrace();
}
return;
}
if ( channel.equals( "PrefixesAndSuffixes" ) ) {
boolean check;
String group;
String affix;
try {
check = in.readBoolean();
group = in.readUTF();
affix = in.readUTF();
if ( check ) {
PrefixSuffixManager.prefixes.put( group, affix );
PrefixSuffixManager.prefix = true;
+ if(Bukkit.getPluginManager().getPermission("bungeesuite.chat.prefix." + group)==null){
Bukkit.getPluginManager().addPermission( new Permission( "bungeesuite.chat.prefix." + group, "Gives access to the " + affix + " prefix", PermissionDefault.FALSE ) );
- } else {
+ }
+ } else {
PrefixSuffixManager.suffixes.put( group, affix );
PrefixSuffixManager.suffix = true;
+ if(Bukkit.getPluginManager().getPermission("bungeesuite.chat.suffix." + group)==null){
Bukkit.getPluginManager().addPermission( new Permission( "bungeesuite.chat.suffix." + group, "Gives access to the " + affix + " suffix", PermissionDefault.FALSE ) );
- }
+ }
+ }
} catch ( IOException e ) {
e.printStackTrace();
}
}
if ( channel.equals( "SendPlayersIgnores" ) ) {
String player = null;
String ignoresString[] = null;
try {
player = in.readUTF();
ignoresString = in.readUTF().split( "%" );
} catch ( IOException e ) {
// TODO Auto-generated catch block
e.printStackTrace();
}
final ArrayList<String> ignores = new ArrayList<>();
for ( String s : ignoresString ) {
ignores.add( s );
}
final String name = player;
BSPlayer p = PlayerManager.getPlayer( player );
if ( p != null ) {
p.setIgnores( ignores );
} else {
Bukkit.getScheduler().runTaskLaterAsynchronously( BungeeSuiteChat.instance, new Runnable() {
@Override
public void run() {
PlayerManager.getPlayer( name ).setIgnores( ignores );
}
}, 10L );
}
return;
}
if ( channel.equals( "ReloadChat" ) ) {
ChannelManager.reload();
return;
}
}
}
| false | true | public void onPluginMessageReceived( String pluginChannel, Player receiver, byte[] message ) {
if ( !pluginChannel.equalsIgnoreCase( BungeeSuiteChat.INCOMING_PLUGIN_CHANNEL ) )
return;
DataInputStream in = new DataInputStream( new ByteArrayInputStream( message ) );
String channel = null;
try {
channel = in.readUTF();
} catch ( IOException e ) {
e.printStackTrace();
}
if ( channel.equals( "SendGlobalChat" ) ) {
try {
ChannelManager.getGlobalChat( in.readUTF(), in.readUTF() );
} catch ( IOException e ) {
e.printStackTrace();
}
return;
}
if ( channel.equals( "SendAdminChat" ) ) {
try {
ChannelManager.getAdminlChat( in.readUTF() );
} catch ( IOException e ) {
e.printStackTrace();
}
return;
}
if ( channel.equals( "SendPlayer" ) ) {
try {
PlayerManager.addPlayer( new BSPlayer( in.readUTF() ) );
} catch ( IOException e ) {
e.printStackTrace();
}
return;
}
if ( channel.equals( "SendChannel" ) ) {
if(!ChannelManager.receivedChannels){
ChannelManager.receivedChannels = true;
}
try {
ChannelManager.addChannel( in.readUTF() );
} catch ( IOException e ) {
e.printStackTrace();
}
return;
}
if ( channel.equals( "SendServerData" ) ) {
try {
ServerData.deserialise( in.readUTF() );
} catch ( IOException e ) {
e.printStackTrace();
}
return;
}
if ( channel.equals( "PrefixesAndSuffixes" ) ) {
boolean check;
String group;
String affix;
try {
check = in.readBoolean();
group = in.readUTF();
affix = in.readUTF();
if ( check ) {
PrefixSuffixManager.prefixes.put( group, affix );
PrefixSuffixManager.prefix = true;
Bukkit.getPluginManager().addPermission( new Permission( "bungeesuite.chat.prefix." + group, "Gives access to the " + affix + " prefix", PermissionDefault.FALSE ) );
} else {
PrefixSuffixManager.suffixes.put( group, affix );
PrefixSuffixManager.suffix = true;
Bukkit.getPluginManager().addPermission( new Permission( "bungeesuite.chat.suffix." + group, "Gives access to the " + affix + " suffix", PermissionDefault.FALSE ) );
}
} catch ( IOException e ) {
e.printStackTrace();
}
}
if ( channel.equals( "SendPlayersIgnores" ) ) {
String player = null;
String ignoresString[] = null;
try {
player = in.readUTF();
ignoresString = in.readUTF().split( "%" );
} catch ( IOException e ) {
// TODO Auto-generated catch block
e.printStackTrace();
}
final ArrayList<String> ignores = new ArrayList<>();
for ( String s : ignoresString ) {
ignores.add( s );
}
final String name = player;
BSPlayer p = PlayerManager.getPlayer( player );
if ( p != null ) {
p.setIgnores( ignores );
} else {
Bukkit.getScheduler().runTaskLaterAsynchronously( BungeeSuiteChat.instance, new Runnable() {
@Override
public void run() {
PlayerManager.getPlayer( name ).setIgnores( ignores );
}
}, 10L );
}
return;
}
if ( channel.equals( "ReloadChat" ) ) {
ChannelManager.reload();
return;
}
}
| public void onPluginMessageReceived( String pluginChannel, Player receiver, byte[] message ) {
if ( !pluginChannel.equalsIgnoreCase( BungeeSuiteChat.INCOMING_PLUGIN_CHANNEL ) )
return;
DataInputStream in = new DataInputStream( new ByteArrayInputStream( message ) );
String channel = null;
try {
channel = in.readUTF();
} catch ( IOException e ) {
e.printStackTrace();
}
if ( channel.equals( "SendGlobalChat" ) ) {
try {
ChannelManager.getGlobalChat( in.readUTF(), in.readUTF() );
} catch ( IOException e ) {
e.printStackTrace();
}
return;
}
if ( channel.equals( "SendAdminChat" ) ) {
try {
ChannelManager.getAdminlChat( in.readUTF() );
} catch ( IOException e ) {
e.printStackTrace();
}
return;
}
if ( channel.equals( "SendPlayer" ) ) {
try {
PlayerManager.addPlayer( new BSPlayer( in.readUTF() ) );
} catch ( IOException e ) {
e.printStackTrace();
}
return;
}
if ( channel.equals( "SendChannel" ) ) {
if(!ChannelManager.receivedChannels){
ChannelManager.receivedChannels = true;
}
try {
ChannelManager.addChannel( in.readUTF() );
} catch ( IOException e ) {
e.printStackTrace();
}
return;
}
if ( channel.equals( "SendServerData" ) ) {
try {
ServerData.deserialise( in.readUTF() );
} catch ( IOException e ) {
e.printStackTrace();
}
return;
}
if ( channel.equals( "PrefixesAndSuffixes" ) ) {
boolean check;
String group;
String affix;
try {
check = in.readBoolean();
group = in.readUTF();
affix = in.readUTF();
if ( check ) {
PrefixSuffixManager.prefixes.put( group, affix );
PrefixSuffixManager.prefix = true;
if(Bukkit.getPluginManager().getPermission("bungeesuite.chat.prefix." + group)==null){
Bukkit.getPluginManager().addPermission( new Permission( "bungeesuite.chat.prefix." + group, "Gives access to the " + affix + " prefix", PermissionDefault.FALSE ) );
}
} else {
PrefixSuffixManager.suffixes.put( group, affix );
PrefixSuffixManager.suffix = true;
if(Bukkit.getPluginManager().getPermission("bungeesuite.chat.suffix." + group)==null){
Bukkit.getPluginManager().addPermission( new Permission( "bungeesuite.chat.suffix." + group, "Gives access to the " + affix + " suffix", PermissionDefault.FALSE ) );
}
}
} catch ( IOException e ) {
e.printStackTrace();
}
}
if ( channel.equals( "SendPlayersIgnores" ) ) {
String player = null;
String ignoresString[] = null;
try {
player = in.readUTF();
ignoresString = in.readUTF().split( "%" );
} catch ( IOException e ) {
// TODO Auto-generated catch block
e.printStackTrace();
}
final ArrayList<String> ignores = new ArrayList<>();
for ( String s : ignoresString ) {
ignores.add( s );
}
final String name = player;
BSPlayer p = PlayerManager.getPlayer( player );
if ( p != null ) {
p.setIgnores( ignores );
} else {
Bukkit.getScheduler().runTaskLaterAsynchronously( BungeeSuiteChat.instance, new Runnable() {
@Override
public void run() {
PlayerManager.getPlayer( name ).setIgnores( ignores );
}
}, 10L );
}
return;
}
if ( channel.equals( "ReloadChat" ) ) {
ChannelManager.reload();
return;
}
}
|
diff --git a/src/main/java/no/auke/demo/m2/DemoRun.java b/src/main/java/no/auke/demo/m2/DemoRun.java
index 64a361e..61cb929 100644
--- a/src/main/java/no/auke/demo/m2/DemoRun.java
+++ b/src/main/java/no/auke/demo/m2/DemoRun.java
@@ -1,112 +1,112 @@
package no.auke.demo.m2;
import no.auke.p2p.m2.InitVar;
public class DemoRun {
/**
* @param args
*/
public static void main(String[] args) {
String namespace = InitParam.NAMESPACE;
String dir = InitParam.USERDIR;
String userid = "TestUser";
String useridRemote = "";
boolean dosend = true;
int port = InitParam.PORT;
- int trialsize = 10000;
+ int trialsize = 1000000;
String trial = "sendreplylocal";
String server = "";
if(args.length >=1 && !args[0].startsWith("-"))
{
server = args[0];
}
int pos = 0;
while (pos < args.length) {
if (args[pos].startsWith("-")) {
if (args[pos].equals("-t") && args.length > pos) {
trial = args[pos + 1];
}
if (args[pos].equals("-port") && args.length > pos) {
port = Integer.parseInt(args[pos + 1]);
}
if (args[pos].equals("-ns") && args.length > pos) {
namespace = args[pos + 1];
}
if (args[pos].equals("-u") && args.length > pos) {
userid = args[pos + 1];
}
if (args[pos].equals("-ur") && args.length > pos) {
useridRemote = args[pos + 1];
}
if (args[pos].equals("-dir") && args.length > pos) {
dir = args[pos + 1];
}
if (args[pos].equals("-nosend") && args.length > pos) {
dosend=false;
}
}
pos++;
}
System.out.println("starting " + trial);
if(trial.isEmpty()){
SimpleSetup s = new SimpleSetup();
s.run(namespace, dir, userid);
} else if(trial.equals("sendreplylocal")){
SendReplyLocal s = new SendReplyLocal();
s.run(namespace, dir, port, userid,trialsize);
} else if(trial.equals("sendreply3services")){
SendReply3Services s = new SendReply3Services();
s.run(namespace, dir, userid, useridRemote, port, dosend, trialsize);
} else if(trial.equals("sendreply")){
SendReply s = new SendReply();
s.run(namespace, dir, userid, useridRemote, port, dosend,trialsize);
} else if(trial.equals("mmtest"))
{
InitVar.SEND_MIDDLEMAN_REQURIED = true;
MMTest s = new MMTest();
s.address = server;
s.run(namespace, dir, userid, useridRemote, port, dosend);
}
else if(trial.equals("mmlocaltest"))
{
InitVar.SEND_MIDDLEMAN_REQURIED = true;
MMLocalTest s = new MMLocalTest();
s.address = server;
s.run(namespace, dir, port, userid);
}
else {
System.out.println("wrong startup " + trial);
}
}
}
| true | true | public static void main(String[] args) {
String namespace = InitParam.NAMESPACE;
String dir = InitParam.USERDIR;
String userid = "TestUser";
String useridRemote = "";
boolean dosend = true;
int port = InitParam.PORT;
int trialsize = 10000;
String trial = "sendreplylocal";
String server = "";
if(args.length >=1 && !args[0].startsWith("-"))
{
server = args[0];
}
int pos = 0;
while (pos < args.length) {
if (args[pos].startsWith("-")) {
if (args[pos].equals("-t") && args.length > pos) {
trial = args[pos + 1];
}
if (args[pos].equals("-port") && args.length > pos) {
port = Integer.parseInt(args[pos + 1]);
}
if (args[pos].equals("-ns") && args.length > pos) {
namespace = args[pos + 1];
}
if (args[pos].equals("-u") && args.length > pos) {
userid = args[pos + 1];
}
if (args[pos].equals("-ur") && args.length > pos) {
useridRemote = args[pos + 1];
}
if (args[pos].equals("-dir") && args.length > pos) {
dir = args[pos + 1];
}
if (args[pos].equals("-nosend") && args.length > pos) {
dosend=false;
}
}
pos++;
}
System.out.println("starting " + trial);
if(trial.isEmpty()){
SimpleSetup s = new SimpleSetup();
s.run(namespace, dir, userid);
} else if(trial.equals("sendreplylocal")){
SendReplyLocal s = new SendReplyLocal();
s.run(namespace, dir, port, userid,trialsize);
} else if(trial.equals("sendreply3services")){
SendReply3Services s = new SendReply3Services();
s.run(namespace, dir, userid, useridRemote, port, dosend, trialsize);
} else if(trial.equals("sendreply")){
SendReply s = new SendReply();
s.run(namespace, dir, userid, useridRemote, port, dosend,trialsize);
} else if(trial.equals("mmtest"))
{
InitVar.SEND_MIDDLEMAN_REQURIED = true;
MMTest s = new MMTest();
s.address = server;
s.run(namespace, dir, userid, useridRemote, port, dosend);
}
else if(trial.equals("mmlocaltest"))
{
InitVar.SEND_MIDDLEMAN_REQURIED = true;
MMLocalTest s = new MMLocalTest();
s.address = server;
s.run(namespace, dir, port, userid);
}
else {
System.out.println("wrong startup " + trial);
}
}
| public static void main(String[] args) {
String namespace = InitParam.NAMESPACE;
String dir = InitParam.USERDIR;
String userid = "TestUser";
String useridRemote = "";
boolean dosend = true;
int port = InitParam.PORT;
int trialsize = 1000000;
String trial = "sendreplylocal";
String server = "";
if(args.length >=1 && !args[0].startsWith("-"))
{
server = args[0];
}
int pos = 0;
while (pos < args.length) {
if (args[pos].startsWith("-")) {
if (args[pos].equals("-t") && args.length > pos) {
trial = args[pos + 1];
}
if (args[pos].equals("-port") && args.length > pos) {
port = Integer.parseInt(args[pos + 1]);
}
if (args[pos].equals("-ns") && args.length > pos) {
namespace = args[pos + 1];
}
if (args[pos].equals("-u") && args.length > pos) {
userid = args[pos + 1];
}
if (args[pos].equals("-ur") && args.length > pos) {
useridRemote = args[pos + 1];
}
if (args[pos].equals("-dir") && args.length > pos) {
dir = args[pos + 1];
}
if (args[pos].equals("-nosend") && args.length > pos) {
dosend=false;
}
}
pos++;
}
System.out.println("starting " + trial);
if(trial.isEmpty()){
SimpleSetup s = new SimpleSetup();
s.run(namespace, dir, userid);
} else if(trial.equals("sendreplylocal")){
SendReplyLocal s = new SendReplyLocal();
s.run(namespace, dir, port, userid,trialsize);
} else if(trial.equals("sendreply3services")){
SendReply3Services s = new SendReply3Services();
s.run(namespace, dir, userid, useridRemote, port, dosend, trialsize);
} else if(trial.equals("sendreply")){
SendReply s = new SendReply();
s.run(namespace, dir, userid, useridRemote, port, dosend,trialsize);
} else if(trial.equals("mmtest"))
{
InitVar.SEND_MIDDLEMAN_REQURIED = true;
MMTest s = new MMTest();
s.address = server;
s.run(namespace, dir, userid, useridRemote, port, dosend);
}
else if(trial.equals("mmlocaltest"))
{
InitVar.SEND_MIDDLEMAN_REQURIED = true;
MMLocalTest s = new MMLocalTest();
s.address = server;
s.run(namespace, dir, port, userid);
}
else {
System.out.println("wrong startup " + trial);
}
}
|
diff --git a/src/java/com/eviware/soapui/impl/wsdl/support/http/ProxyUtils.java b/src/java/com/eviware/soapui/impl/wsdl/support/http/ProxyUtils.java
index 3d84b6e49..102c97a9a 100644
--- a/src/java/com/eviware/soapui/impl/wsdl/support/http/ProxyUtils.java
+++ b/src/java/com/eviware/soapui/impl/wsdl/support/http/ProxyUtils.java
@@ -1,184 +1,193 @@
/*
* soapUI, copyright (C) 2004-2011 eviware.com
*
* soapUI is free software; you can redistribute it and/or modify it under the
* terms of version 2.1 of the GNU Lesser General Public License as published by
* the Free Software Foundation.
*
* soapUI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details at gnu.org.
*/
package com.eviware.soapui.impl.wsdl.support.http;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.NTCredentials;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.protocol.HttpContext;
import com.eviware.soapui.SoapUI;
import com.eviware.soapui.model.propertyexpansion.PropertyExpander;
import com.eviware.soapui.model.propertyexpansion.PropertyExpansionContext;
import com.eviware.soapui.model.settings.Settings;
import com.eviware.soapui.settings.ProxySettings;
import com.eviware.soapui.support.StringUtils;
/**
* Utilities for setting proxy-servers correctly
*
* @author ole.matzura
*/
public class ProxyUtils
{
private static boolean proxyEnabled = SoapUI.getSettings().getBoolean( ProxySettings.ENABLE_PROXY );
public static void initProxySettings( Settings settings, HttpContext httpContext, String urlString,
PropertyExpansionContext context )
{
HttpHost proxy = null;
boolean enabled = proxyEnabled;
// check system properties first
String proxyHost = System.getProperty( "http.proxyHost" );
String proxyPort = System.getProperty( "http.proxyPort" );
- if( proxyHost == null && enabled )
+ if( proxyHost == null )
proxyHost = PropertyExpander.expandProperties( context, settings.getString( ProxySettings.HOST, "" ) );
- if( proxyPort == null && proxyHost != null && enabled )
+ if( proxyPort == null && proxyHost != null )
proxyPort = PropertyExpander.expandProperties( context, settings.getString( ProxySettings.PORT, "" ) );
if( !StringUtils.isNullOrEmpty( proxyHost ) && !StringUtils.isNullOrEmpty( proxyPort ) )
{
// check excludes
String[] excludes = PropertyExpander.expandProperties( context,
settings.getString( ProxySettings.EXCLUDES, "" ) ).split( "," );
try
{
URL url = new URL( urlString );
if( !excludes( excludes, url.getHost(), url.getPort() ) )
{
proxy = new HttpHost( proxyHost, Integer.parseInt( proxyPort ) );
String proxyUsername = PropertyExpander.expandProperties( context,
settings.getString( ProxySettings.USERNAME, null ) );
String proxyPassword = PropertyExpander.expandProperties( context,
settings.getString( ProxySettings.PASSWORD, null ) );
if( proxyUsername != null && proxyPassword != null )
{
Credentials proxyCreds = new UsernamePasswordCredentials( proxyUsername, proxyPassword == null ? ""
: proxyPassword );
// check for nt-username
int ix = proxyUsername.indexOf( '\\' );
if( ix > 0 )
{
String domain = proxyUsername.substring( 0, ix );
if( proxyUsername.length() > ix + 1 )
{
String user = proxyUsername.substring( ix + 1 );
proxyCreds = new NTCredentials( user, proxyPassword, proxyHost, domain );
}
}
- HttpClientSupport.getHttpClient().getCredentialsProvider()
- .setCredentials( new AuthScope( proxy.getHostName(), proxy.getPort() ), proxyCreds );
- HttpClientSupport.getHttpClient().getParams().setParameter( ConnRoutePNames.DEFAULT_PROXY, proxy );
+ if( enabled )
+ {
+ HttpClientSupport.getHttpClient().getCredentialsProvider()
+ .setCredentials( new AuthScope( proxy.getHostName(), proxy.getPort() ), proxyCreds );
+ HttpClientSupport.getHttpClient().getParams().setParameter( ConnRoutePNames.DEFAULT_PROXY, proxy );
+ }
+ else
+ {
+ HttpClientSupport.getHttpClient().getCredentialsProvider()
+ .setCredentials( new AuthScope( proxy.getHostName(), proxy.getPort() ), null );
+ HttpClientSupport.getHttpClient().getParams().removeParameter( ConnRoutePNames.DEFAULT_PROXY );
+ }
}
}
}
catch( MalformedURLException e )
{
SoapUI.logError( e );
}
}
}
public static boolean excludes( String[] excludes, String proxyHost, int proxyPort )
{
for( int c = 0; c < excludes.length; c++ )
{
String exclude = excludes[c].trim();
if( exclude.length() == 0 )
continue;
// check for port
int ix = exclude.indexOf( ':' );
if( ix >= 0 && exclude.length() > ix + 1 )
{
String excludePort = exclude.substring( ix + 1 );
if( proxyPort != -1 && excludePort.equals( String.valueOf( proxyPort ) ) )
{
exclude = exclude.substring( 0, ix );
}
else
{
continue;
}
}
/*
* This will exclude addresses with wildcard *, too.
*/
// if( proxyHost.endsWith( exclude ) )
// return true;
String excludeIp = exclude.indexOf( '*' ) >= 0 ? exclude : nslookup( exclude, true );
String ip = nslookup( proxyHost, true );
Pattern pattern = Pattern.compile( excludeIp );
Matcher matcher = pattern.matcher( ip );
Matcher matcher2 = pattern.matcher( proxyHost );
if( matcher.find() || matcher2.find() )
return true;
}
return false;
}
private static String nslookup( String s, boolean ip )
{
InetAddress host;
String address;
// get the bytes of the IP address
try
{
host = InetAddress.getByName( s );
if( ip )
address = host.getHostAddress();
else
address = host.getHostName();
}
catch( UnknownHostException ue )
{
return s; // no host
}
return address;
} // end lookup
public static boolean isProxyEnabled()
{
return proxyEnabled;
}
public static void setProxyEnabled( boolean proxyEnabled )
{
ProxyUtils.proxyEnabled = proxyEnabled;
}
}
| false | true | public static void initProxySettings( Settings settings, HttpContext httpContext, String urlString,
PropertyExpansionContext context )
{
HttpHost proxy = null;
boolean enabled = proxyEnabled;
// check system properties first
String proxyHost = System.getProperty( "http.proxyHost" );
String proxyPort = System.getProperty( "http.proxyPort" );
if( proxyHost == null && enabled )
proxyHost = PropertyExpander.expandProperties( context, settings.getString( ProxySettings.HOST, "" ) );
if( proxyPort == null && proxyHost != null && enabled )
proxyPort = PropertyExpander.expandProperties( context, settings.getString( ProxySettings.PORT, "" ) );
if( !StringUtils.isNullOrEmpty( proxyHost ) && !StringUtils.isNullOrEmpty( proxyPort ) )
{
// check excludes
String[] excludes = PropertyExpander.expandProperties( context,
settings.getString( ProxySettings.EXCLUDES, "" ) ).split( "," );
try
{
URL url = new URL( urlString );
if( !excludes( excludes, url.getHost(), url.getPort() ) )
{
proxy = new HttpHost( proxyHost, Integer.parseInt( proxyPort ) );
String proxyUsername = PropertyExpander.expandProperties( context,
settings.getString( ProxySettings.USERNAME, null ) );
String proxyPassword = PropertyExpander.expandProperties( context,
settings.getString( ProxySettings.PASSWORD, null ) );
if( proxyUsername != null && proxyPassword != null )
{
Credentials proxyCreds = new UsernamePasswordCredentials( proxyUsername, proxyPassword == null ? ""
: proxyPassword );
// check for nt-username
int ix = proxyUsername.indexOf( '\\' );
if( ix > 0 )
{
String domain = proxyUsername.substring( 0, ix );
if( proxyUsername.length() > ix + 1 )
{
String user = proxyUsername.substring( ix + 1 );
proxyCreds = new NTCredentials( user, proxyPassword, proxyHost, domain );
}
}
HttpClientSupport.getHttpClient().getCredentialsProvider()
.setCredentials( new AuthScope( proxy.getHostName(), proxy.getPort() ), proxyCreds );
HttpClientSupport.getHttpClient().getParams().setParameter( ConnRoutePNames.DEFAULT_PROXY, proxy );
}
}
}
catch( MalformedURLException e )
{
SoapUI.logError( e );
}
}
}
| public static void initProxySettings( Settings settings, HttpContext httpContext, String urlString,
PropertyExpansionContext context )
{
HttpHost proxy = null;
boolean enabled = proxyEnabled;
// check system properties first
String proxyHost = System.getProperty( "http.proxyHost" );
String proxyPort = System.getProperty( "http.proxyPort" );
if( proxyHost == null )
proxyHost = PropertyExpander.expandProperties( context, settings.getString( ProxySettings.HOST, "" ) );
if( proxyPort == null && proxyHost != null )
proxyPort = PropertyExpander.expandProperties( context, settings.getString( ProxySettings.PORT, "" ) );
if( !StringUtils.isNullOrEmpty( proxyHost ) && !StringUtils.isNullOrEmpty( proxyPort ) )
{
// check excludes
String[] excludes = PropertyExpander.expandProperties( context,
settings.getString( ProxySettings.EXCLUDES, "" ) ).split( "," );
try
{
URL url = new URL( urlString );
if( !excludes( excludes, url.getHost(), url.getPort() ) )
{
proxy = new HttpHost( proxyHost, Integer.parseInt( proxyPort ) );
String proxyUsername = PropertyExpander.expandProperties( context,
settings.getString( ProxySettings.USERNAME, null ) );
String proxyPassword = PropertyExpander.expandProperties( context,
settings.getString( ProxySettings.PASSWORD, null ) );
if( proxyUsername != null && proxyPassword != null )
{
Credentials proxyCreds = new UsernamePasswordCredentials( proxyUsername, proxyPassword == null ? ""
: proxyPassword );
// check for nt-username
int ix = proxyUsername.indexOf( '\\' );
if( ix > 0 )
{
String domain = proxyUsername.substring( 0, ix );
if( proxyUsername.length() > ix + 1 )
{
String user = proxyUsername.substring( ix + 1 );
proxyCreds = new NTCredentials( user, proxyPassword, proxyHost, domain );
}
}
if( enabled )
{
HttpClientSupport.getHttpClient().getCredentialsProvider()
.setCredentials( new AuthScope( proxy.getHostName(), proxy.getPort() ), proxyCreds );
HttpClientSupport.getHttpClient().getParams().setParameter( ConnRoutePNames.DEFAULT_PROXY, proxy );
}
else
{
HttpClientSupport.getHttpClient().getCredentialsProvider()
.setCredentials( new AuthScope( proxy.getHostName(), proxy.getPort() ), null );
HttpClientSupport.getHttpClient().getParams().removeParameter( ConnRoutePNames.DEFAULT_PROXY );
}
}
}
}
catch( MalformedURLException e )
{
SoapUI.logError( e );
}
}
}
|
diff --git a/src/main/java/net/croxis/plugins/civilmineation/SignChangeListener.java b/src/main/java/net/croxis/plugins/civilmineation/SignChangeListener.java
index 81b4392..2034055 100644
--- a/src/main/java/net/croxis/plugins/civilmineation/SignChangeListener.java
+++ b/src/main/java/net/croxis/plugins/civilmineation/SignChangeListener.java
@@ -1,54 +1,54 @@
package net.croxis.plugins.civilmineation;
import net.croxis.plugins.civilmineation.components.PlotComponent;
import net.croxis.plugins.civilmineation.components.ResidentComponent;
import org.bukkit.ChatColor;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.SignChangeEvent;
public class SignChangeListener implements Listener{
@EventHandler
public void onSignChangeEvent(SignChangeEvent event){
ResidentComponent resident = CivAPI.getResident(event.getPlayer().getName());
PlotComponent plot = CivAPI.getPlot(event.getBlock().getChunk());
if (event.getLine(0).equalsIgnoreCase("[claim]")){
if (!CivAPI.isCityAdmin(resident)){
cancelBreak(event, "You must be a city admin");
} else if (plot.getCity() != null){
cancelBreak(event, "A city has already claimed this chunk");
}
PlotComponent p = CivAPI.getPlot(event.getBlock().getWorld().getName(), event.getBlock().getChunk().getX() + 1, event.getBlock().getChunk().getZ());
- if (CivAPI.isClaimedByCity(p, resident.getCity())){
+ if (!CivAPI.isClaimedByCity(p, resident.getCity())){
p = CivAPI.getPlot(event.getBlock().getWorld().getName(), event.getBlock().getChunk().getX() - 1, event.getBlock().getChunk().getZ());
- if (CivAPI.isClaimedByCity(p, resident.getCity())){
+ if (!CivAPI.isClaimedByCity(p, resident.getCity())){
p = CivAPI.getPlot(event.getBlock().getWorld().getName(), event.getBlock().getChunk().getX(), event.getBlock().getChunk().getZ() + 1);
- if (CivAPI.isClaimedByCity(p, resident.getCity())){
+ if (!CivAPI.isClaimedByCity(p, resident.getCity())){
p = CivAPI.getPlot(event.getBlock().getWorld().getName(), event.getBlock().getChunk().getX(), event.getBlock().getChunk().getZ() + 1);
- if (CivAPI.isClaimedByCity(p, resident.getCity())){
+ if (!CivAPI.isClaimedByCity(p, resident.getCity())){
cancelBreak(event, "This claim must be adjacent to an existing claim.");
}
}
}
} else if (resident.getCity().getCulture() < Math.pow(CivAPI.getPlots(resident.getCity()).size(), 1.5)){
cancelBreak(event, "You do not have enough culture: " + ChatColor.LIGHT_PURPLE + Integer.toString(resident.getCity().getCulture()) + ChatColor.BLACK + "/" + ChatColor.LIGHT_PURPLE + Double.toString(Math.pow(CivAPI.getPlots(resident.getCity()).size(), 1.5)));
}
if(event.isCancelled())
return;
CivAPI.claimPlot(event.getBlock().getWorld().getName(), event.getBlock().getChunk().getX(), event.getBlock().getChunk().getZ(), event.getBlock(), resident.getCity());
event.setLine(0, resident.getCity().getName());
return;
}
}
public void cancelBreak(SignChangeEvent event, String message){
event.setCancelled(true);
event.getPlayer().sendMessage(message);
event.getBlock().breakNaturally();
return;
}
}
| false | true | public void onSignChangeEvent(SignChangeEvent event){
ResidentComponent resident = CivAPI.getResident(event.getPlayer().getName());
PlotComponent plot = CivAPI.getPlot(event.getBlock().getChunk());
if (event.getLine(0).equalsIgnoreCase("[claim]")){
if (!CivAPI.isCityAdmin(resident)){
cancelBreak(event, "You must be a city admin");
} else if (plot.getCity() != null){
cancelBreak(event, "A city has already claimed this chunk");
}
PlotComponent p = CivAPI.getPlot(event.getBlock().getWorld().getName(), event.getBlock().getChunk().getX() + 1, event.getBlock().getChunk().getZ());
if (CivAPI.isClaimedByCity(p, resident.getCity())){
p = CivAPI.getPlot(event.getBlock().getWorld().getName(), event.getBlock().getChunk().getX() - 1, event.getBlock().getChunk().getZ());
if (CivAPI.isClaimedByCity(p, resident.getCity())){
p = CivAPI.getPlot(event.getBlock().getWorld().getName(), event.getBlock().getChunk().getX(), event.getBlock().getChunk().getZ() + 1);
if (CivAPI.isClaimedByCity(p, resident.getCity())){
p = CivAPI.getPlot(event.getBlock().getWorld().getName(), event.getBlock().getChunk().getX(), event.getBlock().getChunk().getZ() + 1);
if (CivAPI.isClaimedByCity(p, resident.getCity())){
cancelBreak(event, "This claim must be adjacent to an existing claim.");
}
}
}
} else if (resident.getCity().getCulture() < Math.pow(CivAPI.getPlots(resident.getCity()).size(), 1.5)){
cancelBreak(event, "You do not have enough culture: " + ChatColor.LIGHT_PURPLE + Integer.toString(resident.getCity().getCulture()) + ChatColor.BLACK + "/" + ChatColor.LIGHT_PURPLE + Double.toString(Math.pow(CivAPI.getPlots(resident.getCity()).size(), 1.5)));
}
if(event.isCancelled())
return;
CivAPI.claimPlot(event.getBlock().getWorld().getName(), event.getBlock().getChunk().getX(), event.getBlock().getChunk().getZ(), event.getBlock(), resident.getCity());
event.setLine(0, resident.getCity().getName());
return;
}
}
| public void onSignChangeEvent(SignChangeEvent event){
ResidentComponent resident = CivAPI.getResident(event.getPlayer().getName());
PlotComponent plot = CivAPI.getPlot(event.getBlock().getChunk());
if (event.getLine(0).equalsIgnoreCase("[claim]")){
if (!CivAPI.isCityAdmin(resident)){
cancelBreak(event, "You must be a city admin");
} else if (plot.getCity() != null){
cancelBreak(event, "A city has already claimed this chunk");
}
PlotComponent p = CivAPI.getPlot(event.getBlock().getWorld().getName(), event.getBlock().getChunk().getX() + 1, event.getBlock().getChunk().getZ());
if (!CivAPI.isClaimedByCity(p, resident.getCity())){
p = CivAPI.getPlot(event.getBlock().getWorld().getName(), event.getBlock().getChunk().getX() - 1, event.getBlock().getChunk().getZ());
if (!CivAPI.isClaimedByCity(p, resident.getCity())){
p = CivAPI.getPlot(event.getBlock().getWorld().getName(), event.getBlock().getChunk().getX(), event.getBlock().getChunk().getZ() + 1);
if (!CivAPI.isClaimedByCity(p, resident.getCity())){
p = CivAPI.getPlot(event.getBlock().getWorld().getName(), event.getBlock().getChunk().getX(), event.getBlock().getChunk().getZ() + 1);
if (!CivAPI.isClaimedByCity(p, resident.getCity())){
cancelBreak(event, "This claim must be adjacent to an existing claim.");
}
}
}
} else if (resident.getCity().getCulture() < Math.pow(CivAPI.getPlots(resident.getCity()).size(), 1.5)){
cancelBreak(event, "You do not have enough culture: " + ChatColor.LIGHT_PURPLE + Integer.toString(resident.getCity().getCulture()) + ChatColor.BLACK + "/" + ChatColor.LIGHT_PURPLE + Double.toString(Math.pow(CivAPI.getPlots(resident.getCity()).size(), 1.5)));
}
if(event.isCancelled())
return;
CivAPI.claimPlot(event.getBlock().getWorld().getName(), event.getBlock().getChunk().getX(), event.getBlock().getChunk().getZ(), event.getBlock(), resident.getCity());
event.setLine(0, resident.getCity().getName());
return;
}
}
|
diff --git a/core/src/visad/trunk/examples/Test59.java b/core/src/visad/trunk/examples/Test59.java
index 15d3be095..0e90857db 100644
--- a/core/src/visad/trunk/examples/Test59.java
+++ b/core/src/visad/trunk/examples/Test59.java
@@ -1,91 +1,91 @@
import java.awt.Component;
import java.rmi.RemoteException;
import visad.*;
import java.util.Random;
import visad.java3d.DisplayImplJ3D;
import visad.util.ContourWidget;
public class Test59
extends UISkeleton
{
public Test59() { }
public Test59(String args[])
throws VisADException, RemoteException
{
super(args);
}
DisplayImpl[] setupData()
throws VisADException, RemoteException
{
RealType index = new RealType("index", null, null);
RealType vis_radiance = new RealType("vis_radiance", null, null);
RealType ir_radiance = new RealType("ir_radiance", null, null);
RealType[] types = {RealType.Latitude, RealType.Longitude,
vis_radiance, ir_radiance};
RealTupleType radiance = new RealTupleType(types);
FunctionType image_tuple = new FunctionType(index, radiance);
int size = 216;
Set domain_set = new Integer1DSet(size);
FlatField imaget1 = new FlatField(image_tuple, domain_set);
float[][] values = new float[4][size];
Random random = new Random();
for (int i=0; i<size; i++) {
values[0][i] = 2.0f * random.nextFloat() - 1.0f;
values[1][i] = 2.0f * random.nextFloat() - 1.0f;
values[2][i] = 2.0f * random.nextFloat() - 1.0f;
values[3][i] = (float) Math.sqrt(values[0][i] * values[0][i] +
values[1][i] * values[1][i] +
values[2][i] * values[2][i]);
}
imaget1.setSamples(values);
DisplayImpl display1 =
new DisplayImplJ3D("display1", DisplayImplJ3D.APPLETFRAME);
display1.addMap(new ScalarMap(RealType.Latitude, Display.YAxis));
display1.addMap(new ScalarMap(RealType.Longitude, Display.XAxis));
display1.addMap(new ScalarMap(vis_radiance, Display.ZAxis));
display1.addMap(new ScalarMap(RealType.Radius, Display.ZAxis));
display1.addMap(new ScalarMap(ir_radiance, Display.Green));
display1.addMap(new ConstantMap(0.5, Display.Blue));
display1.addMap(new ConstantMap(0.5, Display.Red));
ScalarMap map1contour;
- map1contour = new ScalarMap(vis_radiance, Display.IsoContour);
+ map1contour = new ScalarMap(ir_radiance, Display.IsoContour);
display1.addMap(map1contour);
DataReferenceImpl ref_imaget1 = new DataReferenceImpl("ref_imaget1");
ref_imaget1.setData(imaget1);
display1.addReference(ref_imaget1, null);
DisplayImpl[] dpys = new DisplayImpl[1];
dpys[0] = display1;
return dpys;
}
String getFrameTitle() { return "VisAD irregular iso-level controls"; }
Component getSpecialComponent(DisplayImpl[] dpys)
throws VisADException, RemoteException
{
ScalarMap map1contour = (ScalarMap )dpys[0].getMapVector().lastElement();
return new ContourWidget(map1contour);
}
public String toString()
{
return ": colored iso-surfaces from scatter data and ContourWidget";
}
public static void main(String args[])
throws VisADException, RemoteException
{
Test59 t = new Test59(args);
}
}
| true | true | DisplayImpl[] setupData()
throws VisADException, RemoteException
{
RealType index = new RealType("index", null, null);
RealType vis_radiance = new RealType("vis_radiance", null, null);
RealType ir_radiance = new RealType("ir_radiance", null, null);
RealType[] types = {RealType.Latitude, RealType.Longitude,
vis_radiance, ir_radiance};
RealTupleType radiance = new RealTupleType(types);
FunctionType image_tuple = new FunctionType(index, radiance);
int size = 216;
Set domain_set = new Integer1DSet(size);
FlatField imaget1 = new FlatField(image_tuple, domain_set);
float[][] values = new float[4][size];
Random random = new Random();
for (int i=0; i<size; i++) {
values[0][i] = 2.0f * random.nextFloat() - 1.0f;
values[1][i] = 2.0f * random.nextFloat() - 1.0f;
values[2][i] = 2.0f * random.nextFloat() - 1.0f;
values[3][i] = (float) Math.sqrt(values[0][i] * values[0][i] +
values[1][i] * values[1][i] +
values[2][i] * values[2][i]);
}
imaget1.setSamples(values);
DisplayImpl display1 =
new DisplayImplJ3D("display1", DisplayImplJ3D.APPLETFRAME);
display1.addMap(new ScalarMap(RealType.Latitude, Display.YAxis));
display1.addMap(new ScalarMap(RealType.Longitude, Display.XAxis));
display1.addMap(new ScalarMap(vis_radiance, Display.ZAxis));
display1.addMap(new ScalarMap(RealType.Radius, Display.ZAxis));
display1.addMap(new ScalarMap(ir_radiance, Display.Green));
display1.addMap(new ConstantMap(0.5, Display.Blue));
display1.addMap(new ConstantMap(0.5, Display.Red));
ScalarMap map1contour;
map1contour = new ScalarMap(vis_radiance, Display.IsoContour);
display1.addMap(map1contour);
DataReferenceImpl ref_imaget1 = new DataReferenceImpl("ref_imaget1");
ref_imaget1.setData(imaget1);
display1.addReference(ref_imaget1, null);
DisplayImpl[] dpys = new DisplayImpl[1];
dpys[0] = display1;
return dpys;
}
| DisplayImpl[] setupData()
throws VisADException, RemoteException
{
RealType index = new RealType("index", null, null);
RealType vis_radiance = new RealType("vis_radiance", null, null);
RealType ir_radiance = new RealType("ir_radiance", null, null);
RealType[] types = {RealType.Latitude, RealType.Longitude,
vis_radiance, ir_radiance};
RealTupleType radiance = new RealTupleType(types);
FunctionType image_tuple = new FunctionType(index, radiance);
int size = 216;
Set domain_set = new Integer1DSet(size);
FlatField imaget1 = new FlatField(image_tuple, domain_set);
float[][] values = new float[4][size];
Random random = new Random();
for (int i=0; i<size; i++) {
values[0][i] = 2.0f * random.nextFloat() - 1.0f;
values[1][i] = 2.0f * random.nextFloat() - 1.0f;
values[2][i] = 2.0f * random.nextFloat() - 1.0f;
values[3][i] = (float) Math.sqrt(values[0][i] * values[0][i] +
values[1][i] * values[1][i] +
values[2][i] * values[2][i]);
}
imaget1.setSamples(values);
DisplayImpl display1 =
new DisplayImplJ3D("display1", DisplayImplJ3D.APPLETFRAME);
display1.addMap(new ScalarMap(RealType.Latitude, Display.YAxis));
display1.addMap(new ScalarMap(RealType.Longitude, Display.XAxis));
display1.addMap(new ScalarMap(vis_radiance, Display.ZAxis));
display1.addMap(new ScalarMap(RealType.Radius, Display.ZAxis));
display1.addMap(new ScalarMap(ir_radiance, Display.Green));
display1.addMap(new ConstantMap(0.5, Display.Blue));
display1.addMap(new ConstantMap(0.5, Display.Red));
ScalarMap map1contour;
map1contour = new ScalarMap(ir_radiance, Display.IsoContour);
display1.addMap(map1contour);
DataReferenceImpl ref_imaget1 = new DataReferenceImpl("ref_imaget1");
ref_imaget1.setData(imaget1);
display1.addReference(ref_imaget1, null);
DisplayImpl[] dpys = new DisplayImpl[1];
dpys[0] = display1;
return dpys;
}
|
diff --git a/DarkBeam/src/de/krakel/darkbeam/lib/FColors.java b/DarkBeam/src/de/krakel/darkbeam/lib/FColors.java
index 3a79c8f..b7aa3f8 100644
--- a/DarkBeam/src/de/krakel/darkbeam/lib/FColors.java
+++ b/DarkBeam/src/de/krakel/darkbeam/lib/FColors.java
@@ -1,18 +1,18 @@
package de.krakel.darkbeam.lib;
public final class FColors {
public static final String PREFIX_GRAY = "\u00a77";
public static final String PREFIX_WHITE = "\u00a7f";
public static final String PREFIX_YELLOW = "\u00a7e";
public static final String PURE_WHITE = "ffffff";
private FColors() {
}
public static String get( String name, boolean withColor) {
if (withColor) {
return PREFIX_YELLOW + name + PREFIX_WHITE;
}
- return name;
+ return String.valueOf( name);
}
}
| true | true | public static String get( String name, boolean withColor) {
if (withColor) {
return PREFIX_YELLOW + name + PREFIX_WHITE;
}
return name;
}
| public static String get( String name, boolean withColor) {
if (withColor) {
return PREFIX_YELLOW + name + PREFIX_WHITE;
}
return String.valueOf( name);
}
|
diff --git a/araqne-logdb/src/main/java/org/araqne/logdb/impl/QueryPrintHelper.java b/araqne-logdb/src/main/java/org/araqne/logdb/impl/QueryPrintHelper.java
index 58b52dd5..369be05d 100644
--- a/araqne-logdb/src/main/java/org/araqne/logdb/impl/QueryPrintHelper.java
+++ b/araqne-logdb/src/main/java/org/araqne/logdb/impl/QueryPrintHelper.java
@@ -1,103 +1,104 @@
/*
* Copyright 2013 Eediom, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.araqne.logdb.impl;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import org.araqne.api.ScriptContext;
import org.araqne.logdb.LogQuery;
import org.araqne.logdb.LogQueryCommand;
import org.araqne.logdb.RunMode;
/**
* @since 0.14.0
* @author xeraph
*/
public class QueryPrintHelper {
public static void printQueries(ScriptContext context, Collection<LogQuery> qs, String queryFilter) {
String header = "Log Queries";
if (queryFilter != null)
header += " (filter by \"" + queryFilter + "\")";
context.println(header);
int lineLen = header.length() + 2;
for (int i = 0; i < lineLen; i++)
context.print("-");
context.println("");
ArrayList<LogQuery> queries = new ArrayList<LogQuery>(qs);
Collections.sort(queries, new Comparator<LogQuery>() {
@Override
public int compare(LogQuery o1, LogQuery o2) {
return o1.getId() - o2.getId();
}
});
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
for (LogQuery q : queries) {
if (queryFilter != null && !q.getQueryString().contains(queryFilter))
continue;
String when = "";
if (q.getLastStarted() != null)
when = " at " + df.format(q.getLastStarted());
String loginName = q.getContext().getSession().getLoginName();
Long count = null;
try {
count = q.getResultCount();
if (count == null)
count = 0L;
} catch (Throwable t) {
}
String queryString = q.getQueryString();
if (queryString.length() > 60)
queryString = queryString.substring(0, 60) + "...";
String runMode = q.getRunMode() == RunMode.BACKGROUND ? " (bg)" : "";
- context.println(String.format("[%d:%s%s%s] %s => %d", q.getId(), loginName, when, runMode, queryString, count));
+ String lastStatus = q.getCommands().get(q.getCommands().size() - 1).getStatus().toString();
+ context.println(String.format("[%d:%s:%s%s%s] %s => %d", q.getId(), lastStatus, loginName, when, runMode, queryString, count));
}
}
public static String getQueryStatus(LogQuery query) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
String when = " \t/ not started yet";
if (query.getLastStarted() != null) {
long sec = new Date().getTime() - query.getLastStarted().getTime();
when = String.format(" \t/ %s, %d seconds ago", sdf.format(query.getLastStarted()), sec / 1000);
}
String loginName = query.getContext().getSession().getLoginName();
String status = String.format("[%d:%s] %s%s\n", query.getId(), loginName, query.getQueryString(), when);
if (query.getCommands() != null) {
for (LogQueryCommand cmd : query.getCommands()) {
status += String.format(" [%s] %s \t/ passed %d data to next query\n", cmd.getStatus(), cmd.getQueryString(),
cmd.getPushCount());
}
} else {
status += " null\n";
}
return status;
}
}
| true | true | public static void printQueries(ScriptContext context, Collection<LogQuery> qs, String queryFilter) {
String header = "Log Queries";
if (queryFilter != null)
header += " (filter by \"" + queryFilter + "\")";
context.println(header);
int lineLen = header.length() + 2;
for (int i = 0; i < lineLen; i++)
context.print("-");
context.println("");
ArrayList<LogQuery> queries = new ArrayList<LogQuery>(qs);
Collections.sort(queries, new Comparator<LogQuery>() {
@Override
public int compare(LogQuery o1, LogQuery o2) {
return o1.getId() - o2.getId();
}
});
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
for (LogQuery q : queries) {
if (queryFilter != null && !q.getQueryString().contains(queryFilter))
continue;
String when = "";
if (q.getLastStarted() != null)
when = " at " + df.format(q.getLastStarted());
String loginName = q.getContext().getSession().getLoginName();
Long count = null;
try {
count = q.getResultCount();
if (count == null)
count = 0L;
} catch (Throwable t) {
}
String queryString = q.getQueryString();
if (queryString.length() > 60)
queryString = queryString.substring(0, 60) + "...";
String runMode = q.getRunMode() == RunMode.BACKGROUND ? " (bg)" : "";
context.println(String.format("[%d:%s%s%s] %s => %d", q.getId(), loginName, when, runMode, queryString, count));
}
}
| public static void printQueries(ScriptContext context, Collection<LogQuery> qs, String queryFilter) {
String header = "Log Queries";
if (queryFilter != null)
header += " (filter by \"" + queryFilter + "\")";
context.println(header);
int lineLen = header.length() + 2;
for (int i = 0; i < lineLen; i++)
context.print("-");
context.println("");
ArrayList<LogQuery> queries = new ArrayList<LogQuery>(qs);
Collections.sort(queries, new Comparator<LogQuery>() {
@Override
public int compare(LogQuery o1, LogQuery o2) {
return o1.getId() - o2.getId();
}
});
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
for (LogQuery q : queries) {
if (queryFilter != null && !q.getQueryString().contains(queryFilter))
continue;
String when = "";
if (q.getLastStarted() != null)
when = " at " + df.format(q.getLastStarted());
String loginName = q.getContext().getSession().getLoginName();
Long count = null;
try {
count = q.getResultCount();
if (count == null)
count = 0L;
} catch (Throwable t) {
}
String queryString = q.getQueryString();
if (queryString.length() > 60)
queryString = queryString.substring(0, 60) + "...";
String runMode = q.getRunMode() == RunMode.BACKGROUND ? " (bg)" : "";
String lastStatus = q.getCommands().get(q.getCommands().size() - 1).getStatus().toString();
context.println(String.format("[%d:%s:%s%s%s] %s => %d", q.getId(), lastStatus, loginName, when, runMode, queryString, count));
}
}
|
diff --git a/src/net/sf/gogui/tools/twogtp/TwoGtp.java b/src/net/sf/gogui/tools/twogtp/TwoGtp.java
index 79e6634e..1c93e75c 100644
--- a/src/net/sf/gogui/tools/twogtp/TwoGtp.java
+++ b/src/net/sf/gogui/tools/twogtp/TwoGtp.java
@@ -1,728 +1,730 @@
// TwoGtp.java
package net.sf.gogui.tools.twogtp;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import net.sf.gogui.game.ConstNode;
import net.sf.gogui.game.ConstGameTree;
import net.sf.gogui.game.Game;
import net.sf.gogui.game.NodeUtil;
import net.sf.gogui.game.TimeSettings;
import net.sf.gogui.go.BlackWhiteSet;
import net.sf.gogui.go.ConstBoard;
import net.sf.gogui.go.GoColor;
import static net.sf.gogui.go.GoColor.BLACK;
import static net.sf.gogui.go.GoColor.WHITE;
import net.sf.gogui.go.GoPoint;
import net.sf.gogui.go.InvalidKomiException;
import net.sf.gogui.go.Komi;
import net.sf.gogui.go.Move;
import net.sf.gogui.gtp.GtpCommand;
import net.sf.gogui.gtp.GtpEngine;
import net.sf.gogui.gtp.GtpError;
import net.sf.gogui.gtp.GtpResponseFormatError;
import net.sf.gogui.gtp.GtpUtil;
import net.sf.gogui.util.ErrorMessage;
import net.sf.gogui.util.ObjectUtil;
import net.sf.gogui.util.Platform;
import net.sf.gogui.util.StringUtil;
import net.sf.gogui.version.Version;
/** GTP adapter for playing games between two Go programs. */
public class TwoGtp
extends GtpEngine
{
/** Constructor.
@param komi The fixed komi. See TwoGtp documentation for option
-komi */
public TwoGtp(Program black, Program white, Program referee,
String observer, int size, Komi komi, int numberGames,
boolean alternate, String filePrefix, boolean verbose,
Openings openings, TimeSettings timeSettings,
ResultFile resultFile)
throws Exception
{
super(null);
assert size > 0;
assert size <= GoPoint.MAX_SIZE;
assert komi != null;
if (black.equals(""))
throw new ErrorMessage("No black program set");
if (white.equals(""))
throw new ErrorMessage("No white program set");
m_filePrefix = filePrefix;
m_allPrograms = new ArrayList<Program>();
m_black = black;
m_allPrograms.add(m_black);
m_white = white;
m_allPrograms.add(m_white);
m_referee = referee;
if (m_referee != null)
m_allPrograms.add(m_referee);
if (observer.equals(""))
m_observer = null;
else
{
m_observer = new Program(observer, "Observer", "O", verbose);
m_allPrograms.add(m_observer);
}
for (Program program : m_allPrograms)
program.setLabel(m_allPrograms);
m_size = size;
m_komi = komi;
m_alternate = alternate;
m_numberGames = numberGames;
m_openings = openings;
m_verbose = verbose;
m_timeSettings = timeSettings;
m_resultFile = resultFile;
initGame(size);
}
public void autoPlay() throws Exception
{
StringBuilder response = new StringBuilder(256);
while (true)
{
try
{
newGame(m_size);
while (! gameOver())
{
response.setLength(0);
sendGenmove(getToMove(), response);
}
}
catch (GtpError e)
{
if (m_gameIndex == -1)
break;
handleEndOfGame(true, e.getMessage());
}
}
if (m_black.isProgramDead())
throw new ErrorMessage("Black program died");
if (m_white.isProgramDead())
throw new ErrorMessage("White program died");
}
public void close()
{
for (Program program : m_allPrograms)
program.close();
}
public void handleCommand(GtpCommand cmd) throws GtpError
{
String command = cmd.getCommand();
if (command.equals("boardsize"))
cmdBoardSize(cmd);
else if (command.equals("clear_board"))
cmdClearBoard(cmd);
else if (command.equals("final_score"))
finalStatusCommand(cmd);
else if (command.equals("final_status"))
finalStatusCommand(cmd);
else if (command.equals("final_status_list"))
finalStatusCommand(cmd);
else if (command.equals("gogui-interrupt"))
;
else if (command.equals("gogui-title"))
cmd.setResponse(getTitle());
else if (command.equals("gogui-twogtp-black"))
twogtpColor(m_black, cmd);
else if (command.equals("gogui-twogtp-white"))
twogtpColor(m_white, cmd);
else if (command.equals("gogui-twogtp-referee"))
twogtpReferee(cmd);
else if (command.equals("gogui-twogtp-observer"))
twogtpObserver(cmd);
else if (command.equals("quit"))
{
close();
setQuit();
}
else if (command.equals("play"))
cmdPlay(cmd);
else if (command.equals("undo"))
cmdUndo(cmd);
else if (command.equals("genmove"))
cmdGenmove(cmd);
else if (command.equals("komi"))
komi(cmd);
else if (command.equals("scoring_system"))
sendIfSupported(command, cmd.getLine());
else if (command.equals("name"))
cmd.setResponse("gogui-twogtp");
else if (command.equals("version"))
cmd.setResponse(Version.get());
else if (command.equals("protocol_version"))
cmd.setResponse("2");
else if (command.equals("list_commands"))
cmd.setResponse("boardsize\n" +
"clear_board\n" +
"final_score\n" +
"final_status\n" +
"final_status_list\n" +
"genmove\n" +
"gogui-interrupt\n" +
"gogui-title\n" +
"komi\n" +
"list_commands\n" +
"name\n" +
"play\n" +
"quit\n" +
"scoring_system\n" +
"time_settings\n" +
"gogui-twogtp-black\n" +
"gogui-twogtp-observer\n" +
"gogui-twogtp-referee\n" +
"gogui-twogtp-white\n" +
"undo\n" +
"version\n");
else if (GtpUtil.isStateChangingCommand(command))
throw new GtpError("unknown command");
else if (command.equals("time_settings"))
sendIfSupported(command, cmd.getLine());
else
{
boolean isExtCommandBlack = m_black.isSupported(command);
boolean isExtCommandWhite = m_white.isSupported(command);
boolean isExtCommandReferee = false;
if (m_referee != null)
isExtCommandReferee = m_referee.isSupported(command);
boolean isExtCommandObserver = false;
if (m_observer != null)
isExtCommandObserver = m_observer.isSupported(command);
if (isExtCommandBlack && ! isExtCommandObserver
&& ! isExtCommandWhite && ! isExtCommandReferee)
forward(m_black, cmd);
if (isExtCommandWhite && ! isExtCommandObserver
&& ! isExtCommandBlack && ! isExtCommandReferee)
forward(m_white, cmd);
if (isExtCommandReferee && ! isExtCommandObserver
&& ! isExtCommandBlack && ! isExtCommandWhite)
forward(m_referee, cmd);
if (isExtCommandObserver && ! isExtCommandReferee
&& ! isExtCommandBlack && ! isExtCommandWhite)
forward(m_observer, cmd);
if (! isExtCommandReferee
&& ! isExtCommandBlack
&& ! isExtCommandObserver
&& ! isExtCommandWhite)
throw new GtpError("unknown command");
throw new GtpError("use gogui-twogtp-black/white/referee/observer");
}
}
public void interruptCommand()
{
for (Program program : m_allPrograms)
program.interruptProgram();
}
/** Limit number of moves.
@param maxMoves Maximum number of moves after which genmove will fail,
-1 for no limit. */
public void setMaxMoves(int maxMoves)
{
m_maxMoves = maxMoves;
}
private final boolean m_alternate;
private boolean m_gameSaved;
private int m_maxMoves = 1000;
private int m_gameIndex;
private boolean m_resigned;
private final boolean m_verbose;
private final int m_numberGames;
private final int m_size;
/** Fixed komi. */
private final Komi m_komi;
private Game m_game;
private GoColor m_resignColor;
private final Openings m_openings;
private final Program m_black;
private final Program m_white;
private final Program m_referee;
private final Program m_observer;
private final ArrayList<Program> m_allPrograms;
private final BlackWhiteSet<Double> m_realTime =
new BlackWhiteSet<Double>(0., 0.);
private String m_openingFile;
private final String m_filePrefix;
private final ArrayList<ArrayList<Compare.Placement>> m_games
= new ArrayList<ArrayList<Compare.Placement>>(100);
private ResultFile m_resultFile;
private final TimeSettings m_timeSettings;
private ConstNode m_lastOpeningNode;
private void checkInconsistentState() throws GtpError
{
for (Program program : m_allPrograms)
if (program.isOutOfSync())
throw new GtpError("Inconsistent state");
}
private void cmdBoardSize(GtpCommand cmd) throws GtpError
{
cmd.checkNuArg(1);
int size = cmd.getIntArg(0, 1, GoPoint.MAX_SIZE);
if (size != m_size)
throw new GtpError("Size must be " + m_size);
}
private void cmdClearBoard(GtpCommand cmd) throws GtpError
{
cmd.checkArgNone();
newGame(m_size);
}
private void cmdGenmove(GtpCommand cmd) throws GtpError
{
try
{
sendGenmove(cmd.getColorArg(), cmd.getResponse());
}
catch (ErrorMessage e)
{
throw new GtpError(e.getMessage());
}
}
private void cmdPlay(GtpCommand cmd) throws GtpError
{
cmd.checkNuArg(2);
checkInconsistentState();
GoColor color = cmd.getColorArg(0);
GoPoint point = cmd.getPointArg(1, m_size);
Move move = Move.get(color, point);
m_game.play(move);
synchronize();
}
private void cmdUndo(GtpCommand cmd) throws GtpError
{
cmd.checkArgNone();
int moveNumber = m_game.getMoveNumber();
if (moveNumber == 0)
throw new GtpError("cannot undo");
m_game.gotoNode(getCurrentNode().getFatherConst());
assert m_game.getMoveNumber() == moveNumber - 1;
synchronize();
}
private void finalStatusCommand(GtpCommand cmd) throws GtpError
{
checkInconsistentState();
if (m_referee != null)
forward(m_referee, cmd);
else if (m_black.isSupported("final_status"))
forward(m_black, cmd);
else if (m_white.isSupported("final_status"))
forward(m_white, cmd);
else
throw new GtpError("neither player supports final_status");
}
private void forward(Program program, GtpCommand cmd) throws GtpError
{
cmd.setResponse(program.send(cmd.getLine()));
}
private boolean gameOver()
{
return (getBoard().bothPassed() || m_resigned);
}
private ConstBoard getBoard()
{
return m_game.getBoard();
}
private ConstNode getCurrentNode()
{
return m_game.getCurrentNode();
}
private GoColor getToMove()
{
return m_game.getToMove();
}
private ConstGameTree getTree()
{
return m_game.getTree();
}
private String getTitle()
{
StringBuilder buffer = new StringBuilder();
String nameBlack = m_black.getLabel();
String nameWhite = m_white.getLabel();
if (isAlternated())
{
String tmpName = nameBlack;
nameBlack = nameWhite;
nameWhite = tmpName;
}
buffer.append(nameWhite);
buffer.append(" vs ");
buffer.append(nameBlack);
buffer.append(" (B)");
if (! m_filePrefix.equals(""))
{
buffer.append(" (");
buffer.append(m_gameIndex + 1);
buffer.append(')');
}
return buffer.toString();
}
private void handleEndOfGame(boolean error, String errorMessage)
throws ErrorMessage
{
String resultBlack;
String resultWhite;
String resultReferee;
if (m_resigned)
{
String result = (m_resignColor == BLACK ? "W" : "B");
result = result + "+R";
resultBlack = result;
resultWhite = result;
resultReferee = result;
}
else
{
resultBlack = m_black.getResult();
resultWhite = m_white.getResult();
resultReferee = "?";
if (m_referee != null)
resultReferee = m_referee.getResult();
}
double cpuTimeBlack = m_black.getAndClearCpuTime();
double cpuTimeWhite = m_white.getAndClearCpuTime();
double realTimeBlack = m_realTime.get(BLACK);
double realTimeWhite = m_realTime.get(WHITE);
if (isAlternated())
{
resultBlack = inverseResult(resultBlack);
resultWhite = inverseResult(resultWhite);
resultReferee = inverseResult(resultReferee);
realTimeBlack = m_realTime.get(WHITE);
realTimeWhite = m_realTime.get(BLACK);
}
// If a program is dead we wait for a few seconds, because it
// could be because the TwoGtp process was killed and we don't
// want to write a result in this case.
if (m_black.isProgramDead() || m_white.isProgramDead())
{
try
{
Thread.sleep(3000);
}
catch (InterruptedException e)
{
assert false;
}
}
String nameBlack = m_black.getLabel();
String nameWhite = m_white.getLabel();
String blackCommand = m_black.getProgramCommand();
String whiteCommand = m_white.getProgramCommand();
String blackVersion = m_black.getVersion();
String whiteVersion = m_white.getVersion();
if (isAlternated())
{
nameBlack = m_white.getLabel();
nameWhite = m_black.getLabel();
blackCommand = m_white.getProgramCommand();
whiteCommand = m_black.getProgramCommand();
blackVersion = m_white.getVersion();
whiteVersion = m_black.getVersion();
}
m_game.setPlayer(BLACK, nameBlack);
m_game.setPlayer(WHITE, nameWhite);
if (m_referee != null)
m_game.setResult(resultReferee);
else if (resultBlack.equals(resultWhite) && ! resultBlack.equals("?"))
m_game.setResult(resultBlack);
String host = Platform.getHostInfo();
StringBuilder comment = new StringBuilder();
comment.append("Black command: ");
comment.append(blackCommand);
comment.append("\nWhite command: ");
comment.append(whiteCommand);
comment.append("\nBlack version: ");
comment.append(blackVersion);
comment.append("\nWhite version: ");
comment.append(whiteVersion);
if (m_openings != null)
{
comment.append("\nOpening: ");
comment.append(m_openingFile);
}
comment.append("\nResult[Black]: ");
comment.append(resultBlack);
comment.append("\nResult[White]: ");
comment.append(resultWhite);
if (m_referee != null)
{
comment.append("\nReferee: ");
comment.append(m_referee.getProgramCommand());
comment.append("\nResult[Referee]: ");
comment.append(resultReferee);
}
comment.append("\nHost: ");
comment.append(host);
comment.append("\nDate: ");
comment.append(StringUtil.getDate());
m_game.setComment(comment.toString(), getTree().getRootConst());
int moveNumber = NodeUtil.getMoveNumber(getCurrentNode());
- m_resultFile.addResult(m_gameIndex, m_game, resultBlack, resultWhite,
- resultReferee, isAlternated(), moveNumber,
- error, errorMessage, realTimeBlack,
- realTimeWhite, cpuTimeBlack, cpuTimeWhite);
+ if (m_resultFile != null)
+ m_resultFile.addResult(m_gameIndex, m_game, resultBlack,
+ resultWhite, resultReferee, isAlternated(),
+ moveNumber, error, errorMessage,
+ realTimeBlack, realTimeWhite, cpuTimeBlack,
+ cpuTimeWhite);
}
private void initGame(int size) throws GtpError
{
m_game = new Game(size, m_komi, null, null, null);
m_realTime.set(BLACK, 0.);
m_realTime.set(WHITE, 0.);
// Clock is not needed
m_game.haltClock();
m_resigned = false;
if (m_openings != null)
{
int openingFileIndex;
if (m_alternate)
openingFileIndex = (m_gameIndex / 2) % m_openings.getNumber();
else
openingFileIndex = m_gameIndex % m_openings.getNumber();
try
{
m_openings.loadFile(openingFileIndex);
}
catch (Exception e)
{
throw new GtpError(e.getMessage());
}
m_openingFile = m_openings.getFilename();
if (m_verbose)
System.err.println("Loaded opening " + m_openingFile);
if (m_openings.getBoardSize() != size)
throw new GtpError("Wrong board size: " + m_openingFile);
m_game.init(m_openings.getTree());
m_game.setKomi(m_komi);
m_lastOpeningNode = NodeUtil.getLast(getTree().getRootConst());
// TODO: Check that root node contains no setup stones, if
// TwoGtp is run as a GTP engine, see also comment in sendGenmove()
}
else
m_lastOpeningNode = null;
synchronizeInit();
}
private String inverseResult(String result)
{
if (result.indexOf('B') >= 0)
return result.replaceAll("B", "W");
else if (result.indexOf('W') >= 0)
return result.replaceAll("W", "B");
else
return result;
}
private boolean isAlternated()
{
return (m_alternate && m_gameIndex % 2 != 0);
}
private boolean isInOpening()
{
if (m_lastOpeningNode == null)
return false;
for (ConstNode node = getCurrentNode().getChildConst(); node != null;
node = node.getChildConst())
if (node == m_lastOpeningNode)
return true;
return false;
}
private void komi(GtpCommand cmd) throws GtpError
{
String arg = cmd.getArg();
try
{
Komi komi = Komi.parseKomi(arg);
if (! ObjectUtil.equals(komi, m_komi))
throw new GtpError("komi is fixed at " + m_komi);
}
catch (InvalidKomiException e)
{
throw new GtpError("invalid komi: " + arg);
}
}
private void newGame(int size) throws GtpError
{
if (m_resultFile != null)
m_gameIndex = m_resultFile.getNextGameIndex();
else
{
++m_gameIndex;
if (m_numberGames > 0 && m_gameIndex > m_numberGames)
m_gameIndex = -1;
}
if (m_gameIndex == -1)
throw new GtpError("maximum number of games reached");
if (m_verbose)
{
System.err.println("============================================");
System.err.println("Game " + m_gameIndex);
System.err.println("============================================");
}
m_black.getAndClearCpuTime();
m_white.getAndClearCpuTime();
initGame(size);
m_gameSaved = false;
if (m_timeSettings != null)
sendIfSupported("time_settings",
GtpUtil.getTimeSettingsCommand(m_timeSettings));
}
private void sendGenmove(GoColor color, StringBuilder response)
throws GtpError, ErrorMessage
{
checkInconsistentState();
int moveNumber = m_game.getMoveNumber();
if (m_maxMoves >= 0 && moveNumber > m_maxMoves)
throw new GtpError("move limit exceeded");
if (isInOpening())
{
// TODO: Check that node contains no setup stones or fully support
// openings with setup stones and non-alternating moves in GTP
// engine mode again (by transforming the opening file into a
// sequence of alternating moves, replacing setup stones by moves
// and filling in passes). See also comment in initGame() and
// doc/manual/xml/reference-twogtp.xml
ConstNode child = getCurrentNode().getChildConst();
Move move = child.getMove();
if (move.getColor() != color)
throw new GtpError("next opening move is " + move);
m_game.gotoNode(child);
synchronize();
response.append(GoPoint.toString(move.getPoint()));
return;
}
Program program;
boolean exchangeColors =
(color == BLACK && isAlternated())
|| (color == WHITE && ! isAlternated());
if (exchangeColors)
program = m_white;
else
program = m_black;
long timeMillis = System.currentTimeMillis();
String responseGenmove = program.sendCommandGenmove(color);
double time = (System.currentTimeMillis() - timeMillis) / 1000.;
m_realTime.set(color, m_realTime.get(color) + time);
if (responseGenmove.equalsIgnoreCase("resign"))
{
response.append("resign");
m_resigned = true;
m_resignColor = color;
}
else
{
ConstBoard board = getBoard();
GoPoint point = null;
try
{
point = GtpUtil.parsePoint(responseGenmove, board.getSize());
}
catch (GtpResponseFormatError e)
{
throw new GtpError(program.getLabel()
+ " played invalid move: "
+ responseGenmove);
}
Move move = Move.get(color, point);
m_game.play(move);
program.updateAfterGenmove(board);
synchronize();
response.append(GoPoint.toString(move.getPoint()));
}
if (gameOver() && ! m_gameSaved)
{
handleEndOfGame(false, "");
m_gameSaved = true;
}
}
private void sendIfSupported(String cmd, String cmdLine)
{
for (Program program : m_allPrograms)
program.sendIfSupported(cmd, cmdLine);
}
private void synchronize() throws GtpError
{
for (Program program : m_allPrograms)
program.synchronize(m_game);
}
private void synchronizeInit() throws GtpError
{
for (Program program : m_allPrograms)
program.synchronizeInit(m_game);
}
private void twogtpColor(Program program, GtpCommand cmd) throws GtpError
{
cmd.setResponse(program.send(cmd.getArgLine()));
}
private void twogtpObserver(GtpCommand cmd) throws GtpError
{
if (m_observer == null)
throw new GtpError("no observer enabled");
twogtpColor(m_observer, cmd);
}
private void twogtpReferee(GtpCommand cmd) throws GtpError
{
if (m_referee == null)
throw new GtpError("no referee enabled");
twogtpColor(m_referee, cmd);
}
}
| true | true | private void handleEndOfGame(boolean error, String errorMessage)
throws ErrorMessage
{
String resultBlack;
String resultWhite;
String resultReferee;
if (m_resigned)
{
String result = (m_resignColor == BLACK ? "W" : "B");
result = result + "+R";
resultBlack = result;
resultWhite = result;
resultReferee = result;
}
else
{
resultBlack = m_black.getResult();
resultWhite = m_white.getResult();
resultReferee = "?";
if (m_referee != null)
resultReferee = m_referee.getResult();
}
double cpuTimeBlack = m_black.getAndClearCpuTime();
double cpuTimeWhite = m_white.getAndClearCpuTime();
double realTimeBlack = m_realTime.get(BLACK);
double realTimeWhite = m_realTime.get(WHITE);
if (isAlternated())
{
resultBlack = inverseResult(resultBlack);
resultWhite = inverseResult(resultWhite);
resultReferee = inverseResult(resultReferee);
realTimeBlack = m_realTime.get(WHITE);
realTimeWhite = m_realTime.get(BLACK);
}
// If a program is dead we wait for a few seconds, because it
// could be because the TwoGtp process was killed and we don't
// want to write a result in this case.
if (m_black.isProgramDead() || m_white.isProgramDead())
{
try
{
Thread.sleep(3000);
}
catch (InterruptedException e)
{
assert false;
}
}
String nameBlack = m_black.getLabel();
String nameWhite = m_white.getLabel();
String blackCommand = m_black.getProgramCommand();
String whiteCommand = m_white.getProgramCommand();
String blackVersion = m_black.getVersion();
String whiteVersion = m_white.getVersion();
if (isAlternated())
{
nameBlack = m_white.getLabel();
nameWhite = m_black.getLabel();
blackCommand = m_white.getProgramCommand();
whiteCommand = m_black.getProgramCommand();
blackVersion = m_white.getVersion();
whiteVersion = m_black.getVersion();
}
m_game.setPlayer(BLACK, nameBlack);
m_game.setPlayer(WHITE, nameWhite);
if (m_referee != null)
m_game.setResult(resultReferee);
else if (resultBlack.equals(resultWhite) && ! resultBlack.equals("?"))
m_game.setResult(resultBlack);
String host = Platform.getHostInfo();
StringBuilder comment = new StringBuilder();
comment.append("Black command: ");
comment.append(blackCommand);
comment.append("\nWhite command: ");
comment.append(whiteCommand);
comment.append("\nBlack version: ");
comment.append(blackVersion);
comment.append("\nWhite version: ");
comment.append(whiteVersion);
if (m_openings != null)
{
comment.append("\nOpening: ");
comment.append(m_openingFile);
}
comment.append("\nResult[Black]: ");
comment.append(resultBlack);
comment.append("\nResult[White]: ");
comment.append(resultWhite);
if (m_referee != null)
{
comment.append("\nReferee: ");
comment.append(m_referee.getProgramCommand());
comment.append("\nResult[Referee]: ");
comment.append(resultReferee);
}
comment.append("\nHost: ");
comment.append(host);
comment.append("\nDate: ");
comment.append(StringUtil.getDate());
m_game.setComment(comment.toString(), getTree().getRootConst());
int moveNumber = NodeUtil.getMoveNumber(getCurrentNode());
m_resultFile.addResult(m_gameIndex, m_game, resultBlack, resultWhite,
resultReferee, isAlternated(), moveNumber,
error, errorMessage, realTimeBlack,
realTimeWhite, cpuTimeBlack, cpuTimeWhite);
}
| private void handleEndOfGame(boolean error, String errorMessage)
throws ErrorMessage
{
String resultBlack;
String resultWhite;
String resultReferee;
if (m_resigned)
{
String result = (m_resignColor == BLACK ? "W" : "B");
result = result + "+R";
resultBlack = result;
resultWhite = result;
resultReferee = result;
}
else
{
resultBlack = m_black.getResult();
resultWhite = m_white.getResult();
resultReferee = "?";
if (m_referee != null)
resultReferee = m_referee.getResult();
}
double cpuTimeBlack = m_black.getAndClearCpuTime();
double cpuTimeWhite = m_white.getAndClearCpuTime();
double realTimeBlack = m_realTime.get(BLACK);
double realTimeWhite = m_realTime.get(WHITE);
if (isAlternated())
{
resultBlack = inverseResult(resultBlack);
resultWhite = inverseResult(resultWhite);
resultReferee = inverseResult(resultReferee);
realTimeBlack = m_realTime.get(WHITE);
realTimeWhite = m_realTime.get(BLACK);
}
// If a program is dead we wait for a few seconds, because it
// could be because the TwoGtp process was killed and we don't
// want to write a result in this case.
if (m_black.isProgramDead() || m_white.isProgramDead())
{
try
{
Thread.sleep(3000);
}
catch (InterruptedException e)
{
assert false;
}
}
String nameBlack = m_black.getLabel();
String nameWhite = m_white.getLabel();
String blackCommand = m_black.getProgramCommand();
String whiteCommand = m_white.getProgramCommand();
String blackVersion = m_black.getVersion();
String whiteVersion = m_white.getVersion();
if (isAlternated())
{
nameBlack = m_white.getLabel();
nameWhite = m_black.getLabel();
blackCommand = m_white.getProgramCommand();
whiteCommand = m_black.getProgramCommand();
blackVersion = m_white.getVersion();
whiteVersion = m_black.getVersion();
}
m_game.setPlayer(BLACK, nameBlack);
m_game.setPlayer(WHITE, nameWhite);
if (m_referee != null)
m_game.setResult(resultReferee);
else if (resultBlack.equals(resultWhite) && ! resultBlack.equals("?"))
m_game.setResult(resultBlack);
String host = Platform.getHostInfo();
StringBuilder comment = new StringBuilder();
comment.append("Black command: ");
comment.append(blackCommand);
comment.append("\nWhite command: ");
comment.append(whiteCommand);
comment.append("\nBlack version: ");
comment.append(blackVersion);
comment.append("\nWhite version: ");
comment.append(whiteVersion);
if (m_openings != null)
{
comment.append("\nOpening: ");
comment.append(m_openingFile);
}
comment.append("\nResult[Black]: ");
comment.append(resultBlack);
comment.append("\nResult[White]: ");
comment.append(resultWhite);
if (m_referee != null)
{
comment.append("\nReferee: ");
comment.append(m_referee.getProgramCommand());
comment.append("\nResult[Referee]: ");
comment.append(resultReferee);
}
comment.append("\nHost: ");
comment.append(host);
comment.append("\nDate: ");
comment.append(StringUtil.getDate());
m_game.setComment(comment.toString(), getTree().getRootConst());
int moveNumber = NodeUtil.getMoveNumber(getCurrentNode());
if (m_resultFile != null)
m_resultFile.addResult(m_gameIndex, m_game, resultBlack,
resultWhite, resultReferee, isAlternated(),
moveNumber, error, errorMessage,
realTimeBlack, realTimeWhite, cpuTimeBlack,
cpuTimeWhite);
}
|
diff --git a/tests/org.eclipse.dltk.javascript.core.tests/src/org/eclipse/dltk/javascript/core/tests/typeinference/ExampleMemberEvaluator.java b/tests/org.eclipse.dltk.javascript.core.tests/src/org/eclipse/dltk/javascript/core/tests/typeinference/ExampleMemberEvaluator.java
index 37e0039b..80b72276 100644
--- a/tests/org.eclipse.dltk.javascript.core.tests/src/org/eclipse/dltk/javascript/core/tests/typeinference/ExampleMemberEvaluator.java
+++ b/tests/org.eclipse.dltk.javascript.core.tests/src/org/eclipse/dltk/javascript/core/tests/typeinference/ExampleMemberEvaluator.java
@@ -1,63 +1,63 @@
/*******************************************************************************
* Copyright (c) 2010 xored software, Inc.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* xored software, Inc. - initial API and Implementation (Alex Panchenko)
*******************************************************************************/
package org.eclipse.dltk.javascript.core.tests.typeinference;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.Path;
import org.eclipse.dltk.compiler.env.IModuleSource;
import org.eclipse.dltk.core.ISourceModule;
import org.eclipse.dltk.internal.javascript.ti.TypeInferencer2;
import org.eclipse.dltk.javascript.ast.Script;
import org.eclipse.dltk.javascript.parser.JavaScriptParser;
import org.eclipse.dltk.javascript.typeinference.IValueCollection;
import org.eclipse.dltk.javascript.typeinference.ValueCollectionFactory;
import org.eclipse.dltk.javascript.typeinfo.IMemberEvaluator;
import org.eclipse.dltk.javascript.typeinfo.ITypeInfoContext;
import org.eclipse.dltk.javascript.typeinfo.model.Member;
public class ExampleMemberEvaluator implements IMemberEvaluator {
public IValueCollection valueOf(ITypeInfoContext context,Member member) {
IValueCollection collection = (IValueCollection) member
.getAttribute(ExampleElementResolver.MEMBER_VALUE);
if (collection == null)
{
ISourceModule globals = (ISourceModule) member.getAttribute(ExampleElementResolver.LAZY_MEMBER_VALUE);
- if (globals.exists()) {
+ if (globals != null && globals.exists()) {
final Script script = new JavaScriptParser().parse(
(IModuleSource) globals, null);
if (script != null) {
TypeInferencer2 inferencer = new TypeInferencer2();
inferencer.setModelElement(globals);
inferencer.doInferencing(script);
collection = inferencer.getCollection();
}
}
}
return collection;
}
public IValueCollection getTopValueCollection(ITypeInfoContext context) {
if (context.getSource() != null && context.getSource().getSourceModule().getResource().getName().equals("globals1.js"))
{
IFile file2 = context.getSource().getSourceModule().getResource().getParent().getFile(Path.fromPortableString("globals2.js"));
IFile file3 = context.getSource().getSourceModule().getResource().getParent().getFile(Path.fromPortableString("globals3.js"));
IValueCollection collection = ValueCollectionFactory.createScopeValueCollection();
ValueCollectionFactory.copyInto(collection, ValueCollectionFactory.createValueCollection(file2, true));
ValueCollectionFactory.copyInto(collection, ValueCollectionFactory.createValueCollection(file3, true));
return collection;
}
return null;
}
}
| true | true | public IValueCollection valueOf(ITypeInfoContext context,Member member) {
IValueCollection collection = (IValueCollection) member
.getAttribute(ExampleElementResolver.MEMBER_VALUE);
if (collection == null)
{
ISourceModule globals = (ISourceModule) member.getAttribute(ExampleElementResolver.LAZY_MEMBER_VALUE);
if (globals.exists()) {
final Script script = new JavaScriptParser().parse(
(IModuleSource) globals, null);
if (script != null) {
TypeInferencer2 inferencer = new TypeInferencer2();
inferencer.setModelElement(globals);
inferencer.doInferencing(script);
collection = inferencer.getCollection();
}
}
}
return collection;
}
| public IValueCollection valueOf(ITypeInfoContext context,Member member) {
IValueCollection collection = (IValueCollection) member
.getAttribute(ExampleElementResolver.MEMBER_VALUE);
if (collection == null)
{
ISourceModule globals = (ISourceModule) member.getAttribute(ExampleElementResolver.LAZY_MEMBER_VALUE);
if (globals != null && globals.exists()) {
final Script script = new JavaScriptParser().parse(
(IModuleSource) globals, null);
if (script != null) {
TypeInferencer2 inferencer = new TypeInferencer2();
inferencer.setModelElement(globals);
inferencer.doInferencing(script);
collection = inferencer.getCollection();
}
}
}
return collection;
}
|
diff --git a/oak-core/src/main/java/org/apache/jackrabbit/oak/namepath/NamePathMapperImpl.java b/oak-core/src/main/java/org/apache/jackrabbit/oak/namepath/NamePathMapperImpl.java
index 248e3d9a1c..b4784997f1 100644
--- a/oak-core/src/main/java/org/apache/jackrabbit/oak/namepath/NamePathMapperImpl.java
+++ b/oak-core/src/main/java/org/apache/jackrabbit/oak/namepath/NamePathMapperImpl.java
@@ -1,245 +1,245 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.jackrabbit.oak.namepath;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
/**
* NamePathMapperImpl...
*/
public class NamePathMapperImpl implements NamePathMapper {
/**
* logger instance
*/
private static final Logger log = LoggerFactory.getLogger(NamePathMapperImpl.class);
private final NameMapper nameMapper;
public NamePathMapperImpl(NameMapper nameMapper) {
this.nameMapper = nameMapper;
}
//---------------------------------------------------------< NameMapper >---
@Override
public String getOakName(String jcrName) {
return nameMapper.getOakName(jcrName);
}
@Override
public String getJcrName(String oakName) {
return nameMapper.getJcrName(oakName);
}
//---------------------------------------------------------< PathMapper >---
@Override
public String getOakPath(String jcrPath) {
final List<String> elements = new ArrayList<String>();
final StringBuilder parseErrors = new StringBuilder();
if ("/".equals(jcrPath)) {
// avoid the need to special case the root path later on
return "/";
}
JcrPathParser.Listener listener = new JcrPathParser.Listener() {
@Override
public boolean root() {
if (!elements.isEmpty()) {
parseErrors.append("/ on non-empty path");
return false;
}
elements.add("");
return true;
}
@Override
public boolean identifier(String identifier) {
if (!elements.isEmpty()) {
parseErrors.append("[identifier] on non-empty path");
return false;
}
elements.add(identifier); // todo resolve identifier
// todo seal elements
return true;
}
@Override
public boolean current() {
// nothing to do here
return true;
}
@Override
public boolean parent() {
if (elements.isEmpty() || "..".equals(elements.get(elements.size() - 1))) {
elements.add("..");
return true;
}
elements.remove(elements.size() - 1);
return true;
}
@Override
public boolean index(int index) {
if (index > 1) {
parseErrors.append("index > 1");
return false;
}
return true;
}
@Override
public void error(String message) {
parseErrors.append(message);
}
@Override
public boolean name(String name) {
String p = nameMapper.getOakName(name);
if (p == null) {
parseErrors.append("Invalid name: ").append(name);
return false;
}
elements.add(p);
return true;
}
};
JcrPathParser.parse(jcrPath, listener);
if (parseErrors.length() != 0) {
- log.debug("Could not parser path " + jcrPath + ": " + parseErrors.toString());
+ log.debug("Could not parse path " + jcrPath + ": " + parseErrors.toString());
return null;
}
// Empty path maps to ""
if (elements.isEmpty()) {
return "";
}
StringBuilder oakPath = new StringBuilder();
for (String element : elements) {
if (element.isEmpty()) {
// root
oakPath.append('/');
}
else {
oakPath.append(element);
oakPath.append('/');
}
}
// root path is special-cased early on so it does not need to
// be considered here
oakPath.deleteCharAt(oakPath.length() - 1);
return oakPath.toString();
}
@Override
public String getJcrPath(String oakPath) {
final List<String> elements = new ArrayList<String>();
if ("/".equals(oakPath)) {
// avoid the need to special case the root path later on
return "/";
}
JcrPathParser.Listener listener = new JcrPathParser.Listener() {
@Override
public boolean root() {
if (!elements.isEmpty()) {
throw new IllegalArgumentException("/ on non-empty path");
}
elements.add("");
return true;
}
@Override
public boolean identifier(String identifier) {
if (!elements.isEmpty()) {
throw new IllegalArgumentException("[identifier] on non-empty path");
}
elements.add(identifier); // todo resolve identifier
// todo seal elements
return true;
}
@Override
public boolean current() {
// nothing to do here
return false;
}
@Override
public boolean parent() {
if (elements.isEmpty() || "..".equals(elements.get(elements.size() - 1))) {
elements.add("..");
return true;
}
elements.remove(elements.size() - 1);
return true;
}
@Override
public boolean index(int index) {
if (index > 1) {
throw new IllegalArgumentException("index > 1");
}
return true;
}
@Override
public void error(String message) {
throw new IllegalArgumentException(message);
}
@Override
public boolean name(String name) {
String p = nameMapper.getJcrName(name);
elements.add(p);
return true;
}
};
JcrPathParser.parse(oakPath, listener);
// empty path: map to "."
if (elements.isEmpty()) {
return ".";
}
StringBuilder jcrPath = new StringBuilder();
for (String element : elements) {
if (element.isEmpty()) {
// root
jcrPath.append('/');
}
else {
jcrPath.append(element);
jcrPath.append('/');
}
}
jcrPath.deleteCharAt(jcrPath.length() - 1);
return jcrPath.toString();
}
}
| true | true | public String getOakPath(String jcrPath) {
final List<String> elements = new ArrayList<String>();
final StringBuilder parseErrors = new StringBuilder();
if ("/".equals(jcrPath)) {
// avoid the need to special case the root path later on
return "/";
}
JcrPathParser.Listener listener = new JcrPathParser.Listener() {
@Override
public boolean root() {
if (!elements.isEmpty()) {
parseErrors.append("/ on non-empty path");
return false;
}
elements.add("");
return true;
}
@Override
public boolean identifier(String identifier) {
if (!elements.isEmpty()) {
parseErrors.append("[identifier] on non-empty path");
return false;
}
elements.add(identifier); // todo resolve identifier
// todo seal elements
return true;
}
@Override
public boolean current() {
// nothing to do here
return true;
}
@Override
public boolean parent() {
if (elements.isEmpty() || "..".equals(elements.get(elements.size() - 1))) {
elements.add("..");
return true;
}
elements.remove(elements.size() - 1);
return true;
}
@Override
public boolean index(int index) {
if (index > 1) {
parseErrors.append("index > 1");
return false;
}
return true;
}
@Override
public void error(String message) {
parseErrors.append(message);
}
@Override
public boolean name(String name) {
String p = nameMapper.getOakName(name);
if (p == null) {
parseErrors.append("Invalid name: ").append(name);
return false;
}
elements.add(p);
return true;
}
};
JcrPathParser.parse(jcrPath, listener);
if (parseErrors.length() != 0) {
log.debug("Could not parser path " + jcrPath + ": " + parseErrors.toString());
return null;
}
// Empty path maps to ""
if (elements.isEmpty()) {
return "";
}
StringBuilder oakPath = new StringBuilder();
for (String element : elements) {
if (element.isEmpty()) {
// root
oakPath.append('/');
}
else {
oakPath.append(element);
oakPath.append('/');
}
}
// root path is special-cased early on so it does not need to
// be considered here
oakPath.deleteCharAt(oakPath.length() - 1);
return oakPath.toString();
}
| public String getOakPath(String jcrPath) {
final List<String> elements = new ArrayList<String>();
final StringBuilder parseErrors = new StringBuilder();
if ("/".equals(jcrPath)) {
// avoid the need to special case the root path later on
return "/";
}
JcrPathParser.Listener listener = new JcrPathParser.Listener() {
@Override
public boolean root() {
if (!elements.isEmpty()) {
parseErrors.append("/ on non-empty path");
return false;
}
elements.add("");
return true;
}
@Override
public boolean identifier(String identifier) {
if (!elements.isEmpty()) {
parseErrors.append("[identifier] on non-empty path");
return false;
}
elements.add(identifier); // todo resolve identifier
// todo seal elements
return true;
}
@Override
public boolean current() {
// nothing to do here
return true;
}
@Override
public boolean parent() {
if (elements.isEmpty() || "..".equals(elements.get(elements.size() - 1))) {
elements.add("..");
return true;
}
elements.remove(elements.size() - 1);
return true;
}
@Override
public boolean index(int index) {
if (index > 1) {
parseErrors.append("index > 1");
return false;
}
return true;
}
@Override
public void error(String message) {
parseErrors.append(message);
}
@Override
public boolean name(String name) {
String p = nameMapper.getOakName(name);
if (p == null) {
parseErrors.append("Invalid name: ").append(name);
return false;
}
elements.add(p);
return true;
}
};
JcrPathParser.parse(jcrPath, listener);
if (parseErrors.length() != 0) {
log.debug("Could not parse path " + jcrPath + ": " + parseErrors.toString());
return null;
}
// Empty path maps to ""
if (elements.isEmpty()) {
return "";
}
StringBuilder oakPath = new StringBuilder();
for (String element : elements) {
if (element.isEmpty()) {
// root
oakPath.append('/');
}
else {
oakPath.append(element);
oakPath.append('/');
}
}
// root path is special-cased early on so it does not need to
// be considered here
oakPath.deleteCharAt(oakPath.length() - 1);
return oakPath.toString();
}
|
diff --git a/features/edb/core/src/main/java/org/openengsb/edb/core/repository/jgit/GitCommit.java b/features/edb/core/src/main/java/org/openengsb/edb/core/repository/jgit/GitCommit.java
index 8779dc27b..50f1ed818 100644
--- a/features/edb/core/src/main/java/org/openengsb/edb/core/repository/jgit/GitCommit.java
+++ b/features/edb/core/src/main/java/org/openengsb/edb/core/repository/jgit/GitCommit.java
@@ -1,268 +1,266 @@
/**
Copyright 2010 OpenEngSB Division, Vienna University of Technology
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.openengsb.edb.core.repository.jgit;
import java.io.File;
import java.io.IOException;
import java.util.HashSet;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.GitIndex;
import org.eclipse.jgit.lib.IndexDiff;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.ObjectWriter;
import org.eclipse.jgit.lib.PersonIdent;
import org.eclipse.jgit.lib.RefUpdate;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.lib.Tree;
import org.eclipse.jgit.lib.TreeEntry;
import org.eclipse.jgit.lib.GitIndex.Entry;
import org.openengsb.edb.core.entities.GenericContent;
import org.openengsb.edb.core.repository.Commit;
import org.openengsb.edb.core.repository.RepositoryStateException;
/**
* Implementation of the {@link Commit} interface for a git-repository.
*/
@SuppressWarnings("deprecation")
public class GitCommit implements Commit {
private Log log = LogFactory.getLog(getClass());
private Repository repository;
private GitIndex index;
private File repositoryPath;
private String commiterName;
private String commiterEmail;
private String commitMessage;
private String authorName;
private String authorEmail;
/**
* Creates a new commit object. This requires the repository and the
* repositoryPath at least. Furthermore since the author of a commit can
* vary always the full identification of an commiter is required. This is
* defined by the {@link GitRepository} object and should not change for a
* repository.
*/
public GitCommit(Repository repository, String commiterName, String commiterEmail, File repositoryPath) {
this.repository = repository;
this.commiterName = commiterName;
this.commiterEmail = commiterEmail;
this.repositoryPath = repositoryPath;
try {
this.index = this.repository.getIndex();
} catch (IOException e) {
throw new RepositoryStateException("Cant retrieve index...", e);
}
}
public Commit add(GenericContent... contents) {
for (GenericContent content : contents) {
try {
this.index.add(this.repositoryPath, content.getFileLocation());
} catch (IOException e) {
throw new RepositoryStateException("Cant add generic content to index...", e);
}
}
return this;
}
public Commit add(File... files) {
for (File file : files) {
try {
this.index.add(this.repositoryPath, file);
} catch (IOException e) {
throw new RepositoryStateException("Cant add file to index...", e);
}
}
return this;
}
public Commit delete(File... files) {
for (File file : files) {
try {
this.index.remove(this.repositoryPath, file);
} catch (IOException e) {
throw new RepositoryStateException("Cant remove file from index...", e);
}
}
return this;
}
public Commit delete(GenericContent... contents) {
for (GenericContent content : contents) {
try {
this.index.remove(this.repositoryPath, content.getFileLocation());
} catch (IOException e) {
throw new RepositoryStateException("Cant remove generic content from index...", e);
}
}
return this;
}
public String commit() throws RepositoryStateException {
if (this.commiterEmail == null || this.commiterName == null || this.commitMessage == null
|| this.authorEmail == null || this.authorName == null) {
throw new RepositoryStateException("Requiring all fields to be filled, before executing a commit...");
}
this.log.debug("Doing commit for author [" + this.authorName + "; " + this.authorEmail + "] with message ["
+ this.commitMessage + "]...");
try {
this.log.trace("Writing index...");
this.index.write();
} catch (IOException e) {
throw new RepositoryStateException("Cant write index...", e);
}
IndexDiff diff;
try {
this.log.trace("Creating diff from index...");
diff = new IndexDiff(this.repository.mapTree(Constants.HEAD), this.repository.getIndex());
diff.diff();
} catch (IOException e) {
throw new RepositoryStateException("Cant write diff tree...", e);
}
HashSet<String> allFiles = new HashSet<String>();
allFiles.addAll(diff.getAdded());
allFiles.addAll(diff.getChanged());
allFiles.addAll(diff.getModified());
allFiles.addAll(diff.getRemoved());
this.log.debug("[" + allFiles.size() + "] files changed and to commit...");
try {
this.log.trace("creating repository tree...");
Tree projectTree = this.repository.mapTree(Constants.HEAD);
if (projectTree == null) {
projectTree = new Tree(this.repository);
}
this.log.trace("Iterating each files and write the trees for each of them...");
for (String string : allFiles) {
File actualFile = new File(this.repositoryPath.getAbsolutePath() + File.separator + string);
this.log.debug("Writing file [" + actualFile.getAbsolutePath() + "] to index...");
TreeEntry treeMember = projectTree.findBlobMember(string);
if (treeMember != null) {
treeMember.delete();
}
this.log.trace("Getting entry index...");
Entry idxEntry = this.index.getEntry(string);
- if (diff.getMissing().contains(actualFile)) {
+ if (diff.getMissing().contains(string)) {
this.log.debug("For any reason file is missing and situation have to be handeld...");
File thisFile = new File(this.repositoryPath, string);
if (!thisFile.isFile()) {
this.index.remove(this.repositoryPath, thisFile);
- this.index.write();
continue;
} else {
- if (idxEntry.update(thisFile)) {
- this.index.write();
- }
+ idxEntry.update(thisFile);
}
}
this.log.trace("Adding file to tree...");
if (idxEntry != null) {
projectTree.addFile(string);
TreeEntry newMember = projectTree.findBlobMember(string);
newMember.setId(idxEntry.getObjectId());
}
}
+ this.index.write();
this.log.debug("Writing tree with subtrees...");
writeTreeWithSubTrees(projectTree);
this.log.trace("Retrieving current ids for commit...");
ObjectId currentHeadId = this.repository.resolve(Constants.HEAD);
ObjectId[] parentIds;
if (currentHeadId != null) {
parentIds = new ObjectId[] { currentHeadId };
} else {
parentIds = new ObjectId[0];
}
this.log.trace("Creating commit object and prepare for commit...");
org.eclipse.jgit.lib.Commit commit = new org.eclipse.jgit.lib.Commit(this.repository, parentIds);
commit.setTree(projectTree);
commit.setMessage(this.commitMessage);
commit.setAuthor(new PersonIdent(this.authorName, this.authorEmail));
commit.setCommitter(new PersonIdent(this.commiterName, this.commiterEmail));
this.log.debug("Writing commit to disk...");
ObjectWriter writer = new ObjectWriter(this.repository);
commit.setCommitId(writer.writeCommit(commit));
RefUpdate ru = this.repository.updateRef(Constants.HEAD);
ru.setNewObjectId(commit.getCommitId());
ru.setRefLogMessage(this.commitMessage, true);
if (ru.forceUpdate() == RefUpdate.Result.LOCK_FAILURE) {
throw new RepositoryStateException("Failed to update " + ru.getName() + " to commit "
+ commit.getCommitId() + ".");
}
return commit.getCommitId().name();
} catch (Exception e) {
throw new RepositoryStateException("Cant do commit...", e);
}
}
public Commit setAuthor(String fullName, String email) {
this.authorName = fullName;
this.authorEmail = email;
return this;
}
public Commit setMessage(String message) {
this.commitMessage = message;
return this;
}
private void writeTreeWithSubTrees(Tree tree) throws Exception {
if (tree.getId() == null) {
this.log.debug("writing tree for: " + tree.getFullName());
try {
for (TreeEntry entry : tree.members()) {
if (entry.isModified()) {
if (entry instanceof Tree) {
writeTreeWithSubTrees((Tree) entry);
} else {
this.log.warn("BAD JUJU: " + entry.getFullName());
}
}
}
ObjectWriter writer = new ObjectWriter(tree.getRepository());
tree.setId(writer.writeTree(tree));
} catch (IOException e) {
throw new Exception("Writing trees", e);
}
}
}
}
| false | true | public String commit() throws RepositoryStateException {
if (this.commiterEmail == null || this.commiterName == null || this.commitMessage == null
|| this.authorEmail == null || this.authorName == null) {
throw new RepositoryStateException("Requiring all fields to be filled, before executing a commit...");
}
this.log.debug("Doing commit for author [" + this.authorName + "; " + this.authorEmail + "] with message ["
+ this.commitMessage + "]...");
try {
this.log.trace("Writing index...");
this.index.write();
} catch (IOException e) {
throw new RepositoryStateException("Cant write index...", e);
}
IndexDiff diff;
try {
this.log.trace("Creating diff from index...");
diff = new IndexDiff(this.repository.mapTree(Constants.HEAD), this.repository.getIndex());
diff.diff();
} catch (IOException e) {
throw new RepositoryStateException("Cant write diff tree...", e);
}
HashSet<String> allFiles = new HashSet<String>();
allFiles.addAll(diff.getAdded());
allFiles.addAll(diff.getChanged());
allFiles.addAll(diff.getModified());
allFiles.addAll(diff.getRemoved());
this.log.debug("[" + allFiles.size() + "] files changed and to commit...");
try {
this.log.trace("creating repository tree...");
Tree projectTree = this.repository.mapTree(Constants.HEAD);
if (projectTree == null) {
projectTree = new Tree(this.repository);
}
this.log.trace("Iterating each files and write the trees for each of them...");
for (String string : allFiles) {
File actualFile = new File(this.repositoryPath.getAbsolutePath() + File.separator + string);
this.log.debug("Writing file [" + actualFile.getAbsolutePath() + "] to index...");
TreeEntry treeMember = projectTree.findBlobMember(string);
if (treeMember != null) {
treeMember.delete();
}
this.log.trace("Getting entry index...");
Entry idxEntry = this.index.getEntry(string);
if (diff.getMissing().contains(actualFile)) {
this.log.debug("For any reason file is missing and situation have to be handeld...");
File thisFile = new File(this.repositoryPath, string);
if (!thisFile.isFile()) {
this.index.remove(this.repositoryPath, thisFile);
this.index.write();
continue;
} else {
if (idxEntry.update(thisFile)) {
this.index.write();
}
}
}
this.log.trace("Adding file to tree...");
if (idxEntry != null) {
projectTree.addFile(string);
TreeEntry newMember = projectTree.findBlobMember(string);
newMember.setId(idxEntry.getObjectId());
}
}
this.log.debug("Writing tree with subtrees...");
writeTreeWithSubTrees(projectTree);
this.log.trace("Retrieving current ids for commit...");
ObjectId currentHeadId = this.repository.resolve(Constants.HEAD);
ObjectId[] parentIds;
if (currentHeadId != null) {
parentIds = new ObjectId[] { currentHeadId };
} else {
parentIds = new ObjectId[0];
}
this.log.trace("Creating commit object and prepare for commit...");
org.eclipse.jgit.lib.Commit commit = new org.eclipse.jgit.lib.Commit(this.repository, parentIds);
commit.setTree(projectTree);
commit.setMessage(this.commitMessage);
commit.setAuthor(new PersonIdent(this.authorName, this.authorEmail));
commit.setCommitter(new PersonIdent(this.commiterName, this.commiterEmail));
this.log.debug("Writing commit to disk...");
ObjectWriter writer = new ObjectWriter(this.repository);
commit.setCommitId(writer.writeCommit(commit));
RefUpdate ru = this.repository.updateRef(Constants.HEAD);
ru.setNewObjectId(commit.getCommitId());
ru.setRefLogMessage(this.commitMessage, true);
if (ru.forceUpdate() == RefUpdate.Result.LOCK_FAILURE) {
throw new RepositoryStateException("Failed to update " + ru.getName() + " to commit "
+ commit.getCommitId() + ".");
}
return commit.getCommitId().name();
} catch (Exception e) {
throw new RepositoryStateException("Cant do commit...", e);
}
}
| public String commit() throws RepositoryStateException {
if (this.commiterEmail == null || this.commiterName == null || this.commitMessage == null
|| this.authorEmail == null || this.authorName == null) {
throw new RepositoryStateException("Requiring all fields to be filled, before executing a commit...");
}
this.log.debug("Doing commit for author [" + this.authorName + "; " + this.authorEmail + "] with message ["
+ this.commitMessage + "]...");
try {
this.log.trace("Writing index...");
this.index.write();
} catch (IOException e) {
throw new RepositoryStateException("Cant write index...", e);
}
IndexDiff diff;
try {
this.log.trace("Creating diff from index...");
diff = new IndexDiff(this.repository.mapTree(Constants.HEAD), this.repository.getIndex());
diff.diff();
} catch (IOException e) {
throw new RepositoryStateException("Cant write diff tree...", e);
}
HashSet<String> allFiles = new HashSet<String>();
allFiles.addAll(diff.getAdded());
allFiles.addAll(diff.getChanged());
allFiles.addAll(diff.getModified());
allFiles.addAll(diff.getRemoved());
this.log.debug("[" + allFiles.size() + "] files changed and to commit...");
try {
this.log.trace("creating repository tree...");
Tree projectTree = this.repository.mapTree(Constants.HEAD);
if (projectTree == null) {
projectTree = new Tree(this.repository);
}
this.log.trace("Iterating each files and write the trees for each of them...");
for (String string : allFiles) {
File actualFile = new File(this.repositoryPath.getAbsolutePath() + File.separator + string);
this.log.debug("Writing file [" + actualFile.getAbsolutePath() + "] to index...");
TreeEntry treeMember = projectTree.findBlobMember(string);
if (treeMember != null) {
treeMember.delete();
}
this.log.trace("Getting entry index...");
Entry idxEntry = this.index.getEntry(string);
if (diff.getMissing().contains(string)) {
this.log.debug("For any reason file is missing and situation have to be handeld...");
File thisFile = new File(this.repositoryPath, string);
if (!thisFile.isFile()) {
this.index.remove(this.repositoryPath, thisFile);
continue;
} else {
idxEntry.update(thisFile);
}
}
this.log.trace("Adding file to tree...");
if (idxEntry != null) {
projectTree.addFile(string);
TreeEntry newMember = projectTree.findBlobMember(string);
newMember.setId(idxEntry.getObjectId());
}
}
this.index.write();
this.log.debug("Writing tree with subtrees...");
writeTreeWithSubTrees(projectTree);
this.log.trace("Retrieving current ids for commit...");
ObjectId currentHeadId = this.repository.resolve(Constants.HEAD);
ObjectId[] parentIds;
if (currentHeadId != null) {
parentIds = new ObjectId[] { currentHeadId };
} else {
parentIds = new ObjectId[0];
}
this.log.trace("Creating commit object and prepare for commit...");
org.eclipse.jgit.lib.Commit commit = new org.eclipse.jgit.lib.Commit(this.repository, parentIds);
commit.setTree(projectTree);
commit.setMessage(this.commitMessage);
commit.setAuthor(new PersonIdent(this.authorName, this.authorEmail));
commit.setCommitter(new PersonIdent(this.commiterName, this.commiterEmail));
this.log.debug("Writing commit to disk...");
ObjectWriter writer = new ObjectWriter(this.repository);
commit.setCommitId(writer.writeCommit(commit));
RefUpdate ru = this.repository.updateRef(Constants.HEAD);
ru.setNewObjectId(commit.getCommitId());
ru.setRefLogMessage(this.commitMessage, true);
if (ru.forceUpdate() == RefUpdate.Result.LOCK_FAILURE) {
throw new RepositoryStateException("Failed to update " + ru.getName() + " to commit "
+ commit.getCommitId() + ".");
}
return commit.getCommitId().name();
} catch (Exception e) {
throw new RepositoryStateException("Cant do commit...", e);
}
}
|
diff --git a/extrabiomes/src/extrabiomes/module/summa/worldgen/MarshGenerator.java b/extrabiomes/src/extrabiomes/module/summa/worldgen/MarshGenerator.java
index fbc65971..ad9ba513 100644
--- a/extrabiomes/src/extrabiomes/module/summa/worldgen/MarshGenerator.java
+++ b/extrabiomes/src/extrabiomes/module/summa/worldgen/MarshGenerator.java
@@ -1,53 +1,53 @@
/**
* This work is licensed under the Creative Commons
* Attribution-ShareAlike 3.0 Unported License. To view a copy of this
* license, visit http://creativecommons.org/licenses/by-sa/3.0/.
*/
package extrabiomes.module.summa.worldgen;
import java.util.Random;
import net.minecraft.world.World;
import net.minecraft.world.biome.BiomeGenBase;
import net.minecraft.world.chunk.IChunkProvider;
import net.minecraft.world.gen.feature.WorldGenerator;
import cpw.mods.fml.common.IWorldGenerator;
import extrabiomes.api.BiomeManager;
@SuppressWarnings("deprecation")
public class MarshGenerator implements IWorldGenerator {
private static final WorldGenerator genMarsh = new WorldGenMarshGrass();
private static final WorldGenerator genDirtBed = new WorldGenMarshDirt();
@Override
public void generate(Random random, int chunkX, int chunkZ,
World world, IChunkProvider chunkGenerator,
IChunkProvider chunkProvider)
{
chunkX = chunkX << 4;
chunkZ = chunkZ << 4;
final BiomeGenBase biome = world.getBiomeGenForCoords(chunkX,
- chunkX);
+ chunkZ);
if (BiomeManager.marsh.isPresent()
&& biome == BiomeManager.marsh.get())
generateMarsh(random, chunkX, chunkZ, world);
}
private void generateMarsh(Random rand, int x, int z, World world) {
for (int i = 0; i < 127; i++) {
final int x1 = x + rand.nextInt(16) + 8;
final int z1 = z + rand.nextInt(16) + 8;
genMarsh.generate(world, rand, x1, 0, z1);
}
for (int i = 0; i < 256; i++) {
final int x1 = x + rand.nextInt(1) + 8;
final int z1 = z + rand.nextInt(1) + 8;
genDirtBed.generate(world, rand, x1, 0, z1);
}
}
}
| true | true | public void generate(Random random, int chunkX, int chunkZ,
World world, IChunkProvider chunkGenerator,
IChunkProvider chunkProvider)
{
chunkX = chunkX << 4;
chunkZ = chunkZ << 4;
final BiomeGenBase biome = world.getBiomeGenForCoords(chunkX,
chunkX);
if (BiomeManager.marsh.isPresent()
&& biome == BiomeManager.marsh.get())
generateMarsh(random, chunkX, chunkZ, world);
}
| public void generate(Random random, int chunkX, int chunkZ,
World world, IChunkProvider chunkGenerator,
IChunkProvider chunkProvider)
{
chunkX = chunkX << 4;
chunkZ = chunkZ << 4;
final BiomeGenBase biome = world.getBiomeGenForCoords(chunkX,
chunkZ);
if (BiomeManager.marsh.isPresent()
&& biome == BiomeManager.marsh.get())
generateMarsh(random, chunkX, chunkZ, world);
}
|
diff --git a/src/main/java/se/DMarby/Pets/EntityPigZombiePet.java b/src/main/java/se/DMarby/Pets/EntityPigZombiePet.java
index 0b837a6..4be9a6c 100644
--- a/src/main/java/se/DMarby/Pets/EntityPigZombiePet.java
+++ b/src/main/java/se/DMarby/Pets/EntityPigZombiePet.java
@@ -1,95 +1,95 @@
package se.DMarby.Pets;
import net.minecraft.server.v1_7_R1.*;
import org.bukkit.Bukkit;
import org.bukkit.craftbukkit.v1_7_R1.CraftServer;
import org.bukkit.craftbukkit.v1_7_R1.entity.CraftEntity;
import org.bukkit.craftbukkit.v1_7_R1.entity.CraftPigZombie;
import org.bukkit.craftbukkit.v1_7_R1.entity.CraftPlayer;
import org.bukkit.entity.Player;
import org.bukkit.entity.Zombie;
public class EntityPigZombiePet extends EntityPigZombie { // new AI
private final Player owner;
public EntityPigZombiePet(World world, Player owner) {
super(world);
this.owner = owner;
if (owner != null) {
Util.clearGoals(this.goalSelector, this.targetSelector);
setBaby(true);
}
}
public EntityPigZombiePet(World world) {
this(world, null);
}
private int distToOwner() {
EntityHuman handle = ((CraftPlayer) owner).getHandle();
return (int) (Math.pow(locX - handle.locX, 2) + Math.pow(locY - handle.locY, 2) + Math.pow(locZ
- handle.locZ, 2));
}
@Override
protected Entity findTarget() {
if(owner == null){
return super.findTarget();
}
return ((CraftPlayer) owner).getHandle();
}
@Override
public boolean damageEntity(DamageSource damagesource, float f) {
if(owner == null){
return super.damageEntity(damagesource, f);
}
return false;
}
- public void l_() {
- super.l_();
+ public void h() {
+ super.h();
if (owner == null)
return;
this.getNavigation().a(((CraftPlayer) owner).getHandle(), 0.3F);
if (distToOwner() > Util.MAX_DISTANCE)
this.getBukkitEntity().teleport(owner);
}
@Override
public CraftEntity getBukkitEntity() {
if (owner != null && bukkitEntity == null)
bukkitEntity = new BukkitPigZombiePet(this);
return super.getBukkitEntity();
}
public static class BukkitPigZombiePet extends CraftPigZombie implements PetEntity {
private final Player owner;
public BukkitPigZombiePet(EntityPigZombiePet entity) {
super((CraftServer) Bukkit.getServer(), entity);
this.owner = entity.owner;
}
@Override
public Zombie getBukkitEntity() {
return this;
}
@Override
public Player getOwner() {
return owner;
}
@Override
public void upgrade() {
}
@Override
public void setLevel(int level) {
// setSize(level);
}
}
}
| true | true | public void l_() {
super.l_();
if (owner == null)
return;
this.getNavigation().a(((CraftPlayer) owner).getHandle(), 0.3F);
if (distToOwner() > Util.MAX_DISTANCE)
this.getBukkitEntity().teleport(owner);
}
| public void h() {
super.h();
if (owner == null)
return;
this.getNavigation().a(((CraftPlayer) owner).getHandle(), 0.3F);
if (distToOwner() > Util.MAX_DISTANCE)
this.getBukkitEntity().teleport(owner);
}
|
diff --git a/motech-server-core/src/main/java/org/motechproject/server/ws/WebServiceModelConverterImpl.java b/motech-server-core/src/main/java/org/motechproject/server/ws/WebServiceModelConverterImpl.java
index 3cbe2f66..173e584e 100644
--- a/motech-server-core/src/main/java/org/motechproject/server/ws/WebServiceModelConverterImpl.java
+++ b/motech-server-core/src/main/java/org/motechproject/server/ws/WebServiceModelConverterImpl.java
@@ -1,352 +1,352 @@
/**
* MOTECH PLATFORM OPENSOURCE LICENSE AGREEMENT
*
* Copyright (c) 2010-11 The Trustees of Columbia University in the City of
* New York and Grameen Foundation USA. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of Grameen Foundation USA, Columbia University, or
* their respective contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY GRAMEEN FOUNDATION USA, COLUMBIA UNIVERSITY
* AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRAMEEN FOUNDATION
* USA, COLUMBIA UNIVERSITY OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.motechproject.server.ws;
import org.motechproject.server.model.Community;
import org.motechproject.server.model.ExpectedEncounter;
import org.motechproject.server.model.ExpectedObs;
import org.motechproject.server.model.PatientUpdates;
import org.motechproject.server.svc.RegistrarBean;
import org.motechproject.server.util.GenderTypeConverter;
import org.motechproject.server.util.MotechConstants;
import org.motechproject.ws.Care;
import org.motechproject.ws.ContactNumberType;
import org.motechproject.ws.Patient;
import org.openmrs.*;
import java.util.*;
public class WebServiceModelConverterImpl implements WebServiceModelConverter {
RegistrarBean registrarBean;
public void setRegistrarBean(RegistrarBean registrarBean) {
this.registrarBean = registrarBean;
}
public Patient patientToWebService(org.openmrs.Patient patient,
boolean minimal) {
if (patient == null) {
return null;
}
Patient wsPatient = new Patient();
wsPatient.setPreferredName(patient.getGivenName());
wsPatient.setLastName(patient.getFamilyName());
wsPatient.setBirthDate(patient.getBirthdate());
wsPatient.setSex(GenderTypeConverter
.valueOfOpenMRS(patient.getGender()));
Community community = registrarBean.getCommunityByPatient(patient);
if (community != null) {
wsPatient.setCommunity(community.getName());
}
PatientIdentifier patientId = patient
.getPatientIdentifier(MotechConstants.PATIENT_IDENTIFIER_MOTECH_ID);
if (patientId != null) {
wsPatient.setMotechId(patientId.getIdentifier());
}
if (!minimal) {
for (PersonName name : patient.getNames()) {
if (!name.isPreferred() && name.getGivenName() != null) {
wsPatient.setFirstName(name.getGivenName());
break;
}
}
wsPatient.setAge(patient.getAge());
PersonAttribute phoneNumberAttr = patient
.getAttribute(MotechConstants.PERSON_ATTRIBUTE_PHONE_NUMBER);
if (phoneNumberAttr != null) {
wsPatient.setPhoneNumber(phoneNumberAttr.getValue());
}
PersonAttribute contactNumberType = patient
.getAttribute(MotechConstants.PERSON_ATTRIBUTE_PHONE_TYPE);
- if (phoneNumberAttr != null) {
+ if (contactNumberType != null) {
wsPatient.setContactNumberType(ContactNumberType.valueOf(contactNumberType.getValue()));
}
wsPatient.setEstimateDueDate(registrarBean
.getActivePregnancyDueDate(patient.getPatientId()));
}
return wsPatient;
}
public Patient[] patientToWebService(List<org.openmrs.Patient> patients,
boolean minimal) {
List<Patient> wsPatients = new ArrayList<Patient>();
for (org.openmrs.Patient patient : patients) {
wsPatients.add(patientToWebService(patient, minimal));
}
return wsPatients.toArray(new Patient[wsPatients.size()]);
}
public Patient[] deliveriesToWebServicePatients(List<Encounter> deliveries) {
List<Patient> wsPatients = new ArrayList<Patient>();
for (Encounter deliveryEncounter : deliveries) {
org.openmrs.Patient patient = deliveryEncounter.getPatient();
Patient wsPatient = patientToWebService(patient, true);
wsPatient.setDeliveryDate(deliveryEncounter.getEncounterDatetime());
wsPatients.add(wsPatient);
}
return wsPatients.toArray(new Patient[wsPatients.size()]);
}
public Patient[] dueDatesToWebServicePatients(List<Obs> dueDates) {
List<Patient> wsPatients = new ArrayList<Patient>();
for (Obs dueDate : dueDates) {
Integer patientId = dueDate.getPersonId();
org.openmrs.Patient patient = registrarBean
.getPatientById(patientId);
if (patient != null) {
Patient wsPatient = patientToWebService(patient, true);
wsPatient.setEstimateDueDate(dueDate.getValueDatetime());
wsPatients.add(wsPatient);
}
}
return wsPatients.toArray(new Patient[wsPatients.size()]);
}
public Care[] upcomingObsToWebServiceCares(List<ExpectedObs> upcomingObs) {
List<Care> cares = new ArrayList<Care>();
for (ExpectedObs expectedObs : upcomingObs) {
Care care = new Care();
care.setName(expectedObs.getName());
care.setDate(expectedObs.getDueObsDatetime());
cares.add(care);
}
return cares.toArray(new Care[cares.size()]);
}
public Care[] upcomingEncountersToWebServiceCares(
List<ExpectedEncounter> upcomingEncounters) {
List<Care> cares = new ArrayList<Care>();
for (ExpectedEncounter expectedEncounter : upcomingEncounters) {
Care care = new Care();
care.setName(expectedEncounter.getName());
care.setDate(expectedEncounter.getDueEncounterDatetime());
cares.add(care);
}
return cares.toArray(new Care[cares.size()]);
}
public Care[] upcomingToWebServiceCares(
List<ExpectedEncounter> upcomingEncounters,
List<ExpectedObs> upcomingObs, boolean includePatient) {
List<Care> cares = new ArrayList<Care>();
for (ExpectedEncounter expectedEncounter : upcomingEncounters) {
Care care = new Care();
care.setName(expectedEncounter.getName());
care.setDate(expectedEncounter.getDueEncounterDatetime());
if (includePatient) {
Patient patient = patientToWebService(expectedEncounter
.getPatient(), true);
care.setPatients(new Patient[] { patient });
}
cares.add(care);
}
for (ExpectedObs expectedObs : upcomingObs) {
Care care = new Care();
care.setName(expectedObs.getName());
care.setDate(expectedObs.getDueObsDatetime());
if (includePatient) {
Patient patient = patientToWebService(expectedObs.getPatient(),
true);
care.setPatients(new Patient[] { patient });
}
cares.add(care);
}
Collections.sort(cares, new CareDateComparator());
return cares.toArray(new Care[cares.size()]);
}
public Care[] defaultedObsToWebServiceCares(List<ExpectedObs> defaultedObs) {
List<Care> cares = new ArrayList<Care>();
Map<String, List<org.openmrs.Patient>> carePatientMap = new HashMap<String, List<org.openmrs.Patient>>();
for (ExpectedObs expectedObs : defaultedObs) {
List<org.openmrs.Patient> patients = carePatientMap.get(expectedObs
.getName());
if (patients == null) {
patients = new ArrayList<org.openmrs.Patient>();
}
patients.add(expectedObs.getPatient());
carePatientMap.put(expectedObs.getName(), patients);
}
for (Map.Entry<String, List<org.openmrs.Patient>> entry : carePatientMap
.entrySet()) {
Care care = new Care();
care.setName(entry.getKey());
Patient[] patients = patientToWebService(entry.getValue(), true);
care.setPatients(patients);
cares.add(care);
}
Collections.sort(cares, new CareDateComparator(true));
return cares.toArray(new Care[cares.size()]);
}
public Care[] defaultedEncountersToWebServiceCares(
List<ExpectedEncounter> defaultedEncounters) {
List<Care> cares = new ArrayList<Care>();
Map<String, List<org.openmrs.Patient>> carePatientMap = new HashMap<String, List<org.openmrs.Patient>>();
for (ExpectedEncounter expectedEncounter : defaultedEncounters) {
List<org.openmrs.Patient> patients = carePatientMap
.get(expectedEncounter.getName());
if (patients == null) {
patients = new ArrayList<org.openmrs.Patient>();
}
patients.add(expectedEncounter.getPatient());
carePatientMap.put(expectedEncounter.getName(), patients);
}
for (Map.Entry<String, List<org.openmrs.Patient>> entry : carePatientMap
.entrySet()) {
Care care = new Care();
care.setName(entry.getKey());
Patient[] patients = patientToWebService(entry.getValue(), true);
care.setPatients(patients);
cares.add(care);
}
Collections.sort(cares, new CareDateComparator(true));
return cares.toArray(new Care[cares.size()]);
}
public Care[] defaultedToWebServiceCares(
List<ExpectedEncounter> defaultedEncounters,
List<ExpectedObs> defaultedObs) {
List<Care> cares = new ArrayList<Care>();
Map<String, List<org.openmrs.Patient>> carePatientMap = new HashMap<String, List<org.openmrs.Patient>>();
for (ExpectedEncounter expectedEncounter : defaultedEncounters) {
List<org.openmrs.Patient> patients = carePatientMap
.get(expectedEncounter.getName());
if (patients == null) {
patients = new ArrayList<org.openmrs.Patient>();
}
patients.add(expectedEncounter.getPatient());
carePatientMap.put(expectedEncounter.getName(), patients);
}
for (ExpectedObs expectedObs : defaultedObs) {
List<org.openmrs.Patient> patients = carePatientMap.get(expectedObs
.getName());
if (patients == null) {
patients = new ArrayList<org.openmrs.Patient>();
}
patients.add(expectedObs.getPatient());
carePatientMap.put(expectedObs.getName(), patients);
}
for (Map.Entry<String, List<org.openmrs.Patient>> entry : carePatientMap
.entrySet()) {
Care care = new Care();
care.setName(entry.getKey());
Patient[] patients = patientToWebService(entry.getValue(), true);
care.setPatients(patients);
cares.add(care);
}
Collections.sort(cares, new CareDateComparator(true));
return cares.toArray(new Care[cares.size()]);
}
public Patient upcomingObsToWebServicePatient(ExpectedObs upcomingObs) {
org.openmrs.Patient patient = upcomingObs.getPatient();
Patient wsPatient = patientToWebService(patient, true);
Care care = new Care();
care.setName(upcomingObs.getName());
care.setDate(upcomingObs.getDueObsDatetime());
wsPatient.setCares(new Care[] { care });
return wsPatient;
}
public Patient upcomingEncounterToWebServicePatient(
ExpectedEncounter upcomingEncounter) {
org.openmrs.Patient patient = upcomingEncounter.getPatient();
Patient wsPatient = patientToWebService(patient, true);
Care care = new Care();
care.setName(upcomingEncounter.getName());
care.setDate(upcomingEncounter.getDueEncounterDatetime());
wsPatient.setCares(new Care[] { care });
return wsPatient;
}
public Patient patientToWebService(org.openmrs.Patient patient, boolean minimal, PatientUpdates patientUpdates) {
Patient wsPatient = patientToWebService(patient, minimal);
wsPatient.setContactNumberType(patientUpdates.contactNumberType());
wsPatient.setPhoneNumber(patientUpdates.phoneNumber());
return wsPatient;
}
}
| true | true | public Patient patientToWebService(org.openmrs.Patient patient,
boolean minimal) {
if (patient == null) {
return null;
}
Patient wsPatient = new Patient();
wsPatient.setPreferredName(patient.getGivenName());
wsPatient.setLastName(patient.getFamilyName());
wsPatient.setBirthDate(patient.getBirthdate());
wsPatient.setSex(GenderTypeConverter
.valueOfOpenMRS(patient.getGender()));
Community community = registrarBean.getCommunityByPatient(patient);
if (community != null) {
wsPatient.setCommunity(community.getName());
}
PatientIdentifier patientId = patient
.getPatientIdentifier(MotechConstants.PATIENT_IDENTIFIER_MOTECH_ID);
if (patientId != null) {
wsPatient.setMotechId(patientId.getIdentifier());
}
if (!minimal) {
for (PersonName name : patient.getNames()) {
if (!name.isPreferred() && name.getGivenName() != null) {
wsPatient.setFirstName(name.getGivenName());
break;
}
}
wsPatient.setAge(patient.getAge());
PersonAttribute phoneNumberAttr = patient
.getAttribute(MotechConstants.PERSON_ATTRIBUTE_PHONE_NUMBER);
if (phoneNumberAttr != null) {
wsPatient.setPhoneNumber(phoneNumberAttr.getValue());
}
PersonAttribute contactNumberType = patient
.getAttribute(MotechConstants.PERSON_ATTRIBUTE_PHONE_TYPE);
if (phoneNumberAttr != null) {
wsPatient.setContactNumberType(ContactNumberType.valueOf(contactNumberType.getValue()));
}
wsPatient.setEstimateDueDate(registrarBean
.getActivePregnancyDueDate(patient.getPatientId()));
}
return wsPatient;
}
| public Patient patientToWebService(org.openmrs.Patient patient,
boolean minimal) {
if (patient == null) {
return null;
}
Patient wsPatient = new Patient();
wsPatient.setPreferredName(patient.getGivenName());
wsPatient.setLastName(patient.getFamilyName());
wsPatient.setBirthDate(patient.getBirthdate());
wsPatient.setSex(GenderTypeConverter
.valueOfOpenMRS(patient.getGender()));
Community community = registrarBean.getCommunityByPatient(patient);
if (community != null) {
wsPatient.setCommunity(community.getName());
}
PatientIdentifier patientId = patient
.getPatientIdentifier(MotechConstants.PATIENT_IDENTIFIER_MOTECH_ID);
if (patientId != null) {
wsPatient.setMotechId(patientId.getIdentifier());
}
if (!minimal) {
for (PersonName name : patient.getNames()) {
if (!name.isPreferred() && name.getGivenName() != null) {
wsPatient.setFirstName(name.getGivenName());
break;
}
}
wsPatient.setAge(patient.getAge());
PersonAttribute phoneNumberAttr = patient
.getAttribute(MotechConstants.PERSON_ATTRIBUTE_PHONE_NUMBER);
if (phoneNumberAttr != null) {
wsPatient.setPhoneNumber(phoneNumberAttr.getValue());
}
PersonAttribute contactNumberType = patient
.getAttribute(MotechConstants.PERSON_ATTRIBUTE_PHONE_TYPE);
if (contactNumberType != null) {
wsPatient.setContactNumberType(ContactNumberType.valueOf(contactNumberType.getValue()));
}
wsPatient.setEstimateDueDate(registrarBean
.getActivePregnancyDueDate(patient.getPatientId()));
}
return wsPatient;
}
|
diff --git a/src/AudioTest.java b/src/AudioTest.java
index dc9d021..282e721 100644
--- a/src/AudioTest.java
+++ b/src/AudioTest.java
@@ -1,65 +1,66 @@
import org.lwjgl.LWJGLException;
import org.lwjgl.input.Keyboard;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.util.Scanner;
import org.lwjgl.BufferUtils;
import org.lwjgl.LWJGLException;
import org.lwjgl.openal.AL;
import org.lwjgl.openal.AL10;
import org.lwjgl.util.WaveData;
import audio.Audio;
import audio.OggFloatStream;
import audio.Sound;
import org.newdawn.slick.util.Log;
public class AudioTest {
public static void main(String[] args) {
new AudioTest().execute();
}
public void execute() {
try {
Display.setDisplayMode(new DisplayMode(800,600));
Display.create();
} catch (LWJGLException e) {
e.printStackTrace();
System.exit(0);
}
Audio audio = new Audio();
audio.init();
// WaveData waveFile;
// try {
// waveFile = WaveData.create(new FileInputStream("music_lead2.wav"));
// System.out.println(waveFile.data.capacity()/4);
// waveFile.dispose();
// } catch (FileNotFoundException e) {
// e.printStackTrace();
// }
Sound sound = audio.newSoundStream("music1_lead2.ogg");
sound.setLooping(true);
- //sound.play();
+ sound.seek(2000000);
+ sound.play();
Sound s = audio.newSound("menumove.ogg");
while (!Display.isCloseRequested()) {
s.play();
audio.update(0.0);
- Display.sync(10);
+ Display.sync(30);
Display.update();
}
audio.finish();
Display.destroy();
}
}
| false | true | public void execute() {
try {
Display.setDisplayMode(new DisplayMode(800,600));
Display.create();
} catch (LWJGLException e) {
e.printStackTrace();
System.exit(0);
}
Audio audio = new Audio();
audio.init();
// WaveData waveFile;
// try {
// waveFile = WaveData.create(new FileInputStream("music_lead2.wav"));
// System.out.println(waveFile.data.capacity()/4);
// waveFile.dispose();
// } catch (FileNotFoundException e) {
// e.printStackTrace();
// }
Sound sound = audio.newSoundStream("music1_lead2.ogg");
sound.setLooping(true);
//sound.play();
Sound s = audio.newSound("menumove.ogg");
while (!Display.isCloseRequested()) {
s.play();
audio.update(0.0);
Display.sync(10);
Display.update();
}
audio.finish();
Display.destroy();
}
| public void execute() {
try {
Display.setDisplayMode(new DisplayMode(800,600));
Display.create();
} catch (LWJGLException e) {
e.printStackTrace();
System.exit(0);
}
Audio audio = new Audio();
audio.init();
// WaveData waveFile;
// try {
// waveFile = WaveData.create(new FileInputStream("music_lead2.wav"));
// System.out.println(waveFile.data.capacity()/4);
// waveFile.dispose();
// } catch (FileNotFoundException e) {
// e.printStackTrace();
// }
Sound sound = audio.newSoundStream("music1_lead2.ogg");
sound.setLooping(true);
sound.seek(2000000);
sound.play();
Sound s = audio.newSound("menumove.ogg");
while (!Display.isCloseRequested()) {
s.play();
audio.update(0.0);
Display.sync(30);
Display.update();
}
audio.finish();
Display.destroy();
}
|
diff --git a/src/com/android/packageinstaller/InstallAppProgress.java b/src/com/android/packageinstaller/InstallAppProgress.java
index 71c792e..b690f8a 100755
--- a/src/com/android/packageinstaller/InstallAppProgress.java
+++ b/src/com/android/packageinstaller/InstallAppProgress.java
@@ -1,300 +1,301 @@
/*
**
** Copyright 2007, The Android Open Source Project
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.android.packageinstaller;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.IPackageInstallObserver;
import android.content.pm.ManifestDigest;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.content.pm.VerificationParams;
import android.graphics.drawable.LevelListDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import java.io.File;
import java.util.List;
/**
* This activity corresponds to a download progress screen that is displayed
* when the user tries
* to install an application bundled as an apk file. The result of the application install
* is indicated in the result code that gets set to the corresponding installation status
* codes defined in PackageManager. If the package being installed already exists,
* the existing package is replaced with the new one.
*/
public class InstallAppProgress extends Activity implements View.OnClickListener, OnCancelListener {
private final String TAG="InstallAppProgress";
private boolean localLOGV = false;
static final String EXTRA_MANIFEST_DIGEST =
"com.android.packageinstaller.extras.manifest_digest";
private ApplicationInfo mAppInfo;
private Uri mPackageURI;
private ProgressBar mProgressBar;
private View mOkPanel;
private TextView mStatusTextView;
private TextView mExplanationTextView;
private Button mDoneButton;
private Button mLaunchButton;
private final int INSTALL_COMPLETE = 1;
private Intent mLaunchIntent;
private static final int DLG_OUT_OF_SPACE = 1;
private CharSequence mLabel;
private Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case INSTALL_COMPLETE:
if (getIntent().getBooleanExtra(Intent.EXTRA_RETURN_RESULT, false)) {
Intent result = new Intent();
result.putExtra(Intent.EXTRA_INSTALL_RESULT, msg.arg1);
setResult(msg.arg1 == PackageManager.INSTALL_SUCCEEDED
? Activity.RESULT_OK : Activity.RESULT_FIRST_USER,
result);
finish();
return;
}
// Update the status text
mProgressBar.setVisibility(View.INVISIBLE);
// Show the ok button
int centerTextLabel;
int centerExplanationLabel = -1;
LevelListDrawable centerTextDrawable = (LevelListDrawable) getResources()
.getDrawable(R.drawable.ic_result_status);
if (msg.arg1 == PackageManager.INSTALL_SUCCEEDED) {
mLaunchButton.setVisibility(View.VISIBLE);
centerTextDrawable.setLevel(0);
centerTextLabel = R.string.install_done;
// Enable or disable launch button
mLaunchIntent = getPackageManager().getLaunchIntentForPackage(
mAppInfo.packageName);
boolean enabled = false;
if(mLaunchIntent != null) {
List<ResolveInfo> list = getPackageManager().
queryIntentActivities(mLaunchIntent, 0);
if (list != null && list.size() > 0) {
enabled = true;
}
}
if (enabled) {
mLaunchButton.setOnClickListener(InstallAppProgress.this);
} else {
mLaunchButton.setEnabled(false);
}
} else if (msg.arg1 == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
showDialogInner(DLG_OUT_OF_SPACE);
return;
} else {
// Generic error handling for all other error codes.
centerTextDrawable.setLevel(1);
centerExplanationLabel = getExplanationFromErrorCode(msg.arg1);
centerTextLabel = R.string.install_failed;
mLaunchButton.setVisibility(View.INVISIBLE);
}
if (centerTextDrawable != null) {
centerTextDrawable.setBounds(0, 0,
centerTextDrawable.getIntrinsicWidth(),
centerTextDrawable.getIntrinsicHeight());
- mStatusTextView.setCompoundDrawables(centerTextDrawable, null, null, null);
+ mStatusTextView.setCompoundDrawablesRelative(centerTextDrawable, null,
+ null, null);
}
mStatusTextView.setText(centerTextLabel);
if (centerExplanationLabel != -1) {
mExplanationTextView.setText(centerExplanationLabel);
mExplanationTextView.setVisibility(View.VISIBLE);
} else {
mExplanationTextView.setVisibility(View.GONE);
}
mDoneButton.setOnClickListener(InstallAppProgress.this);
mOkPanel.setVisibility(View.VISIBLE);
break;
default:
break;
}
}
};
private int getExplanationFromErrorCode(int errCode) {
Log.d(TAG, "Installation error code: " + errCode);
switch (errCode) {
case PackageManager.INSTALL_FAILED_INVALID_APK:
return R.string.install_failed_invalid_apk;
case PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES:
return R.string.install_failed_inconsistent_certificates;
case PackageManager.INSTALL_FAILED_OLDER_SDK:
return R.string.install_failed_older_sdk;
case PackageManager.INSTALL_FAILED_CPU_ABI_INCOMPATIBLE:
return R.string.install_failed_cpu_abi_incompatible;
default:
return -1;
}
}
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
Intent intent = getIntent();
mAppInfo = intent.getParcelableExtra(PackageUtil.INTENT_ATTR_APPLICATION_INFO);
mPackageURI = intent.getData();
final String scheme = mPackageURI.getScheme();
if (scheme != null && !"file".equals(scheme) && !"package".equals(scheme)) {
throw new IllegalArgumentException("unexpected scheme " + scheme);
}
initView();
}
@Override
public Dialog onCreateDialog(int id, Bundle bundle) {
switch (id) {
case DLG_OUT_OF_SPACE:
String dlgText = getString(R.string.out_of_space_dlg_text, mLabel);
return new AlertDialog.Builder(this)
.setTitle(R.string.out_of_space_dlg_title)
.setMessage(dlgText)
.setPositiveButton(R.string.manage_applications, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//launch manage applications
Intent intent = new Intent("android.intent.action.MANAGE_PACKAGE_STORAGE");
startActivity(intent);
finish();
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Log.i(TAG, "Canceling installation");
finish();
}
})
.setOnCancelListener(this)
.create();
}
return null;
}
private void showDialogInner(int id) {
removeDialog(id);
showDialog(id);
}
class PackageInstallObserver extends IPackageInstallObserver.Stub {
public void packageInstalled(String packageName, int returnCode) {
Message msg = mHandler.obtainMessage(INSTALL_COMPLETE);
msg.arg1 = returnCode;
mHandler.sendMessage(msg);
}
}
public void initView() {
setContentView(R.layout.op_progress);
int installFlags = 0;
PackageManager pm = getPackageManager();
try {
PackageInfo pi = pm.getPackageInfo(mAppInfo.packageName,
PackageManager.GET_UNINSTALLED_PACKAGES);
if(pi != null) {
installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
}
} catch (NameNotFoundException e) {
}
if((installFlags & PackageManager.INSTALL_REPLACE_EXISTING )!= 0) {
Log.w(TAG, "Replacing package:" + mAppInfo.packageName);
}
final PackageUtil.AppSnippet as;
if ("package".equals(mPackageURI.getScheme())) {
as = new PackageUtil.AppSnippet(pm.getApplicationLabel(mAppInfo),
pm.getApplicationIcon(mAppInfo));
} else {
final File sourceFile = new File(mPackageURI.getPath());
as = PackageUtil.getAppSnippet(this, mAppInfo, sourceFile);
}
mLabel = as.label;
PackageUtil.initSnippetForNewApp(this, as, R.id.app_snippet);
mStatusTextView = (TextView)findViewById(R.id.center_text);
mStatusTextView.setText(R.string.installing);
mExplanationTextView = (TextView) findViewById(R.id.center_explanation);
mProgressBar = (ProgressBar) findViewById(R.id.progress_bar);
mProgressBar.setIndeterminate(true);
// Hide button till progress is being displayed
mOkPanel = (View)findViewById(R.id.buttons_panel);
mDoneButton = (Button)findViewById(R.id.done_button);
mLaunchButton = (Button)findViewById(R.id.launch_button);
mOkPanel.setVisibility(View.INVISIBLE);
String installerPackageName = getIntent().getStringExtra(
Intent.EXTRA_INSTALLER_PACKAGE_NAME);
Uri originatingURI = getIntent().getParcelableExtra(Intent.EXTRA_ORIGINATING_URI);
Uri referrer = getIntent().getParcelableExtra(Intent.EXTRA_REFERRER);
int originatingUid = getIntent().getIntExtra(Intent.EXTRA_ORIGINATING_UID,
VerificationParams.NO_UID);
ManifestDigest manifestDigest = getIntent().getParcelableExtra(EXTRA_MANIFEST_DIGEST);
VerificationParams verificationParams = new VerificationParams(null, originatingURI,
referrer, originatingUid, manifestDigest);
PackageInstallObserver observer = new PackageInstallObserver();
if ("package".equals(mPackageURI.getScheme())) {
try {
pm.installExistingPackage(mAppInfo.packageName);
observer.packageInstalled(mAppInfo.packageName,
PackageManager.INSTALL_SUCCEEDED);
} catch (PackageManager.NameNotFoundException e) {
observer.packageInstalled(mAppInfo.packageName,
PackageManager.INSTALL_FAILED_INVALID_APK);
}
} else {
pm.installPackageWithVerificationAndEncryption(mPackageURI, observer, installFlags,
installerPackageName, verificationParams, null);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
}
public void onClick(View v) {
if(v == mDoneButton) {
if (mAppInfo.packageName != null) {
Log.i(TAG, "Finished installing "+mAppInfo.packageName);
}
finish();
} else if(v == mLaunchButton) {
startActivity(mLaunchIntent);
finish();
}
}
public void onCancel(DialogInterface dialog) {
finish();
}
}
| true | true | public void handleMessage(Message msg) {
switch (msg.what) {
case INSTALL_COMPLETE:
if (getIntent().getBooleanExtra(Intent.EXTRA_RETURN_RESULT, false)) {
Intent result = new Intent();
result.putExtra(Intent.EXTRA_INSTALL_RESULT, msg.arg1);
setResult(msg.arg1 == PackageManager.INSTALL_SUCCEEDED
? Activity.RESULT_OK : Activity.RESULT_FIRST_USER,
result);
finish();
return;
}
// Update the status text
mProgressBar.setVisibility(View.INVISIBLE);
// Show the ok button
int centerTextLabel;
int centerExplanationLabel = -1;
LevelListDrawable centerTextDrawable = (LevelListDrawable) getResources()
.getDrawable(R.drawable.ic_result_status);
if (msg.arg1 == PackageManager.INSTALL_SUCCEEDED) {
mLaunchButton.setVisibility(View.VISIBLE);
centerTextDrawable.setLevel(0);
centerTextLabel = R.string.install_done;
// Enable or disable launch button
mLaunchIntent = getPackageManager().getLaunchIntentForPackage(
mAppInfo.packageName);
boolean enabled = false;
if(mLaunchIntent != null) {
List<ResolveInfo> list = getPackageManager().
queryIntentActivities(mLaunchIntent, 0);
if (list != null && list.size() > 0) {
enabled = true;
}
}
if (enabled) {
mLaunchButton.setOnClickListener(InstallAppProgress.this);
} else {
mLaunchButton.setEnabled(false);
}
} else if (msg.arg1 == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
showDialogInner(DLG_OUT_OF_SPACE);
return;
} else {
// Generic error handling for all other error codes.
centerTextDrawable.setLevel(1);
centerExplanationLabel = getExplanationFromErrorCode(msg.arg1);
centerTextLabel = R.string.install_failed;
mLaunchButton.setVisibility(View.INVISIBLE);
}
if (centerTextDrawable != null) {
centerTextDrawable.setBounds(0, 0,
centerTextDrawable.getIntrinsicWidth(),
centerTextDrawable.getIntrinsicHeight());
mStatusTextView.setCompoundDrawables(centerTextDrawable, null, null, null);
}
mStatusTextView.setText(centerTextLabel);
if (centerExplanationLabel != -1) {
mExplanationTextView.setText(centerExplanationLabel);
mExplanationTextView.setVisibility(View.VISIBLE);
} else {
mExplanationTextView.setVisibility(View.GONE);
}
mDoneButton.setOnClickListener(InstallAppProgress.this);
mOkPanel.setVisibility(View.VISIBLE);
break;
default:
break;
}
}
| public void handleMessage(Message msg) {
switch (msg.what) {
case INSTALL_COMPLETE:
if (getIntent().getBooleanExtra(Intent.EXTRA_RETURN_RESULT, false)) {
Intent result = new Intent();
result.putExtra(Intent.EXTRA_INSTALL_RESULT, msg.arg1);
setResult(msg.arg1 == PackageManager.INSTALL_SUCCEEDED
? Activity.RESULT_OK : Activity.RESULT_FIRST_USER,
result);
finish();
return;
}
// Update the status text
mProgressBar.setVisibility(View.INVISIBLE);
// Show the ok button
int centerTextLabel;
int centerExplanationLabel = -1;
LevelListDrawable centerTextDrawable = (LevelListDrawable) getResources()
.getDrawable(R.drawable.ic_result_status);
if (msg.arg1 == PackageManager.INSTALL_SUCCEEDED) {
mLaunchButton.setVisibility(View.VISIBLE);
centerTextDrawable.setLevel(0);
centerTextLabel = R.string.install_done;
// Enable or disable launch button
mLaunchIntent = getPackageManager().getLaunchIntentForPackage(
mAppInfo.packageName);
boolean enabled = false;
if(mLaunchIntent != null) {
List<ResolveInfo> list = getPackageManager().
queryIntentActivities(mLaunchIntent, 0);
if (list != null && list.size() > 0) {
enabled = true;
}
}
if (enabled) {
mLaunchButton.setOnClickListener(InstallAppProgress.this);
} else {
mLaunchButton.setEnabled(false);
}
} else if (msg.arg1 == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
showDialogInner(DLG_OUT_OF_SPACE);
return;
} else {
// Generic error handling for all other error codes.
centerTextDrawable.setLevel(1);
centerExplanationLabel = getExplanationFromErrorCode(msg.arg1);
centerTextLabel = R.string.install_failed;
mLaunchButton.setVisibility(View.INVISIBLE);
}
if (centerTextDrawable != null) {
centerTextDrawable.setBounds(0, 0,
centerTextDrawable.getIntrinsicWidth(),
centerTextDrawable.getIntrinsicHeight());
mStatusTextView.setCompoundDrawablesRelative(centerTextDrawable, null,
null, null);
}
mStatusTextView.setText(centerTextLabel);
if (centerExplanationLabel != -1) {
mExplanationTextView.setText(centerExplanationLabel);
mExplanationTextView.setVisibility(View.VISIBLE);
} else {
mExplanationTextView.setVisibility(View.GONE);
}
mDoneButton.setOnClickListener(InstallAppProgress.this);
mOkPanel.setVisibility(View.VISIBLE);
break;
default:
break;
}
}
|
diff --git a/main/src/main/java/com/chinarewards/qqgbvpn/main/impl/DefaultPosServer.java b/main/src/main/java/com/chinarewards/qqgbvpn/main/impl/DefaultPosServer.java
index 021f0578..69002110 100644
--- a/main/src/main/java/com/chinarewards/qqgbvpn/main/impl/DefaultPosServer.java
+++ b/main/src/main/java/com/chinarewards/qqgbvpn/main/impl/DefaultPosServer.java
@@ -1,299 +1,299 @@
/**
*
*/
package com.chinarewards.qqgbvpn.main.impl;
import java.io.IOException;
import java.net.InetSocketAddress;
import org.apache.commons.configuration.Configuration;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.logging.LogLevel;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.chinarewards.qqgbvpn.main.ConfigKey;
import com.chinarewards.qqgbvpn.main.PosServer;
import com.chinarewards.qqgbvpn.main.PosServerException;
import com.chinarewards.qqgbvpn.main.SessionStore;
import com.chinarewards.qqgbvpn.main.protocol.CmdCodecFactory;
import com.chinarewards.qqgbvpn.main.protocol.CmdMapping;
import com.chinarewards.qqgbvpn.main.protocol.CodecMappingConfigBuilder;
import com.chinarewards.qqgbvpn.main.protocol.ServiceDispatcher;
import com.chinarewards.qqgbvpn.main.protocol.ServiceHandlerObjectFactory;
import com.chinarewards.qqgbvpn.main.protocol.ServiceMapping;
import com.chinarewards.qqgbvpn.main.protocol.SimpleCmdCodecFactory;
import com.chinarewards.qqgbvpn.main.protocol.filter.BodyMessageFilter;
import com.chinarewards.qqgbvpn.main.protocol.filter.ErrorConnectionKillerFilter;
import com.chinarewards.qqgbvpn.main.protocol.filter.IdleConnectionKillerFilter;
import com.chinarewards.qqgbvpn.main.protocol.filter.LoginFilter;
import com.chinarewards.qqgbvpn.main.protocol.filter.SessionKeyMessageFilter;
import com.chinarewards.qqgbvpn.main.protocol.handler.ServerSessionHandler;
import com.chinarewards.qqgbvpn.main.protocol.socket.mina.codec.MessageCoderFactory;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.persist.PersistService;
/**
* Concrete implementation of <code>PosServer</code>.
*
* @author Cyril
* @since 0.1.0
*/
public class DefaultPosServer implements PosServer {
/**
* Default timeout, in seconds, which the server will disconnect a client.
*/
public static final int DEFAULT_SERVER_CLIENTMAXIDLETIME = 1800;
protected final Configuration configuration;
protected final Injector injector;
protected Logger log = LoggerFactory.getLogger(PosServer.class);
protected ServiceMapping mapping;
protected CmdMapping cmdMapping;
protected CmdCodecFactory cmdCodecFactory;
protected final ServiceHandlerObjectFactory serviceHandlerObjectFactory;
protected final ServiceDispatcher serviceDispatcher;
/**
* socket server address
*/
InetSocketAddress serverAddr;
/**
* The configured port to use.
*/
protected int port;
/**
* Whether the PersistService of Guice has been initialized, i.e. the
* .start() method has been called. We need to remember this state since it
* cannot be called twice (strange!).
*/
protected boolean isPersistServiceInited = false;
/**
* acceptor
*/
NioSocketAcceptor acceptor;
boolean persistenceServiceInited = false;
@Inject
public DefaultPosServer(Configuration configuration, Injector injector,
ServiceDispatcher serviceDispatcher,
ServiceHandlerObjectFactory serviceHandlerObjectFactory) {
this.configuration = configuration;
this.injector = injector;
this.serviceDispatcher = serviceDispatcher;
this.serviceHandlerObjectFactory = serviceHandlerObjectFactory;
}
/*
* (non-Javadoc)
*
* @see com.chinarewards.qqgbvpn.main.PosServer#start()
*/
@Override
public void start() throws PosServerException {
buildCodecMapping();
// start the JPA persistence service
startPersistenceService();
// setup Apache Mina server.
startMinaService();
log.info("Server running, listening on {}", getLocalPort());
}
protected void buildCodecMapping() {
CodecMappingConfigBuilder builder = new CodecMappingConfigBuilder();
CmdMapping cmdMapping = builder.buildMapping(configuration);
// and then the factory
this.cmdCodecFactory = new SimpleCmdCodecFactory(cmdMapping);
this.cmdMapping = cmdMapping;
}
/**
* Start the Apache Mina service.
*
* @throws PosServerException
*/
protected void startMinaService() throws PosServerException {
// default 1800 seconds
int idleTime = configuration.getInt(ConfigKey.SERVER_CLIENTMAXIDLETIME,
DEFAULT_SERVER_CLIENTMAXIDLETIME);
port = configuration.getInt("server.port");
serverAddr = new InetSocketAddress(port);
// =============== server side ===================
// Programmers: You MUST consult your team before rearranging the
// order of the following Mina filters, as the ordering may affects
// the behaviour of the application which may lead to unpredictable
// result.
acceptor = new NioSocketAcceptor();
// ManageIoSessionConnect filter if idle server will not close any idle IoSession
acceptor.getFilterChain().addLast("ManageIoSessionConnect",
new IdleConnectionKillerFilter());
// our logging filter
acceptor.getFilterChain()
.addLast(
"cr-logger",
new com.chinarewards.qqgbvpn.main.protocol.filter.LoggingFilter());
acceptor.getFilterChain().addLast("logger", buildLoggingFilter());
// decode message
// TODO config MessageCoderFactory to allow setting the maximum message size
acceptor.getFilterChain().addLast(
"codec",
new ProtocolCodecFilter(new MessageCoderFactory(cmdCodecFactory)));
// kills error connection if too many.
acceptor.getFilterChain().addLast("errorConnectionKiller",
new ErrorConnectionKillerFilter());
// bodyMessage filter - short-circuit if error message is received.
acceptor.getFilterChain().addLast("bodyMessage",
new BodyMessageFilter());
// bodyMessage filter - short-circuit if error message is received.
acceptor.getFilterChain().addLast(
"sessionKeyFilter",
new SessionKeyMessageFilter(injector.getInstance(SessionStore.class),
new UuidSessionIdGenerator()));
// Login filter.
acceptor.getFilterChain().addLast("login",
injector.getInstance(LoginFilter.class));
// the handler class
acceptor.setHandler(new ServerSessionHandler(serviceDispatcher,
- mapping, configuration));
+ mapping, configuration, injector.getInstance(SessionStore.class)));
// additional configuration
acceptor.setCloseOnDeactivation(true);
acceptor.setReuseAddress(true);
// acceptor.getSessionConfig().setReadBufferSize(2048);
if (idleTime > 0) {
log.info("Client idle timeout set to {} seconds", idleTime);
} else {
log.info("Client idle timeout set to {} seconds, will be disabled",
idleTime);
}
acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, idleTime);
// start the acceptor and listen to incomming connection!
try {
acceptor.bind(serverAddr);
} catch (IOException e) {
throw new PosServerException("Error binding server port", e);
}
}
/**
* Build an new instance of LoggingFilter with sane logging level. The
* principle is to hide unnecessary logging under INFO level.
*
* @return
*/
protected LoggingFilter buildLoggingFilter() {
LoggingFilter loggingFilter = new LoggingFilter();
loggingFilter.setMessageReceivedLogLevel(LogLevel.DEBUG);
loggingFilter.setMessageSentLogLevel(LogLevel.DEBUG);
loggingFilter.setSessionIdleLogLevel(LogLevel.TRACE);
return loggingFilter;
}
protected void startPersistenceService() {
// the guice-persist's PersistService can only be started once.
if (persistenceServiceInited) {
return;
}
// start the PersistService.
PersistService ps = injector.getInstance(PersistService.class);
ps.start();
persistenceServiceInited = true;
}
/*
* (non-Javadoc)
*
* @see com.chinarewards.qqgbvpn.main.PosServer#stop()
*/
@Override
public void stop() {
acceptor.unbind(serverAddr);
acceptor.dispose();
}
/*
* (non-Javadoc)
*
* @see com.chinarewards.qqgbvpn.main.PosServer#shutdown()
*/
@Override
public void shutdown() {
try {
PersistService ps = injector.getInstance(PersistService.class);
ps.stop();
} catch (Throwable t) {
// mute
log.warn("An error occurred when stopping persistence service", t);
}
}
/*
* (non-Javadoc)
*
* @see com.chinarewards.qqgbvpn.main.PosServer#isStopped()
*/
@Override
public boolean isStopped() {
if (acceptor == null)
return true;
if (!acceptor.isActive() || acceptor.isDisposed())
return true;
return false;
}
@Override
public int getLocalPort() {
if (acceptor != null) {
InetSocketAddress d = (InetSocketAddress) acceptor
.getLocalAddress();
return d.getPort();
}
return port;
}
}
| true | true | protected void startMinaService() throws PosServerException {
// default 1800 seconds
int idleTime = configuration.getInt(ConfigKey.SERVER_CLIENTMAXIDLETIME,
DEFAULT_SERVER_CLIENTMAXIDLETIME);
port = configuration.getInt("server.port");
serverAddr = new InetSocketAddress(port);
// =============== server side ===================
// Programmers: You MUST consult your team before rearranging the
// order of the following Mina filters, as the ordering may affects
// the behaviour of the application which may lead to unpredictable
// result.
acceptor = new NioSocketAcceptor();
// ManageIoSessionConnect filter if idle server will not close any idle IoSession
acceptor.getFilterChain().addLast("ManageIoSessionConnect",
new IdleConnectionKillerFilter());
// our logging filter
acceptor.getFilterChain()
.addLast(
"cr-logger",
new com.chinarewards.qqgbvpn.main.protocol.filter.LoggingFilter());
acceptor.getFilterChain().addLast("logger", buildLoggingFilter());
// decode message
// TODO config MessageCoderFactory to allow setting the maximum message size
acceptor.getFilterChain().addLast(
"codec",
new ProtocolCodecFilter(new MessageCoderFactory(cmdCodecFactory)));
// kills error connection if too many.
acceptor.getFilterChain().addLast("errorConnectionKiller",
new ErrorConnectionKillerFilter());
// bodyMessage filter - short-circuit if error message is received.
acceptor.getFilterChain().addLast("bodyMessage",
new BodyMessageFilter());
// bodyMessage filter - short-circuit if error message is received.
acceptor.getFilterChain().addLast(
"sessionKeyFilter",
new SessionKeyMessageFilter(injector.getInstance(SessionStore.class),
new UuidSessionIdGenerator()));
// Login filter.
acceptor.getFilterChain().addLast("login",
injector.getInstance(LoginFilter.class));
// the handler class
acceptor.setHandler(new ServerSessionHandler(serviceDispatcher,
mapping, configuration));
// additional configuration
acceptor.setCloseOnDeactivation(true);
acceptor.setReuseAddress(true);
// acceptor.getSessionConfig().setReadBufferSize(2048);
if (idleTime > 0) {
log.info("Client idle timeout set to {} seconds", idleTime);
} else {
log.info("Client idle timeout set to {} seconds, will be disabled",
idleTime);
}
acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, idleTime);
// start the acceptor and listen to incomming connection!
try {
acceptor.bind(serverAddr);
} catch (IOException e) {
throw new PosServerException("Error binding server port", e);
}
}
| protected void startMinaService() throws PosServerException {
// default 1800 seconds
int idleTime = configuration.getInt(ConfigKey.SERVER_CLIENTMAXIDLETIME,
DEFAULT_SERVER_CLIENTMAXIDLETIME);
port = configuration.getInt("server.port");
serverAddr = new InetSocketAddress(port);
// =============== server side ===================
// Programmers: You MUST consult your team before rearranging the
// order of the following Mina filters, as the ordering may affects
// the behaviour of the application which may lead to unpredictable
// result.
acceptor = new NioSocketAcceptor();
// ManageIoSessionConnect filter if idle server will not close any idle IoSession
acceptor.getFilterChain().addLast("ManageIoSessionConnect",
new IdleConnectionKillerFilter());
// our logging filter
acceptor.getFilterChain()
.addLast(
"cr-logger",
new com.chinarewards.qqgbvpn.main.protocol.filter.LoggingFilter());
acceptor.getFilterChain().addLast("logger", buildLoggingFilter());
// decode message
// TODO config MessageCoderFactory to allow setting the maximum message size
acceptor.getFilterChain().addLast(
"codec",
new ProtocolCodecFilter(new MessageCoderFactory(cmdCodecFactory)));
// kills error connection if too many.
acceptor.getFilterChain().addLast("errorConnectionKiller",
new ErrorConnectionKillerFilter());
// bodyMessage filter - short-circuit if error message is received.
acceptor.getFilterChain().addLast("bodyMessage",
new BodyMessageFilter());
// bodyMessage filter - short-circuit if error message is received.
acceptor.getFilterChain().addLast(
"sessionKeyFilter",
new SessionKeyMessageFilter(injector.getInstance(SessionStore.class),
new UuidSessionIdGenerator()));
// Login filter.
acceptor.getFilterChain().addLast("login",
injector.getInstance(LoginFilter.class));
// the handler class
acceptor.setHandler(new ServerSessionHandler(serviceDispatcher,
mapping, configuration, injector.getInstance(SessionStore.class)));
// additional configuration
acceptor.setCloseOnDeactivation(true);
acceptor.setReuseAddress(true);
// acceptor.getSessionConfig().setReadBufferSize(2048);
if (idleTime > 0) {
log.info("Client idle timeout set to {} seconds", idleTime);
} else {
log.info("Client idle timeout set to {} seconds, will be disabled",
idleTime);
}
acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, idleTime);
// start the acceptor and listen to incomming connection!
try {
acceptor.bind(serverAddr);
} catch (IOException e) {
throw new PosServerException("Error binding server port", e);
}
}
|
diff --git a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/ScheduleTaskMenuContributor.java b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/ScheduleTaskMenuContributor.java
index 1aa06cc45..7022d2ef8 100644
--- a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/ScheduleTaskMenuContributor.java
+++ b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/ScheduleTaskMenuContributor.java
@@ -1,289 +1,289 @@
/*******************************************************************************
* Copyright (c) 2004, 2010 Tasktop Technologies and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Tasktop Technologies - initial API and implementation
*******************************************************************************/
package org.eclipse.mylyn.internal.tasks.ui;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.window.Window;
import org.eclipse.mylyn.internal.provisional.commons.ui.CommonImages;
import org.eclipse.mylyn.internal.provisional.commons.ui.DatePicker;
import org.eclipse.mylyn.internal.provisional.commons.ui.DateSelectionDialog;
import org.eclipse.mylyn.internal.provisional.commons.ui.WorkbenchUtil;
import org.eclipse.mylyn.internal.tasks.core.AbstractTask;
import org.eclipse.mylyn.internal.tasks.core.DateRange;
import org.eclipse.mylyn.internal.tasks.core.TaskActivityUtil;
import org.eclipse.mylyn.internal.tasks.core.WeekDateRange;
import org.eclipse.mylyn.tasks.core.IRepositoryElement;
import org.eclipse.mylyn.tasks.core.ITask;
import org.eclipse.swt.widgets.Shell;
/**
* @author Rob Elves
* @author Mik Kersten
*/
public class ScheduleTaskMenuContributor implements IDynamicSubMenuContributor {
private AbstractTask singleTaskSelection;
private final List<IRepositoryElement> taskListElementsToSchedule = new ArrayList<IRepositoryElement>();
public MenuManager getSubMenuManager(final List<IRepositoryElement> selectedElements) {
singleTaskSelection = null;
taskListElementsToSchedule.clear();
final MenuManager subMenuManager = new MenuManager(Messages.ScheduleTaskMenuContributor_Schedule_for);
if (selectedElements.size() == 1) {
IRepositoryElement selectedElement = selectedElements.get(0);
if (selectedElement instanceof ITask) {
singleTaskSelection = (AbstractTask) selectedElement;
}
}
for (IRepositoryElement selectedElement : selectedElements) {
if (selectedElement instanceof ITask) {
taskListElementsToSchedule.add(selectedElement);
}
}
if (selectionIncludesCompletedTasks()) {
Action action = new Action() {
@Override
public void run() {
// ignore
}
};
action.setText(Messages.ScheduleTaskMenuContributor_Cannot_schedule_completed_tasks);
action.setEnabled(false);
subMenuManager.add(action);
return subMenuManager;
}
WeekDateRange week = TaskActivityUtil.getCurrentWeek();
int days = 0;
for (DateRange day : week.getDaysOfWeek()) {
if (day.includes(TaskActivityUtil.getCalendar())) {
days++;
// Today
Action action = createDateSelectionAction(day, CommonImages.SCHEDULE_DAY);
subMenuManager.add(action);
// Special case: Over scheduled tasks always 'scheduled' for today
if (singleTaskSelection != null && isPastReminder(singleTaskSelection)) {
action.setChecked(true);
}
} else if (day.after(TaskActivityUtil.getCalendar())) {
days++;
// Week Days
Action action = createDateSelectionAction(day, null);
subMenuManager.add(action);
}
}
// Next week days
int toAdd = 7 - days;
WeekDateRange nextWeek = TaskActivityUtil.getNextWeek();
for (int x = 0; x < toAdd; x++) {
int next = TasksUiPlugin.getTaskActivityManager().getWeekStartDay() + x;
if (next > Calendar.SATURDAY) {
- next = x;
+ next = next - Calendar.SATURDAY;
}
DateRange day = nextWeek.getDayOfWeek(next);
Action action = createDateSelectionAction(day, null);
subMenuManager.add(action);
}
subMenuManager.add(new Separator());
// This Week
Action action = createDateSelectionAction(week, CommonImages.SCHEDULE_WEEK);
subMenuManager.add(action);
// Special case: This Week holds previous weeks' scheduled tasks
if (isThisWeek(singleTaskSelection)) {
// Tasks scheduled for 'someday' float into this week
action.setChecked(true);
}
// Next Week
action = createDateSelectionAction(week.next(), null);
subMenuManager.add(action);
// Two Weeks
action = createDateSelectionAction(week.next().next(), null);
subMenuManager.add(action);
if (singleTaskSelection != null && getScheduledForDate(singleTaskSelection) != null) {
// Update Two Weeks
DateRange range = getScheduledForDate(singleTaskSelection);
if (range.equals(TaskActivityUtil.getNextWeek().next())
|| TaskActivityUtil.getNextWeek().next().includes(range)) {
action.setChecked(true);
}
// Future
if (getScheduledForDate(singleTaskSelection).after(week.next().next().getEndDate())
&& !(getScheduledForDate(singleTaskSelection) instanceof WeekDateRange)) {
action = new Action() {
@Override
public void run() {
// ignore
}
};
action.setChecked(true);
action.setText(Messages.ScheduleTaskMenuContributor_Future);
subMenuManager.add(action);
}
}
subMenuManager.add(new Separator());
// Date Selection Dialog
action = new Action() {
@Override
public void run() {
Calendar theCalendar = TaskActivityUtil.getCalendar();
if (getScheduledForDate(singleTaskSelection) != null) {
theCalendar.setTime(getScheduledForDate(singleTaskSelection).getStartDate().getTime());
}
Shell shell = null;
if (subMenuManager != null && subMenuManager.getMenu() != null
&& !subMenuManager.getMenu().isDisposed()) {
// we should try to use the same shell that the menu was created with
// so that it shows up on top of that shell correctly
shell = subMenuManager.getMenu().getShell();
}
if (shell == null) {
shell = WorkbenchUtil.getShell();
}
DateSelectionDialog reminderDialog = new DateSelectionDialog(shell, theCalendar,
DatePicker.TITLE_DIALOG, false, TasksUiPlugin.getDefault()
.getPreferenceStore()
.getInt(ITasksUiPreferenceConstants.PLANNING_ENDHOUR));
int result = reminderDialog.open();
if (result == Window.OK) {
DateRange range = null;
if (reminderDialog.getDate() != null) {
range = TaskActivityUtil.getDayOf(reminderDialog.getDate());
}
setScheduledDate(range);
}
}
};
action.setText(Messages.ScheduleTaskMenuContributor_Choose_Date_);
action.setEnabled(canSchedule());
subMenuManager.add(action);
action = new Action() {
@Override
public void run() {
setScheduledDate(null);
}
};
action.setText(Messages.ScheduleTaskMenuContributor_Not_Scheduled);
action.setChecked(false);
if (singleTaskSelection != null) {
if (getScheduledForDate(singleTaskSelection) == null) {
action.setChecked(true);
}
}
subMenuManager.add(action);
return subMenuManager;
}
private boolean isThisWeek(AbstractTask task) {
return task != null && task.getScheduledForDate() != null
&& task.getScheduledForDate() instanceof WeekDateRange
&& task.getScheduledForDate().isBefore(TaskActivityUtil.getCurrentWeek());
}
private boolean selectionIncludesCompletedTasks() {
if (singleTaskSelection instanceof AbstractTask) {
if ((singleTaskSelection).isCompleted()) {
return true;
}
}
if (taskListElementsToSchedule.size() > 0) {
for (IRepositoryElement task : taskListElementsToSchedule) {
if (task instanceof AbstractTask) {
if (((AbstractTask) task).isCompleted()) {
return true;
}
}
}
}
return false;
}
private Action createDateSelectionAction(final DateRange dateContainer, ImageDescriptor imageDescriptor) {
Action action = new Action() {
@Override
public void run() {
setScheduledDate(dateContainer);
}
};
action.setText(dateContainer.toString());
action.setImageDescriptor(imageDescriptor);
action.setEnabled(canSchedule());
DateRange scheduledDate = getScheduledForDate(singleTaskSelection);
if (scheduledDate != null) {
action.setChecked(dateContainer.equals(scheduledDate));
}
return action;
}
private boolean canSchedule() {
if (taskListElementsToSchedule.size() == 0) {
return true;
} else if (singleTaskSelection instanceof ITask) {
return ((!(singleTaskSelection).isCompleted()) || taskListElementsToSchedule.size() > 0);
} else {
return taskListElementsToSchedule.size() > 0;
}
}
protected void setScheduledDate(DateRange dateContainer) {
for (IRepositoryElement element : taskListElementsToSchedule) {
if (element instanceof AbstractTask) {
AbstractTask task = (AbstractTask) element;
if (TasksUiPlugin.getTaskList().getTask(task.getRepositoryUrl(), task.getTaskId()) == null) {
TasksUiPlugin.getTaskList().addTask(task, TasksUiPlugin.getTaskList().getDefaultCategory());
}
if (dateContainer != null) {
TasksUiPlugin.getTaskActivityManager().setScheduledFor(task, dateContainer);
} else {
TasksUiPlugin.getTaskActivityManager().setScheduledFor(task, null);
}
}
}
}
protected DateRange getScheduledForDate(final AbstractTask selectedTask) {
if (selectedTask != null) {
return selectedTask.getScheduledForDate();
}
return null;
}
private boolean isPastReminder(AbstractTask task) {
return TasksUiPlugin.getTaskActivityManager().isPastReminder(task);
}
}
| true | true | public MenuManager getSubMenuManager(final List<IRepositoryElement> selectedElements) {
singleTaskSelection = null;
taskListElementsToSchedule.clear();
final MenuManager subMenuManager = new MenuManager(Messages.ScheduleTaskMenuContributor_Schedule_for);
if (selectedElements.size() == 1) {
IRepositoryElement selectedElement = selectedElements.get(0);
if (selectedElement instanceof ITask) {
singleTaskSelection = (AbstractTask) selectedElement;
}
}
for (IRepositoryElement selectedElement : selectedElements) {
if (selectedElement instanceof ITask) {
taskListElementsToSchedule.add(selectedElement);
}
}
if (selectionIncludesCompletedTasks()) {
Action action = new Action() {
@Override
public void run() {
// ignore
}
};
action.setText(Messages.ScheduleTaskMenuContributor_Cannot_schedule_completed_tasks);
action.setEnabled(false);
subMenuManager.add(action);
return subMenuManager;
}
WeekDateRange week = TaskActivityUtil.getCurrentWeek();
int days = 0;
for (DateRange day : week.getDaysOfWeek()) {
if (day.includes(TaskActivityUtil.getCalendar())) {
days++;
// Today
Action action = createDateSelectionAction(day, CommonImages.SCHEDULE_DAY);
subMenuManager.add(action);
// Special case: Over scheduled tasks always 'scheduled' for today
if (singleTaskSelection != null && isPastReminder(singleTaskSelection)) {
action.setChecked(true);
}
} else if (day.after(TaskActivityUtil.getCalendar())) {
days++;
// Week Days
Action action = createDateSelectionAction(day, null);
subMenuManager.add(action);
}
}
// Next week days
int toAdd = 7 - days;
WeekDateRange nextWeek = TaskActivityUtil.getNextWeek();
for (int x = 0; x < toAdd; x++) {
int next = TasksUiPlugin.getTaskActivityManager().getWeekStartDay() + x;
if (next > Calendar.SATURDAY) {
next = x;
}
DateRange day = nextWeek.getDayOfWeek(next);
Action action = createDateSelectionAction(day, null);
subMenuManager.add(action);
}
subMenuManager.add(new Separator());
// This Week
Action action = createDateSelectionAction(week, CommonImages.SCHEDULE_WEEK);
subMenuManager.add(action);
// Special case: This Week holds previous weeks' scheduled tasks
if (isThisWeek(singleTaskSelection)) {
// Tasks scheduled for 'someday' float into this week
action.setChecked(true);
}
// Next Week
action = createDateSelectionAction(week.next(), null);
subMenuManager.add(action);
// Two Weeks
action = createDateSelectionAction(week.next().next(), null);
subMenuManager.add(action);
if (singleTaskSelection != null && getScheduledForDate(singleTaskSelection) != null) {
// Update Two Weeks
DateRange range = getScheduledForDate(singleTaskSelection);
if (range.equals(TaskActivityUtil.getNextWeek().next())
|| TaskActivityUtil.getNextWeek().next().includes(range)) {
action.setChecked(true);
}
// Future
if (getScheduledForDate(singleTaskSelection).after(week.next().next().getEndDate())
&& !(getScheduledForDate(singleTaskSelection) instanceof WeekDateRange)) {
action = new Action() {
@Override
public void run() {
// ignore
}
};
action.setChecked(true);
action.setText(Messages.ScheduleTaskMenuContributor_Future);
subMenuManager.add(action);
}
}
subMenuManager.add(new Separator());
// Date Selection Dialog
action = new Action() {
@Override
public void run() {
Calendar theCalendar = TaskActivityUtil.getCalendar();
if (getScheduledForDate(singleTaskSelection) != null) {
theCalendar.setTime(getScheduledForDate(singleTaskSelection).getStartDate().getTime());
}
Shell shell = null;
if (subMenuManager != null && subMenuManager.getMenu() != null
&& !subMenuManager.getMenu().isDisposed()) {
// we should try to use the same shell that the menu was created with
// so that it shows up on top of that shell correctly
shell = subMenuManager.getMenu().getShell();
}
if (shell == null) {
shell = WorkbenchUtil.getShell();
}
DateSelectionDialog reminderDialog = new DateSelectionDialog(shell, theCalendar,
DatePicker.TITLE_DIALOG, false, TasksUiPlugin.getDefault()
.getPreferenceStore()
.getInt(ITasksUiPreferenceConstants.PLANNING_ENDHOUR));
int result = reminderDialog.open();
if (result == Window.OK) {
DateRange range = null;
if (reminderDialog.getDate() != null) {
range = TaskActivityUtil.getDayOf(reminderDialog.getDate());
}
setScheduledDate(range);
}
}
};
action.setText(Messages.ScheduleTaskMenuContributor_Choose_Date_);
action.setEnabled(canSchedule());
subMenuManager.add(action);
action = new Action() {
@Override
public void run() {
setScheduledDate(null);
}
};
action.setText(Messages.ScheduleTaskMenuContributor_Not_Scheduled);
action.setChecked(false);
if (singleTaskSelection != null) {
if (getScheduledForDate(singleTaskSelection) == null) {
action.setChecked(true);
}
}
subMenuManager.add(action);
return subMenuManager;
}
| public MenuManager getSubMenuManager(final List<IRepositoryElement> selectedElements) {
singleTaskSelection = null;
taskListElementsToSchedule.clear();
final MenuManager subMenuManager = new MenuManager(Messages.ScheduleTaskMenuContributor_Schedule_for);
if (selectedElements.size() == 1) {
IRepositoryElement selectedElement = selectedElements.get(0);
if (selectedElement instanceof ITask) {
singleTaskSelection = (AbstractTask) selectedElement;
}
}
for (IRepositoryElement selectedElement : selectedElements) {
if (selectedElement instanceof ITask) {
taskListElementsToSchedule.add(selectedElement);
}
}
if (selectionIncludesCompletedTasks()) {
Action action = new Action() {
@Override
public void run() {
// ignore
}
};
action.setText(Messages.ScheduleTaskMenuContributor_Cannot_schedule_completed_tasks);
action.setEnabled(false);
subMenuManager.add(action);
return subMenuManager;
}
WeekDateRange week = TaskActivityUtil.getCurrentWeek();
int days = 0;
for (DateRange day : week.getDaysOfWeek()) {
if (day.includes(TaskActivityUtil.getCalendar())) {
days++;
// Today
Action action = createDateSelectionAction(day, CommonImages.SCHEDULE_DAY);
subMenuManager.add(action);
// Special case: Over scheduled tasks always 'scheduled' for today
if (singleTaskSelection != null && isPastReminder(singleTaskSelection)) {
action.setChecked(true);
}
} else if (day.after(TaskActivityUtil.getCalendar())) {
days++;
// Week Days
Action action = createDateSelectionAction(day, null);
subMenuManager.add(action);
}
}
// Next week days
int toAdd = 7 - days;
WeekDateRange nextWeek = TaskActivityUtil.getNextWeek();
for (int x = 0; x < toAdd; x++) {
int next = TasksUiPlugin.getTaskActivityManager().getWeekStartDay() + x;
if (next > Calendar.SATURDAY) {
next = next - Calendar.SATURDAY;
}
DateRange day = nextWeek.getDayOfWeek(next);
Action action = createDateSelectionAction(day, null);
subMenuManager.add(action);
}
subMenuManager.add(new Separator());
// This Week
Action action = createDateSelectionAction(week, CommonImages.SCHEDULE_WEEK);
subMenuManager.add(action);
// Special case: This Week holds previous weeks' scheduled tasks
if (isThisWeek(singleTaskSelection)) {
// Tasks scheduled for 'someday' float into this week
action.setChecked(true);
}
// Next Week
action = createDateSelectionAction(week.next(), null);
subMenuManager.add(action);
// Two Weeks
action = createDateSelectionAction(week.next().next(), null);
subMenuManager.add(action);
if (singleTaskSelection != null && getScheduledForDate(singleTaskSelection) != null) {
// Update Two Weeks
DateRange range = getScheduledForDate(singleTaskSelection);
if (range.equals(TaskActivityUtil.getNextWeek().next())
|| TaskActivityUtil.getNextWeek().next().includes(range)) {
action.setChecked(true);
}
// Future
if (getScheduledForDate(singleTaskSelection).after(week.next().next().getEndDate())
&& !(getScheduledForDate(singleTaskSelection) instanceof WeekDateRange)) {
action = new Action() {
@Override
public void run() {
// ignore
}
};
action.setChecked(true);
action.setText(Messages.ScheduleTaskMenuContributor_Future);
subMenuManager.add(action);
}
}
subMenuManager.add(new Separator());
// Date Selection Dialog
action = new Action() {
@Override
public void run() {
Calendar theCalendar = TaskActivityUtil.getCalendar();
if (getScheduledForDate(singleTaskSelection) != null) {
theCalendar.setTime(getScheduledForDate(singleTaskSelection).getStartDate().getTime());
}
Shell shell = null;
if (subMenuManager != null && subMenuManager.getMenu() != null
&& !subMenuManager.getMenu().isDisposed()) {
// we should try to use the same shell that the menu was created with
// so that it shows up on top of that shell correctly
shell = subMenuManager.getMenu().getShell();
}
if (shell == null) {
shell = WorkbenchUtil.getShell();
}
DateSelectionDialog reminderDialog = new DateSelectionDialog(shell, theCalendar,
DatePicker.TITLE_DIALOG, false, TasksUiPlugin.getDefault()
.getPreferenceStore()
.getInt(ITasksUiPreferenceConstants.PLANNING_ENDHOUR));
int result = reminderDialog.open();
if (result == Window.OK) {
DateRange range = null;
if (reminderDialog.getDate() != null) {
range = TaskActivityUtil.getDayOf(reminderDialog.getDate());
}
setScheduledDate(range);
}
}
};
action.setText(Messages.ScheduleTaskMenuContributor_Choose_Date_);
action.setEnabled(canSchedule());
subMenuManager.add(action);
action = new Action() {
@Override
public void run() {
setScheduledDate(null);
}
};
action.setText(Messages.ScheduleTaskMenuContributor_Not_Scheduled);
action.setChecked(false);
if (singleTaskSelection != null) {
if (getScheduledForDate(singleTaskSelection) == null) {
action.setChecked(true);
}
}
subMenuManager.add(action);
return subMenuManager;
}
|
diff --git a/loci/formats/in/SlidebookReader.java b/loci/formats/in/SlidebookReader.java
index 2fd21d6e2..4d075256b 100644
--- a/loci/formats/in/SlidebookReader.java
+++ b/loci/formats/in/SlidebookReader.java
@@ -1,439 +1,443 @@
//
// SlidebookReader.java
//
/*
LOCI Bio-Formats package for reading and converting biological file formats.
Copyright (C) 2005-@year@ Melissa Linkert, Curtis Rueden, Chris Allan,
Eric Kjellman and Brian Loranger.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Library General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package loci.formats.in;
import java.io.*;
import java.util.Arrays;
import java.util.Vector;
import loci.formats.*;
import loci.formats.meta.FilterMetadata;
import loci.formats.meta.MetadataStore;
/**
* SlidebookReader is the file format reader for 3I Slidebook files.
* The strategies employed by this reader are highly suboptimal, as we
* have very little information on the Slidebook format.
*
* <dl><dt><b>Source code:</b></dt>
* <dd><a href="https://skyking.microscopy.wisc.edu/trac/java/browser/trunk/loci/formats/in/SlidebookReader.java">Trac</a>,
* <a href="https://skyking.microscopy.wisc.edu/svn/java/trunk/loci/formats/in/SlidebookReader.java">SVN</a></dd></dl>
*
* @author Melissa Linkert linkert at wisc.edu
*/
public class SlidebookReader extends FormatReader {
// -- Fields --
private Vector metadataOffsets;
private Vector pixelOffsets;
private Vector pixelLengths;
// -- Constructor --
/** Constructs a new Slidebook reader. */
public SlidebookReader() { super("Olympus Slidebook", "sld"); }
// -- IFormatReader API methods --
/* @see loci.formats.IFormatReader#isThisType(byte[]) */
public boolean isThisType(byte[] block) {
if (block.length < 8) return false;
return block[0] == 0x6c && block[1] == 0 && block[2] == 0 &&
block[3] == 1 && block[4] == 0x49 && block[5] == 0x49 && block[6] == 0;
}
/**
* @see loci.formats.IFormatReader#openBytes(int, byte[], int, int, int, int)
*/
public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h)
throws FormatException, IOException
{
FormatTools.assertId(currentId, true, 1);
FormatTools.checkPlaneNumber(this, no);
FormatTools.checkBufferSize(this, buf.length, w, h);
int plane = core.sizeX[series] * core.sizeY[series] * 2;
long offset = ((Long) pixelOffsets.get(series)).longValue() + plane * no;
in.seek(offset + y * core.sizeX[series] * 2);
for (int row=0; row<h; row++) {
in.skipBytes(x * 2);
in.read(buf, row * w * 2, w * 2);
in.skipBytes(2 * (core.sizeX[series] - w - x));
}
return buf;
}
// -- IFormatHandler API methods --
/* @see loci.formats.IFormatHandler#close() */
public void close() throws IOException {
super.close();
metadataOffsets = pixelOffsets = pixelLengths = null;
}
// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
protected void initFile(String id) throws FormatException, IOException {
if (debug) debug("SlidebookReader.initFile(" + id + ")");
super.initFile(id);
in = new RandomAccessStream(id);
status("Finding offsets to pixel data");
// Slidebook files appear to be comprised of four types of blocks:
// variable length pixel data blocks, 512 byte metadata blocks,
// 128 byte metadata blocks, and variable length metadata blocks.
//
// Fixed-length metadata blocks begin with a 2 byte identifier,
// e.g. 'i' or 'h'.
// Following this are two unknown bytes (usually 256), then a 2 byte
// endianness identifier - II or MM, for little or big endian, respectively.
// Presumably these blocks contain useful information, but for the most
// part we aren't sure what it is or how to extract it.
//
// Variable length metadata blocks begin with 0xffff and are
// (as far as I know) always between two fixed-length metadata blocks.
// These appear to be a relatively new addition to the format - they are
// only present in files received on/after March 30, 2008.
//
// Each pixel data block corresponds to one series.
// The first 'i' metadata block after each pixel data block contains
// the width and height of the planes in that block - this can (and does)
// vary between blocks.
//
// Z, C, and T sizes are computed heuristically based on the number of
// metadata blocks of a specific type.
in.skipBytes(4);
core.littleEndian[0] = in.read() == 0x49;
in.order(core.littleEndian[0]);
metadataOffsets = new Vector();
pixelOffsets = new Vector();
pixelLengths = new Vector();
in.seek(0);
// gather offsets to metadata and pixel data blocks
while (in.getFilePointer() < in.length() - 8) {
in.skipBytes(4);
int checkOne = in.read();
int checkTwo = in.read();
if ((checkOne == 'I' && checkTwo == 'I') ||
(checkOne == 'M' && checkTwo == 'M'))
{
metadataOffsets.add(new Long(in.getFilePointer() - 6));
in.skipBytes(in.readShort() - 8);
}
else if (checkOne == -1 && checkTwo == -1) {
boolean foundBlock = false;
byte[] block = new byte[8192];
in.read(block);
while (!foundBlock) {
for (int i=0; i<block.length-2; i++) {
if ((block[i] == 'M' && block[i + 1] == 'M') ||
(block[i] == 'I' && block[i + 1] == 'I'))
{
foundBlock = true;
in.seek(in.getFilePointer() - block.length + i - 2);
metadataOffsets.add(new Long(in.getFilePointer() - 2));
in.skipBytes(in.readShort() - 5);
break;
}
}
if (!foundBlock) {
block[0] = block[block.length - 2];
block[1] = block[block.length - 1];
in.read(block, 2, block.length - 2);
}
}
}
else {
String s = null;
long fp = in.getFilePointer() - 6;
in.seek(fp);
int len = in.read();
if (len > 0 && len <= 32) {
s = in.readString(len);
}
if (s != null && s.indexOf("Annotation") != -1) {
if (s.equals("CTimelapseAnnotation")) {
in.skipBytes(41);
if (in.read() == 0) in.skipBytes(10);
else in.seek(in.getFilePointer() - 1);
}
else if (s.equals("CIntensityBarAnnotation")) {
in.skipBytes(56);
int n = in.read();
while (n == 0 || n < 6 || n > 0x80) n = in.read();
in.seek(in.getFilePointer() - 1);
}
else if (s.equals("CCubeAnnotation")) {
in.skipBytes(66);
int n = in.read();
if (n != 0) in.seek(in.getFilePointer() - 1);
}
else if (s.equals("CScaleBarAnnotation")) {
in.skipBytes(52);
}
}
else if (s != null && s.indexOf("Decon") != -1) {
in.seek(fp);
while (in.read() != ']');
}
else {
if ((fp % 2) == 1) fp -= 2;
in.seek(fp);
pixelOffsets.add(new Long(fp));
try {
byte[] buf = new byte[8192];
boolean found = false;
int n = in.read(buf);
while (!found && in.getFilePointer() < in.length()) {
for (int i=0; i<buf.length-6; i++) {
if ((buf[i] == 'h' && buf[i+4] == 'I' && buf[i+5] == 'I') ||
(buf[i+1] == 'h' && buf[i+4] == 'M' && buf[i+5] == 'M'))
{
found = true;
in.seek(in.getFilePointer() - n + i - 20);
break;
}
}
if (!found) {
byte[] tmp = buf;
buf = new byte[8192];
System.arraycopy(tmp, tmp.length - 20, buf, 0, 20);
n = in.read(buf, 20, buf.length - 20);
}
}
if (in.getFilePointer() <= in.length()) {
pixelLengths.add(new Long(in.getFilePointer() - fp));
}
else pixelOffsets.remove(pixelOffsets.size() - 1);
}
catch (EOFException e) {
pixelOffsets.remove(pixelOffsets.size() - 1);
}
}
}
}
for (int i=0; i<pixelOffsets.size(); i++) {
long length = ((Long) pixelLengths.get(i)).longValue();
long offset = ((Long) pixelOffsets.get(i)).longValue();
in.seek(offset);
byte checkByte = in.readByte();
if (length + offset >= in.length()) {
pixelOffsets.remove(i);
pixelLengths.remove(i);
i--;
}
else if (checkByte == 'l') {
long lengthSum = ((Long) pixelLengths.get(0)).longValue();
while (pixelLengths.size() > 1) {
int size = pixelLengths.size() - 1;
lengthSum += ((Long) pixelLengths.get(size)).longValue();
pixelLengths.remove(size);
pixelOffsets.remove(size);
}
for (int q=0; q<metadataOffsets.size(); q++) {
long mOffset = ((Long) metadataOffsets.get(q)).longValue();
if (mOffset > lengthSum) {
lengthSum = mOffset - offset;
break;
}
}
pixelLengths.setElementAt(new Long(lengthSum), 0);
break;
}
}
if (pixelOffsets.size() > 1) {
if (pixelOffsets.size() > 2) {
int size = pixelOffsets.size();
long last = ((Long) pixelOffsets.get(size - 1)).longValue();
long nextToLast = ((Long) pixelOffsets.get(size - 2)).longValue();
long diff = in.length() - last;
if (last - nextToLast > 2*diff && diff < (256 * 256 * 2)) {
pixelOffsets.removeElementAt(size - 1);
}
}
boolean little = core.littleEndian[0];
core = new CoreMetadata(pixelOffsets.size());
Arrays.fill(core.littleEndian, little);
}
status("Determining dimensions");
// determine total number of pixel bytes
long pixelBytes = 0;
for (int i=0; i<pixelLengths.size(); i++) {
pixelBytes += ((Long) pixelLengths.get(i)).longValue();
}
String[] imageNames = new String[core.sizeX.length];
Vector channelNames = new Vector();
int nextName = 0;
// try to find the width and height
int iCount = 0;
int hCount = 0;
int uCount = 0;
int prevSeries = -1;
int prevSeriesU = -1;
int nextChannel = 0;
for (int i=0; i<metadataOffsets.size(); i++) {
long off = ((Long) metadataOffsets.get(i)).longValue();
in.seek(off);
long next = i == metadataOffsets.size() - 1 ? in.length() :
((Long) metadataOffsets.get(i + 1)).longValue();
int count = 0;
while (off + count * 128 < next) {
in.seek(off + count * 128);
count++;
char n = (char) in.readShort();
if (n == 'i') {
iCount++;
in.skipBytes(78);
int start = 0;
for (int j=start; j<pixelOffsets.size(); j++) {
long length = ((Long) pixelLengths.get(j)).longValue();
long offset = ((Long) pixelOffsets.get(j)).longValue();
long end = j == pixelOffsets.size() - 1 ? in.length() :
((Long) pixelOffsets.get(j + 1)).longValue();
if (in.getFilePointer() >= (length + offset) &&
in.getFilePointer() < end)
{
if (core.sizeX[j - start] == 0) {
core.sizeX[j - start] = in.readShort();
core.sizeY[j - start] = in.readShort();
int checkX = in.readShort();
int checkY = in.readShort();
int div = in.readShort();
core.sizeX[j - start] /= div;
div = in.readShort();
core.sizeY[j - start] /= div;
}
if (prevSeries != j - start) {
iCount = 1;
}
prevSeries = j - start;
core.sizeC[j - start] = iCount;
break;
}
}
}
else if (n == 'u') {
uCount++;
int start = 0;
for (int j=start; j<pixelOffsets.size(); j++) {
long length = ((Long) pixelLengths.get(j)).longValue();
long offset = ((Long) pixelOffsets.get(j)).longValue();
long end = j == pixelOffsets.size() - 1 ? in.length() :
((Long) pixelOffsets.get(j + 1)).longValue();
if (in.getFilePointer() >= (length + offset) &&
in.getFilePointer() < end)
{
if (prevSeriesU != j - start) {
uCount = 1;
}
prevSeriesU = j - start;
core.sizeZ[j - start] = uCount;
break;
}
}
}
else if (n == 'h') hCount++;
else if (n == 'j') {
- // this block should contain an image name
- in.skipBytes(14);
- if (nextName < imageNames.length) {
- imageNames[nextName++] = in.readCString().trim();
+ in.skipBytes(2);
+ String check = in.readString(2);
+ if (check.equals("II") || check.equals("MM")) {
+ // this block should contain an image name
+ in.skipBytes(10);
+ if (nextName < imageNames.length) {
+ imageNames[nextName++] = in.readCString().trim();
+ }
}
}
else if (n == 'm') {
// this block should contain a channel name
if (in.getFilePointer() > ((Long) pixelOffsets.get(0)).longValue()) {
in.skipBytes(14);
channelNames.add(in.readCString().trim());
}
}
}
}
for (int i=0; i<core.sizeX.length; i++) {
long pixels = ((Long) pixelLengths.get(i)).longValue() / 2;
boolean x = true;
while (core.sizeX[i] * core.sizeY[i] * core.sizeC[i] * core.sizeZ[i] >
pixels)
{
if (x) core.sizeX[i] /= 2;
else core.sizeY[i] /= 2;
x = !x;
}
if (core.sizeZ[i] == 0) core.sizeZ[i] = 1;
core.sizeT[i] = (int) (pixels /
(core.sizeX[i] * core.sizeY[i] * core.sizeZ[i] * core.sizeC[i]));
if (core.sizeT[i] == 0) core.sizeT[i] = 1;
core.imageCount[i] = core.sizeZ[i] * core.sizeT[i] * core.sizeC[i];
core.pixelType[i] = FormatTools.UINT16;
core.currentOrder[i] = "XYZTC";
core.indexed[i] = false;
core.falseColor[i] = false;
core.metadataComplete[i] = true;
}
MetadataStore store =
new FilterMetadata(getMetadataStore(), isMetadataFiltered());
MetadataTools.populatePixels(store, this);
int index = 0;
for (int i=0; i<core.sizeX.length; i++) {
store.setImageName(imageNames[i], i);
store.setImageCreationDate(
DataTools.convertDate(System.currentTimeMillis(), DataTools.UNIX), i);
for (int c=0; c<core.sizeC[i]; c++) {
if (index < channelNames.size()) {
store.setLogicalChannelName((String) channelNames.get(index++), i, c);
addMeta(imageNames[i] + " channel " + c, channelNames.get(index - 1));
}
}
}
}
}
| true | true | protected void initFile(String id) throws FormatException, IOException {
if (debug) debug("SlidebookReader.initFile(" + id + ")");
super.initFile(id);
in = new RandomAccessStream(id);
status("Finding offsets to pixel data");
// Slidebook files appear to be comprised of four types of blocks:
// variable length pixel data blocks, 512 byte metadata blocks,
// 128 byte metadata blocks, and variable length metadata blocks.
//
// Fixed-length metadata blocks begin with a 2 byte identifier,
// e.g. 'i' or 'h'.
// Following this are two unknown bytes (usually 256), then a 2 byte
// endianness identifier - II or MM, for little or big endian, respectively.
// Presumably these blocks contain useful information, but for the most
// part we aren't sure what it is or how to extract it.
//
// Variable length metadata blocks begin with 0xffff and are
// (as far as I know) always between two fixed-length metadata blocks.
// These appear to be a relatively new addition to the format - they are
// only present in files received on/after March 30, 2008.
//
// Each pixel data block corresponds to one series.
// The first 'i' metadata block after each pixel data block contains
// the width and height of the planes in that block - this can (and does)
// vary between blocks.
//
// Z, C, and T sizes are computed heuristically based on the number of
// metadata blocks of a specific type.
in.skipBytes(4);
core.littleEndian[0] = in.read() == 0x49;
in.order(core.littleEndian[0]);
metadataOffsets = new Vector();
pixelOffsets = new Vector();
pixelLengths = new Vector();
in.seek(0);
// gather offsets to metadata and pixel data blocks
while (in.getFilePointer() < in.length() - 8) {
in.skipBytes(4);
int checkOne = in.read();
int checkTwo = in.read();
if ((checkOne == 'I' && checkTwo == 'I') ||
(checkOne == 'M' && checkTwo == 'M'))
{
metadataOffsets.add(new Long(in.getFilePointer() - 6));
in.skipBytes(in.readShort() - 8);
}
else if (checkOne == -1 && checkTwo == -1) {
boolean foundBlock = false;
byte[] block = new byte[8192];
in.read(block);
while (!foundBlock) {
for (int i=0; i<block.length-2; i++) {
if ((block[i] == 'M' && block[i + 1] == 'M') ||
(block[i] == 'I' && block[i + 1] == 'I'))
{
foundBlock = true;
in.seek(in.getFilePointer() - block.length + i - 2);
metadataOffsets.add(new Long(in.getFilePointer() - 2));
in.skipBytes(in.readShort() - 5);
break;
}
}
if (!foundBlock) {
block[0] = block[block.length - 2];
block[1] = block[block.length - 1];
in.read(block, 2, block.length - 2);
}
}
}
else {
String s = null;
long fp = in.getFilePointer() - 6;
in.seek(fp);
int len = in.read();
if (len > 0 && len <= 32) {
s = in.readString(len);
}
if (s != null && s.indexOf("Annotation") != -1) {
if (s.equals("CTimelapseAnnotation")) {
in.skipBytes(41);
if (in.read() == 0) in.skipBytes(10);
else in.seek(in.getFilePointer() - 1);
}
else if (s.equals("CIntensityBarAnnotation")) {
in.skipBytes(56);
int n = in.read();
while (n == 0 || n < 6 || n > 0x80) n = in.read();
in.seek(in.getFilePointer() - 1);
}
else if (s.equals("CCubeAnnotation")) {
in.skipBytes(66);
int n = in.read();
if (n != 0) in.seek(in.getFilePointer() - 1);
}
else if (s.equals("CScaleBarAnnotation")) {
in.skipBytes(52);
}
}
else if (s != null && s.indexOf("Decon") != -1) {
in.seek(fp);
while (in.read() != ']');
}
else {
if ((fp % 2) == 1) fp -= 2;
in.seek(fp);
pixelOffsets.add(new Long(fp));
try {
byte[] buf = new byte[8192];
boolean found = false;
int n = in.read(buf);
while (!found && in.getFilePointer() < in.length()) {
for (int i=0; i<buf.length-6; i++) {
if ((buf[i] == 'h' && buf[i+4] == 'I' && buf[i+5] == 'I') ||
(buf[i+1] == 'h' && buf[i+4] == 'M' && buf[i+5] == 'M'))
{
found = true;
in.seek(in.getFilePointer() - n + i - 20);
break;
}
}
if (!found) {
byte[] tmp = buf;
buf = new byte[8192];
System.arraycopy(tmp, tmp.length - 20, buf, 0, 20);
n = in.read(buf, 20, buf.length - 20);
}
}
if (in.getFilePointer() <= in.length()) {
pixelLengths.add(new Long(in.getFilePointer() - fp));
}
else pixelOffsets.remove(pixelOffsets.size() - 1);
}
catch (EOFException e) {
pixelOffsets.remove(pixelOffsets.size() - 1);
}
}
}
}
for (int i=0; i<pixelOffsets.size(); i++) {
long length = ((Long) pixelLengths.get(i)).longValue();
long offset = ((Long) pixelOffsets.get(i)).longValue();
in.seek(offset);
byte checkByte = in.readByte();
if (length + offset >= in.length()) {
pixelOffsets.remove(i);
pixelLengths.remove(i);
i--;
}
else if (checkByte == 'l') {
long lengthSum = ((Long) pixelLengths.get(0)).longValue();
while (pixelLengths.size() > 1) {
int size = pixelLengths.size() - 1;
lengthSum += ((Long) pixelLengths.get(size)).longValue();
pixelLengths.remove(size);
pixelOffsets.remove(size);
}
for (int q=0; q<metadataOffsets.size(); q++) {
long mOffset = ((Long) metadataOffsets.get(q)).longValue();
if (mOffset > lengthSum) {
lengthSum = mOffset - offset;
break;
}
}
pixelLengths.setElementAt(new Long(lengthSum), 0);
break;
}
}
if (pixelOffsets.size() > 1) {
if (pixelOffsets.size() > 2) {
int size = pixelOffsets.size();
long last = ((Long) pixelOffsets.get(size - 1)).longValue();
long nextToLast = ((Long) pixelOffsets.get(size - 2)).longValue();
long diff = in.length() - last;
if (last - nextToLast > 2*diff && diff < (256 * 256 * 2)) {
pixelOffsets.removeElementAt(size - 1);
}
}
boolean little = core.littleEndian[0];
core = new CoreMetadata(pixelOffsets.size());
Arrays.fill(core.littleEndian, little);
}
status("Determining dimensions");
// determine total number of pixel bytes
long pixelBytes = 0;
for (int i=0; i<pixelLengths.size(); i++) {
pixelBytes += ((Long) pixelLengths.get(i)).longValue();
}
String[] imageNames = new String[core.sizeX.length];
Vector channelNames = new Vector();
int nextName = 0;
// try to find the width and height
int iCount = 0;
int hCount = 0;
int uCount = 0;
int prevSeries = -1;
int prevSeriesU = -1;
int nextChannel = 0;
for (int i=0; i<metadataOffsets.size(); i++) {
long off = ((Long) metadataOffsets.get(i)).longValue();
in.seek(off);
long next = i == metadataOffsets.size() - 1 ? in.length() :
((Long) metadataOffsets.get(i + 1)).longValue();
int count = 0;
while (off + count * 128 < next) {
in.seek(off + count * 128);
count++;
char n = (char) in.readShort();
if (n == 'i') {
iCount++;
in.skipBytes(78);
int start = 0;
for (int j=start; j<pixelOffsets.size(); j++) {
long length = ((Long) pixelLengths.get(j)).longValue();
long offset = ((Long) pixelOffsets.get(j)).longValue();
long end = j == pixelOffsets.size() - 1 ? in.length() :
((Long) pixelOffsets.get(j + 1)).longValue();
if (in.getFilePointer() >= (length + offset) &&
in.getFilePointer() < end)
{
if (core.sizeX[j - start] == 0) {
core.sizeX[j - start] = in.readShort();
core.sizeY[j - start] = in.readShort();
int checkX = in.readShort();
int checkY = in.readShort();
int div = in.readShort();
core.sizeX[j - start] /= div;
div = in.readShort();
core.sizeY[j - start] /= div;
}
if (prevSeries != j - start) {
iCount = 1;
}
prevSeries = j - start;
core.sizeC[j - start] = iCount;
break;
}
}
}
else if (n == 'u') {
uCount++;
int start = 0;
for (int j=start; j<pixelOffsets.size(); j++) {
long length = ((Long) pixelLengths.get(j)).longValue();
long offset = ((Long) pixelOffsets.get(j)).longValue();
long end = j == pixelOffsets.size() - 1 ? in.length() :
((Long) pixelOffsets.get(j + 1)).longValue();
if (in.getFilePointer() >= (length + offset) &&
in.getFilePointer() < end)
{
if (prevSeriesU != j - start) {
uCount = 1;
}
prevSeriesU = j - start;
core.sizeZ[j - start] = uCount;
break;
}
}
}
else if (n == 'h') hCount++;
else if (n == 'j') {
// this block should contain an image name
in.skipBytes(14);
if (nextName < imageNames.length) {
imageNames[nextName++] = in.readCString().trim();
}
}
else if (n == 'm') {
// this block should contain a channel name
if (in.getFilePointer() > ((Long) pixelOffsets.get(0)).longValue()) {
in.skipBytes(14);
channelNames.add(in.readCString().trim());
}
}
}
}
for (int i=0; i<core.sizeX.length; i++) {
long pixels = ((Long) pixelLengths.get(i)).longValue() / 2;
boolean x = true;
while (core.sizeX[i] * core.sizeY[i] * core.sizeC[i] * core.sizeZ[i] >
pixels)
{
if (x) core.sizeX[i] /= 2;
else core.sizeY[i] /= 2;
x = !x;
}
if (core.sizeZ[i] == 0) core.sizeZ[i] = 1;
core.sizeT[i] = (int) (pixels /
(core.sizeX[i] * core.sizeY[i] * core.sizeZ[i] * core.sizeC[i]));
if (core.sizeT[i] == 0) core.sizeT[i] = 1;
core.imageCount[i] = core.sizeZ[i] * core.sizeT[i] * core.sizeC[i];
core.pixelType[i] = FormatTools.UINT16;
core.currentOrder[i] = "XYZTC";
core.indexed[i] = false;
core.falseColor[i] = false;
core.metadataComplete[i] = true;
}
MetadataStore store =
new FilterMetadata(getMetadataStore(), isMetadataFiltered());
MetadataTools.populatePixels(store, this);
int index = 0;
for (int i=0; i<core.sizeX.length; i++) {
store.setImageName(imageNames[i], i);
store.setImageCreationDate(
DataTools.convertDate(System.currentTimeMillis(), DataTools.UNIX), i);
for (int c=0; c<core.sizeC[i]; c++) {
if (index < channelNames.size()) {
store.setLogicalChannelName((String) channelNames.get(index++), i, c);
addMeta(imageNames[i] + " channel " + c, channelNames.get(index - 1));
}
}
}
}
| protected void initFile(String id) throws FormatException, IOException {
if (debug) debug("SlidebookReader.initFile(" + id + ")");
super.initFile(id);
in = new RandomAccessStream(id);
status("Finding offsets to pixel data");
// Slidebook files appear to be comprised of four types of blocks:
// variable length pixel data blocks, 512 byte metadata blocks,
// 128 byte metadata blocks, and variable length metadata blocks.
//
// Fixed-length metadata blocks begin with a 2 byte identifier,
// e.g. 'i' or 'h'.
// Following this are two unknown bytes (usually 256), then a 2 byte
// endianness identifier - II or MM, for little or big endian, respectively.
// Presumably these blocks contain useful information, but for the most
// part we aren't sure what it is or how to extract it.
//
// Variable length metadata blocks begin with 0xffff and are
// (as far as I know) always between two fixed-length metadata blocks.
// These appear to be a relatively new addition to the format - they are
// only present in files received on/after March 30, 2008.
//
// Each pixel data block corresponds to one series.
// The first 'i' metadata block after each pixel data block contains
// the width and height of the planes in that block - this can (and does)
// vary between blocks.
//
// Z, C, and T sizes are computed heuristically based on the number of
// metadata blocks of a specific type.
in.skipBytes(4);
core.littleEndian[0] = in.read() == 0x49;
in.order(core.littleEndian[0]);
metadataOffsets = new Vector();
pixelOffsets = new Vector();
pixelLengths = new Vector();
in.seek(0);
// gather offsets to metadata and pixel data blocks
while (in.getFilePointer() < in.length() - 8) {
in.skipBytes(4);
int checkOne = in.read();
int checkTwo = in.read();
if ((checkOne == 'I' && checkTwo == 'I') ||
(checkOne == 'M' && checkTwo == 'M'))
{
metadataOffsets.add(new Long(in.getFilePointer() - 6));
in.skipBytes(in.readShort() - 8);
}
else if (checkOne == -1 && checkTwo == -1) {
boolean foundBlock = false;
byte[] block = new byte[8192];
in.read(block);
while (!foundBlock) {
for (int i=0; i<block.length-2; i++) {
if ((block[i] == 'M' && block[i + 1] == 'M') ||
(block[i] == 'I' && block[i + 1] == 'I'))
{
foundBlock = true;
in.seek(in.getFilePointer() - block.length + i - 2);
metadataOffsets.add(new Long(in.getFilePointer() - 2));
in.skipBytes(in.readShort() - 5);
break;
}
}
if (!foundBlock) {
block[0] = block[block.length - 2];
block[1] = block[block.length - 1];
in.read(block, 2, block.length - 2);
}
}
}
else {
String s = null;
long fp = in.getFilePointer() - 6;
in.seek(fp);
int len = in.read();
if (len > 0 && len <= 32) {
s = in.readString(len);
}
if (s != null && s.indexOf("Annotation") != -1) {
if (s.equals("CTimelapseAnnotation")) {
in.skipBytes(41);
if (in.read() == 0) in.skipBytes(10);
else in.seek(in.getFilePointer() - 1);
}
else if (s.equals("CIntensityBarAnnotation")) {
in.skipBytes(56);
int n = in.read();
while (n == 0 || n < 6 || n > 0x80) n = in.read();
in.seek(in.getFilePointer() - 1);
}
else if (s.equals("CCubeAnnotation")) {
in.skipBytes(66);
int n = in.read();
if (n != 0) in.seek(in.getFilePointer() - 1);
}
else if (s.equals("CScaleBarAnnotation")) {
in.skipBytes(52);
}
}
else if (s != null && s.indexOf("Decon") != -1) {
in.seek(fp);
while (in.read() != ']');
}
else {
if ((fp % 2) == 1) fp -= 2;
in.seek(fp);
pixelOffsets.add(new Long(fp));
try {
byte[] buf = new byte[8192];
boolean found = false;
int n = in.read(buf);
while (!found && in.getFilePointer() < in.length()) {
for (int i=0; i<buf.length-6; i++) {
if ((buf[i] == 'h' && buf[i+4] == 'I' && buf[i+5] == 'I') ||
(buf[i+1] == 'h' && buf[i+4] == 'M' && buf[i+5] == 'M'))
{
found = true;
in.seek(in.getFilePointer() - n + i - 20);
break;
}
}
if (!found) {
byte[] tmp = buf;
buf = new byte[8192];
System.arraycopy(tmp, tmp.length - 20, buf, 0, 20);
n = in.read(buf, 20, buf.length - 20);
}
}
if (in.getFilePointer() <= in.length()) {
pixelLengths.add(new Long(in.getFilePointer() - fp));
}
else pixelOffsets.remove(pixelOffsets.size() - 1);
}
catch (EOFException e) {
pixelOffsets.remove(pixelOffsets.size() - 1);
}
}
}
}
for (int i=0; i<pixelOffsets.size(); i++) {
long length = ((Long) pixelLengths.get(i)).longValue();
long offset = ((Long) pixelOffsets.get(i)).longValue();
in.seek(offset);
byte checkByte = in.readByte();
if (length + offset >= in.length()) {
pixelOffsets.remove(i);
pixelLengths.remove(i);
i--;
}
else if (checkByte == 'l') {
long lengthSum = ((Long) pixelLengths.get(0)).longValue();
while (pixelLengths.size() > 1) {
int size = pixelLengths.size() - 1;
lengthSum += ((Long) pixelLengths.get(size)).longValue();
pixelLengths.remove(size);
pixelOffsets.remove(size);
}
for (int q=0; q<metadataOffsets.size(); q++) {
long mOffset = ((Long) metadataOffsets.get(q)).longValue();
if (mOffset > lengthSum) {
lengthSum = mOffset - offset;
break;
}
}
pixelLengths.setElementAt(new Long(lengthSum), 0);
break;
}
}
if (pixelOffsets.size() > 1) {
if (pixelOffsets.size() > 2) {
int size = pixelOffsets.size();
long last = ((Long) pixelOffsets.get(size - 1)).longValue();
long nextToLast = ((Long) pixelOffsets.get(size - 2)).longValue();
long diff = in.length() - last;
if (last - nextToLast > 2*diff && diff < (256 * 256 * 2)) {
pixelOffsets.removeElementAt(size - 1);
}
}
boolean little = core.littleEndian[0];
core = new CoreMetadata(pixelOffsets.size());
Arrays.fill(core.littleEndian, little);
}
status("Determining dimensions");
// determine total number of pixel bytes
long pixelBytes = 0;
for (int i=0; i<pixelLengths.size(); i++) {
pixelBytes += ((Long) pixelLengths.get(i)).longValue();
}
String[] imageNames = new String[core.sizeX.length];
Vector channelNames = new Vector();
int nextName = 0;
// try to find the width and height
int iCount = 0;
int hCount = 0;
int uCount = 0;
int prevSeries = -1;
int prevSeriesU = -1;
int nextChannel = 0;
for (int i=0; i<metadataOffsets.size(); i++) {
long off = ((Long) metadataOffsets.get(i)).longValue();
in.seek(off);
long next = i == metadataOffsets.size() - 1 ? in.length() :
((Long) metadataOffsets.get(i + 1)).longValue();
int count = 0;
while (off + count * 128 < next) {
in.seek(off + count * 128);
count++;
char n = (char) in.readShort();
if (n == 'i') {
iCount++;
in.skipBytes(78);
int start = 0;
for (int j=start; j<pixelOffsets.size(); j++) {
long length = ((Long) pixelLengths.get(j)).longValue();
long offset = ((Long) pixelOffsets.get(j)).longValue();
long end = j == pixelOffsets.size() - 1 ? in.length() :
((Long) pixelOffsets.get(j + 1)).longValue();
if (in.getFilePointer() >= (length + offset) &&
in.getFilePointer() < end)
{
if (core.sizeX[j - start] == 0) {
core.sizeX[j - start] = in.readShort();
core.sizeY[j - start] = in.readShort();
int checkX = in.readShort();
int checkY = in.readShort();
int div = in.readShort();
core.sizeX[j - start] /= div;
div = in.readShort();
core.sizeY[j - start] /= div;
}
if (prevSeries != j - start) {
iCount = 1;
}
prevSeries = j - start;
core.sizeC[j - start] = iCount;
break;
}
}
}
else if (n == 'u') {
uCount++;
int start = 0;
for (int j=start; j<pixelOffsets.size(); j++) {
long length = ((Long) pixelLengths.get(j)).longValue();
long offset = ((Long) pixelOffsets.get(j)).longValue();
long end = j == pixelOffsets.size() - 1 ? in.length() :
((Long) pixelOffsets.get(j + 1)).longValue();
if (in.getFilePointer() >= (length + offset) &&
in.getFilePointer() < end)
{
if (prevSeriesU != j - start) {
uCount = 1;
}
prevSeriesU = j - start;
core.sizeZ[j - start] = uCount;
break;
}
}
}
else if (n == 'h') hCount++;
else if (n == 'j') {
in.skipBytes(2);
String check = in.readString(2);
if (check.equals("II") || check.equals("MM")) {
// this block should contain an image name
in.skipBytes(10);
if (nextName < imageNames.length) {
imageNames[nextName++] = in.readCString().trim();
}
}
}
else if (n == 'm') {
// this block should contain a channel name
if (in.getFilePointer() > ((Long) pixelOffsets.get(0)).longValue()) {
in.skipBytes(14);
channelNames.add(in.readCString().trim());
}
}
}
}
for (int i=0; i<core.sizeX.length; i++) {
long pixels = ((Long) pixelLengths.get(i)).longValue() / 2;
boolean x = true;
while (core.sizeX[i] * core.sizeY[i] * core.sizeC[i] * core.sizeZ[i] >
pixels)
{
if (x) core.sizeX[i] /= 2;
else core.sizeY[i] /= 2;
x = !x;
}
if (core.sizeZ[i] == 0) core.sizeZ[i] = 1;
core.sizeT[i] = (int) (pixels /
(core.sizeX[i] * core.sizeY[i] * core.sizeZ[i] * core.sizeC[i]));
if (core.sizeT[i] == 0) core.sizeT[i] = 1;
core.imageCount[i] = core.sizeZ[i] * core.sizeT[i] * core.sizeC[i];
core.pixelType[i] = FormatTools.UINT16;
core.currentOrder[i] = "XYZTC";
core.indexed[i] = false;
core.falseColor[i] = false;
core.metadataComplete[i] = true;
}
MetadataStore store =
new FilterMetadata(getMetadataStore(), isMetadataFiltered());
MetadataTools.populatePixels(store, this);
int index = 0;
for (int i=0; i<core.sizeX.length; i++) {
store.setImageName(imageNames[i], i);
store.setImageCreationDate(
DataTools.convertDate(System.currentTimeMillis(), DataTools.UNIX), i);
for (int c=0; c<core.sizeC[i]; c++) {
if (index < channelNames.size()) {
store.setLogicalChannelName((String) channelNames.get(index++), i, c);
addMeta(imageNames[i] + " channel " + c, channelNames.get(index - 1));
}
}
}
}
|
diff --git a/src/main/java/org/hardisonbrewing/clover/ReductMojo.java b/src/main/java/org/hardisonbrewing/clover/ReductMojo.java
index 8f9d3e0..7cde2ee 100644
--- a/src/main/java/org/hardisonbrewing/clover/ReductMojo.java
+++ b/src/main/java/org/hardisonbrewing/clover/ReductMojo.java
@@ -1,590 +1,591 @@
/**
* Copyright (c) 2013 Martin M Reed
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.hardisonbrewing.clover;
import generated.ClassMetrics;
import generated.Construct;
import generated.Coverage;
import generated.FileMetrics;
import generated.Line;
import generated.PackageMetrics;
import generated.Project;
import generated.ProjectMetrics;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.project.MavenProject;
import org.codehaus.plexus.util.FileUtils;
import org.codehaus.plexus.util.cli.CommandLineException;
import org.codehaus.plexus.util.cli.CommandLineUtils;
import org.codehaus.plexus.util.cli.Commandline;
import org.codehaus.plexus.util.cli.StreamConsumer;
import org.hardisonbrewing.jaxb.JAXB;
import com.google.common.collect.SortedArraySet;
/**
* @goal reduct
* @phase reduct
* @requiresProject false
*/
public final class ReductMojo extends AbstractMojo {
private static final int DEFAULT_THREAD_COUNT = 15;
private static final String CLOVER = "clover";
private static final String WORKING_COPY = "workingCopy";
private static final String CUTOFF_DATE = "cutoffDate";
private static final String THREAD_COUNT = "threads";
private static final String SVN_USERNAME = "svnUsername";
private File cloverReportFile;
private String svnUsername;
private String workingCopyPath;
private String cutoffDate;
private int threadCount = DEFAULT_THREAD_COUNT;
private File targetDirectory;
private long cutoffRevision;
/**
* @parameter expression="${project}"
* @required
*/
private MavenProject mavenProject;
/**
* @parameter expression="${session}"
* @readonly
* @required
*/
private MavenSession mavenSession;
@Override
public final void execute() throws MojoExecutionException, MojoFailureException {
if ( !mavenProject.isExecutionRoot() ) {
return;
}
long start = System.currentTimeMillis();
try {
_execute();
}
catch (Exception e) {
throw new IllegalStateException( e );
}
finally {
long end = System.currentTimeMillis();
getLog().info( "Executed in " + ( ( end - start ) / 1000.0 ) + "s" );
}
}
private void _execute() throws Exception {
svnUsername = getProperty( SVN_USERNAME );
initCloverFilePath();
initWorkingCopyPath();
initCutoffDate();
initThreadCount();
getLog().info( "Using coverage report from: " + cloverReportFile.getPath() );
targetDirectory = new File( "target", "clover-reductor" );
targetDirectory.mkdirs();
FileUtils.copyFile( cloverReportFile, new File( targetDirectory, "clover-original.xml" ) );
Coverage coverage = JAXB.unmarshal( cloverReportFile, Coverage.class );
Project project = coverage.getProject();
getLog().info( "Running Reductor: " + project.getName() );
List<generated.Package> packages = project.getPackage();
if ( packages.isEmpty() ) {
getLog().info( "No packages found." );
return;
}
cutoffRevision = findCutoffRevision( workingCopyPath );
getLog().info( "Cutoff Revision: " + cutoffRevision );
int fileCount = 0;
- for (generated.Package _package : packages) {
+ for (int i = packages.size() - 1; i >= 0; i--) {
+ generated.Package _package = packages.get( i );
List<generated.File> files = _package.getFile();
if ( files.isEmpty() ) {
packages.remove( _package );
continue;
}
fileCount += files.size();
}
if ( fileCount == 0 ) {
getLog().info( "No files found." );
return;
}
BlameThread[] threads = new BlameThread[Math.min( fileCount, threadCount )];
List<generated.Package> packagesReduced = new LinkedList<generated.Package>();
for (int i = 0; i < threads.length; i++) {
threads[i] = new BlameThread( packages, packagesReduced );
new Thread( threads[i] ).start();
}
for (BlameThread thread : threads) {
thread.waitUntilFinished();
}
Project projectReduced = new Project();
projectReduced.setMetrics( new ProjectMetrics() );
projectReduced.setName( project.getName() );
projectReduced.setTimestamp( project.getTimestamp() );
for (generated.Package _package : packagesReduced) {
add( projectReduced, _package );
}
Coverage coverageReduced = new Coverage();
coverageReduced.setProject( projectReduced );
coverageReduced.setClover( coverageReduced.getClover() );
coverageReduced.setGenerated( coverage.getGenerated() );
File cloverReportReducedFile = reducedFile( cloverReportFile );
getLog().info( "Saving new coverage report to: " + cloverReportReducedFile.getPath() );
JAXB.marshal( cloverReportReducedFile, coverageReduced );
}
private File reducedFile( File file ) {
String name = file.getName();
String extension = FileUtils.extension( name );
name = name.substring( 0, name.length() - ( extension.length() + 1 ) );
name = name + "-reduced." + extension;
return new File( file.getParent(), name );
}
private String getProperty( String key ) {
String value = mavenSession.getExecutionProperties().getProperty( key );
if ( value == null ) {
value = mavenProject.getProperties().getProperty( key );
}
if ( value == null ) {
return null;
}
boolean startsWith = value.startsWith( "\"" );
boolean endsWith = value.endsWith( "\"" );
if ( startsWith || endsWith ) {
int length = value.length();
int start = startsWith ? 1 : 0;
int end = endsWith ? length - 1 : length;
value = value.substring( start, end );
}
return value;
}
private void initCloverFilePath() throws Exception {
String cloverReportPath = getProperty( CLOVER );
if ( cloverReportPath == null || cloverReportPath.length() == 0 ) {
getLog().error( "Required property `" + CLOVER + "` missing. Use -D" + CLOVER + "=<path to xml>" );
throw new IllegalArgumentException();
}
cloverReportFile = new File( cloverReportPath );
if ( !cloverReportFile.exists() ) {
throw new FileNotFoundException( cloverReportFile.getPath() );
}
}
private void initWorkingCopyPath() throws Exception {
workingCopyPath = getProperty( WORKING_COPY );
if ( workingCopyPath == null || workingCopyPath.length() == 0 ) {
getLog().error( "Required property `" + WORKING_COPY + "` missing. Use -D" + WORKING_COPY + "=<path to working copy>" );
throw new IllegalArgumentException();
}
if ( !new File( workingCopyPath ).exists() ) {
throw new FileNotFoundException( workingCopyPath );
}
if ( !new File( workingCopyPath, ".svn" ).exists() ) {
getLog().error( "Directory is not a working copy: " + workingCopyPath );
throw new IllegalArgumentException();
}
}
private void initCutoffDate() throws Exception {
cutoffDate = getProperty( CUTOFF_DATE );
if ( cutoffDate == null || cutoffDate.length() == 0 ) {
getLog().error( "Required property `" + CUTOFF_DATE + "` missing. Use -D" + CUTOFF_DATE + "=<timestamp>" );
throw new IllegalArgumentException();
}
}
private void initThreadCount() throws Exception {
String threadCountStr = getProperty( THREAD_COUNT );
if ( threadCountStr != null && threadCountStr.length() > 0 ) {
try {
threadCount = Integer.parseInt( threadCountStr );
}
catch (NumberFormatException e) {
getLog().error( "Illegal thread count specified: -D" + THREAD_COUNT + "=" + threadCountStr + ". Must be an integer." );
throw new IllegalArgumentException();
}
}
}
private generated.File reduceFile( generated.File file ) throws Exception {
String filePath = file.getPath();
if ( !new File( filePath ).exists() ) {
throw new FileNotFoundException( filePath );
}
Properties properties = info( filePath );
long revision = Long.parseLong( properties.getProperty( "Revision" ) );
if ( revision < cutoffRevision ) {
return null;
}
generated.File fileReduced = null;
Set<Line> sortedLines = null;
List<Long> revisions = blame( file.getPath() );
for (Line line : file.getLine()) {
int lineNumber = line.getNum();
if ( cutoffRevision >= revisions.get( lineNumber - 1 ) ) {
continue;
}
if ( fileReduced == null ) {
fileReduced = new generated.File();
fileReduced.setMetrics( new FileMetrics() );
fileReduced.setName( file.getName() );
fileReduced.setPath( file.getPath() );
sortedLines = new SortedArraySet<Line>( new LineComparator() );
}
addMetrics( fileReduced, line );
sortedLines.add( line );
}
if ( fileReduced != null ) {
List<Line> lines = fileReduced.getLine();
lines.addAll( sortedLines );
}
return fileReduced;
}
private void addMetrics( generated.File file, Line line ) {
FileMetrics fileMetrics = file.getMetrics();
int elements = 0;
int coveredElements = 0;
switch (line.getType()) {
case STMT: {
elements = 1;
coveredElements = Math.min( 1, line.getCount() );
fileMetrics.setLoc( _int( fileMetrics.getLoc() ) + 1 );
fileMetrics.setStatements( fileMetrics.getStatements() + elements );
fileMetrics.setCoveredstatements( fileMetrics.getCoveredstatements() + coveredElements );
break;
}
case COND: {
elements = 2;
coveredElements = Math.min( 1, line.getTruecount() ) + Math.min( 1, line.getFalsecount() );
fileMetrics.setConditionals( fileMetrics.getConditionals() + elements );
fileMetrics.setCoveredconditionals( fileMetrics.getCoveredconditionals() + coveredElements );
break;
}
case METHOD: {
elements = 1;
coveredElements = Math.min( 1, line.getCount() );
fileMetrics.setMethods( fileMetrics.getMethods() + elements );
fileMetrics.setCoveredmethods( fileMetrics.getCoveredmethods() + coveredElements );
break;
}
}
fileMetrics.setElements( fileMetrics.getElements() + elements );
fileMetrics.setCoveredelements( fileMetrics.getCoveredelements() + coveredElements );
}
private void add( generated.Package _package, generated.File file ) {
PackageMetrics packageMetrics = _package.getMetrics();
packageMetrics.setFiles( _int( packageMetrics.getFiles() ) + 1 );
add( packageMetrics, file.getMetrics() );
List<generated.File> files = _package.getFile();
files.add( file );
}
private int _int( Integer integer ) {
return integer == null ? 0 : integer.intValue();
}
private void add( Project project, generated.Package _package ) {
ProjectMetrics projectMetrics = project.getMetrics();
projectMetrics.setPackages( _int( projectMetrics.getPackages() ) + 1 );
add( projectMetrics, _package.getMetrics() );
List<generated.Package> packages = project.getPackage();
packages.add( _package );
}
private void add( PackageMetrics parent, PackageMetrics child ) {
parent.setFiles( _int( parent.getFiles() ) + _int( child.getFiles() ) );
add( (FileMetrics) parent, child );
}
private void add( FileMetrics parent, FileMetrics child ) {
parent.setClasses( _int( parent.getClasses() ) + _int( child.getClasses() ) );
parent.setLoc( _int( parent.getLoc() ) + _int( child.getLoc() ) );
add( (ClassMetrics) parent, child );
}
private void add( ClassMetrics parent, ClassMetrics child ) {
parent.setStatements( parent.getStatements() + child.getStatements() );
parent.setConditionals( parent.getConditionals() + child.getConditionals() );
parent.setMethods( parent.getMethods() + child.getMethods() );
parent.setElements( parent.getElements() + child.getElements() );
parent.setCoveredstatements( parent.getCoveredstatements() + child.getCoveredstatements() );
parent.setCoveredconditionals( parent.getCoveredconditionals() + child.getCoveredconditionals() );
parent.setCoveredmethods( parent.getCoveredmethods() + child.getCoveredmethods() );
parent.setCoveredelements( parent.getCoveredelements() + child.getCoveredelements() );
}
private Properties info( String filePath ) throws Exception {
List<String> cmd = new LinkedList<String>();
cmd.add( "svn" );
cmd.add( "info" );
if ( svnUsername != null ) {
cmd.add( "--username=" + svnUsername );
}
cmd.add( filePath );
Properties properties = new Properties();
StreamConsumer streamConsumer = new InfoStreamConsumer( properties );
CommandLineUtils.executeCommandLine( build( cmd ), streamConsumer, streamConsumer );
return properties;
}
private List<Long> blame( String filePath ) throws Exception {
List<String> cmd = new LinkedList<String>();
cmd.add( "svn" );
cmd.add( "blame" );
if ( svnUsername != null ) {
cmd.add( "--username=" + svnUsername );
}
cmd.add( filePath );
List<Long> revisions = new LinkedList<Long>();
StreamConsumer streamConsumer = new BlameStreamConsumer( revisions );
CommandLineUtils.executeCommandLine( build( cmd ), streamConsumer, streamConsumer );
return revisions;
}
private long findCutoffRevision( String workingCopy ) throws Exception {
Properties properties = info( workingCopy );
List<String> cmd = new LinkedList<String>();
cmd.add( "svn" );
cmd.add( "checkout" );
if ( svnUsername != null ) {
cmd.add( "--username=" + svnUsername );
}
cmd.add( "-r" );
cmd.add( "{" + cutoffDate + "}" );
cmd.add( "--depth" );
cmd.add( "empty" );
cmd.add( properties.getProperty( "Repository Root" ) );
cmd.add( targetDirectory.getPath() );
RevisionStreamConsumer streamConsumer = new RevisionStreamConsumer();
CommandLineUtils.executeCommandLine( build( cmd ), streamConsumer, streamConsumer );
return streamConsumer.getRevision();
}
private Commandline build( List<String> cmd ) throws CommandLineException {
Commandline commandLine = new Commandline();
commandLine.setExecutable( cmd.get( 0 ) );
for (int i = 1; i < cmd.size(); i++) {
commandLine.createArg().setValue( cmd.get( i ) );
}
return commandLine;
}
private final class BlameThread implements Runnable {
private final Object lock = new Object();
private final List<generated.Package> packages;
private final List<generated.Package> packagesReduced;
private boolean finished;
public BlameThread(List<generated.Package> packages, List<generated.Package> packagesReduced) {
this.packages = packages;
this.packagesReduced = packagesReduced;
}
@Override
public void run() {
try {
while (true) {
generated.Package _package = null;
generated.File file = null;
synchronized (packages) {
if ( packages.isEmpty() ) {
break;
}
_package = packages.get( 0 );
List<generated.File> files = _package.getFile();
file = files.remove( 0 );
if ( files.isEmpty() ) {
packages.remove( 0 );
}
}
generated.File fileReduced = null;
try {
fileReduced = reduceFile( file );
}
catch (Exception e) {
getLog().error( "Unable to inspect file: " + file.getName() );
e.printStackTrace();
}
if ( fileReduced != null ) {
synchronized (packages) {
generated.Package packageReduced = getPackage( _package.getName() );
add( packageReduced, fileReduced );
}
}
}
}
finally {
finished = true;
synchronized (lock) {
lock.notify();
}
}
}
private generated.Package getPackage( String name ) {
for (generated.Package _package : packagesReduced) {
if ( name.equals( _package.getName() ) ) {
return _package;
}
}
generated.Package _package = new generated.Package();
_package.setMetrics( new PackageMetrics() );
_package.setName( name );
packagesReduced.add( _package );
return _package;
}
private void waitUntilFinished() {
if ( finished ) {
return;
}
synchronized (lock) {
while (!finished) {
try {
lock.wait();
}
catch (InterruptedException e) {
// do nothing
}
}
}
}
}
private static class LineComparator implements Comparator<Line> {
@Override
public int compare( Line line1, Line line2 ) {
int num1 = line1.getNum();
int num2 = line2.getNum();
if ( num1 != num2 ) {
return num1 - num2;
}
Construct type1 = line1.getType();
Construct type2 = line2.getType();
if ( type1 != type2 ) {
return type1.ordinal() - type2.ordinal();
}
return 1;
}
}
}
| false | true | private void _execute() throws Exception {
svnUsername = getProperty( SVN_USERNAME );
initCloverFilePath();
initWorkingCopyPath();
initCutoffDate();
initThreadCount();
getLog().info( "Using coverage report from: " + cloverReportFile.getPath() );
targetDirectory = new File( "target", "clover-reductor" );
targetDirectory.mkdirs();
FileUtils.copyFile( cloverReportFile, new File( targetDirectory, "clover-original.xml" ) );
Coverage coverage = JAXB.unmarshal( cloverReportFile, Coverage.class );
Project project = coverage.getProject();
getLog().info( "Running Reductor: " + project.getName() );
List<generated.Package> packages = project.getPackage();
if ( packages.isEmpty() ) {
getLog().info( "No packages found." );
return;
}
cutoffRevision = findCutoffRevision( workingCopyPath );
getLog().info( "Cutoff Revision: " + cutoffRevision );
int fileCount = 0;
for (generated.Package _package : packages) {
List<generated.File> files = _package.getFile();
if ( files.isEmpty() ) {
packages.remove( _package );
continue;
}
fileCount += files.size();
}
if ( fileCount == 0 ) {
getLog().info( "No files found." );
return;
}
BlameThread[] threads = new BlameThread[Math.min( fileCount, threadCount )];
List<generated.Package> packagesReduced = new LinkedList<generated.Package>();
for (int i = 0; i < threads.length; i++) {
threads[i] = new BlameThread( packages, packagesReduced );
new Thread( threads[i] ).start();
}
for (BlameThread thread : threads) {
thread.waitUntilFinished();
}
Project projectReduced = new Project();
projectReduced.setMetrics( new ProjectMetrics() );
projectReduced.setName( project.getName() );
projectReduced.setTimestamp( project.getTimestamp() );
for (generated.Package _package : packagesReduced) {
add( projectReduced, _package );
}
Coverage coverageReduced = new Coverage();
coverageReduced.setProject( projectReduced );
coverageReduced.setClover( coverageReduced.getClover() );
coverageReduced.setGenerated( coverage.getGenerated() );
File cloverReportReducedFile = reducedFile( cloverReportFile );
getLog().info( "Saving new coverage report to: " + cloverReportReducedFile.getPath() );
JAXB.marshal( cloverReportReducedFile, coverageReduced );
}
| private void _execute() throws Exception {
svnUsername = getProperty( SVN_USERNAME );
initCloverFilePath();
initWorkingCopyPath();
initCutoffDate();
initThreadCount();
getLog().info( "Using coverage report from: " + cloverReportFile.getPath() );
targetDirectory = new File( "target", "clover-reductor" );
targetDirectory.mkdirs();
FileUtils.copyFile( cloverReportFile, new File( targetDirectory, "clover-original.xml" ) );
Coverage coverage = JAXB.unmarshal( cloverReportFile, Coverage.class );
Project project = coverage.getProject();
getLog().info( "Running Reductor: " + project.getName() );
List<generated.Package> packages = project.getPackage();
if ( packages.isEmpty() ) {
getLog().info( "No packages found." );
return;
}
cutoffRevision = findCutoffRevision( workingCopyPath );
getLog().info( "Cutoff Revision: " + cutoffRevision );
int fileCount = 0;
for (int i = packages.size() - 1; i >= 0; i--) {
generated.Package _package = packages.get( i );
List<generated.File> files = _package.getFile();
if ( files.isEmpty() ) {
packages.remove( _package );
continue;
}
fileCount += files.size();
}
if ( fileCount == 0 ) {
getLog().info( "No files found." );
return;
}
BlameThread[] threads = new BlameThread[Math.min( fileCount, threadCount )];
List<generated.Package> packagesReduced = new LinkedList<generated.Package>();
for (int i = 0; i < threads.length; i++) {
threads[i] = new BlameThread( packages, packagesReduced );
new Thread( threads[i] ).start();
}
for (BlameThread thread : threads) {
thread.waitUntilFinished();
}
Project projectReduced = new Project();
projectReduced.setMetrics( new ProjectMetrics() );
projectReduced.setName( project.getName() );
projectReduced.setTimestamp( project.getTimestamp() );
for (generated.Package _package : packagesReduced) {
add( projectReduced, _package );
}
Coverage coverageReduced = new Coverage();
coverageReduced.setProject( projectReduced );
coverageReduced.setClover( coverageReduced.getClover() );
coverageReduced.setGenerated( coverage.getGenerated() );
File cloverReportReducedFile = reducedFile( cloverReportFile );
getLog().info( "Saving new coverage report to: " + cloverReportReducedFile.getPath() );
JAXB.marshal( cloverReportReducedFile, coverageReduced );
}
|
diff --git a/src/org/ohmage/service/UploadService.java b/src/org/ohmage/service/UploadService.java
index d731142..e1aac23 100644
--- a/src/org/ohmage/service/UploadService.java
+++ b/src/org/ohmage/service/UploadService.java
@@ -1,250 +1,250 @@
package org.ohmage.service;
import java.io.File;
import java.io.FilenameFilter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.ohmage.CampaignManager;
import org.ohmage.NotificationHelper;
import org.ohmage.OhmageApi;
import org.ohmage.Utilities;
import org.ohmage.OhmageApi.Result;
import org.ohmage.SharedPreferencesHelper;
import org.ohmage.activity.CampaignListActivity;
import org.ohmage.activity.LoginActivity;
import org.ohmage.activity.UploadQueueActivity;
import org.ohmage.db.DbContract.Campaigns;
import org.ohmage.db.DbContract.PromptResponses;
import org.ohmage.db.DbContract.Responses;
import org.ohmage.db.DbContract.SurveyPrompts;
import org.ohmage.db.DbHelper;
import org.ohmage.db.DbHelper.Tables;
import org.ohmage.db.Models.Campaign;
import org.ohmage.db.Models.Response;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import com.commonsware.cwac.wakeful.WakefulIntentService;
import edu.ucla.cens.systemlog.Log;
public class UploadService extends WakefulIntentService {
private static final String TAG = "UploadService";
public UploadService() {
super(TAG);
}
@Override
protected void doWakefulWork(Intent intent) {
String serverUrl = SharedPreferencesHelper.DEFAULT_SERVER_URL;
SharedPreferencesHelper helper = new SharedPreferencesHelper(this);
String username = helper.getUsername();
String hashedPassword = helper.getHashedPassword();
boolean isBackground = intent.getBooleanExtra("is_background", false);
boolean uploadErrorOccurred = false;
boolean authErrorOccurred = false;
OhmageApi api = new OhmageApi(this);
DbHelper dbHelper = new DbHelper(this);
Uri dataUri = intent.getData();
ContentResolver cr = getContentResolver();
String [] projection = new String [] {
Tables.RESPONSES + "." + Responses._ID,
Responses.RESPONSE_DATE,
Responses.RESPONSE_TIME,
Responses.RESPONSE_TIMEZONE,
Responses.RESPONSE_LOCATION_STATUS,
Responses.RESPONSE_LOCATION_LATITUDE,
Responses.RESPONSE_LOCATION_LONGITUDE,
Responses.RESPONSE_LOCATION_PROVIDER,
Responses.RESPONSE_LOCATION_ACCURACY,
Responses.RESPONSE_LOCATION_TIME,
Tables.RESPONSES + "." + Responses.SURVEY_ID,
Responses.RESPONSE_SURVEY_LAUNCH_CONTEXT,
Responses.RESPONSE_JSON,
Tables.RESPONSES + "." + Responses.CAMPAIGN_URN,
Campaigns.CAMPAIGN_CREATED};
String select = Responses.RESPONSE_STATUS + "!=" + Response.STATUS_DOWNLOADED + " AND " +
Responses.RESPONSE_STATUS + "!=" + Response.STATUS_UPLOADED + " AND " +
Responses.RESPONSE_STATUS + "!=" + Response.STATUS_WAITING_FOR_LOCATION;
Cursor cursor = cr.query(dataUri, projection, select, null, null);
cursor.moveToFirst();
ContentValues cv = new ContentValues();
cv.put(Responses.RESPONSE_STATUS, Response.STATUS_QUEUED);
cr.update(dataUri, cv, select, null);
for (int i = 0; i < cursor.getCount(); i++) {
long responseId = cursor.getLong(cursor.getColumnIndex(Responses._ID));
ContentValues values = new ContentValues();
values.put(Responses.RESPONSE_STATUS, Response.STATUS_UPLOADING);
cr.update(Responses.buildResponseUri(responseId), values, null, null);
// cr.update(Responses.CONTENT_URI, values, Tables.RESPONSES + "." + Responses._ID + "=" + responseId, null);
JSONArray responsesJsonArray = new JSONArray();
JSONObject responseJson = new JSONObject();
final ArrayList<String> photoUUIDs = new ArrayList<String>();
try {
responseJson.put("date", cursor.getString(cursor.getColumnIndex(Responses.RESPONSE_DATE)));
responseJson.put("time", cursor.getLong(cursor.getColumnIndex(Responses.RESPONSE_TIME)));
responseJson.put("timezone", cursor.getString(cursor.getColumnIndex(Responses.RESPONSE_TIMEZONE)));
String locationStatus = cursor.getString(cursor.getColumnIndex(Responses.RESPONSE_LOCATION_STATUS));
responseJson.put("location_status", locationStatus);
if (! locationStatus.equals(SurveyGeotagService.LOCATION_UNAVAILABLE)) {
JSONObject locationJson = new JSONObject();
locationJson.put("latitude", cursor.getDouble(cursor.getColumnIndex(Responses.RESPONSE_LOCATION_LATITUDE)));
locationJson.put("longitude", cursor.getDouble(cursor.getColumnIndex(Responses.RESPONSE_LOCATION_LONGITUDE)));
locationJson.put("provider", cursor.getString(cursor.getColumnIndex(Responses.RESPONSE_LOCATION_PROVIDER)));
locationJson.put("accuracy", cursor.getFloat(cursor.getColumnIndex(Responses.RESPONSE_LOCATION_ACCURACY)));
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String locationTimestamp = dateFormat.format(new Date(cursor.getLong(cursor.getColumnIndex(Responses.RESPONSE_LOCATION_TIME))));
locationJson.put("timestamp", locationTimestamp);
responseJson.put("location", locationJson);
}
responseJson.put("survey_id", cursor.getString(cursor.getColumnIndex(Responses.SURVEY_ID)));
responseJson.put("survey_launch_context", new JSONObject(cursor.getString(cursor.getColumnIndex(Responses.RESPONSE_SURVEY_LAUNCH_CONTEXT))));
responseJson.put("responses", new JSONArray(cursor.getString(cursor.getColumnIndex(Responses.RESPONSE_JSON))));
ContentResolver cr2 = getContentResolver();
Cursor promptsCursor = cr2.query(Responses.buildPromptResponsesUri(responseId), new String [] {PromptResponses.PROMPT_RESPONSE_VALUE, SurveyPrompts.SURVEY_PROMPT_TYPE}, SurveyPrompts.SURVEY_PROMPT_TYPE + "='photo'", null, null);
while (promptsCursor.moveToNext()) {
photoUUIDs.add(promptsCursor.getString(promptsCursor.getColumnIndex(PromptResponses.PROMPT_RESPONSE_VALUE)));
}
promptsCursor.close();
} catch (JSONException e) {
throw new RuntimeException(e);
}
responsesJsonArray.put(responseJson);
String campaignUrn = cursor.getString(cursor.getColumnIndex(Responses.CAMPAIGN_URN));
String campaignCreationTimestamp = cursor.getString(cursor.getColumnIndex(Campaigns.CAMPAIGN_CREATED));
File [] photos = Campaign.getCampaignImageDir(this, campaignUrn).listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String filename) {
if (photoUUIDs.contains(filename.split("\\.")[0])) {
return true;
}
return false;
}
});
OhmageApi.UploadResponse response = api.surveyUpload(serverUrl, username, hashedPassword, SharedPreferencesHelper.CLIENT_STRING, campaignUrn, campaignCreationTimestamp, responsesJsonArray.toString(), photos);
if (response.getResult() == Result.SUCCESS) {
dbHelper.setResponseRowUploaded(responseId);
} else {
int errorStatusCode = Response.STATUS_ERROR_OTHER;
switch (response.getResult()) {
case FAILURE:
Log.e(TAG, "Upload failed due to error codes: " + Utilities.stringArrayToString(response.getErrorCodes(), ", "));
uploadErrorOccurred = true;
boolean isAuthenticationError = false;
boolean isUserDisabled = false;
String errorCode = null;
for (String code : response.getErrorCodes()) {
if (code.charAt(1) == '2') {
authErrorOccurred = true;
isAuthenticationError = true;
if (code.equals("0201")) {
isUserDisabled = true;
}
}
if (code.equals("0700") || code.equals("0707") || code.equals("0703") || code.equals("0710")) {
errorCode = code;
break;
}
}
if (isUserDisabled) {
new SharedPreferencesHelper(this).setUserDisabled(true);
}
if (isAuthenticationError) {
errorStatusCode = Response.STATUS_ERROR_AUTHENTICATION;
- } else if (errorCode.equals("0700")) {
+ } else if ("0700".equals(errorCode)) {
errorStatusCode = Response.STATUS_ERROR_CAMPAIGN_NO_EXIST;
dbHelper.updateCampaignStatus(campaignUrn, Campaign.STATUS_NO_EXIST);
- } else if (errorCode.equals("0707")) {
+ } else if ("0707".equals(errorCode)) {
errorStatusCode = Response.STATUS_ERROR_INVALID_USER_ROLE;
dbHelper.updateCampaignStatus(campaignUrn, Campaign.STATUS_INVALID_USER_ROLE);
- } else if (errorCode.equals("0703")) {
+ } else if ("0703".equals(errorCode)) {
errorStatusCode = Response.STATUS_ERROR_CAMPAIGN_STOPPED;
dbHelper.updateCampaignStatus(campaignUrn, Campaign.STATUS_STOPPED);
- } else if (errorCode.equals("0710")) {
+ } else if ("0710".equals(errorCode)) {
errorStatusCode = Response.STATUS_ERROR_CAMPAIGN_OUT_OF_DATE;
dbHelper.updateCampaignStatus(campaignUrn, Campaign.STATUS_OUT_OF_DATE);
} else {
errorStatusCode = Response.STATUS_ERROR_OTHER;
}
break;
case INTERNAL_ERROR:
uploadErrorOccurred = true;
errorStatusCode = Response.STATUS_ERROR_OTHER;
break;
case HTTP_ERROR:
errorStatusCode = Response.STATUS_ERROR_HTTP;
break;
}
ContentValues cv2 = new ContentValues();
cv2.put(Responses.RESPONSE_STATUS, errorStatusCode);
cr.update(Responses.buildResponseUri(responseId), cv2, null, null);
}
cursor.moveToNext();
}
cursor.close();
if (isBackground) {
if (authErrorOccurred) {
NotificationHelper.showAuthNotification(this);
} else if (uploadErrorOccurred) {
NotificationHelper.showUploadErrorNotification(this);
}
}
}
}
| false | true | protected void doWakefulWork(Intent intent) {
String serverUrl = SharedPreferencesHelper.DEFAULT_SERVER_URL;
SharedPreferencesHelper helper = new SharedPreferencesHelper(this);
String username = helper.getUsername();
String hashedPassword = helper.getHashedPassword();
boolean isBackground = intent.getBooleanExtra("is_background", false);
boolean uploadErrorOccurred = false;
boolean authErrorOccurred = false;
OhmageApi api = new OhmageApi(this);
DbHelper dbHelper = new DbHelper(this);
Uri dataUri = intent.getData();
ContentResolver cr = getContentResolver();
String [] projection = new String [] {
Tables.RESPONSES + "." + Responses._ID,
Responses.RESPONSE_DATE,
Responses.RESPONSE_TIME,
Responses.RESPONSE_TIMEZONE,
Responses.RESPONSE_LOCATION_STATUS,
Responses.RESPONSE_LOCATION_LATITUDE,
Responses.RESPONSE_LOCATION_LONGITUDE,
Responses.RESPONSE_LOCATION_PROVIDER,
Responses.RESPONSE_LOCATION_ACCURACY,
Responses.RESPONSE_LOCATION_TIME,
Tables.RESPONSES + "." + Responses.SURVEY_ID,
Responses.RESPONSE_SURVEY_LAUNCH_CONTEXT,
Responses.RESPONSE_JSON,
Tables.RESPONSES + "." + Responses.CAMPAIGN_URN,
Campaigns.CAMPAIGN_CREATED};
String select = Responses.RESPONSE_STATUS + "!=" + Response.STATUS_DOWNLOADED + " AND " +
Responses.RESPONSE_STATUS + "!=" + Response.STATUS_UPLOADED + " AND " +
Responses.RESPONSE_STATUS + "!=" + Response.STATUS_WAITING_FOR_LOCATION;
Cursor cursor = cr.query(dataUri, projection, select, null, null);
cursor.moveToFirst();
ContentValues cv = new ContentValues();
cv.put(Responses.RESPONSE_STATUS, Response.STATUS_QUEUED);
cr.update(dataUri, cv, select, null);
for (int i = 0; i < cursor.getCount(); i++) {
long responseId = cursor.getLong(cursor.getColumnIndex(Responses._ID));
ContentValues values = new ContentValues();
values.put(Responses.RESPONSE_STATUS, Response.STATUS_UPLOADING);
cr.update(Responses.buildResponseUri(responseId), values, null, null);
// cr.update(Responses.CONTENT_URI, values, Tables.RESPONSES + "." + Responses._ID + "=" + responseId, null);
JSONArray responsesJsonArray = new JSONArray();
JSONObject responseJson = new JSONObject();
final ArrayList<String> photoUUIDs = new ArrayList<String>();
try {
responseJson.put("date", cursor.getString(cursor.getColumnIndex(Responses.RESPONSE_DATE)));
responseJson.put("time", cursor.getLong(cursor.getColumnIndex(Responses.RESPONSE_TIME)));
responseJson.put("timezone", cursor.getString(cursor.getColumnIndex(Responses.RESPONSE_TIMEZONE)));
String locationStatus = cursor.getString(cursor.getColumnIndex(Responses.RESPONSE_LOCATION_STATUS));
responseJson.put("location_status", locationStatus);
if (! locationStatus.equals(SurveyGeotagService.LOCATION_UNAVAILABLE)) {
JSONObject locationJson = new JSONObject();
locationJson.put("latitude", cursor.getDouble(cursor.getColumnIndex(Responses.RESPONSE_LOCATION_LATITUDE)));
locationJson.put("longitude", cursor.getDouble(cursor.getColumnIndex(Responses.RESPONSE_LOCATION_LONGITUDE)));
locationJson.put("provider", cursor.getString(cursor.getColumnIndex(Responses.RESPONSE_LOCATION_PROVIDER)));
locationJson.put("accuracy", cursor.getFloat(cursor.getColumnIndex(Responses.RESPONSE_LOCATION_ACCURACY)));
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String locationTimestamp = dateFormat.format(new Date(cursor.getLong(cursor.getColumnIndex(Responses.RESPONSE_LOCATION_TIME))));
locationJson.put("timestamp", locationTimestamp);
responseJson.put("location", locationJson);
}
responseJson.put("survey_id", cursor.getString(cursor.getColumnIndex(Responses.SURVEY_ID)));
responseJson.put("survey_launch_context", new JSONObject(cursor.getString(cursor.getColumnIndex(Responses.RESPONSE_SURVEY_LAUNCH_CONTEXT))));
responseJson.put("responses", new JSONArray(cursor.getString(cursor.getColumnIndex(Responses.RESPONSE_JSON))));
ContentResolver cr2 = getContentResolver();
Cursor promptsCursor = cr2.query(Responses.buildPromptResponsesUri(responseId), new String [] {PromptResponses.PROMPT_RESPONSE_VALUE, SurveyPrompts.SURVEY_PROMPT_TYPE}, SurveyPrompts.SURVEY_PROMPT_TYPE + "='photo'", null, null);
while (promptsCursor.moveToNext()) {
photoUUIDs.add(promptsCursor.getString(promptsCursor.getColumnIndex(PromptResponses.PROMPT_RESPONSE_VALUE)));
}
promptsCursor.close();
} catch (JSONException e) {
throw new RuntimeException(e);
}
responsesJsonArray.put(responseJson);
String campaignUrn = cursor.getString(cursor.getColumnIndex(Responses.CAMPAIGN_URN));
String campaignCreationTimestamp = cursor.getString(cursor.getColumnIndex(Campaigns.CAMPAIGN_CREATED));
File [] photos = Campaign.getCampaignImageDir(this, campaignUrn).listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String filename) {
if (photoUUIDs.contains(filename.split("\\.")[0])) {
return true;
}
return false;
}
});
OhmageApi.UploadResponse response = api.surveyUpload(serverUrl, username, hashedPassword, SharedPreferencesHelper.CLIENT_STRING, campaignUrn, campaignCreationTimestamp, responsesJsonArray.toString(), photos);
if (response.getResult() == Result.SUCCESS) {
dbHelper.setResponseRowUploaded(responseId);
} else {
int errorStatusCode = Response.STATUS_ERROR_OTHER;
switch (response.getResult()) {
case FAILURE:
Log.e(TAG, "Upload failed due to error codes: " + Utilities.stringArrayToString(response.getErrorCodes(), ", "));
uploadErrorOccurred = true;
boolean isAuthenticationError = false;
boolean isUserDisabled = false;
String errorCode = null;
for (String code : response.getErrorCodes()) {
if (code.charAt(1) == '2') {
authErrorOccurred = true;
isAuthenticationError = true;
if (code.equals("0201")) {
isUserDisabled = true;
}
}
if (code.equals("0700") || code.equals("0707") || code.equals("0703") || code.equals("0710")) {
errorCode = code;
break;
}
}
if (isUserDisabled) {
new SharedPreferencesHelper(this).setUserDisabled(true);
}
if (isAuthenticationError) {
errorStatusCode = Response.STATUS_ERROR_AUTHENTICATION;
} else if (errorCode.equals("0700")) {
errorStatusCode = Response.STATUS_ERROR_CAMPAIGN_NO_EXIST;
dbHelper.updateCampaignStatus(campaignUrn, Campaign.STATUS_NO_EXIST);
} else if (errorCode.equals("0707")) {
errorStatusCode = Response.STATUS_ERROR_INVALID_USER_ROLE;
dbHelper.updateCampaignStatus(campaignUrn, Campaign.STATUS_INVALID_USER_ROLE);
} else if (errorCode.equals("0703")) {
errorStatusCode = Response.STATUS_ERROR_CAMPAIGN_STOPPED;
dbHelper.updateCampaignStatus(campaignUrn, Campaign.STATUS_STOPPED);
} else if (errorCode.equals("0710")) {
errorStatusCode = Response.STATUS_ERROR_CAMPAIGN_OUT_OF_DATE;
dbHelper.updateCampaignStatus(campaignUrn, Campaign.STATUS_OUT_OF_DATE);
} else {
errorStatusCode = Response.STATUS_ERROR_OTHER;
}
break;
case INTERNAL_ERROR:
uploadErrorOccurred = true;
errorStatusCode = Response.STATUS_ERROR_OTHER;
break;
case HTTP_ERROR:
errorStatusCode = Response.STATUS_ERROR_HTTP;
break;
}
ContentValues cv2 = new ContentValues();
cv2.put(Responses.RESPONSE_STATUS, errorStatusCode);
cr.update(Responses.buildResponseUri(responseId), cv2, null, null);
}
cursor.moveToNext();
}
cursor.close();
if (isBackground) {
if (authErrorOccurred) {
NotificationHelper.showAuthNotification(this);
} else if (uploadErrorOccurred) {
NotificationHelper.showUploadErrorNotification(this);
}
}
}
| protected void doWakefulWork(Intent intent) {
String serverUrl = SharedPreferencesHelper.DEFAULT_SERVER_URL;
SharedPreferencesHelper helper = new SharedPreferencesHelper(this);
String username = helper.getUsername();
String hashedPassword = helper.getHashedPassword();
boolean isBackground = intent.getBooleanExtra("is_background", false);
boolean uploadErrorOccurred = false;
boolean authErrorOccurred = false;
OhmageApi api = new OhmageApi(this);
DbHelper dbHelper = new DbHelper(this);
Uri dataUri = intent.getData();
ContentResolver cr = getContentResolver();
String [] projection = new String [] {
Tables.RESPONSES + "." + Responses._ID,
Responses.RESPONSE_DATE,
Responses.RESPONSE_TIME,
Responses.RESPONSE_TIMEZONE,
Responses.RESPONSE_LOCATION_STATUS,
Responses.RESPONSE_LOCATION_LATITUDE,
Responses.RESPONSE_LOCATION_LONGITUDE,
Responses.RESPONSE_LOCATION_PROVIDER,
Responses.RESPONSE_LOCATION_ACCURACY,
Responses.RESPONSE_LOCATION_TIME,
Tables.RESPONSES + "." + Responses.SURVEY_ID,
Responses.RESPONSE_SURVEY_LAUNCH_CONTEXT,
Responses.RESPONSE_JSON,
Tables.RESPONSES + "." + Responses.CAMPAIGN_URN,
Campaigns.CAMPAIGN_CREATED};
String select = Responses.RESPONSE_STATUS + "!=" + Response.STATUS_DOWNLOADED + " AND " +
Responses.RESPONSE_STATUS + "!=" + Response.STATUS_UPLOADED + " AND " +
Responses.RESPONSE_STATUS + "!=" + Response.STATUS_WAITING_FOR_LOCATION;
Cursor cursor = cr.query(dataUri, projection, select, null, null);
cursor.moveToFirst();
ContentValues cv = new ContentValues();
cv.put(Responses.RESPONSE_STATUS, Response.STATUS_QUEUED);
cr.update(dataUri, cv, select, null);
for (int i = 0; i < cursor.getCount(); i++) {
long responseId = cursor.getLong(cursor.getColumnIndex(Responses._ID));
ContentValues values = new ContentValues();
values.put(Responses.RESPONSE_STATUS, Response.STATUS_UPLOADING);
cr.update(Responses.buildResponseUri(responseId), values, null, null);
// cr.update(Responses.CONTENT_URI, values, Tables.RESPONSES + "." + Responses._ID + "=" + responseId, null);
JSONArray responsesJsonArray = new JSONArray();
JSONObject responseJson = new JSONObject();
final ArrayList<String> photoUUIDs = new ArrayList<String>();
try {
responseJson.put("date", cursor.getString(cursor.getColumnIndex(Responses.RESPONSE_DATE)));
responseJson.put("time", cursor.getLong(cursor.getColumnIndex(Responses.RESPONSE_TIME)));
responseJson.put("timezone", cursor.getString(cursor.getColumnIndex(Responses.RESPONSE_TIMEZONE)));
String locationStatus = cursor.getString(cursor.getColumnIndex(Responses.RESPONSE_LOCATION_STATUS));
responseJson.put("location_status", locationStatus);
if (! locationStatus.equals(SurveyGeotagService.LOCATION_UNAVAILABLE)) {
JSONObject locationJson = new JSONObject();
locationJson.put("latitude", cursor.getDouble(cursor.getColumnIndex(Responses.RESPONSE_LOCATION_LATITUDE)));
locationJson.put("longitude", cursor.getDouble(cursor.getColumnIndex(Responses.RESPONSE_LOCATION_LONGITUDE)));
locationJson.put("provider", cursor.getString(cursor.getColumnIndex(Responses.RESPONSE_LOCATION_PROVIDER)));
locationJson.put("accuracy", cursor.getFloat(cursor.getColumnIndex(Responses.RESPONSE_LOCATION_ACCURACY)));
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String locationTimestamp = dateFormat.format(new Date(cursor.getLong(cursor.getColumnIndex(Responses.RESPONSE_LOCATION_TIME))));
locationJson.put("timestamp", locationTimestamp);
responseJson.put("location", locationJson);
}
responseJson.put("survey_id", cursor.getString(cursor.getColumnIndex(Responses.SURVEY_ID)));
responseJson.put("survey_launch_context", new JSONObject(cursor.getString(cursor.getColumnIndex(Responses.RESPONSE_SURVEY_LAUNCH_CONTEXT))));
responseJson.put("responses", new JSONArray(cursor.getString(cursor.getColumnIndex(Responses.RESPONSE_JSON))));
ContentResolver cr2 = getContentResolver();
Cursor promptsCursor = cr2.query(Responses.buildPromptResponsesUri(responseId), new String [] {PromptResponses.PROMPT_RESPONSE_VALUE, SurveyPrompts.SURVEY_PROMPT_TYPE}, SurveyPrompts.SURVEY_PROMPT_TYPE + "='photo'", null, null);
while (promptsCursor.moveToNext()) {
photoUUIDs.add(promptsCursor.getString(promptsCursor.getColumnIndex(PromptResponses.PROMPT_RESPONSE_VALUE)));
}
promptsCursor.close();
} catch (JSONException e) {
throw new RuntimeException(e);
}
responsesJsonArray.put(responseJson);
String campaignUrn = cursor.getString(cursor.getColumnIndex(Responses.CAMPAIGN_URN));
String campaignCreationTimestamp = cursor.getString(cursor.getColumnIndex(Campaigns.CAMPAIGN_CREATED));
File [] photos = Campaign.getCampaignImageDir(this, campaignUrn).listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String filename) {
if (photoUUIDs.contains(filename.split("\\.")[0])) {
return true;
}
return false;
}
});
OhmageApi.UploadResponse response = api.surveyUpload(serverUrl, username, hashedPassword, SharedPreferencesHelper.CLIENT_STRING, campaignUrn, campaignCreationTimestamp, responsesJsonArray.toString(), photos);
if (response.getResult() == Result.SUCCESS) {
dbHelper.setResponseRowUploaded(responseId);
} else {
int errorStatusCode = Response.STATUS_ERROR_OTHER;
switch (response.getResult()) {
case FAILURE:
Log.e(TAG, "Upload failed due to error codes: " + Utilities.stringArrayToString(response.getErrorCodes(), ", "));
uploadErrorOccurred = true;
boolean isAuthenticationError = false;
boolean isUserDisabled = false;
String errorCode = null;
for (String code : response.getErrorCodes()) {
if (code.charAt(1) == '2') {
authErrorOccurred = true;
isAuthenticationError = true;
if (code.equals("0201")) {
isUserDisabled = true;
}
}
if (code.equals("0700") || code.equals("0707") || code.equals("0703") || code.equals("0710")) {
errorCode = code;
break;
}
}
if (isUserDisabled) {
new SharedPreferencesHelper(this).setUserDisabled(true);
}
if (isAuthenticationError) {
errorStatusCode = Response.STATUS_ERROR_AUTHENTICATION;
} else if ("0700".equals(errorCode)) {
errorStatusCode = Response.STATUS_ERROR_CAMPAIGN_NO_EXIST;
dbHelper.updateCampaignStatus(campaignUrn, Campaign.STATUS_NO_EXIST);
} else if ("0707".equals(errorCode)) {
errorStatusCode = Response.STATUS_ERROR_INVALID_USER_ROLE;
dbHelper.updateCampaignStatus(campaignUrn, Campaign.STATUS_INVALID_USER_ROLE);
} else if ("0703".equals(errorCode)) {
errorStatusCode = Response.STATUS_ERROR_CAMPAIGN_STOPPED;
dbHelper.updateCampaignStatus(campaignUrn, Campaign.STATUS_STOPPED);
} else if ("0710".equals(errorCode)) {
errorStatusCode = Response.STATUS_ERROR_CAMPAIGN_OUT_OF_DATE;
dbHelper.updateCampaignStatus(campaignUrn, Campaign.STATUS_OUT_OF_DATE);
} else {
errorStatusCode = Response.STATUS_ERROR_OTHER;
}
break;
case INTERNAL_ERROR:
uploadErrorOccurred = true;
errorStatusCode = Response.STATUS_ERROR_OTHER;
break;
case HTTP_ERROR:
errorStatusCode = Response.STATUS_ERROR_HTTP;
break;
}
ContentValues cv2 = new ContentValues();
cv2.put(Responses.RESPONSE_STATUS, errorStatusCode);
cr.update(Responses.buildResponseUri(responseId), cv2, null, null);
}
cursor.moveToNext();
}
cursor.close();
if (isBackground) {
if (authErrorOccurred) {
NotificationHelper.showAuthNotification(this);
} else if (uploadErrorOccurred) {
NotificationHelper.showUploadErrorNotification(this);
}
}
}
|
diff --git a/LanPlaylistServer/src/main/java/net/kokkeli/data/db/PlaylistsTable.java b/LanPlaylistServer/src/main/java/net/kokkeli/data/db/PlaylistsTable.java
index 09298e2..2241057 100644
--- a/LanPlaylistServer/src/main/java/net/kokkeli/data/db/PlaylistsTable.java
+++ b/LanPlaylistServer/src/main/java/net/kokkeli/data/db/PlaylistsTable.java
@@ -1,65 +1,65 @@
package net.kokkeli.data.db;
import java.io.File;
import com.almworks.sqlite4java.SQLiteConnection;
import com.almworks.sqlite4java.SQLiteException;
import com.almworks.sqlite4java.SQLiteStatement;
public class PlaylistsTable{
private static final String TABLENAME = "playlists";
private static final String ALLLISTS = "SELECT * FROM " + TABLENAME;
private static final String COLUMN_ID = "Id";
private final String databaseLocation;
/**
* Creates PlaylistTable with given databaselocation
* @param databaseLocation Location of database
*/
public PlaylistsTable(String databaseLocation) {
this.databaseLocation = databaseLocation;
}
/**
* Returns Playlist with given id. Playlist doesn't contain tracks.
* @param id Id of playlist
* @return Found playlist
* @throws DatabaseException thrown if there is problem with database
* @throws NotFoundInDatabase thrown if no such item is found with given id.
*/
public PlayList get(long id) throws DatabaseException, NotFoundInDatabase{
SQLiteConnection db = new SQLiteConnection(new File(databaseLocation));
PlayList list = null;
try {
db.open(false);
SQLiteStatement st = db.prepare(getSingleItemQuery(id));
try {
while (st.step()) {
list = new PlayList(st.columnLong(0));
list.setName(st.columnString(1));
}
} finally {
st.dispose();
}
db.dispose();
} catch (SQLiteException e) {
- throw new DatabaseException("Unable to get user with Id: " + id, e);
+ throw new DatabaseException("Unable to get playlist with Id: " + id, e);
}
if (list == null)
throw new NotFoundInDatabase("No such playlist in database.");
return list;
}
/**
* Creates query selecting single user.
* @param id Id of wanted user
* @return Query for selecting single user.
*/
private static String getSingleItemQuery(long id){
return ALLLISTS + " WHERE "+ COLUMN_ID+" = " + id;
}
}
| true | true | public PlayList get(long id) throws DatabaseException, NotFoundInDatabase{
SQLiteConnection db = new SQLiteConnection(new File(databaseLocation));
PlayList list = null;
try {
db.open(false);
SQLiteStatement st = db.prepare(getSingleItemQuery(id));
try {
while (st.step()) {
list = new PlayList(st.columnLong(0));
list.setName(st.columnString(1));
}
} finally {
st.dispose();
}
db.dispose();
} catch (SQLiteException e) {
throw new DatabaseException("Unable to get user with Id: " + id, e);
}
if (list == null)
throw new NotFoundInDatabase("No such playlist in database.");
return list;
}
| public PlayList get(long id) throws DatabaseException, NotFoundInDatabase{
SQLiteConnection db = new SQLiteConnection(new File(databaseLocation));
PlayList list = null;
try {
db.open(false);
SQLiteStatement st = db.prepare(getSingleItemQuery(id));
try {
while (st.step()) {
list = new PlayList(st.columnLong(0));
list.setName(st.columnString(1));
}
} finally {
st.dispose();
}
db.dispose();
} catch (SQLiteException e) {
throw new DatabaseException("Unable to get playlist with Id: " + id, e);
}
if (list == null)
throw new NotFoundInDatabase("No such playlist in database.");
return list;
}
|
diff --git a/BaasioAndroid/src/com/kth/baasio/entity/push/BaasioPush.java b/BaasioAndroid/src/com/kth/baasio/entity/push/BaasioPush.java
index 39de2e2..9eee27d 100644
--- a/BaasioAndroid/src/com/kth/baasio/entity/push/BaasioPush.java
+++ b/BaasioAndroid/src/com/kth/baasio/entity/push/BaasioPush.java
@@ -1,532 +1,536 @@
package com.kth.baasio.entity.push;
import com.google.android.gcm.GCMRegistrar;
import com.kth.baasio.Baas;
import com.kth.baasio.BuildConfig;
import com.kth.baasio.callback.BaasioAsyncTask;
import com.kth.baasio.callback.BaasioCallback;
import com.kth.baasio.callback.BaasioDeviceAsyncTask;
import com.kth.baasio.callback.BaasioDeviceCallback;
import com.kth.baasio.callback.BaasioResponseCallback;
import com.kth.baasio.exception.BaasioError;
import com.kth.baasio.exception.BaasioException;
import com.kth.baasio.preferences.BaasioPreferences;
import com.kth.baasio.response.BaasioResponse;
import com.kth.baasio.utils.ObjectUtils;
import com.kth.common.utils.LogUtils;
import org.springframework.http.HttpMethod;
import android.content.Context;
import android.text.TextUtils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.Random;
import java.util.regex.Pattern;
public class BaasioPush {
enum REG_STATE {
CREATE_DEVICE, UPDATE_DEVICE_BY_REGID, UPDATE_DEVICE_BY_UUID
};
private static final String TAG = LogUtils.makeLogTag(BaasioPush.class);
private static final int MAX_ATTEMPTS = 5;
private static final int BACKOFF_MILLIS = 4000;
private static final int BACKOFF_MILLIS_DEFAULT = 3000;
private static final Random sRandom = new Random();
private static final String TAG_REGEXP = "^[a-zA-Z0-9-_]*$";
static List<String> getTagList(String tagString) {
List<String> result = new ArrayList<String>();
String[] tags = tagString.split("\\,");
for (String tag : tags) {
tag = tag.toLowerCase(Locale.getDefault()).trim();
if (!ObjectUtils.isEmpty(tag)) {
result.add(tag);
}
}
return result;
}
public BaasioPush() {
}
private static boolean needRegister(Context context, String signedInUsername, String regId,
String oldRegId, String newTags) {
boolean bResult = true;
if (GCMRegistrar.isRegisteredOnServer(context)) {
String registeredUsername = BaasioPreferences.getRegisteredUserName(context);
if (registeredUsername.equals(signedInUsername)) {
String curTags = BaasioPreferences.getRegisteredTags(context);
if (curTags.equals(newTags)) {
if (oldRegId.equals(regId)) {
LogUtils.LOGV(TAG, "BaasioPush.register() called but already registered.");
bResult = false;
} else {
LogUtils.LOGV(
TAG,
"BaasioPush.register() called. Already registered on the GCM server. But, need to register again because regId changed.");
}
} else {
LogUtils.LOGV(
TAG,
"BaasioPush.register() called. Already registered on the GCM server. But, need to register again because tags changed.");
}
} else {
LogUtils.LOGV(
TAG,
"BaasioPush.register() called. Already registered on the GCM server. But, need to register again because username changed.");
}
}
return bResult;
}
public static BaasioDevice register(Context context, String regId) throws BaasioException {
if (!Baas.io().isGcmEnabled()) {
throw new BaasioException(BaasioError.ERROR_GCM_DISABLED);
}
GCMRegistrar.checkDevice(context);
if (BuildConfig.DEBUG) {
GCMRegistrar.checkManifest(context);
}
String signedInUsername = "";
if (!ObjectUtils.isEmpty(Baas.io().getSignedInUser())) {
signedInUsername = Baas.io().getSignedInUser().getUsername();
}
String newTags = BaasioPreferences.getNeedRegisteredTags(context);
String oldRegId = BaasioPreferences.getRegisteredRegId(context);
if (!needRegister(context, signedInUsername, regId, oldRegId, newTags)) {
throw new BaasioException(BaasioError.ERROR_GCM_ALREADY_REGISTERED);
}
BaasioDevice device = new BaasioDevice();
if (ObjectUtils.isEmpty(device.getType())) {
throw new IllegalArgumentException(BaasioError.ERROR_MISSING_TYPE);
}
if (ObjectUtils.isEmpty(device.getPlatform())) {
device.setPlatform("G");
}
if (ObjectUtils.isEmpty(regId)) {
throw new IllegalArgumentException(BaasioError.ERROR_GCM_MISSING_REGID);
}
device.setToken(regId);
String tagString = BaasioPreferences.getNeedRegisteredTags(context);
List<String> tags = getTagList(tagString);
device.setTags(tags);
long backoff = BACKOFF_MILLIS + sRandom.nextInt(1000);
REG_STATE eREG_STATE = REG_STATE.CREATE_DEVICE;
if (!ObjectUtils.isEmpty(oldRegId)) {
if (!oldRegId.equals(regId)) {
LogUtils.LOGV(TAG, "RegId changed!!!!");
LogUtils.LOGV(TAG, "New RegId: " + regId);
LogUtils.LOGV(TAG, "Old RegId: " + oldRegId);
} else {
LogUtils.LOGV(TAG, "New and old regId are same!!!");
LogUtils.LOGV(TAG, "RegId: " + oldRegId);
}
eREG_STATE = REG_STATE.UPDATE_DEVICE_BY_REGID;
}
for (int i = 1; i <= MAX_ATTEMPTS; i++) {
LogUtils.LOGV(TAG, "#" + i + " Attempt..");
REG_STATE curState = eREG_STATE;
try {
BaasioResponse response = null;
switch (eREG_STATE) {
case CREATE_DEVICE: {
LogUtils.LOGV(TAG, "POST /devices");
LogUtils.LOGV(TAG, "Request: " + device.toString());
response = Baas.io().apiRequest(HttpMethod.POST, null, device, "devices");
LogUtils.LOGV(TAG, "Response: " + response.toString());
break;
}
case UPDATE_DEVICE_BY_REGID: {
LogUtils.LOGV(TAG, "PUT /devices/" + oldRegId);
LogUtils.LOGV(TAG, "Request: " + device.toString());
response = Baas.io().apiRequest(HttpMethod.PUT, null, device, "devices",
oldRegId);
LogUtils.LOGV(TAG, "Response: " + response.toString());
break;
}
case UPDATE_DEVICE_BY_UUID: {
String deviceUuid = BaasioPreferences.getDeviceUuidForPush(context);
LogUtils.LOGV(TAG, "PUT /devices/" + deviceUuid);
LogUtils.LOGV(TAG, "Request: " + device.toString());
response = Baas.io().apiRequest(HttpMethod.PUT, null, device, "devices",
deviceUuid);
LogUtils.LOGV(TAG, "Response: " + response.toString());
break;
}
}
if (response != null) {
BaasioDevice entity = response.getFirstEntity().toType(BaasioDevice.class);
if (!ObjectUtils.isEmpty(entity)) {
BaasioPreferences
.setRegisteredSenderId(context, Baas.io().getGcmSenderId());
GCMRegistrar.setRegisteredOnServer(context, true);
BaasioPreferences.setRegisteredTags(context, tagString);
BaasioPreferences.setRegisteredUserName(context, signedInUsername);
String newDeviceUuid = entity.getUuid().toString();
BaasioPreferences.setDeviceUuidForPush(context, newDeviceUuid);
BaasioPreferences.setRegisteredRegId(context, regId);
return entity;
}
throw new BaasioException(BaasioError.ERROR_UNKNOWN_NORESULT_ENTITY);
}
} catch (BaasioException e) {
LogUtils.LOGV(TAG, "Failed to register on attempt " + i, e);
String statusCode = e.getStatusCode();
if (!ObjectUtils.isEmpty(statusCode)) {
if (eREG_STATE == REG_STATE.CREATE_DEVICE) {
if (statusCode.equals("400") && e.getErrorCode() == 913) {
// 이미 regId가 등록되어 있음. 하지만 태그 정보가 업데이트되어 있는지 알 수 없으니
// Retry
LogUtils.LOGV(
TAG,
"Already registered on the GCM server. But, need to register again because other data could be changed.");
oldRegId = regId;
i--;
eREG_STATE = REG_STATE.UPDATE_DEVICE_BY_REGID;
}
} else if (eREG_STATE == REG_STATE.UPDATE_DEVICE_BY_REGID) {
if (statusCode.equals("400")
&& (e.getErrorCode() == 620 || e.getErrorCode() == 103)) {
String deviceUuid = BaasioPreferences.getDeviceUuidForPush(context);
if (!ObjectUtils.isEmpty(deviceUuid)) {
eREG_STATE = REG_STATE.UPDATE_DEVICE_BY_UUID;
i--;
} else {
LogUtils.LOGE(TAG,
- "Failed to register. This should not happen. Give up registering.");
+ "Failed to register. This should not happen. Give up registering.(400)");
break;
}
+ } else if (statusCode.equals("404")) {
+ LogUtils.LOGE(TAG,
+ "Failed to register. This should not happen. Give up registering.(404)");
+ break;
}
} else if (eREG_STATE == REG_STATE.UPDATE_DEVICE_BY_UUID) {
if (statusCode.equals("404")) {
eREG_STATE = REG_STATE.CREATE_DEVICE;
i--;
} else if (statusCode.equals("400")
&& (e.getErrorCode() == 620 || e.getErrorCode() == 103)) {
eREG_STATE = REG_STATE.CREATE_DEVICE;
i--;
}
}
}
// Here we are simplifying and retrying on any error; in a real
// application, it should retry only on unrecoverable errors
// (like HTTP error code 503).
if (i >= MAX_ATTEMPTS) {
LogUtils.LOGE(TAG,
"Failed all attempts to register. Next time application launched, will try again.");
break;
}
if (curState == eREG_STATE) {
try {
LogUtils.LOGV(TAG, "Sleeping for " + backoff + " ms before retry");
Thread.sleep(backoff);
} catch (InterruptedException e1) {
// Activity finished before we complete - exit.
LogUtils.LOGD(TAG, "Thread interrupted: abort remaining retries!");
Thread.currentThread().interrupt();
return null;
}
// increase backoff exponentially
backoff *= 2;
} else {
try {
LogUtils.LOGV(TAG, "Sleeping for " + BACKOFF_MILLIS_DEFAULT
+ " ms before retry");
Thread.sleep(BACKOFF_MILLIS_DEFAULT);
} catch (InterruptedException e1) {
// Activity finished before we complete - exit.
LogUtils.LOGD(TAG, "Thread interrupted: abort remaining retries!");
Thread.currentThread().interrupt();
return null;
}
}
}
}
return null;
}
private static boolean compareArrays(String[] arr1, String[] arr2) {
if (ObjectUtils.isEmpty(arr1) || ObjectUtils.isEmpty(arr2)) {
return false;
}
Arrays.sort(arr1);
Arrays.sort(arr2);
return Arrays.equals(arr1, arr2);
}
private static boolean needRegisterSenderId(Context context, String regId) {
if (TextUtils.isEmpty(regId)) {
LogUtils.LOGD(TAG, "RegId is empty. Need register Sender ID.");
return true;
}
String[] oldSenderIds = BaasioPreferences.getRegisteredSenderId(context);
String[] newSenderIds = Baas.io().getGcmSenderId();
if (!compareArrays(oldSenderIds, newSenderIds)) {
LogUtils.LOGD(TAG, "SenderID is different. Need register Sender ID.");
return true;
}
return false;
}
/**
* Register device. If server is not available(HTTP status 5xx), it will
* retry 5 times. Executes asynchronously in background and the callbacks
* are called in the UI thread.
*
* @param context Context
* @param callback GCM registration result callback
* @return registration task
*/
public static BaasioDeviceAsyncTask registerInBackground(final Context context,
final BaasioDeviceCallback callback) {
if (!Baas.io().isGcmEnabled()) {
if (callback != null) {
callback.onException(new BaasioException(BaasioError.ERROR_GCM_DISABLED));
}
return null;
}
final String regId = GCMRegistrar.getRegistrationId(context);
if (needRegisterSenderId(context, regId)) {
GCMRegistrar.register(context, Baas.io().getGcmSenderId());
} else {
BaasioDeviceAsyncTask task = new BaasioDeviceAsyncTask(callback) {
@Override
public BaasioDevice doTask() throws BaasioException {
BaasioDevice device = register(context, regId);
if (ObjectUtils.isEmpty(device)) {
GCMRegistrar.unregister(context);
}
return device;
}
};
task.execute();
return task;
}
return null;
}
/**
* Register device with tags. If server is not available(HTTP status 5xx),
* it will retry 5 times. Executes asynchronously in background and the
* callbacks are called in the UI thread.
*
* @param context Context
* @param tags Tags. The max length of each tag is 36.
* @param callback GCM registration result callback
* @return registration task
*/
public static BaasioDeviceAsyncTask registerWithTagsInBackground(final Context context,
String tags, final BaasioDeviceCallback callback) {
if (!Baas.io().isGcmEnabled()) {
if (callback != null) {
callback.onException(new BaasioException(BaasioError.ERROR_GCM_DISABLED));
}
return null;
}
List<String> tagList = getTagList(tags);
for (String tag : tagList) {
if (tag.length() > 36) {
throw new IllegalArgumentException(BaasioError.ERROR_GCM_TAG_LENGTH_EXCEED);
}
Pattern pattern = Pattern.compile(TAG_REGEXP);
if (!pattern.matcher(tag).matches()) {
throw new IllegalArgumentException(BaasioError.ERROR_GCM_TAG_PATTERN_MISS_MATCHED);
}
}
BaasioPreferences.setNeedRegisteredTags(context, tags);
return registerInBackground(context, callback);
}
/**
* Unregister device. If request failed, it will not retry.
*
* @param context Context
*/
public static BaasioResponse unregister(Context context) throws BaasioException {
if (!Baas.io().isGcmEnabled()) {
throw new BaasioException(BaasioError.ERROR_GCM_DISABLED);
}
if (!GCMRegistrar.isRegisteredOnServer(context)) {
throw new BaasioException(BaasioError.ERROR_GCM_ALREADY_UNREGISTERED);
}
String deviceUuid = BaasioPreferences.getDeviceUuidForPush(context);
String oldRegId = BaasioPreferences.getRegisteredRegId(context);
BaasioPreferences.setDeviceUuidForPush(context, "");
BaasioPreferences.setNeedRegisteredTags(context, "");
BaasioPreferences.setRegisteredUserName(context, "");
BaasioPreferences.setRegisteredTags(context, "");
BaasioPreferences.setRegisteredRegId(context, "");
GCMRegistrar.setRegisteredOnServer(context, false);
if (!ObjectUtils.isEmpty(deviceUuid)) {
LogUtils.LOGV(TAG, "DELETE /devices/" + deviceUuid);
BaasioResponse response = Baas.io().apiRequest(HttpMethod.DELETE, null, null,
"devices", deviceUuid);
if (response != null) {
LogUtils.LOGV(TAG, "Response: " + response.toString());
return response;
} else {
throw new BaasioException(BaasioError.ERROR_UNKNOWN_NO_RESPONSE_DATA);
}
} else {
if (!ObjectUtils.isEmpty(oldRegId)) {
LogUtils.LOGV(TAG, "DELETE /devices/" + oldRegId);
BaasioResponse response = Baas.io().apiRequest(HttpMethod.DELETE, null, null,
"devices", oldRegId);
if (response != null) {
LogUtils.LOGV(TAG, "Response: " + response.toString());
return response;
} else {
throw new BaasioException(BaasioError.ERROR_UNKNOWN_NO_RESPONSE_DATA);
}
}
}
throw new BaasioException(BaasioError.ERROR_GCM_MISSING_REGID);
}
/**
* Unregister device. However, server is not available(HTTP status 5xx), it
* will not retry. Executes asynchronously in background and the callbacks
* are called in the UI thread.
*
* @param context Context
* @param callback GCM unregistration result callback
*/
public static void unregisterInBackground(final Context context,
final BaasioResponseCallback callback) {
if (!Baas.io().isGcmEnabled()) {
if (callback != null) {
callback.onException(new BaasioException(BaasioError.ERROR_GCM_DISABLED));
}
return;
}
(new BaasioAsyncTask<BaasioResponse>(callback) {
@Override
public BaasioResponse doTask() throws BaasioException {
return unregister(context);
}
}).execute();
}
/**
* Send a push message.
*
* @param message push message
*/
public static BaasioMessage sendPush(BaasioMessage message) throws BaasioException {
if (ObjectUtils.isEmpty(message)) {
throw new IllegalArgumentException(BaasioError.ERROR_MISSING_MESSAGE);
}
if (ObjectUtils.isEmpty(message.getTarget())) {
throw new IllegalArgumentException(BaasioError.ERROR_MISSING_TARGET);
}
BaasioResponse response = Baas.io().apiRequest(HttpMethod.POST, null, message, "pushes");
if (response != null) {
BaasioMessage entity = response.getFirstEntity().toType(BaasioMessage.class);
if (!ObjectUtils.isEmpty(entity)) {
return entity;
}
throw new BaasioException(BaasioError.ERROR_UNKNOWN_NORESULT_ENTITY);
}
throw new BaasioException(BaasioError.ERROR_UNKNOWN_NO_RESPONSE_DATA);
}
/**
* Send a push message. Executes asynchronously in background and the
* callbacks are called in the UI thread.
*
* @param message Push message
* @param callback Result callback
*/
public static void sendPushInBackground(final BaasioMessage message,
final BaasioCallback<BaasioMessage> callback) {
(new BaasioAsyncTask<BaasioMessage>(callback) {
@Override
public BaasioMessage doTask() throws BaasioException {
return sendPush(message);
}
}).execute();
}
}
| false | true | public static BaasioDevice register(Context context, String regId) throws BaasioException {
if (!Baas.io().isGcmEnabled()) {
throw new BaasioException(BaasioError.ERROR_GCM_DISABLED);
}
GCMRegistrar.checkDevice(context);
if (BuildConfig.DEBUG) {
GCMRegistrar.checkManifest(context);
}
String signedInUsername = "";
if (!ObjectUtils.isEmpty(Baas.io().getSignedInUser())) {
signedInUsername = Baas.io().getSignedInUser().getUsername();
}
String newTags = BaasioPreferences.getNeedRegisteredTags(context);
String oldRegId = BaasioPreferences.getRegisteredRegId(context);
if (!needRegister(context, signedInUsername, regId, oldRegId, newTags)) {
throw new BaasioException(BaasioError.ERROR_GCM_ALREADY_REGISTERED);
}
BaasioDevice device = new BaasioDevice();
if (ObjectUtils.isEmpty(device.getType())) {
throw new IllegalArgumentException(BaasioError.ERROR_MISSING_TYPE);
}
if (ObjectUtils.isEmpty(device.getPlatform())) {
device.setPlatform("G");
}
if (ObjectUtils.isEmpty(regId)) {
throw new IllegalArgumentException(BaasioError.ERROR_GCM_MISSING_REGID);
}
device.setToken(regId);
String tagString = BaasioPreferences.getNeedRegisteredTags(context);
List<String> tags = getTagList(tagString);
device.setTags(tags);
long backoff = BACKOFF_MILLIS + sRandom.nextInt(1000);
REG_STATE eREG_STATE = REG_STATE.CREATE_DEVICE;
if (!ObjectUtils.isEmpty(oldRegId)) {
if (!oldRegId.equals(regId)) {
LogUtils.LOGV(TAG, "RegId changed!!!!");
LogUtils.LOGV(TAG, "New RegId: " + regId);
LogUtils.LOGV(TAG, "Old RegId: " + oldRegId);
} else {
LogUtils.LOGV(TAG, "New and old regId are same!!!");
LogUtils.LOGV(TAG, "RegId: " + oldRegId);
}
eREG_STATE = REG_STATE.UPDATE_DEVICE_BY_REGID;
}
for (int i = 1; i <= MAX_ATTEMPTS; i++) {
LogUtils.LOGV(TAG, "#" + i + " Attempt..");
REG_STATE curState = eREG_STATE;
try {
BaasioResponse response = null;
switch (eREG_STATE) {
case CREATE_DEVICE: {
LogUtils.LOGV(TAG, "POST /devices");
LogUtils.LOGV(TAG, "Request: " + device.toString());
response = Baas.io().apiRequest(HttpMethod.POST, null, device, "devices");
LogUtils.LOGV(TAG, "Response: " + response.toString());
break;
}
case UPDATE_DEVICE_BY_REGID: {
LogUtils.LOGV(TAG, "PUT /devices/" + oldRegId);
LogUtils.LOGV(TAG, "Request: " + device.toString());
response = Baas.io().apiRequest(HttpMethod.PUT, null, device, "devices",
oldRegId);
LogUtils.LOGV(TAG, "Response: " + response.toString());
break;
}
case UPDATE_DEVICE_BY_UUID: {
String deviceUuid = BaasioPreferences.getDeviceUuidForPush(context);
LogUtils.LOGV(TAG, "PUT /devices/" + deviceUuid);
LogUtils.LOGV(TAG, "Request: " + device.toString());
response = Baas.io().apiRequest(HttpMethod.PUT, null, device, "devices",
deviceUuid);
LogUtils.LOGV(TAG, "Response: " + response.toString());
break;
}
}
if (response != null) {
BaasioDevice entity = response.getFirstEntity().toType(BaasioDevice.class);
if (!ObjectUtils.isEmpty(entity)) {
BaasioPreferences
.setRegisteredSenderId(context, Baas.io().getGcmSenderId());
GCMRegistrar.setRegisteredOnServer(context, true);
BaasioPreferences.setRegisteredTags(context, tagString);
BaasioPreferences.setRegisteredUserName(context, signedInUsername);
String newDeviceUuid = entity.getUuid().toString();
BaasioPreferences.setDeviceUuidForPush(context, newDeviceUuid);
BaasioPreferences.setRegisteredRegId(context, regId);
return entity;
}
throw new BaasioException(BaasioError.ERROR_UNKNOWN_NORESULT_ENTITY);
}
} catch (BaasioException e) {
LogUtils.LOGV(TAG, "Failed to register on attempt " + i, e);
String statusCode = e.getStatusCode();
if (!ObjectUtils.isEmpty(statusCode)) {
if (eREG_STATE == REG_STATE.CREATE_DEVICE) {
if (statusCode.equals("400") && e.getErrorCode() == 913) {
// 이미 regId가 등록되어 있음. 하지만 태그 정보가 업데이트되어 있는지 알 수 없으니
// Retry
LogUtils.LOGV(
TAG,
"Already registered on the GCM server. But, need to register again because other data could be changed.");
oldRegId = regId;
i--;
eREG_STATE = REG_STATE.UPDATE_DEVICE_BY_REGID;
}
} else if (eREG_STATE == REG_STATE.UPDATE_DEVICE_BY_REGID) {
if (statusCode.equals("400")
&& (e.getErrorCode() == 620 || e.getErrorCode() == 103)) {
String deviceUuid = BaasioPreferences.getDeviceUuidForPush(context);
if (!ObjectUtils.isEmpty(deviceUuid)) {
eREG_STATE = REG_STATE.UPDATE_DEVICE_BY_UUID;
i--;
} else {
LogUtils.LOGE(TAG,
"Failed to register. This should not happen. Give up registering.");
break;
}
}
} else if (eREG_STATE == REG_STATE.UPDATE_DEVICE_BY_UUID) {
if (statusCode.equals("404")) {
eREG_STATE = REG_STATE.CREATE_DEVICE;
i--;
} else if (statusCode.equals("400")
&& (e.getErrorCode() == 620 || e.getErrorCode() == 103)) {
eREG_STATE = REG_STATE.CREATE_DEVICE;
i--;
}
}
}
// Here we are simplifying and retrying on any error; in a real
// application, it should retry only on unrecoverable errors
// (like HTTP error code 503).
if (i >= MAX_ATTEMPTS) {
LogUtils.LOGE(TAG,
"Failed all attempts to register. Next time application launched, will try again.");
break;
}
if (curState == eREG_STATE) {
try {
LogUtils.LOGV(TAG, "Sleeping for " + backoff + " ms before retry");
Thread.sleep(backoff);
} catch (InterruptedException e1) {
// Activity finished before we complete - exit.
LogUtils.LOGD(TAG, "Thread interrupted: abort remaining retries!");
Thread.currentThread().interrupt();
return null;
}
// increase backoff exponentially
backoff *= 2;
} else {
try {
LogUtils.LOGV(TAG, "Sleeping for " + BACKOFF_MILLIS_DEFAULT
+ " ms before retry");
Thread.sleep(BACKOFF_MILLIS_DEFAULT);
} catch (InterruptedException e1) {
// Activity finished before we complete - exit.
LogUtils.LOGD(TAG, "Thread interrupted: abort remaining retries!");
Thread.currentThread().interrupt();
return null;
}
}
}
}
return null;
}
| public static BaasioDevice register(Context context, String regId) throws BaasioException {
if (!Baas.io().isGcmEnabled()) {
throw new BaasioException(BaasioError.ERROR_GCM_DISABLED);
}
GCMRegistrar.checkDevice(context);
if (BuildConfig.DEBUG) {
GCMRegistrar.checkManifest(context);
}
String signedInUsername = "";
if (!ObjectUtils.isEmpty(Baas.io().getSignedInUser())) {
signedInUsername = Baas.io().getSignedInUser().getUsername();
}
String newTags = BaasioPreferences.getNeedRegisteredTags(context);
String oldRegId = BaasioPreferences.getRegisteredRegId(context);
if (!needRegister(context, signedInUsername, regId, oldRegId, newTags)) {
throw new BaasioException(BaasioError.ERROR_GCM_ALREADY_REGISTERED);
}
BaasioDevice device = new BaasioDevice();
if (ObjectUtils.isEmpty(device.getType())) {
throw new IllegalArgumentException(BaasioError.ERROR_MISSING_TYPE);
}
if (ObjectUtils.isEmpty(device.getPlatform())) {
device.setPlatform("G");
}
if (ObjectUtils.isEmpty(regId)) {
throw new IllegalArgumentException(BaasioError.ERROR_GCM_MISSING_REGID);
}
device.setToken(regId);
String tagString = BaasioPreferences.getNeedRegisteredTags(context);
List<String> tags = getTagList(tagString);
device.setTags(tags);
long backoff = BACKOFF_MILLIS + sRandom.nextInt(1000);
REG_STATE eREG_STATE = REG_STATE.CREATE_DEVICE;
if (!ObjectUtils.isEmpty(oldRegId)) {
if (!oldRegId.equals(regId)) {
LogUtils.LOGV(TAG, "RegId changed!!!!");
LogUtils.LOGV(TAG, "New RegId: " + regId);
LogUtils.LOGV(TAG, "Old RegId: " + oldRegId);
} else {
LogUtils.LOGV(TAG, "New and old regId are same!!!");
LogUtils.LOGV(TAG, "RegId: " + oldRegId);
}
eREG_STATE = REG_STATE.UPDATE_DEVICE_BY_REGID;
}
for (int i = 1; i <= MAX_ATTEMPTS; i++) {
LogUtils.LOGV(TAG, "#" + i + " Attempt..");
REG_STATE curState = eREG_STATE;
try {
BaasioResponse response = null;
switch (eREG_STATE) {
case CREATE_DEVICE: {
LogUtils.LOGV(TAG, "POST /devices");
LogUtils.LOGV(TAG, "Request: " + device.toString());
response = Baas.io().apiRequest(HttpMethod.POST, null, device, "devices");
LogUtils.LOGV(TAG, "Response: " + response.toString());
break;
}
case UPDATE_DEVICE_BY_REGID: {
LogUtils.LOGV(TAG, "PUT /devices/" + oldRegId);
LogUtils.LOGV(TAG, "Request: " + device.toString());
response = Baas.io().apiRequest(HttpMethod.PUT, null, device, "devices",
oldRegId);
LogUtils.LOGV(TAG, "Response: " + response.toString());
break;
}
case UPDATE_DEVICE_BY_UUID: {
String deviceUuid = BaasioPreferences.getDeviceUuidForPush(context);
LogUtils.LOGV(TAG, "PUT /devices/" + deviceUuid);
LogUtils.LOGV(TAG, "Request: " + device.toString());
response = Baas.io().apiRequest(HttpMethod.PUT, null, device, "devices",
deviceUuid);
LogUtils.LOGV(TAG, "Response: " + response.toString());
break;
}
}
if (response != null) {
BaasioDevice entity = response.getFirstEntity().toType(BaasioDevice.class);
if (!ObjectUtils.isEmpty(entity)) {
BaasioPreferences
.setRegisteredSenderId(context, Baas.io().getGcmSenderId());
GCMRegistrar.setRegisteredOnServer(context, true);
BaasioPreferences.setRegisteredTags(context, tagString);
BaasioPreferences.setRegisteredUserName(context, signedInUsername);
String newDeviceUuid = entity.getUuid().toString();
BaasioPreferences.setDeviceUuidForPush(context, newDeviceUuid);
BaasioPreferences.setRegisteredRegId(context, regId);
return entity;
}
throw new BaasioException(BaasioError.ERROR_UNKNOWN_NORESULT_ENTITY);
}
} catch (BaasioException e) {
LogUtils.LOGV(TAG, "Failed to register on attempt " + i, e);
String statusCode = e.getStatusCode();
if (!ObjectUtils.isEmpty(statusCode)) {
if (eREG_STATE == REG_STATE.CREATE_DEVICE) {
if (statusCode.equals("400") && e.getErrorCode() == 913) {
// 이미 regId가 등록되어 있음. 하지만 태그 정보가 업데이트되어 있는지 알 수 없으니
// Retry
LogUtils.LOGV(
TAG,
"Already registered on the GCM server. But, need to register again because other data could be changed.");
oldRegId = regId;
i--;
eREG_STATE = REG_STATE.UPDATE_DEVICE_BY_REGID;
}
} else if (eREG_STATE == REG_STATE.UPDATE_DEVICE_BY_REGID) {
if (statusCode.equals("400")
&& (e.getErrorCode() == 620 || e.getErrorCode() == 103)) {
String deviceUuid = BaasioPreferences.getDeviceUuidForPush(context);
if (!ObjectUtils.isEmpty(deviceUuid)) {
eREG_STATE = REG_STATE.UPDATE_DEVICE_BY_UUID;
i--;
} else {
LogUtils.LOGE(TAG,
"Failed to register. This should not happen. Give up registering.(400)");
break;
}
} else if (statusCode.equals("404")) {
LogUtils.LOGE(TAG,
"Failed to register. This should not happen. Give up registering.(404)");
break;
}
} else if (eREG_STATE == REG_STATE.UPDATE_DEVICE_BY_UUID) {
if (statusCode.equals("404")) {
eREG_STATE = REG_STATE.CREATE_DEVICE;
i--;
} else if (statusCode.equals("400")
&& (e.getErrorCode() == 620 || e.getErrorCode() == 103)) {
eREG_STATE = REG_STATE.CREATE_DEVICE;
i--;
}
}
}
// Here we are simplifying and retrying on any error; in a real
// application, it should retry only on unrecoverable errors
// (like HTTP error code 503).
if (i >= MAX_ATTEMPTS) {
LogUtils.LOGE(TAG,
"Failed all attempts to register. Next time application launched, will try again.");
break;
}
if (curState == eREG_STATE) {
try {
LogUtils.LOGV(TAG, "Sleeping for " + backoff + " ms before retry");
Thread.sleep(backoff);
} catch (InterruptedException e1) {
// Activity finished before we complete - exit.
LogUtils.LOGD(TAG, "Thread interrupted: abort remaining retries!");
Thread.currentThread().interrupt();
return null;
}
// increase backoff exponentially
backoff *= 2;
} else {
try {
LogUtils.LOGV(TAG, "Sleeping for " + BACKOFF_MILLIS_DEFAULT
+ " ms before retry");
Thread.sleep(BACKOFF_MILLIS_DEFAULT);
} catch (InterruptedException e1) {
// Activity finished before we complete - exit.
LogUtils.LOGD(TAG, "Thread interrupted: abort remaining retries!");
Thread.currentThread().interrupt();
return null;
}
}
}
}
return null;
}
|
diff --git a/src/net/enkun/javatter/history/HistoryObjectFactory.java b/src/net/enkun/javatter/history/HistoryObjectFactory.java
index 450d126..21edd71 100644
--- a/src/net/enkun/javatter/history/HistoryObjectFactory.java
+++ b/src/net/enkun/javatter/history/HistoryObjectFactory.java
@@ -1,186 +1,186 @@
package net.enkun.javatter.history;
import java.awt.BorderLayout;
import java.awt.Desktop;
import java.awt.Dimension;
import java.awt.Font;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextPane;
import javax.swing.JToggleButton;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
import com.orekyuu.javatter.util.BackGroundColor;
import com.orekyuu.javatter.util.IconCache;
import twitter4j.Status;
import twitter4j.User;
public class HistoryObjectFactory {
/*
* retweet, favorite, unfavorite => user, status
*
* follow => user
*
* ほいさほいさ
*/
private User user;
private Status status;
private EventType type;
public enum EventType {
Retweet,
Favorite,
Unfavorite,
Follow
}
public HistoryObjectFactory(User user, Status status, EventType type) {
this.user = user;
this.status = status;
this.type = type;
}
public HistoryObjectFactory(User user) {
this.user = user;
this.status = null;
}
public JPanel createHistoryObject(HistoryViewObserver view) {
JPanel base = new JPanel();
base.setBackground(BackGroundColor.color);
base.setAlignmentX(0.0F);
base.setAlignmentY(0.0F);
base.setMaximumSize(new Dimension(375, Integer.MAX_VALUE));
base.setLayout(new BorderLayout());
base.add(createImage(), "Before");
base.add(createText(view), "Center");
return base;
}
private JPanel createImage() {
IconCache cache = IconCache.getInstance();
JPanel panel = new JPanel();
panel.setBackground(BackGroundColor.color);
panel.setLayout(new BoxLayout(panel, 3));
try {
URL url = new URL(this.user.getProfileImageURL());
panel.add(new JLabel(cache.getIcon(url)));
} catch (MalformedURLException e) {
e.printStackTrace();
}
panel.setAlignmentX(0.0F);
panel.setAlignmentY(0.0F);
return panel;
}
private JPanel createText(HistoryViewObserver view) {
JPanel textPanel = new JPanel();
textPanel.setMaximumSize(new Dimension(375, Integer.MAX_VALUE));
textPanel.setLayout(new BoxLayout(textPanel, 3));
JLabel userName = new JLabel();
userName.setMaximumSize(new Dimension(375, Integer.MAX_VALUE));
Font font = new Font("MS ゴシック", 1, 13);
userName.setFont(font);
userName.setText("@" + user.getScreenName() + "に" + type + "されました");
textPanel.add(userName);
- String tweet = this.status.getText();
+ String tweet = this.status == null ? "" : this.status.getText();
JTextPane textArea = new JTextPane();
textArea.setContentType("text/html");
textArea.setEditable(false);
textArea.setText(createHTMLText(tweet));
textArea.setBackground(BackGroundColor.color);
textArea.setAlignmentX(0.0F);
textArea.setAlignmentY(0.0F);
textArea.addHyperlinkListener(new HyperlinkListener() {
public void hyperlinkUpdate(HyperlinkEvent e) {
if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
URL url = e.getURL();
Desktop dp = Desktop.getDesktop();
try {
dp.browse(url.toURI());
} catch (IOException e1) {
e1.printStackTrace();
} catch (URISyntaxException e1) {
e1.printStackTrace();
}
}
}
});
textPanel.add(textArea);
textPanel.add(createButtons(view));
textPanel.setAlignmentX(0.0F);
textPanel.setAlignmentY(0.0F);
textPanel.setBackground(BackGroundColor.color);
return textPanel;
}
private String createHTMLText(String tweet) {
final String urlRegex = "(?<![\\w])https?://(([\\w]|[^ -~])+(([\\w\\-]|[^ -~])+([\\w]|[^ -~]))?\\.)+(aero|asia|biz|cat|com|coop|edu|gov|info|int|jobs|mil|mobi|museum|name|net|org|pro|tel|travel|xxx|ac|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|au|aw|ax|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cs|cu|cv|cx|cy|cz|dd|de|dj|dk|dm|do|dz|ec|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|nr|nu|nz|om|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ro|rs|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|ss|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tl|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|za|zm|zw)(?![\\w])(/([\\w\\.\\-\\$&%/:=#~!]*\\??[\\w\\.\\-\\$&%/:=#~!]*[\\w\\-\\$/#])?)?";
Pattern p = Pattern.compile(urlRegex);
Matcher m = p.matcher(urlRegex);
String t = tweet;
while (m.find()) {
String s = m.group();
t = t.replaceFirst(s, "<a href='" + s + "'>" + s + "</a>");
}
t = t.replaceAll("\n", "<br>");
return t;
}
private JPanel createButtons(HistoryViewObserver view) {
//ButtonClickEventListener model = new ButtonClickEventListener(this.user, this.status, view);
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, 2));
/*
JButton rep = new JButton("リプ");
rep.addActionListener(model);
model.setHogeButton(rep);
panel.add(rep);
*/
/*
JToggleButton rt = new JToggleButton("RT");
rt.addActionListener(model);
model.setRtButton(rt);
rt.setEnabled(!s.isRetweetedByMe());
panel.add(rt);
JToggleButton fav = new JToggleButton("☆");
fav.addActionListener(model);
fav.setSelected(s.isFavorited());
model.setFavButton(fav);
panel.add(fav);
*/
panel.setAlignmentX(0.0F);
panel.setAlignmentY(0.0F);
return panel;
}
}
| true | true | private JPanel createText(HistoryViewObserver view) {
JPanel textPanel = new JPanel();
textPanel.setMaximumSize(new Dimension(375, Integer.MAX_VALUE));
textPanel.setLayout(new BoxLayout(textPanel, 3));
JLabel userName = new JLabel();
userName.setMaximumSize(new Dimension(375, Integer.MAX_VALUE));
Font font = new Font("MS ゴシック", 1, 13);
userName.setFont(font);
userName.setText("@" + user.getScreenName() + "に" + type + "されました");
textPanel.add(userName);
String tweet = this.status.getText();
JTextPane textArea = new JTextPane();
textArea.setContentType("text/html");
textArea.setEditable(false);
textArea.setText(createHTMLText(tweet));
textArea.setBackground(BackGroundColor.color);
textArea.setAlignmentX(0.0F);
textArea.setAlignmentY(0.0F);
textArea.addHyperlinkListener(new HyperlinkListener() {
public void hyperlinkUpdate(HyperlinkEvent e) {
if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
URL url = e.getURL();
Desktop dp = Desktop.getDesktop();
try {
dp.browse(url.toURI());
} catch (IOException e1) {
e1.printStackTrace();
} catch (URISyntaxException e1) {
e1.printStackTrace();
}
}
}
});
textPanel.add(textArea);
textPanel.add(createButtons(view));
textPanel.setAlignmentX(0.0F);
textPanel.setAlignmentY(0.0F);
textPanel.setBackground(BackGroundColor.color);
return textPanel;
}
| private JPanel createText(HistoryViewObserver view) {
JPanel textPanel = new JPanel();
textPanel.setMaximumSize(new Dimension(375, Integer.MAX_VALUE));
textPanel.setLayout(new BoxLayout(textPanel, 3));
JLabel userName = new JLabel();
userName.setMaximumSize(new Dimension(375, Integer.MAX_VALUE));
Font font = new Font("MS ゴシック", 1, 13);
userName.setFont(font);
userName.setText("@" + user.getScreenName() + "に" + type + "されました");
textPanel.add(userName);
String tweet = this.status == null ? "" : this.status.getText();
JTextPane textArea = new JTextPane();
textArea.setContentType("text/html");
textArea.setEditable(false);
textArea.setText(createHTMLText(tweet));
textArea.setBackground(BackGroundColor.color);
textArea.setAlignmentX(0.0F);
textArea.setAlignmentY(0.0F);
textArea.addHyperlinkListener(new HyperlinkListener() {
public void hyperlinkUpdate(HyperlinkEvent e) {
if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
URL url = e.getURL();
Desktop dp = Desktop.getDesktop();
try {
dp.browse(url.toURI());
} catch (IOException e1) {
e1.printStackTrace();
} catch (URISyntaxException e1) {
e1.printStackTrace();
}
}
}
});
textPanel.add(textArea);
textPanel.add(createButtons(view));
textPanel.setAlignmentX(0.0F);
textPanel.setAlignmentY(0.0F);
textPanel.setBackground(BackGroundColor.color);
return textPanel;
}
|
diff --git a/src/com/eteks/sweethome3d/viewcontroller/PlanController.java b/src/com/eteks/sweethome3d/viewcontroller/PlanController.java
index ed50ccb7..e711f4fe 100644
--- a/src/com/eteks/sweethome3d/viewcontroller/PlanController.java
+++ b/src/com/eteks/sweethome3d/viewcontroller/PlanController.java
@@ -1,9640 +1,9640 @@
/*
* PlanController.java 2 juin 2006
*
* Sweet Home 3D, Copyright (c) 2006 Emmanuel PUYBARET / eTeks <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package com.eteks.sweethome3d.viewcontroller;
import java.awt.BasicStroke;
import java.awt.Shape;
import java.awt.geom.AffineTransform;
import java.awt.geom.Area;
import java.awt.geom.GeneralPath;
import java.awt.geom.Line2D;
import java.awt.geom.PathIterator;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import javax.swing.undo.AbstractUndoableEdit;
import javax.swing.undo.CannotRedoException;
import javax.swing.undo.CannotUndoException;
import javax.swing.undo.UndoableEdit;
import javax.swing.undo.UndoableEditSupport;
import com.eteks.sweethome3d.model.Camera;
import com.eteks.sweethome3d.model.CollectionEvent;
import com.eteks.sweethome3d.model.CollectionListener;
import com.eteks.sweethome3d.model.Compass;
import com.eteks.sweethome3d.model.DimensionLine;
import com.eteks.sweethome3d.model.Elevatable;
import com.eteks.sweethome3d.model.Home;
import com.eteks.sweethome3d.model.HomeDoorOrWindow;
import com.eteks.sweethome3d.model.HomeFurnitureGroup;
import com.eteks.sweethome3d.model.HomeLight;
import com.eteks.sweethome3d.model.HomePieceOfFurniture;
import com.eteks.sweethome3d.model.HomeTexture;
import com.eteks.sweethome3d.model.Label;
import com.eteks.sweethome3d.model.LengthUnit;
import com.eteks.sweethome3d.model.Level;
import com.eteks.sweethome3d.model.ObserverCamera;
import com.eteks.sweethome3d.model.Room;
import com.eteks.sweethome3d.model.Selectable;
import com.eteks.sweethome3d.model.SelectionEvent;
import com.eteks.sweethome3d.model.SelectionListener;
import com.eteks.sweethome3d.model.TextStyle;
import com.eteks.sweethome3d.model.UserPreferences;
import com.eteks.sweethome3d.model.Wall;
/**
* A MVC controller for the plan view.
* @author Emmanuel Puybaret
*/
public class PlanController extends FurnitureController implements Controller {
public enum Property {MODE, MODIFICATION_STATE, SCALE}
/**
* Selectable modes in controller.
*/
public static class Mode {
// Don't qualify Mode as an enumeration to be able to extend Mode class
public static final Mode SELECTION = new Mode("SELECTION");
public static final Mode PANNING = new Mode("PANNING");
public static final Mode WALL_CREATION = new Mode("WALL_CREATION");
public static final Mode ROOM_CREATION = new Mode("ROOM_CREATION");
public static final Mode DIMENSION_LINE_CREATION = new Mode("DIMENSION_LINE_CREATION");
public static final Mode LABEL_CREATION = new Mode("LABEL_CREATION");
private final String name;
protected Mode(String name) {
this.name = name;
}
public final String name() {
return this.name;
}
@Override
public String toString() {
return this.name;
}
};
/**
* Fields that can be edited in plan view.
*/
public static enum EditableProperty {X, Y, LENGTH, ANGLE, THICKNESS, OFFSET, ARC_EXTENT}
private static final String SCALE_VISUAL_PROPERTY = "com.eteks.sweethome3d.SweetHome3D.PlanScale";
private static final int PIXEL_MARGIN = 4;
private static final int INDICATOR_PIXEL_MARGIN = 4;
private static final int WALL_ENDS_PIXEL_MARGIN = 2;
private final Home home;
private final UserPreferences preferences;
private final ViewFactory viewFactory;
private final ContentManager contentManager;
private final UndoableEditSupport undoSupport;
private final PropertyChangeSupport propertyChangeSupport;
private PlanView planView;
private SelectionListener selectionListener;
// Possibles states
private final ControllerState selectionState;
private final ControllerState rectangleSelectionState;
private final ControllerState selectionMoveState;
private final ControllerState panningState;
private final ControllerState dragAndDropState;
private final ControllerState wallCreationState;
private final ControllerState wallDrawingState;
private final ControllerState wallResizeState;
private final ControllerState pieceOfFurnitureRotationState;
private final ControllerState pieceOfFurnitureElevationState;
private final ControllerState pieceOfFurnitureHeightState;
private final ControllerState pieceOfFurnitureResizeState;
private final ControllerState lightPowerModificationState;
private final ControllerState pieceOfFurnitureNameOffsetState;
private final ControllerState cameraYawRotationState;
private final ControllerState cameraPitchRotationState;
private final ControllerState cameraElevationState;
private final ControllerState dimensionLineCreationState;
private final ControllerState dimensionLineDrawingState;
private final ControllerState dimensionLineResizeState;
private final ControllerState dimensionLineOffsetState;
private final ControllerState roomCreationState;
private final ControllerState roomDrawingState;
private final ControllerState roomResizeState;
private final ControllerState roomAreaOffsetState;
private final ControllerState roomNameOffsetState;
private final ControllerState labelCreationState;
private final ControllerState compassRotationState;
private final ControllerState compassResizeState;
// Current state
private ControllerState state;
private ControllerState previousState;
// Mouse cursor position at last mouse press
private float xLastMousePress;
private float yLastMousePress;
private boolean shiftDownLastMousePress;
private boolean duplicationActivatedLastMousePress;
private float xLastMouseMove;
private float yLastMouseMove;
private Area wallsAreaCache;
private Area insideWallsAreaCache;
private List<GeneralPath> roomPathsCache;
private Map<HomePieceOfFurniture, Area> furnitureSidesCache;
private List<Selectable> draggedItems;
/**
* Creates the controller of plan view.
* @param home the home plan edited by this controller and its view
* @param preferences the preferences of the application
* @param viewFactory a factory able to create the plan view managed by this controller
* @param contentManager a content manager used to import furniture
* @param undoSupport undo support to post changes on plan by this controller
*/
public PlanController(Home home,
UserPreferences preferences,
ViewFactory viewFactory,
ContentManager contentManager,
UndoableEditSupport undoSupport) {
super(home, preferences, viewFactory, contentManager, undoSupport);
this.home = home;
this.preferences = preferences;
this.viewFactory = viewFactory;
this.contentManager = contentManager;
this.undoSupport = undoSupport;
this.propertyChangeSupport = new PropertyChangeSupport(this);
this.furnitureSidesCache = new Hashtable<HomePieceOfFurniture, Area>();
// Initialize states
this.selectionState = new SelectionState();
this.selectionMoveState = new SelectionMoveState();
this.rectangleSelectionState = new RectangleSelectionState();
this.panningState = new PanningState();
this.dragAndDropState = new DragAndDropState();
this.wallCreationState = new WallCreationState();
this.wallDrawingState = new WallDrawingState();
this.wallResizeState = new WallResizeState();
this.pieceOfFurnitureRotationState = new PieceOfFurnitureRotationState();
this.pieceOfFurnitureElevationState = new PieceOfFurnitureElevationState();
this.pieceOfFurnitureHeightState = new PieceOfFurnitureHeightState();
this.pieceOfFurnitureResizeState = new PieceOfFurnitureResizeState();
this.lightPowerModificationState = new LightPowerModificationState();
this.pieceOfFurnitureNameOffsetState = new PieceOfFurnitureNameOffsetState();
this.cameraYawRotationState = new CameraYawRotationState();
this.cameraPitchRotationState = new CameraPitchRotationState();
this.cameraElevationState = new CameraElevationState();
this.dimensionLineCreationState = new DimensionLineCreationState();
this.dimensionLineDrawingState = new DimensionLineDrawingState();
this.dimensionLineResizeState = new DimensionLineResizeState();
this.dimensionLineOffsetState = new DimensionLineOffsetState();
this.roomCreationState = new RoomCreationState();
this.roomDrawingState = new RoomDrawingState();
this.roomResizeState = new RoomResizeState();
this.roomAreaOffsetState = new RoomAreaOffsetState();
this.roomNameOffsetState = new RoomNameOffsetState();
this.labelCreationState = new LabelCreationState();
this.compassRotationState = new CompassRotationState();
this.compassResizeState = new CompassResizeState();
// Set default state to selectionState
setState(this.selectionState);
addModelListeners();
// Restore previous scale if it exists
Float scale = (Float)home.getVisualProperty(SCALE_VISUAL_PROPERTY);
if (scale != null) {
setScale(scale);
}
}
/**
* Returns the view associated with this controller.
*/
public PlanView getView() {
// Create view lazily only once it's needed
if (this.planView == null) {
this.planView = this.viewFactory.createPlanView(this.home, this.preferences, this);
}
return this.planView;
}
/**
* Changes current state of controller.
*/
protected void setState(ControllerState state) {
boolean oldModificationState = false;
if (this.state != null) {
this.state.exit();
oldModificationState = this.state.isModificationState();
}
this.previousState = this.state;
this.state = state;
if (oldModificationState != state.isModificationState()) {
this.propertyChangeSupport.firePropertyChange(Property.MODIFICATION_STATE.name(),
oldModificationState, !oldModificationState);
}
this.state.enter();
}
/**
* Adds the property change <code>listener</code> in parameter to this controller.
*/
public void addPropertyChangeListener(Property property, PropertyChangeListener listener) {
this.propertyChangeSupport.addPropertyChangeListener(property.name(), listener);
}
/**
* Removes the property change <code>listener</code> in parameter from this controller.
*/
public void removePropertyChangeListener(Property property, PropertyChangeListener listener) {
this.propertyChangeSupport.removePropertyChangeListener(property.name(), listener);
}
/**
* Returns the active mode of this controller.
*/
public Mode getMode() {
return this.state.getMode();
}
/**
* Sets the active mode of this controller and fires a <code>PropertyChangeEvent</code>.
*/
public void setMode(Mode mode) {
Mode oldMode = this.state.getMode();
if (mode != oldMode) {
this.state.setMode(mode);
this.propertyChangeSupport.firePropertyChange(Property.MODE.name(), oldMode, mode);
}
}
/**
* Returns <code>true</code> if the interactions in the current mode may modify
* the state of a home.
*/
public boolean isModificationState() {
return this.state.isModificationState();
}
/**
* Deletes the selection in home.
*/
@Override
public void deleteSelection() {
this.state.deleteSelection();
}
/**
* Escapes of current action.
*/
public void escape() {
this.state.escape();
}
/**
* Moves the selection of (<code>dx</code>,<code>dy</code>) in home.
*/
public void moveSelection(float dx, float dy) {
this.state.moveSelection(dx, dy);
}
/**
* Toggles temporary magnetism feature of user preferences.
* @param magnetismToggled if <code>true</code> then magnetism feature is toggled.
*/
public void toggleMagnetism(boolean magnetismToggled) {
this.state.toggleMagnetism(magnetismToggled);
}
/**
* Activates or deactivates duplication feature.
* @param duplicationActivated if <code>true</code> then duplication is active.
*/
public void setDuplicationActivated(boolean duplicationActivated) {
this.state.setDuplicationActivated(duplicationActivated);
}
/**
* Activates or deactivates edition.
* @param editionActivated if <code>true</code> then edition is active
*/
public void setEditionActivated(boolean editionActivated) {
this.state.setEditionActivated(editionActivated);
}
/**
* Updates an editable property with the entered <code>value</code>.
*/
public void updateEditableProperty(EditableProperty editableProperty, Object value) {
this.state.updateEditableProperty(editableProperty, value);
}
/**
* Processes a mouse button pressed event.
*/
public void pressMouse(float x, float y, int clickCount,
boolean shiftDown, boolean duplicationActivated) {
// Store the last coordinates of a mouse press
this.xLastMousePress = x;
this.yLastMousePress = y;
this.xLastMouseMove = x;
this.yLastMouseMove = y;
this.shiftDownLastMousePress = shiftDown;
this.duplicationActivatedLastMousePress = duplicationActivated;
this.state.pressMouse(x, y, clickCount, shiftDown, duplicationActivated);
}
/**
* Processes a mouse button released event.
*/
public void releaseMouse(float x, float y) {
this.state.releaseMouse(x, y);
}
/**
* Processes a mouse button moved event.
*/
public void moveMouse(float x, float y) {
// Store the last coordinates of a mouse move
this.xLastMouseMove = x;
this.yLastMouseMove = y;
this.state.moveMouse(x, y);
}
/**
* Processes a zoom event.
*/
public void zoom(float factor) {
this.state.zoom(factor);
}
/**
* Returns the selection state.
*/
protected ControllerState getSelectionState() {
return this.selectionState;
}
/**
* Returns the selection move state.
*/
protected ControllerState getSelectionMoveState() {
return this.selectionMoveState;
}
/**
* Returns the rectangle selection state.
*/
protected ControllerState getRectangleSelectionState() {
return this.rectangleSelectionState;
}
/**
* Returns the panning state.
*/
protected ControllerState getPanningState() {
return this.panningState;
}
/**
* Returns the drag and drop state.
*/
protected ControllerState getDragAndDropState() {
return this.dragAndDropState;
}
/**
* Returns the wall creation state.
*/
protected ControllerState getWallCreationState() {
return this.wallCreationState;
}
/**
* Returns the wall drawing state.
*/
protected ControllerState getWallDrawingState() {
return this.wallDrawingState;
}
/**
* Returns the wall resize state.
*/
protected ControllerState getWallResizeState() {
return this.wallResizeState;
}
/**
* Returns the piece rotation state.
*/
protected ControllerState getPieceOfFurnitureRotationState() {
return this.pieceOfFurnitureRotationState;
}
/**
* Returns the piece elevation state.
*/
protected ControllerState getPieceOfFurnitureElevationState() {
return this.pieceOfFurnitureElevationState;
}
/**
* Returns the piece height state.
*/
protected ControllerState getPieceOfFurnitureHeightState() {
return this.pieceOfFurnitureHeightState;
}
/**
* Returns the piece resize state.
*/
protected ControllerState getPieceOfFurnitureResizeState() {
return this.pieceOfFurnitureResizeState;
}
/**
* Returns the light power modification state.
*/
protected ControllerState getLightPowerModificationState() {
return this.lightPowerModificationState;
}
/**
* Returns the piece name offset state.
*/
protected ControllerState getPieceOfFurnitureNameOffsetState() {
return this.pieceOfFurnitureNameOffsetState;
}
/**
* Returns the camera yaw rotation state.
*/
protected ControllerState getCameraYawRotationState() {
return this.cameraYawRotationState;
}
/**
* Returns the camera pitch rotation state.
*/
protected ControllerState getCameraPitchRotationState() {
return this.cameraPitchRotationState;
}
/**
* Returns the camera elevation state.
*/
protected ControllerState getCameraElevationState() {
return this.cameraElevationState;
}
/**
* Returns the dimension line creation state.
*/
protected ControllerState getDimensionLineCreationState() {
return this.dimensionLineCreationState;
}
/**
* Returns the dimension line drawing state.
*/
protected ControllerState getDimensionLineDrawingState() {
return this.dimensionLineDrawingState;
}
/**
* Returns the dimension line resize state.
*/
protected ControllerState getDimensionLineResizeState() {
return this.dimensionLineResizeState;
}
/**
* Returns the dimension line offset state.
*/
protected ControllerState getDimensionLineOffsetState() {
return this.dimensionLineOffsetState;
}
/**
* Returns the room creation state.
*/
protected ControllerState getRoomCreationState() {
return this.roomCreationState;
}
/**
* Returns the room drawing state.
*/
protected ControllerState getRoomDrawingState() {
return this.roomDrawingState;
}
/**
* Returns the room resize state.
*/
protected ControllerState getRoomResizeState() {
return this.roomResizeState;
}
/**
* Returns the room area offset state.
*/
protected ControllerState getRoomAreaOffsetState() {
return this.roomAreaOffsetState;
}
/**
* Returns the room name offset state.
*/
protected ControllerState getRoomNameOffsetState() {
return this.roomNameOffsetState;
}
/**
* Returns the label creation state.
*/
protected ControllerState getLabelCreationState() {
return this.labelCreationState;
}
/**
* Returns the compass rotation state.
*/
protected ControllerState getCompassRotationState() {
return this.compassRotationState;
}
/**
* Returns the compass resize state.
*/
protected ControllerState getCompassResizeState() {
return this.compassResizeState;
}
/**
* Returns the abscissa of mouse position at last mouse press.
*/
protected float getXLastMousePress() {
return this.xLastMousePress;
}
/**
* Returns the ordinate of mouse position at last mouse press.
*/
protected float getYLastMousePress() {
return this.yLastMousePress;
}
/**
* Returns <code>true</code> if shift key was down at last mouse press.
*/
protected boolean wasShiftDownLastMousePress() {
return this.shiftDownLastMousePress;
}
/**
* Returns <code>true</code> if duplication was activated at last mouse press.
*/
protected boolean wasDuplicationActivatedLastMousePress() {
return this.duplicationActivatedLastMousePress;
}
/**
* Returns the abscissa of mouse position at last mouse move.
*/
protected float getXLastMouseMove() {
return this.xLastMouseMove;
}
/**
* Returns the ordinate of mouse position at last mouse move.
*/
protected float getYLastMouseMove() {
return this.yLastMouseMove;
}
/**
* Controls the modification of selected walls.
*/
public void modifySelectedWalls() {
if (!Home.getWallsSubList(this.home.getSelectedItems()).isEmpty()) {
new WallController(this.home, this.preferences, this.viewFactory,
this.contentManager, this.undoSupport).displayView(getView());
}
}
/**
* Locks home base plan.
*/
public void lockBasePlan() {
if (!this.home.isBasePlanLocked()) {
List<Selectable> selection = this.home.getSelectedItems();
final Selectable [] oldSelectedItems =
selection.toArray(new Selectable [selection.size()]);
List<Selectable> newSelection = getItemsNotPartOfBasePlan(selection);
final Selectable [] newSelectedItems =
newSelection.toArray(new Selectable [newSelection.size()]);
this.home.setBasePlanLocked(true);
selectItems(newSelection);
UndoableEdit undoableEdit = new AbstractUndoableEdit() {
@Override
public void undo() throws CannotUndoException {
super.undo();
home.setBasePlanLocked(false);
selectAndShowItems(Arrays.asList(oldSelectedItems));
}
@Override
public void redo() throws CannotRedoException {
super.redo();
home.setBasePlanLocked(true);
selectAndShowItems(Arrays.asList(newSelectedItems));
}
@Override
public String getPresentationName() {
return preferences.getLocalizedString(
PlanController.class, "undoLockBasePlan");
}
};
this.undoSupport.postEdit(undoableEdit);
}
}
/**
* Returns <code>true</code> it the given <code>item</code> belongs
* to the base plan.
*/
protected boolean isItemPartOfBasePlan(Selectable item) {
if (item instanceof HomePieceOfFurniture) {
return isPieceOfFurniturePartOfBasePlan((HomePieceOfFurniture)item);
} else {
return !(item instanceof ObserverCamera);
}
}
/**
* Returns the items among the given list that are not part of the base plan.
*/
private List<Selectable> getItemsNotPartOfBasePlan(List<? extends Selectable> items) {
List<Selectable> itemsNotPartOfBasePlan = new ArrayList<Selectable>();
for (Selectable item : items) {
if (!isItemPartOfBasePlan(item)) {
itemsNotPartOfBasePlan.add(item);
}
}
return itemsNotPartOfBasePlan;
}
/**
* Unlocks home base plan.
*/
public void unlockBasePlan() {
if (this.home.isBasePlanLocked()) {
List<Selectable> selection = this.home.getSelectedItems();
final Selectable [] selectedItems =
selection.toArray(new Selectable [selection.size()]);
this.home.setBasePlanLocked(false);
UndoableEdit undoableEdit = new AbstractUndoableEdit() {
@Override
public void undo() throws CannotUndoException {
super.undo();
home.setBasePlanLocked(true);
selectAndShowItems(Arrays.asList(selectedItems));
}
@Override
public void redo() throws CannotRedoException {
super.redo();
home.setBasePlanLocked(false);
selectAndShowItems(Arrays.asList(selectedItems));
}
@Override
public String getPresentationName() {
return preferences.getLocalizedString(
PlanController.class, "undoUnlockBasePlan");
}
};
this.undoSupport.postEdit(undoableEdit);
}
}
/**
* Returns <code>true</code> if the given <code>item</code> may be moved
* in the plan. Default implementation returns <code>true</code>.
*/
protected boolean isItemMovable(Selectable item) {
if (item instanceof HomePieceOfFurniture) {
return isPieceOfFurnitureMovable((HomePieceOfFurniture)item);
} else {
return true;
}
}
/**
* Returns <code>true</code> if the given <code>item</code> may be resized.
* Default implementation returns <code>false</code> if the given <code>item</code>
* is a non resizable piece of furniture.
*/
protected boolean isItemResizable(Selectable item) {
if (item instanceof HomePieceOfFurniture) {
return ((HomePieceOfFurniture)item).isResizable();
} else {
return true;
}
}
/**
* Returns <code>true</code> if the given <code>item</code> may be deleted.
* Default implementation returns <code>true</code> except if the given <code>item</code>
* is a camera or a compass or if the given <code>item</code> isn't a
* {@linkplain #isPieceOfFurnitureDeletable(HomePieceOfFurniture) deletable piece of furniture}.
*/
protected boolean isItemDeletable(Selectable item) {
if (item instanceof HomePieceOfFurniture) {
return isPieceOfFurnitureDeletable((HomePieceOfFurniture)item);
} else {
return !(item instanceof Compass || item instanceof Camera);
}
}
/**
* Controls the direction reverse of selected walls.
*/
public void reverseSelectedWallsDirection() {
List<Wall> selectedWalls = Home.getWallsSubList(this.home.getSelectedItems());
if (!selectedWalls.isEmpty()) {
Wall [] reversedWalls = selectedWalls.toArray(new Wall [selectedWalls.size()]);
doReverseWallsDirection(reversedWalls);
postReverseSelectedWallsDirection(reversedWalls, this.home.getSelectedItems());
}
}
/**
* Posts an undoable reverse wall operation, about <code>walls</code>.
*/
private void postReverseSelectedWallsDirection(final Wall [] walls,
List<Selectable> oldSelection) {
final Selectable [] oldSelectedItems =
oldSelection.toArray(new Selectable [oldSelection.size()]);
UndoableEdit undoableEdit = new AbstractUndoableEdit() {
@Override
public void undo() throws CannotUndoException {
super.undo();
doReverseWallsDirection(walls);
selectAndShowItems(Arrays.asList(oldSelectedItems));
}
@Override
public void redo() throws CannotRedoException {
super.redo();
doReverseWallsDirection(walls);
selectAndShowItems(Arrays.asList(oldSelectedItems));
}
@Override
public String getPresentationName() {
return preferences.getLocalizedString(
PlanController.class, "undoReverseWallsDirectionName");
}
};
this.undoSupport.postEdit(undoableEdit);
}
/**
* Reverses the <code>walls</code> direction.
*/
private void doReverseWallsDirection(Wall [] walls) {
for (Wall wall : walls) {
float xStart = wall.getXStart();
float yStart = wall.getYStart();
float xEnd = wall.getXEnd();
float yEnd = wall.getYEnd();
wall.setXStart(xEnd);
wall.setYStart(yEnd);
wall.setXEnd(xStart);
wall.setYEnd(yStart);
if (wall.getArcExtent() != null) {
wall.setArcExtent(-wall.getArcExtent());
}
Wall wallAtStart = wall.getWallAtStart();
boolean joinedAtEndOfWallAtStart =
wallAtStart != null
&& wallAtStart.getWallAtEnd() == wall;
boolean joinedAtStartOfWallAtStart =
wallAtStart != null
&& wallAtStart.getWallAtStart() == wall;
Wall wallAtEnd = wall.getWallAtEnd();
boolean joinedAtEndOfWallAtEnd =
wallAtEnd != null
&& wallAtEnd.getWallAtEnd() == wall;
boolean joinedAtStartOfWallAtEnd =
wallAtEnd != null
&& wallAtEnd.getWallAtStart() == wall;
wall.setWallAtStart(wallAtEnd);
wall.setWallAtEnd(wallAtStart);
if (joinedAtEndOfWallAtStart) {
wallAtStart.setWallAtEnd(wall);
} else if (joinedAtStartOfWallAtStart) {
wallAtStart.setWallAtStart(wall);
}
if (joinedAtEndOfWallAtEnd) {
wallAtEnd.setWallAtEnd(wall);
} else if (joinedAtStartOfWallAtEnd) {
wallAtEnd.setWallAtStart(wall);
}
Integer rightSideColor = wall.getRightSideColor();
HomeTexture rightSideTexture = wall.getRightSideTexture();
float leftSideShininess = wall.getLeftSideShininess();
Integer leftSideColor = wall.getLeftSideColor();
HomeTexture leftSideTexture = wall.getLeftSideTexture();
float rightSideShininess = wall.getRightSideShininess();
wall.setLeftSideColor(rightSideColor);
wall.setLeftSideTexture(rightSideTexture);
wall.setLeftSideShininess(rightSideShininess);
wall.setRightSideColor(leftSideColor);
wall.setRightSideTexture(leftSideTexture);
wall.setRightSideShininess(leftSideShininess);
Float heightAtEnd = wall.getHeightAtEnd();
if (heightAtEnd != null) {
Float height = wall.getHeight();
wall.setHeight(heightAtEnd);
wall.setHeightAtEnd(height);
}
}
}
/**
* Controls the split of the selected wall in two joined walls of equal length.
*/
public void splitSelectedWall() {
List<Selectable> selectedItems = this.home.getSelectedItems();
List<Wall> selectedWalls = Home.getWallsSubList(selectedItems);
if (selectedWalls.size() == 1) {
boolean basePlanLocked = this.home.isBasePlanLocked();
Wall splitWall = selectedWalls.get(0);
JoinedWall splitJoinedWall = new JoinedWall(splitWall);
float xStart = splitWall.getXStart();
float yStart = splitWall.getYStart();
float xEnd = splitWall.getXEnd();
float yEnd = splitWall.getYEnd();
float xMiddle = (xStart + xEnd) / 2;
float yMiddle = (yStart + yEnd) / 2;
Wall wallAtStart = splitWall.getWallAtStart();
boolean joinedAtEndOfWallAtStart =
wallAtStart != null
&& wallAtStart.getWallAtEnd() == splitWall;
boolean joinedAtStartOfWallAtStart =
wallAtStart != null
&& wallAtStart.getWallAtStart() == splitWall;
Wall wallAtEnd = splitWall.getWallAtEnd();
boolean joinedAtEndOfWallAtEnd =
wallAtEnd != null
&& wallAtEnd.getWallAtEnd() == splitWall;
boolean joinedAtStartOfWallAtEnd =
wallAtEnd != null
&& wallAtEnd.getWallAtStart() == splitWall;
// Clone new walls to copy their characteristics
Wall firstWall = splitWall.clone();
this.home.addWall(firstWall);
firstWall.setLevel(splitWall.getLevel());
Wall secondWall = splitWall.clone();
this.home.addWall(secondWall);
secondWall.setLevel(splitWall.getLevel());
// Change split walls end and start point
firstWall.setXEnd(xMiddle);
firstWall.setYEnd(yMiddle);
secondWall.setXStart(xMiddle);
secondWall.setYStart(yMiddle);
if (splitWall.getHeightAtEnd() != null) {
Float heightAtMiddle = (splitWall.getHeight() + splitWall.getHeightAtEnd()) / 2;
firstWall.setHeightAtEnd(heightAtMiddle);
secondWall.setHeight(heightAtMiddle);
}
firstWall.setWallAtEnd(secondWall);
secondWall.setWallAtStart(firstWall);
firstWall.setWallAtStart(wallAtStart);
if (joinedAtEndOfWallAtStart) {
wallAtStart.setWallAtEnd(firstWall);
} else if (joinedAtStartOfWallAtStart) {
wallAtStart.setWallAtStart(firstWall);
}
secondWall.setWallAtEnd(wallAtEnd);
if (joinedAtEndOfWallAtEnd) {
wallAtEnd.setWallAtEnd(secondWall);
} else if (joinedAtStartOfWallAtEnd) {
wallAtEnd.setWallAtStart(secondWall);
}
// Delete split wall
this.home.deleteWall(splitWall);
selectAndShowItems(Arrays.asList(new Wall [] {firstWall}));
postSplitSelectedWall(splitJoinedWall,
new JoinedWall(firstWall), new JoinedWall(secondWall), selectedItems, basePlanLocked);
}
}
/**
* Posts an undoable split wall operation.
*/
private void postSplitSelectedWall(final JoinedWall splitJoinedWall,
final JoinedWall firstJoinedWall,
final JoinedWall secondJoinedWall,
List<Selectable> oldSelection,
final boolean oldBasePlanLocked) {
final Selectable [] oldSelectedItems =
oldSelection.toArray(new Selectable [oldSelection.size()]);
final boolean newBasePlanLocked = this.home.isBasePlanLocked();
UndoableEdit undoableEdit = new AbstractUndoableEdit() {
@Override
public void undo() throws CannotUndoException {
super.undo();
doDeleteWalls(new JoinedWall [] {firstJoinedWall, secondJoinedWall}, oldBasePlanLocked);
doAddWalls(new JoinedWall [] {splitJoinedWall}, oldBasePlanLocked);
selectAndShowItems(Arrays.asList(oldSelectedItems));
}
@Override
public void redo() throws CannotRedoException {
super.redo();
doDeleteWalls(new JoinedWall [] {splitJoinedWall}, newBasePlanLocked);
doAddWalls(new JoinedWall [] {firstJoinedWall, secondJoinedWall}, newBasePlanLocked);
selectAndShowItems(Arrays.asList(new Wall [] {firstJoinedWall.getWall()}));
}
@Override
public String getPresentationName() {
return preferences.getLocalizedString(
PlanController.class, "undoSplitWallName");
}
};
this.undoSupport.postEdit(undoableEdit);
}
/**
* Controls the modification of the selected rooms.
*/
public void modifySelectedRooms() {
if (!Home.getRoomsSubList(this.home.getSelectedItems()).isEmpty()) {
new RoomController(this.home, this.preferences, this.viewFactory,
this.contentManager, this.undoSupport).displayView(getView());
}
}
/**
* Returns a new label. The new label isn't added to home.
*/
private void createLabel(float x, float y) {
new LabelController(this.home, x, y, this.preferences, this.viewFactory,
this.undoSupport).displayView(getView());
}
/**
* Controls the modification of the selected labels.
*/
public void modifySelectedLabels() {
if (!Home.getLabelsSubList(this.home.getSelectedItems()).isEmpty()) {
new LabelController(this.home, this.preferences, this.viewFactory,
this.undoSupport).displayView(getView());
}
}
/**
* Controls the modification of the compass.
*/
public void modifyCompass() {
new CompassController(this.home, this.preferences, this.viewFactory,
this.undoSupport).displayView(getView());
}
/**
* Controls the modification of the observer camera.
*/
public void modifyObserverCamera() {
new ObserverCameraController(this.home, this.preferences, this.viewFactory).displayView(getView());
}
/**
* Toggles bold style of texts in selected items.
*/
public void toggleBoldStyle() {
// Find if selected items are all bold or not
Boolean selectionBoldStyle = null;
for (Selectable item : this.home.getSelectedItems()) {
Boolean bold;
if (item instanceof Label) {
bold = getItemTextStyle(item, ((Label)item).getStyle()).isBold();
} else if (item instanceof HomePieceOfFurniture
&& ((HomePieceOfFurniture)item).isVisible()) {
bold = getItemTextStyle(item, ((HomePieceOfFurniture)item).getNameStyle()).isBold();
} else if (item instanceof Room) {
Room room = (Room)item;
bold = getItemTextStyle(room, room.getNameStyle()).isBold();
if (bold != getItemTextStyle(room, room.getAreaStyle()).isBold()) {
bold = null;
}
} else if (item instanceof DimensionLine) {
bold = getItemTextStyle(item, ((DimensionLine)item).getLengthStyle()).isBold();
} else {
continue;
}
if (selectionBoldStyle == null) {
selectionBoldStyle = bold;
} else if (bold == null || !selectionBoldStyle.equals(bold)) {
selectionBoldStyle = null;
break;
}
}
// Apply new bold style to all selected items
if (selectionBoldStyle == null) {
selectionBoldStyle = Boolean.TRUE;
} else {
selectionBoldStyle = !selectionBoldStyle;
}
List<Selectable> itemsWithText = new ArrayList<Selectable>();
List<TextStyle> oldTextStyles = new ArrayList<TextStyle>();
List<TextStyle> textStyles = new ArrayList<TextStyle>();
for (Selectable item : this.home.getSelectedItems()) {
if (item instanceof Label) {
Label label = (Label)item;
itemsWithText.add(label);
TextStyle oldTextStyle = getItemTextStyle(label, label.getStyle());
oldTextStyles.add(oldTextStyle);
textStyles.add(oldTextStyle.deriveBoldStyle(selectionBoldStyle));
} else if (item instanceof HomePieceOfFurniture) {
HomePieceOfFurniture piece = (HomePieceOfFurniture)item;
if (piece.isVisible()) {
itemsWithText.add(piece);
TextStyle oldNameStyle = getItemTextStyle(piece, piece.getNameStyle());
oldTextStyles.add(oldNameStyle);
textStyles.add(oldNameStyle.deriveBoldStyle(selectionBoldStyle));
}
} else if (item instanceof Room) {
final Room room = (Room)item;
itemsWithText.add(room);
TextStyle oldNameStyle = getItemTextStyle(room, room.getNameStyle());
oldTextStyles.add(oldNameStyle);
textStyles.add(oldNameStyle.deriveBoldStyle(selectionBoldStyle));
TextStyle oldAreaStyle = getItemTextStyle(room, room.getAreaStyle());
oldTextStyles.add(oldAreaStyle);
textStyles.add(oldAreaStyle.deriveBoldStyle(selectionBoldStyle));
} else if (item instanceof DimensionLine) {
DimensionLine dimensionLine = (DimensionLine)item;
itemsWithText.add(dimensionLine);
TextStyle oldLengthStyle = getItemTextStyle(dimensionLine, dimensionLine.getLengthStyle());
oldTextStyles.add(oldLengthStyle);
textStyles.add(oldLengthStyle.deriveBoldStyle(selectionBoldStyle));
}
}
modifyTextStyle(itemsWithText.toArray(new Selectable [itemsWithText.size()]),
oldTextStyles.toArray(new TextStyle [oldTextStyles.size()]),
textStyles.toArray(new TextStyle [textStyles.size()]));
}
/**
* Returns <code>textStyle</code> if not null or the default text style.
*/
private TextStyle getItemTextStyle(Selectable item, TextStyle textStyle) {
if (textStyle == null) {
textStyle = this.preferences.getDefaultTextStyle(item.getClass());
}
return textStyle;
}
/**
* Toggles italic style of texts in selected items.
*/
public void toggleItalicStyle() {
// Find if selected items are all italic or not
Boolean selectionItalicStyle = null;
for (Selectable item : this.home.getSelectedItems()) {
Boolean italic;
if (item instanceof Label) {
italic = getItemTextStyle(item, ((Label)item).getStyle()).isItalic();
} else if (item instanceof HomePieceOfFurniture
&& ((HomePieceOfFurniture)item).isVisible()) {
italic = getItemTextStyle(item, ((HomePieceOfFurniture)item).getNameStyle()).isItalic();
} else if (item instanceof Room) {
Room room = (Room)item;
italic = getItemTextStyle(room, room.getNameStyle()).isItalic();
if (italic != getItemTextStyle(room, room.getAreaStyle()).isItalic()) {
italic = null;
}
} else if (item instanceof DimensionLine) {
italic = getItemTextStyle(item, ((DimensionLine)item).getLengthStyle()).isItalic();
} else {
continue;
}
if (selectionItalicStyle == null) {
selectionItalicStyle = italic;
} else if (italic == null || !selectionItalicStyle.equals(italic)) {
selectionItalicStyle = null;
break;
}
}
// Apply new italic style to all selected items
if (selectionItalicStyle == null) {
selectionItalicStyle = Boolean.TRUE;
} else {
selectionItalicStyle = !selectionItalicStyle;
}
List<Selectable> itemsWithText = new ArrayList<Selectable>();
List<TextStyle> oldTextStyles = new ArrayList<TextStyle>();
List<TextStyle> textStyles = new ArrayList<TextStyle>();
for (Selectable item : this.home.getSelectedItems()) {
if (item instanceof Label) {
Label label = (Label)item;
itemsWithText.add(label);
TextStyle oldTextStyle = getItemTextStyle(label, label.getStyle());
oldTextStyles.add(oldTextStyle);
textStyles.add(oldTextStyle.deriveItalicStyle(selectionItalicStyle));
} else if (item instanceof HomePieceOfFurniture) {
HomePieceOfFurniture piece = (HomePieceOfFurniture)item;
if (piece.isVisible()) {
itemsWithText.add(piece);
TextStyle oldNameStyle = getItemTextStyle(piece, piece.getNameStyle());
oldTextStyles.add(oldNameStyle);
textStyles.add(oldNameStyle.deriveItalicStyle(selectionItalicStyle));
}
} else if (item instanceof Room) {
final Room room = (Room)item;
itemsWithText.add(room);
TextStyle oldNameStyle = getItemTextStyle(room, room.getNameStyle());
oldTextStyles.add(oldNameStyle);
textStyles.add(oldNameStyle.deriveItalicStyle(selectionItalicStyle));
TextStyle oldAreaStyle = getItemTextStyle(room, room.getAreaStyle());
oldTextStyles.add(oldAreaStyle);
textStyles.add(oldAreaStyle.deriveItalicStyle(selectionItalicStyle));
} else if (item instanceof DimensionLine) {
DimensionLine dimensionLine = (DimensionLine)item;
itemsWithText.add(dimensionLine);
TextStyle oldLengthStyle = getItemTextStyle(dimensionLine, dimensionLine.getLengthStyle());
oldTextStyles.add(oldLengthStyle);
textStyles.add(oldLengthStyle.deriveItalicStyle(selectionItalicStyle));
}
}
modifyTextStyle(itemsWithText.toArray(new Selectable [itemsWithText.size()]),
oldTextStyles.toArray(new TextStyle [oldTextStyles.size()]),
textStyles.toArray(new TextStyle [textStyles.size()]));
}
/**
* Increase the size of texts in selected items.
*/
public void increaseTextSize() {
applyFactorToTextSize(1.1f);
}
/**
* Decrease the size of texts in selected items.
*/
public void decreaseTextSize() {
applyFactorToTextSize(1 / 1.1f);
}
/**
* Applies a factor to the font size of the texts of the selected items in home.
*/
private void applyFactorToTextSize(float factor) {
List<Selectable> itemsWithText = new ArrayList<Selectable>();
List<TextStyle> oldTextStyles = new ArrayList<TextStyle>();
List<TextStyle> textStyles = new ArrayList<TextStyle>();
for (Selectable item : this.home.getSelectedItems()) {
if (item instanceof Label) {
Label label = (Label)item;
itemsWithText.add(label);
TextStyle oldLabelStyle = getItemTextStyle(item, label.getStyle());
oldTextStyles.add(oldLabelStyle);
textStyles.add(oldLabelStyle.deriveStyle(Math.round(oldLabelStyle.getFontSize() * factor)));
} else if (item instanceof HomePieceOfFurniture) {
HomePieceOfFurniture piece = (HomePieceOfFurniture)item;
if (piece.isVisible()) {
itemsWithText.add(piece);
TextStyle oldNameStyle = getItemTextStyle(piece, piece.getNameStyle());
oldTextStyles.add(oldNameStyle);
textStyles.add(oldNameStyle.deriveStyle(Math.round(oldNameStyle.getFontSize() * factor)));
}
} else if (item instanceof Room) {
final Room room = (Room)item;
itemsWithText.add(room);
TextStyle oldNameStyle = getItemTextStyle(room, room.getNameStyle());
oldTextStyles.add(oldNameStyle);
textStyles.add(oldNameStyle.deriveStyle(Math.round(oldNameStyle.getFontSize() * factor)));
TextStyle oldAreaStyle = getItemTextStyle(room, room.getAreaStyle());
oldTextStyles.add(oldAreaStyle);
textStyles.add(oldAreaStyle.deriveStyle(Math.round(oldAreaStyle.getFontSize() * factor)));
} else if (item instanceof DimensionLine) {
DimensionLine dimensionLine = (DimensionLine)item;
itemsWithText.add(dimensionLine);
TextStyle oldLengthStyle = getItemTextStyle(dimensionLine, dimensionLine.getLengthStyle());
oldTextStyles.add(oldLengthStyle);
textStyles.add(oldLengthStyle.deriveStyle(Math.round(oldLengthStyle.getFontSize() * factor)));
}
}
modifyTextStyle(itemsWithText.toArray(new Selectable [itemsWithText.size()]),
oldTextStyles.toArray(new TextStyle [oldTextStyles.size()]),
textStyles.toArray(new TextStyle [textStyles.size()]));
}
/**
* Changes the style of items and posts an undoable change style operation.
*/
private void modifyTextStyle(final Selectable [] items,
final TextStyle [] oldStyles,
final TextStyle [] styles) {
List<Selectable> oldSelection = this.home.getSelectedItems();
final Selectable [] oldSelectedItems =
oldSelection.toArray(new Selectable [oldSelection.size()]);
doModifyTextStyle(items, styles);
UndoableEdit undoableEdit = new AbstractUndoableEdit() {
@Override
public void undo() throws CannotUndoException {
super.undo();
doModifyTextStyle(items, oldStyles);
selectAndShowItems(Arrays.asList(oldSelectedItems));
}
@Override
public void redo() throws CannotRedoException {
super.redo();
doModifyTextStyle(items, styles);
selectAndShowItems(Arrays.asList(oldSelectedItems));
}
@Override
public String getPresentationName() {
return preferences.getLocalizedString(
PlanController.class, "undoModifyTextStyleName");
}
};
this.undoSupport.postEdit(undoableEdit);
}
/**
* Changes the style of items.
*/
private void doModifyTextStyle(Selectable [] items, TextStyle [] styles) {
int styleIndex = 0;
for (Selectable item : items) {
if (item instanceof Label) {
((Label)item).setStyle(styles [styleIndex++]);
} else if (item instanceof HomePieceOfFurniture) {
HomePieceOfFurniture piece = (HomePieceOfFurniture)item;
if (piece.isVisible()) {
piece.setNameStyle(styles [styleIndex++]);
}
} else if (item instanceof Room) {
final Room room = (Room)item;
room.setNameStyle(styles [styleIndex++]);
room.setAreaStyle(styles [styleIndex++]);
} else if (item instanceof DimensionLine) {
((DimensionLine)item).setLengthStyle(styles [styleIndex++]);
}
}
}
/**
* Returns the minimum scale of the plan view.
*/
public float getMinimumScale() {
return 0.01f;
}
/**
* Returns the maximum scale of the plan view.
*/
public float getMaximumScale() {
return 5f;
}
/**
* Returns the scale in plan view.
*/
public float getScale() {
return getView().getScale();
}
/**
* Controls the scale in plan view and and fires a <code>PropertyChangeEvent</code>.
*/
public void setScale(float scale) {
scale = Math.max(getMinimumScale(), Math.min(scale, getMaximumScale()));
if (scale != getView().getScale()) {
float oldScale = getView().getScale();
this.furnitureSidesCache.clear();
if (getView() != null) {
int x = getView().convertXModelToScreen(getXLastMouseMove());
int y = getView().convertXModelToScreen(getYLastMouseMove());
getView().setScale(scale);
// Update mouse location
moveMouse(getView().convertXPixelToModel(x), getView().convertYPixelToModel(y));
}
this.propertyChangeSupport.firePropertyChange(Property.SCALE.name(), oldScale, scale);
this.home.setVisualProperty(SCALE_VISUAL_PROPERTY, scale);
}
}
/**
* Sets the selected level in home.
*/
public void setSelectedLevel(Level level) {
this.home.setSelectedLevel(level);
}
/**
* Selects all visible items in the selected level of home.
*/
@Override
public void selectAll() {
List<Selectable> all = getVisibleItemsAtSelectedLevel();
if (this.home.isBasePlanLocked()) {
this.home.setSelectedItems(getItemsNotPartOfBasePlan(all));
} else {
this.home.setSelectedItems(all);
}
}
/**
* Returns the visible and selectable home items at the selected level, except camera.
*/
private List<Selectable> getVisibleItemsAtSelectedLevel() {
List<Selectable> selectableItems = new ArrayList<Selectable>();
Level selectedLevel = this.home.getSelectedLevel();
for (Wall wall : this.home.getWalls()) {
if (wall.isAtLevel(selectedLevel)) {
selectableItems.add(wall);
}
}
for (Room room : this.home.getRooms()) {
if (room.isAtLevel(selectedLevel)) {
selectableItems.add(room);
}
}
for (DimensionLine dimensionLine : this.home.getDimensionLines()) {
if (dimensionLine.isAtLevel(selectedLevel)) {
selectableItems.add(dimensionLine);
}
}
for (Label label : this.home.getLabels()) {
if (label.isAtLevel(selectedLevel)) {
selectableItems.add(label);
}
}
for (HomePieceOfFurniture piece : this.home.getFurniture()) {
if (isPieceOfFurnitureVisibleAtSelectedLevel(piece)) {
selectableItems.add(piece);
}
}
if (this.home.getCompass().isVisible()) {
selectableItems.add(this.home.getCompass());
}
return selectableItems;
}
/**
* Returns <code>true</code> if the given piece is viewable and
* its height and elevation make it viewable at the selected level in home.
*/
private boolean isPieceOfFurnitureVisibleAtSelectedLevel(HomePieceOfFurniture piece) {
Level selectedLevel = this.home.getSelectedLevel();
return piece.isVisible()
&& (piece.getLevel() == selectedLevel
|| piece.isAtLevel(selectedLevel));
}
/**
* Returns the visible (fully or partially) rooms at the selected level in home.
*/
private List<Room> getDetectableRoomsAtSelectedLevel() {
List<Room> rooms = this.home.getRooms();
Level selectedLevel = this.home.getSelectedLevel();
List<Level> levels = this.home.getLevels();
if (selectedLevel == null || levels.size() <= 1) {
return rooms;
} else {
List<Room> visibleRooms = new ArrayList<Room>(rooms.size());
int selectedLevelIndex = levels.indexOf(selectedLevel);
boolean level0 = levels.get(0) == selectedLevel
|| levels.get(selectedLevelIndex - 1).getElevation() == selectedLevel.getElevation();
Level otherLevel = levels.get(level0 && selectedLevelIndex < levels.size() - 1
? selectedLevelIndex + 1
: selectedLevelIndex - 1);
for (Room room : rooms) {
if (room.isAtLevel(selectedLevel)
|| otherLevel != null
&& room.isAtLevel(otherLevel)
&& (level0 && room.isFloorVisible()
|| !level0 && room.isCeilingVisible())) {
visibleRooms.add(room);
}
}
return visibleRooms;
}
}
/**
* Returns the visible (fully or partially) walls at the selected level in home.
*/
private Collection<Wall> getDetectableWallsAtSelectedLevel() {
Collection<Wall> walls = this.home.getWalls();
Level selectedLevel = this.home.getSelectedLevel();
List<Level> levels = this.home.getLevels();
if (selectedLevel == null || levels.size() <= 1) {
return walls;
} else {
Collection<Wall> visibleWalls = new ArrayList<Wall>(walls.size());
int selectedLevelIndex = levels.indexOf(selectedLevel);
boolean level0 = levels.get(0) == selectedLevel
|| levels.get(selectedLevelIndex - 1).getElevation() == selectedLevel.getElevation();
Level otherLevel = levels.get(level0 && selectedLevelIndex < levels.size() - 1
? selectedLevelIndex + 1
: selectedLevelIndex - 1);
for (Wall wall : walls) {
if (wall.isAtLevel(selectedLevel)
|| otherLevel != null
&& wall.isAtLevel(otherLevel)) {
visibleWalls.add(wall);
}
}
return visibleWalls;
}
}
/**
* Returns the horizontal ruler of the plan view.
*/
public View getHorizontalRulerView() {
return getView().getHorizontalRuler();
}
/**
* Returns the vertical ruler of the plan view.
*/
public View getVerticalRulerView() {
return getView().getVerticalRuler();
}
private void addModelListeners() {
this.selectionListener = new SelectionListener() {
public void selectionChanged(SelectionEvent ev) {
selectLevelFromSelectedItems();
if (getView() != null) {
getView().makeSelectionVisible();
}
}
};
this.home.addSelectionListener(this.selectionListener);
// Ensure observer camera is visible when its size, location or angles change
this.home.getObserverCamera().addPropertyChangeListener(new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
if (home.getSelectedItems().contains(ev.getSource())) {
if (getView() != null) {
getView().makeSelectionVisible();
}
}
}
});
// Add listener to update roomPathsCache when walls change
final PropertyChangeListener wallChangeListener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
String propertyName = ev.getPropertyName();
if (Wall.Property.X_START.name().equals(propertyName)
|| Wall.Property.X_END.name().equals(propertyName)
|| Wall.Property.Y_START.name().equals(propertyName)
|| Wall.Property.Y_END.name().equals(propertyName)
|| Wall.Property.WALL_AT_START.name().equals(propertyName)
|| Wall.Property.WALL_AT_END.name().equals(propertyName)
|| Wall.Property.THICKNESS.name().equals(propertyName)
|| Wall.Property.LEVEL.name().equals(propertyName)
|| Wall.Property.HEIGHT.name().equals(propertyName)
|| Wall.Property.HEIGHT_AT_END.name().equals(propertyName)) {
resetAreaCache();
// Unselect unreachable wall
Wall wall = (Wall)ev.getSource();
if (!wall.isAtLevel(home.getSelectedLevel())) {
List<Selectable> selectedItems = new ArrayList<Selectable>(home.getSelectedItems());
if (selectedItems.remove(wall)) {
selectItems(selectedItems);
}
}
}
}
};
for (Wall wall : this.home.getWalls()) {
wall.addPropertyChangeListener(wallChangeListener);
}
this.home.addWallsListener(new CollectionListener<Wall> () {
public void collectionChanged(CollectionEvent<Wall> ev) {
if (ev.getType() == CollectionEvent.Type.ADD) {
ev.getItem().addPropertyChangeListener(wallChangeListener);
} else if (ev.getType() == CollectionEvent.Type.DELETE) {
ev.getItem().removePropertyChangeListener(wallChangeListener);
}
resetAreaCache();
}
});
// Add listener to update furnitureBordersCache when walls change
final PropertyChangeListener furnitureChangeListener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
String propertyName = ev.getPropertyName();
if (HomePieceOfFurniture.Property.X.name().equals(propertyName)
|| HomePieceOfFurniture.Property.Y.name().equals(propertyName)
|| HomePieceOfFurniture.Property.WIDTH.name().equals(propertyName)
|| HomePieceOfFurniture.Property.DEPTH.name().equals(propertyName)) {
furnitureSidesCache.remove((HomePieceOfFurniture)ev.getSource());
}
}
};
for (HomePieceOfFurniture piece : this.home.getFurniture()) {
piece.addPropertyChangeListener(furnitureChangeListener);
}
this.home.addFurnitureListener(new CollectionListener<HomePieceOfFurniture> () {
public void collectionChanged(CollectionEvent<HomePieceOfFurniture> ev) {
if (ev.getType() == CollectionEvent.Type.ADD) {
ev.getItem().addPropertyChangeListener(furnitureChangeListener);
} else if (ev.getType() == CollectionEvent.Type.DELETE) {
ev.getItem().removePropertyChangeListener(furnitureChangeListener);
furnitureSidesCache.remove(ev.getItem());
}
}
});
this.home.addPropertyChangeListener(Home.Property.SELECTED_LEVEL, new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
resetAreaCache();
}
});
this.home.getObserverCamera().setFixedSize(home.getLevels().size() >= 2);
this.home.addLevelsListener(new CollectionListener<Level>() {
public void collectionChanged(CollectionEvent<Level> ev) {
home.getObserverCamera().setFixedSize(home.getLevels().size() >= 2);
}
});
}
private void resetAreaCache() {
wallsAreaCache = null;
insideWallsAreaCache = null;
roomPathsCache = null;
}
/**
* Displays in plan view the feedback of <code>draggedItems</code>,
* during a drag and drop operation initiated from outside of plan view.
*/
public void startDraggedItems(List<Selectable> draggedItems, float x, float y) {
this.draggedItems = draggedItems;
// If magnetism is enabled, adjust furniture size and elevation
if (this.preferences.isMagnetismEnabled()) {
for (HomePieceOfFurniture piece : Home.getFurnitureSubList(draggedItems)) {
if (piece.isResizable()) {
piece.setWidth(this.preferences.getLengthUnit().getMagnetizedLength(piece.getWidth(), 0.1f));
piece.setDepth(this.preferences.getLengthUnit().getMagnetizedLength(piece.getDepth(), 0.1f));
piece.setHeight(this.preferences.getLengthUnit().getMagnetizedLength(piece.getHeight(), 0.1f));
}
piece.setElevation(this.preferences.getLengthUnit().getMagnetizedLength(piece.getElevation(), 0.1f));
}
}
setState(getDragAndDropState());
moveMouse(x, y);
}
/**
* Deletes in plan view the feedback of the dragged items.
*/
public void stopDraggedItems() {
if (this.state != getDragAndDropState()) {
throw new IllegalStateException("Controller isn't in a drag and drop state");
}
this.draggedItems = null;
setState(this.previousState);
}
/**
* Attempts to modify <code>piece</code> location depending of its context.
* If the <code>piece</code> is a door or a window and the point (<code>x</code>, <code>y</code>)
* belongs to a wall, the piece will be resized, rotated and moved so
* its opening depth is equal to wall thickness and its angle matches wall direction.
* If the <code>piece</code> isn't a door or a window and the point (<code>x</code>, <code>y</code>)
* belongs to a wall, the piece will be rotated and moved so
* its back face lies along the closest wall side and its angle matches wall direction.
* If the <code>piece</code> isn't a door or a window, its bounding box is included in
* the one of an other object and its elevation is equal to zero, it will be elevated
* to appear on the top of the latter.
*/
protected void adjustMagnetizedPieceOfFurniture(HomePieceOfFurniture piece, float x, float y) {
Wall magnetWall = adjustPieceOfFurnitureOnWallAt(piece, x, y, true);
if (adjustPieceOfFurnitureElevation(piece) == null) {
adjustPieceOfFurnitureSideBySideAt(piece, magnetWall == null, magnetWall != null);
}
}
/**
* Attempts to move and resize <code>piece</code> depending on the wall under the
* point (<code>x</code>, <code>y</code>) and returns that wall it it exists.
* @see #adjustMagnetizedPieceOfFurniture(HomePieceOfFurniture, float, float)
*/
private Wall adjustPieceOfFurnitureOnWallAt(HomePieceOfFurniture piece,
float x, float y, boolean forceOrientation) {
float margin = PIXEL_MARGIN / getScale();
Level selectedLevel = this.home.getSelectedLevel();
float [][] piecePoints = piece.getPoints();
Area wallsArea = getWallsArea();
Collection<Wall> walls = this.home.getWalls();
Wall referenceWall = null;
if (forceOrientation
|| !piece.isDoorOrWindow()) {
// Search if point (x, y) is contained in home walls with no margin
for (Wall wall : walls) {
if (wall.isAtLevel(selectedLevel)
&& wall.containsPoint(x, y, 0)
&& wall.getStartPointToEndPointDistance() > 0) {
referenceWall = getReferenceWall(wall, x, y);
break;
}
}
if (referenceWall == null) {
// If not found search if point (x, y) is contained in home walls with a margin
for (Wall wall : walls) {
if (wall.isAtLevel(selectedLevel)
&& wall.containsPoint(x, y, margin)
&& wall.getStartPointToEndPointDistance() > 0) {
referenceWall = getReferenceWall(wall, x, y);
break;
}
}
}
}
if (referenceWall == null) {
// Search if the border of a wall at floor level intersects with the given piece
Area pieceAreaWithMargin = new Area(getRotatedRectangle(
- piece.getX() - piece.getWidth() / 2 - margin, piece.getY() - piece.getDepth() / 2 - margin,
+ piece.getX() - piece.getWidth() / 2 - margin, piece.getY() - piece.getDepth() / 2 - margin,
piece.getWidth() + 2 * margin, piece.getDepth() + 2 * margin, piece.getAngle()));
float intersectionWithReferenceWallSurface = 0;
for (Wall wall : walls) {
if (wall.isAtLevel(selectedLevel)
&& wall.getStartPointToEndPointDistance() > 0) {
float [][] wallPoints = wall.getPoints();
Area wallAreaIntersection = new Area(getPath(wallPoints));
wallAreaIntersection.intersect(pieceAreaWithMargin);
if (!wallAreaIntersection.isEmpty()) {
float surface = getArea(wallAreaIntersection);
if (surface > intersectionWithReferenceWallSurface) {
- surface = intersectionWithReferenceWallSurface;
+ intersectionWithReferenceWallSurface = surface;
if (forceOrientation) {
referenceWall = getReferenceWall(wall, x, y);
} else {
Rectangle2D intersectionBounds = wallAreaIntersection.getBounds2D();
referenceWall = getReferenceWall(wall, (float)intersectionBounds.getCenterX(), (float)intersectionBounds.getCenterY());
}
}
}
}
}
}
if (referenceWall != null
&& (referenceWall.getArcExtent() == null
|| !piece.isDoorOrWindow())) {
float xPiece = x;
float yPiece = y;
float pieceAngle = piece.getAngle();
float halfWidth = piece.getWidth() / 2;
float halfDepth = piece.getDepth() / 2;
double wallAngle = Math.atan2(referenceWall.getYEnd() - referenceWall.getYStart(),
referenceWall.getXEnd() - referenceWall.getXStart());
float [][] wallPoints = referenceWall.getPoints();
boolean magnetizedAtRight = wallAngle > -Math.PI / 2 && wallAngle <= Math.PI / 2;
double cosWallAngle = Math.cos(wallAngle);
double sinWallAngle = Math.sin(wallAngle);
double distanceToLeftSide = Line2D.ptLineDist(
wallPoints [0][0], wallPoints [0][1], wallPoints [1][0], wallPoints [1][1], x, y);
double distanceToRightSide = Line2D.ptLineDist(
wallPoints [2][0], wallPoints [2][1], wallPoints [3][0], wallPoints [3][1], x, y);
boolean adjustOrientation = forceOrientation
|| piece.isDoorOrWindow()
|| referenceWall.containsPoint(x, y, PIXEL_MARGIN / getScale());
if (adjustOrientation) {
double distanceToPieceLeftSide = Line2D.ptLineDist(
piecePoints [0][0], piecePoints [0][1], piecePoints [3][0], piecePoints [3][1], x, y);
double distanceToPieceRightSide = Line2D.ptLineDist(
piecePoints [1][0], piecePoints [1][1], piecePoints [2][0], piecePoints [2][1], x, y);
double distanceToPieceSide = pieceAngle > (3 * Math.PI / 2 + 1E-6) || pieceAngle < (Math.PI / 2 + 1E-6)
? distanceToPieceLeftSide
: distanceToPieceRightSide;
pieceAngle = (float)(distanceToRightSide < distanceToLeftSide
? wallAngle
: wallAngle + Math.PI);
if (piece.isDoorOrWindow()) {
final float thicknessEpsilon = 0.00025f;
float wallDistance = thicknessEpsilon / 2;
if (piece instanceof HomeDoorOrWindow) {
HomeDoorOrWindow doorOrWindow = (HomeDoorOrWindow)piece;
if (piece.isResizable()
&& isItemResizable(piece)) {
piece.setDepth(thicknessEpsilon
+ referenceWall.getThickness() / doorOrWindow.getWallThickness());
halfDepth = piece.getDepth() / 2;
}
wallDistance += piece.getDepth() * doorOrWindow.getWallDistance();
}
if (distanceToRightSide < distanceToLeftSide) {
xPiece += sinWallAngle * ( (distanceToLeftSide + wallDistance) - halfDepth);
yPiece += cosWallAngle * (-(distanceToLeftSide + wallDistance) + halfDepth);
} else {
xPiece += sinWallAngle * (-(distanceToRightSide + wallDistance) + halfDepth);
yPiece += cosWallAngle * ( (distanceToRightSide + wallDistance) - halfDepth);
}
if (magnetizedAtRight) {
xPiece += cosWallAngle * (halfWidth - distanceToPieceSide);
yPiece += sinWallAngle * (halfWidth - distanceToPieceSide);
} else {
// Ensure adjusted window is at the right of the cursor
xPiece += -cosWallAngle * (halfWidth - distanceToPieceSide);
yPiece += -sinWallAngle * (halfWidth - distanceToPieceSide);
}
} else {
if (distanceToRightSide < distanceToLeftSide) {
int pointIndicator = Line2D.relativeCCW(
wallPoints [2][0], wallPoints [2][1], wallPoints [3][0], wallPoints [3][1], x, y);
xPiece += pointIndicator * sinWallAngle * distanceToRightSide - sinWallAngle * halfDepth;
yPiece += -pointIndicator * cosWallAngle * distanceToRightSide + cosWallAngle * halfDepth;
} else {
int pointIndicator = Line2D.relativeCCW(
wallPoints [0][0], wallPoints [0][1], wallPoints [1][0], wallPoints [1][1], x, y);
xPiece += -pointIndicator * sinWallAngle * distanceToLeftSide + sinWallAngle * halfDepth;
yPiece += pointIndicator * cosWallAngle * distanceToLeftSide - cosWallAngle * halfDepth;
}
if (magnetizedAtRight) {
xPiece += cosWallAngle * (halfWidth - distanceToPieceSide);
yPiece += sinWallAngle * (halfWidth - distanceToPieceSide);
} else {
// Ensure adjusted piece is at the right of the cursor
xPiece += -cosWallAngle * (halfWidth - distanceToPieceSide);
yPiece += -sinWallAngle * (halfWidth - distanceToPieceSide);
}
}
} else {
// Search the distance required to align piece on the left or right side of the reference wall
Line2D centerLine = new Line2D.Float(referenceWall.getXStart(), referenceWall.getYStart(),
referenceWall.getXEnd(), referenceWall.getYEnd());
Shape pieceBoundingBox = getRotatedRectangle(0, 0, piece.getWidth(), piece.getDepth(), (float)(pieceAngle - wallAngle));
double rotatedBoundingBoxDepth = pieceBoundingBox.getBounds2D().getHeight();
double distance = centerLine.relativeCCW(piece.getX(), piece.getY())
* (-referenceWall.getThickness() / 2 + centerLine.ptLineDist(piece.getX(), piece.getY()) - rotatedBoundingBoxDepth / 2);
if (Math.signum(centerLine.relativeCCW(x, y)) != Math.signum(centerLine.relativeCCW(piece.getX(), piece.getY()))) {
distance -= Math.signum(centerLine.relativeCCW(x, y)) * (rotatedBoundingBoxDepth + referenceWall.getThickness());
}
xPiece = piece.getX() + (float)(-distance * sinWallAngle);
yPiece = piece.getY() + (float)(distance * cosWallAngle);
}
if (!piece.isDoorOrWindow()
&& (referenceWall.getArcExtent() == null // Ignore reoriented piece when (x, y) is inside a round wall
|| !adjustOrientation
|| Line2D.relativeCCW(referenceWall.getXStart(), referenceWall.getYStart(),
referenceWall.getXEnd(), referenceWall.getYEnd(), x, y) > 0)) {
// Search if piece intersects some other walls and avoid it intersects the closest one
Area wallsAreaIntersection = new Area(wallsArea);
Area adjustedPieceArea = new Area(getRotatedRectangle(xPiece - halfWidth,
yPiece - halfDepth, piece.getWidth(), piece.getDepth(), pieceAngle));
wallsAreaIntersection.subtract(new Area(getPath(wallPoints)));
wallsAreaIntersection.intersect(adjustedPieceArea);
if (!wallsAreaIntersection.isEmpty()) {
// Search the wall intersection path the closest to (x, y)
GeneralPath closestWallIntersectionPath = getClosestPath(getAreaPaths(wallsAreaIntersection), x, y);
if (closestWallIntersectionPath != null) {
// In case the adjusted piece crosses a wall, search the area intersecting that wall
// + other parts which crossed the wall (the farthest ones from (x,y))
adjustedPieceArea.subtract(wallsArea);
if (adjustedPieceArea.isEmpty()) {
return null;
} else {
List<GeneralPath> adjustedPieceAreaPaths = getAreaPaths(adjustedPieceArea);
// Ignore too complex cases when the piece intersect many walls and is not parallel to a wall
double angleDifference = (wallAngle - pieceAngle + 2 * Math.PI) % Math.PI;
if (angleDifference < 1E-5
|| Math.PI - angleDifference < 1E-5
|| adjustedPieceAreaPaths.size() < 2) {
GeneralPath adjustedPiecePathInArea = getClosestPath(adjustedPieceAreaPaths, x, y);
Area adjustingArea = new Area(closestWallIntersectionPath);
for (GeneralPath path : adjustedPieceAreaPaths) {
if (path != adjustedPiecePathInArea) {
adjustingArea.add(new Area(path));
}
}
AffineTransform rotation = AffineTransform.getRotateInstance(-wallAngle);
Rectangle2D adjustingAreaBounds = adjustingArea.createTransformedArea(rotation).getBounds2D();
Rectangle2D adjustedPiecePathInAreaBounds = adjustedPiecePathInArea.createTransformedShape(rotation).getBounds2D();
if (!adjustingAreaBounds.contains(adjustedPiecePathInAreaBounds)) {
double adjustLeftBorder = Math.signum(adjustedPiecePathInAreaBounds.getCenterX() - adjustingAreaBounds.getCenterX());
xPiece += adjustingAreaBounds.getWidth() * cosWallAngle * adjustLeftBorder;
yPiece += adjustingAreaBounds.getWidth() * sinWallAngle * adjustLeftBorder;
}
}
}
}
}
}
piece.setAngle(pieceAngle);
piece.setX(xPiece);
piece.setY(yPiece);
if (piece instanceof HomeDoorOrWindow) {
((HomeDoorOrWindow) piece).setBoundToWall(true);
}
return referenceWall;
}
return null;
}
/**
* Returns <code>wall</code> or a small wall part at the angle formed by the line joining wall center to
* (<code>x</code>, <code>y</code>) point if the given <code>wall</code> is round.
*/
public Wall getReferenceWall(Wall wall, float x, float y) {
if (wall.getArcExtent() == null) {
return wall;
} else {
double angle = Math.atan2(wall.getYArcCircleCenter() - y, x - wall.getXArcCircleCenter());
double radius = Point2D.distance(wall.getXArcCircleCenter(), wall.getYArcCircleCenter(), wall.getXStart(), wall.getYStart());
float epsilonAngle = 0.001f;
Wall wallPart = new Wall((float)(wall.getXArcCircleCenter() + Math.cos(angle + epsilonAngle) * radius),
(float)(wall.getYArcCircleCenter() - Math.sin(angle + epsilonAngle) * radius),
(float)(wall.getXArcCircleCenter() + Math.cos(angle - epsilonAngle) * radius),
(float)(wall.getYArcCircleCenter() - Math.sin(angle - epsilonAngle) * radius), wall.getThickness(), 0);
wallPart.setArcExtent(epsilonAngle * 2);
return wallPart;
}
}
/**
* Returns the closest path among <code>area</code> ones to the given point.
*/
public GeneralPath getClosestPath(List<GeneralPath> paths, float x, float y) {
GeneralPath closestPath = null;
double closestPathDistance = Double.MAX_VALUE;
for (GeneralPath path : paths) {
float [][] pathPoints = getPathPoints(path, true);
for (int i = 0; i < pathPoints.length; i++) {
double distanceToPath = Line2D.ptSegDistSq(pathPoints [i][0], pathPoints [i][1],
pathPoints [(i + 1) % pathPoints.length][0], pathPoints [(i + 1) % pathPoints.length][1], x, y);
if (distanceToPath < closestPathDistance) {
closestPathDistance = distanceToPath;
closestPath = path;
}
}
}
return closestPath;
}
/**
* Returns the dimension lines that indicates how is placed a given <code>piece</code>
* along a <code>wall</code>.
*/
private List<DimensionLine> getDimensionLinesAlongWall(HomePieceOfFurniture piece, Wall wall) {
// Search the points on the wall side closest to piece
float [][] piecePoints = piece.getPoints();
float angle = piece.getAngle();
float [][] wallPoints = wall.getPoints();
float [] pieceLeftPoint;
float [] pieceRightPoint;
float [] piecePoint = piece.isDoorOrWindow()
? piecePoints [3] // Front side point
: piecePoints [0]; // Back side point
if (Line2D.ptLineDistSq(wallPoints [0][0], wallPoints [0][1],
wallPoints [1][0], wallPoints [1][1],
piecePoint [0], piecePoint [1])
<= Line2D.ptLineDistSq(wallPoints [2][0], wallPoints [2][1],
wallPoints [3][0], wallPoints [3][1],
piecePoint [0], piecePoint [1])) {
pieceLeftPoint = computeIntersection(wallPoints [0], wallPoints [1], piecePoints [0], piecePoints [3]);
pieceRightPoint = computeIntersection(wallPoints [0], wallPoints [1], piecePoints [1], piecePoints [2]);
} else {
pieceLeftPoint = computeIntersection(wallPoints [2], wallPoints [3], piecePoints [0], piecePoints [3]);
pieceRightPoint = computeIntersection(wallPoints [2], wallPoints [3], piecePoints [1], piecePoints [2]);
}
List<DimensionLine> dimensionLines = new ArrayList<DimensionLine>();
float [] wallEndPointJoinedToPieceLeftPoint = null;
float [] wallEndPointJoinedToPieceRightPoint = null;
// Search among room paths which segment includes pieceLeftPoint and pieceRightPoint
List<GeneralPath> roomPaths = getRoomPathsFromWalls();
for (int i = 0;
i < roomPaths.size()
&& wallEndPointJoinedToPieceLeftPoint == null
&& wallEndPointJoinedToPieceRightPoint == null; i++) {
float [][] roomPoints = getPathPoints(roomPaths.get(i), true);
for (int j = 0; j < roomPoints.length; j++) {
float [] startPoint = roomPoints [j];
float [] endPoint = roomPoints [(j + 1) % roomPoints.length];
float deltaX = endPoint [0] - startPoint [0];
float deltaY = endPoint [1] - startPoint [1];
double segmentAngle = Math.abs(deltaX) < 1E-5
? Math.PI / 2
: (Math.abs(deltaY) < 1E-5
? 0
: Math.atan2(deltaY, deltaX));
// If segment and piece are parallel
double angleDifference = (segmentAngle - angle + 2 * Math.PI) % Math.PI;
if (angleDifference < 1E-5 || Math.PI - angleDifference < 1E-5) {
boolean segmentContainsLeftPoint = Line2D.ptSegDistSq(startPoint [0], startPoint [1],
endPoint [0], endPoint [1], pieceLeftPoint [0], pieceLeftPoint [1]) < 0.0001;
boolean segmentContainsRightPoint = Line2D.ptSegDistSq(startPoint [0], startPoint [1],
endPoint [0], endPoint [1], pieceRightPoint [0], pieceRightPoint [1]) < 0.0001;
if (segmentContainsLeftPoint || segmentContainsRightPoint) {
if (segmentContainsLeftPoint) {
// Compute distances to segment start point
double startPointToLeftPointDistance = Point2D.distanceSq(startPoint [0], startPoint [1],
pieceLeftPoint [0], pieceLeftPoint [1]);
double startPointToRightPointDistance = Point2D.distanceSq(startPoint [0], startPoint [1],
pieceRightPoint [0], pieceRightPoint [1]);
if (startPointToLeftPointDistance < startPointToRightPointDistance
|| !segmentContainsRightPoint) {
wallEndPointJoinedToPieceLeftPoint = startPoint.clone();
} else {
wallEndPointJoinedToPieceLeftPoint = endPoint.clone();
}
}
if (segmentContainsRightPoint) {
// Compute distances to segment start point
double endPointToLeftPointDistance = Point2D.distanceSq(endPoint [0], endPoint [1],
pieceLeftPoint [0], pieceLeftPoint [1]);
double endPointToRightPointDistance = Point2D.distanceSq(endPoint [0], endPoint [1],
pieceRightPoint [0], pieceRightPoint [1]);
if (endPointToLeftPointDistance < endPointToRightPointDistance
&& segmentContainsLeftPoint) {
wallEndPointJoinedToPieceRightPoint = startPoint.clone();
} else {
wallEndPointJoinedToPieceRightPoint = endPoint.clone();
}
}
break;
}
}
}
}
boolean reverse = angle > Math.PI / 2 && angle <= 3 * Math.PI / 2;
boolean pieceFrontSideAlongWallSide = !piece.isDoorOrWindow()
&& Line2D.ptLineDistSq(wall.getXStart(), wall.getYStart(), wall.getXEnd(), wall.getYEnd(), piecePoint [0], piecePoint [1])
> Line2D.ptLineDistSq(wall.getXStart(), wall.getYStart(), wall.getXEnd(), wall.getYEnd(), piecePoints [3][0], piecePoints [3][1]);
if (wallEndPointJoinedToPieceLeftPoint != null) {
float offset = (float)Point2D.distance(pieceLeftPoint [0], pieceLeftPoint [1],
piecePoints [3][0], piecePoints [3][1]) + 10 / getView().getScale();
if (pieceFrontSideAlongWallSide) {
offset = -(float)Point2D.distance(pieceLeftPoint [0], pieceLeftPoint [1],
piecePoints [0][0], piecePoints [0][1]) - 10 / getView().getScale();
}
if (reverse) {
dimensionLines.add(new DimensionLine(pieceLeftPoint [0], pieceLeftPoint [1],
wallEndPointJoinedToPieceLeftPoint [0],
wallEndPointJoinedToPieceLeftPoint [1], -offset));
} else {
dimensionLines.add(new DimensionLine(wallEndPointJoinedToPieceLeftPoint [0],
wallEndPointJoinedToPieceLeftPoint [1],
pieceLeftPoint [0], pieceLeftPoint [1], offset));
}
}
if (wallEndPointJoinedToPieceRightPoint != null) {
float offset = (float)Point2D.distance(pieceRightPoint [0], pieceRightPoint [1],
piecePoints [2][0], piecePoints [2][1]) + 10 / getView().getScale();
if (pieceFrontSideAlongWallSide) {
offset = -(float)Point2D.distance(pieceRightPoint [0], pieceRightPoint [1],
piecePoints [1][0], piecePoints [1][1]) - 10 / getView().getScale();
}
if (reverse) {
dimensionLines.add(new DimensionLine(wallEndPointJoinedToPieceRightPoint [0],
wallEndPointJoinedToPieceRightPoint [1],
pieceRightPoint [0], pieceRightPoint [1], -offset));
} else {
dimensionLines.add(new DimensionLine(pieceRightPoint [0], pieceRightPoint [1],
wallEndPointJoinedToPieceRightPoint [0],
wallEndPointJoinedToPieceRightPoint [1], offset));
}
}
for (Iterator<DimensionLine> it = dimensionLines.iterator(); it.hasNext(); ) {
if (it.next().getLength() < 0.01f) {
it.remove();
}
}
return dimensionLines;
}
/**
* Returns the intersection point between the lines defined by the points
* (<code>point1</code>, <code>point2</code>) and (<code>point3</code>, <code>pont4</code>).
*/
private float [] computeIntersection(float [] point1, float [] point2, float [] point3, float [] point4) {
float x = point2 [0];
float y = point2 [1];
float alpha1 = (point2 [1] - point1 [1]) / (point2 [0] - point1 [0]);
float alpha2 = (point4 [1] - point3 [1]) / (point4 [0] - point3 [0]);
if (alpha1 != alpha2) {
// If first line is vertical
if (Math.abs(alpha1) > 1E5) {
if (Math.abs(alpha2) < 1E5) {
x = point1 [0];
float beta2 = point4 [1] - alpha2 * point4 [0];
y = alpha2 * x + beta2;
}
// If second line is vertical
} else if (Math.abs(alpha2) > 1E5) {
if (Math.abs(alpha1) < 1E5) {
x = point3 [0];
float beta1 = point2 [1] - alpha1 * point2 [0];
y = alpha1 * x + beta1;
}
} else {
boolean sameSignum = Math.signum(alpha1) == Math.signum(alpha2);
if ((sameSignum && (Math.abs(alpha1) > Math.abs(alpha2) ? alpha1 / alpha2 : alpha2 / alpha1) > 1.0001)
|| (!sameSignum && Math.abs(alpha1 - alpha2) > 1E-5)) {
float beta1 = point2 [1] - alpha1 * point2 [0];
float beta2 = point4 [1] - alpha2 * point4 [0];
x = (beta2 - beta1) / (alpha1 - alpha2);
y = alpha1 * x + beta1;
}
}
}
return new float [] {x, y};
}
/**
* Attempts to elevate <code>piece</code> depending on the highest piece that includes
* its bounding box and returns that piece.
* @see #adjustMagnetizedPieceOfFurniture(HomePieceOfFurniture, float, float)
*/
private HomePieceOfFurniture adjustPieceOfFurnitureElevation(HomePieceOfFurniture piece) {
// Search if another piece at floor level contains the given piece to elevate it at its height
if (!piece.isDoorOrWindow()
&& piece.getElevation() == 0) {
float [][] piecePoints = piece.getPoints();
HomePieceOfFurniture highestSurroundingPiece = null;
float highestElevation = Float.MIN_VALUE;
for (HomePieceOfFurniture homePiece : this.home.getFurniture()) {
if (homePiece != piece
&& !homePiece.isDoorOrWindow()
&& isPieceOfFurnitureVisibleAtSelectedLevel(homePiece)) {
Shape shape = getPath(homePiece.getPoints());
boolean surroundingPieceContainsPiece = true;
for (float [] point : piecePoints) {
if (!shape.contains(point [0], point [1])) {
surroundingPieceContainsPiece = false;
break;
}
}
if (surroundingPieceContainsPiece) {
float elevation = homePiece.getElevation() + homePiece.getHeight();
if (elevation > highestElevation) {
highestElevation = elevation;
highestSurroundingPiece = homePiece;
}
}
}
}
if (highestSurroundingPiece != null) {
piece.setElevation(highestElevation);
return highestSurroundingPiece;
}
}
return null;
}
/**
* Attempts to align <code>piece</code> on the borders of home furniture at the the same elevation
* that intersect with it and returns that piece.
* @see #adjustMagnetizedPieceOfFurniture(HomePieceOfFurniture, float, float)
*/
private HomePieceOfFurniture adjustPieceOfFurnitureSideBySideAt(HomePieceOfFurniture piece,
boolean forceOrientation,
boolean alignOnlyOnSides) {
float [][] piecePoints = piece.getPoints();
Area pieceArea = new Area(getPath(piecePoints));
boolean doorOrWindowBoundToWall = piece instanceof HomeDoorOrWindow
&& ((HomeDoorOrWindow)piece).isBoundToWall();
// Search if the border of another piece at floor level intersects with the given piece
float pieceElevation = piece.getGroundElevation();
float margin = 2 * PIXEL_MARGIN / getScale();
BasicStroke stroke = new BasicStroke(margin);
HomePieceOfFurniture referencePiece = null;
Area intersectionWithReferencePieceArea = null;
float intersectionWithReferencePieceSurface = Float.MAX_VALUE;
float [][] referencePiecePoints = null;
for (HomePieceOfFurniture homePiece : this.home.getFurniture()) {
float homePieceElevation = homePiece.getGroundElevation();
if (homePiece != piece
&& isPieceOfFurnitureVisibleAtSelectedLevel(homePiece)
&& pieceElevation < homePieceElevation + homePiece.getHeight()
&& pieceElevation + piece.getHeight() > homePieceElevation
&& (!doorOrWindowBoundToWall // Ignore other furniture for doors and windows bound to a wall
|| homePiece.isDoorOrWindow())) {
float [][] points = homePiece.getPoints();
GeneralPath path = getPath(points);
Area marginArea;
if (doorOrWindowBoundToWall && homePiece.isDoorOrWindow()) {
marginArea = new Area(stroke.createStrokedShape(new Line2D.Float(
points [1][0], points [1][1], points [2][0], points [2][1])));
marginArea.add(new Area(stroke.createStrokedShape(new Line2D.Float(
points [3][0], points [3][1], points [0][0], points [0][1]))));
} else {
marginArea = this.furnitureSidesCache.get(homePiece);
if (marginArea == null) {
marginArea = new Area(stroke.createStrokedShape(path));
this.furnitureSidesCache.put(homePiece, marginArea);
}
}
Area intersection = new Area(marginArea);
intersection.intersect(pieceArea);
if (!intersection.isEmpty()) {
Area exclusiveOr = new Area(pieceArea);
exclusiveOr.exclusiveOr(intersection);
if (exclusiveOr.isSingular()) {
Area insideArea = new Area(path);
insideArea.subtract(marginArea);
insideArea.intersect(pieceArea);
if (insideArea.isEmpty()) {
float surface = getArea(intersection);
if (surface < intersectionWithReferencePieceSurface) {
surface = intersectionWithReferencePieceSurface;
referencePiece = homePiece;
referencePiecePoints = points;
intersectionWithReferencePieceArea = intersection;
}
}
}
}
}
}
if (referencePiece != null) {
boolean alignedOnReferencePieceFrontOrBackSide;
if (doorOrWindowBoundToWall && referencePiece.isDoorOrWindow()) {
alignedOnReferencePieceFrontOrBackSide = false;
} else {
GeneralPath referencePieceLargerBoundingBox = getRotatedRectangle(referencePiece.getX() - referencePiece.getWidth(),
referencePiece.getY() - referencePiece.getDepth(), referencePiece.getWidth() * 2, referencePiece.getDepth() * 2,
referencePiece.getAngle());
float [][] pathPoints = getPathPoints(referencePieceLargerBoundingBox, false);
alignedOnReferencePieceFrontOrBackSide = isAreaLargerOnFrontOrBackSide(intersectionWithReferencePieceArea, pathPoints);
}
if (forceOrientation) {
piece.setAngle(referencePiece.getAngle());
}
Shape pieceBoundingBox = getRotatedRectangle(0, 0, piece.getWidth(), piece.getDepth(), piece.getAngle() - referencePiece.getAngle());
float deltaX = 0;
float deltaY = 0;
if (!alignedOnReferencePieceFrontOrBackSide) {
// Search the distance required to align piece on the left or right side of the reference piece
Line2D centerLine = new Line2D.Float(referencePiece.getX(), referencePiece.getY(),
(referencePiecePoints [0][0] + referencePiecePoints [1][0]) / 2, (referencePiecePoints [0][1] + referencePiecePoints [1][1]) / 2);
double rotatedBoundingBoxWidth = pieceBoundingBox.getBounds2D().getWidth();
double distance = centerLine.relativeCCW(piece.getX(), piece.getY())
* (-referencePiece.getWidth() / 2 + centerLine.ptLineDist(piece.getX(), piece.getY()) - rotatedBoundingBoxWidth / 2);
deltaX = (float)(distance * Math.cos(referencePiece.getAngle()));
deltaY = (float)(distance * Math.sin(referencePiece.getAngle()));
} else if (!alignOnlyOnSides) {
// Search the distance required to align piece on the front or back side of the reference piece
Line2D centerLine = new Line2D.Float(referencePiece.getX(), referencePiece.getY(),
(referencePiecePoints [2][0] + referencePiecePoints [1][0]) / 2, (referencePiecePoints [2][1] + referencePiecePoints [1][1]) / 2);
double rotatedBoundingBoxDepth = pieceBoundingBox.getBounds2D().getHeight();
double distance = centerLine.relativeCCW(piece.getX(), piece.getY())
* (-referencePiece.getDepth() / 2 + centerLine.ptLineDist(piece.getX(), piece.getY()) - rotatedBoundingBoxDepth / 2);
deltaX = (float)(-distance * Math.sin(referencePiece.getAngle()));
deltaY = (float)(distance * Math.cos(referencePiece.getAngle()));
}
// Accept move only if reference piece and moved piece share some points
if (!isIntersectionEmpty(piece, referencePiece, deltaX, deltaY)) {
piece.move(deltaX, deltaY);
return referencePiece;
} else {
if (forceOrientation) {
// Update points array
piecePoints = piece.getPoints();
}
boolean alignedOnPieceFrontOrBackSide = isAreaLargerOnFrontOrBackSide(intersectionWithReferencePieceArea, piecePoints);
Shape referencePieceBoundingBox = getRotatedRectangle(0, 0, referencePiece.getWidth(), referencePiece.getDepth(),
referencePiece.getAngle() - piece.getAngle());
if (!alignedOnPieceFrontOrBackSide) {
// Search the distance required to align piece on its left or right side
Line2D centerLine = new Line2D.Float(piece.getX(), piece.getY(),
(piecePoints [0][0] + piecePoints [1][0]) / 2, (piecePoints [0][1] + piecePoints [1][1]) / 2);
double rotatedBoundingBoxWidth = referencePieceBoundingBox.getBounds2D().getWidth();
double distance = centerLine.relativeCCW(referencePiece.getX(), referencePiece.getY())
* (-piece.getWidth() / 2 + centerLine.ptLineDist(referencePiece.getX(), referencePiece.getY()) - rotatedBoundingBoxWidth / 2);
deltaX = -(float)(distance * Math.cos(piece.getAngle()));
deltaY = -(float)(distance * Math.sin(piece.getAngle()));
} else if (!alignOnlyOnSides) {
// Search the distance required to align piece on its front or back side
Line2D centerLine = new Line2D.Float(piece.getX(), piece.getY(),
(piecePoints [2][0] + piecePoints [1][0]) / 2, (piecePoints [2][1] + piecePoints [1][1]) / 2);
double rotatedBoundingBoxDepth = referencePieceBoundingBox.getBounds2D().getHeight();
double distance = centerLine.relativeCCW(referencePiece.getX(), referencePiece.getY())
* (-piece.getDepth() / 2 + centerLine.ptLineDist(referencePiece.getX(), referencePiece.getY()) - rotatedBoundingBoxDepth / 2);
deltaX = -(float)(-distance * Math.sin(piece.getAngle()));
deltaY = -(float)(distance * Math.cos(piece.getAngle()));
}
// Accept move only if reference piece and moved piece share some points
if (!isIntersectionEmpty(piece, referencePiece, deltaX, deltaY)) {
piece.move(deltaX, deltaY);
return referencePiece;
}
}
return referencePiece;
}
return null;
}
/**
* Returns <code>true</code> if the intersection between the given <code>area</code> and
* the front or back sides of the rectangle defined by <code>piecePoints</code> is larger
* than with the left and right sides of this rectangle.
*/
public boolean isAreaLargerOnFrontOrBackSide(Area area, float [][] piecePoints) {
GeneralPath pieceFrontAndBackQuarters = new GeneralPath();
pieceFrontAndBackQuarters.moveTo(piecePoints [0][0], piecePoints [0][1]);
pieceFrontAndBackQuarters.lineTo(piecePoints [2][0], piecePoints [2][1]);
pieceFrontAndBackQuarters.lineTo(piecePoints [3][0], piecePoints [3][1]);
pieceFrontAndBackQuarters.lineTo(piecePoints [1][0], piecePoints [1][1]);
pieceFrontAndBackQuarters.closePath();
Area intersectionWithFrontOrBack = new Area(area);
intersectionWithFrontOrBack.intersect(new Area(pieceFrontAndBackQuarters));
if (intersectionWithFrontOrBack.isEmpty()) {
return false;
} else {
GeneralPath pieceLeftAndRightQuarters = new GeneralPath();
pieceLeftAndRightQuarters.moveTo(piecePoints [0][0], piecePoints [0][1]);
pieceLeftAndRightQuarters.lineTo(piecePoints [2][0], piecePoints [2][1]);
pieceLeftAndRightQuarters.lineTo(piecePoints [1][0], piecePoints [1][1]);
pieceLeftAndRightQuarters.lineTo(piecePoints [3][0], piecePoints [3][1]);
pieceLeftAndRightQuarters.closePath();
Area intersectionWithLeftAndRight = new Area(area);
intersectionWithLeftAndRight.intersect(new Area(pieceLeftAndRightQuarters));
return getArea(intersectionWithFrontOrBack) > getArea(intersectionWithLeftAndRight);
}
}
/**
* Returns the area of the given shape.
*/
public float getArea(Area area) {
float [][] pathPoints = getPathPoints(getPath(area), false);
if (pathPoints.length > 1) {
return new Room(pathPoints).getArea();
} else {
return 0;
}
}
/**
* Returns <code>true</code> if the given pieces don't intersect once the first is moved from
* (<code>deltaX</code>, <code>deltaY</code>) vector.
*/
private boolean isIntersectionEmpty(HomePieceOfFurniture piece1, HomePieceOfFurniture piece2,
float deltaX, float deltaY) {
Area intersection = new Area(getRotatedRectangle(piece1.getX() - piece1.getWidth() / 2 + deltaX,
piece1.getY() - piece1.getDepth() / 2 + deltaY, piece1.getWidth(), piece1.getDepth(), piece1.getAngle()));
float epsilon = 0.01f;
intersection.intersect(new Area(getRotatedRectangle(piece2.getX() - piece2.getWidth() / 2 - epsilon,
piece2.getY() - piece2.getDepth() / 2 - epsilon,
piece2.getWidth() + 2 * epsilon, piece2.getDepth() + 2 * epsilon, piece2.getAngle())));
return intersection.isEmpty();
}
/**
* Returns the shape of the given rectangle rotated of a given <code>angle</code>.
*/
private GeneralPath getRotatedRectangle(float x, float y, float width, float height, float angle) {
Rectangle2D referencePieceLargerBoundingBox = new Rectangle2D.Float(x, y, width, height);
AffineTransform rotation = AffineTransform.getRotateInstance(angle, x + width / 2, y + height / 2);
GeneralPath rotatedBoundingBox = new GeneralPath();
rotatedBoundingBox.append(referencePieceLargerBoundingBox.getPathIterator(rotation), false);
return rotatedBoundingBox;
}
/**
* Returns the dimension line that measures the side of a piece, the length of a room side
* or the length of a wall side at (<code>x</code>, <code>y</code>) point,
* or <code>null</code> if it doesn't exist.
*/
private DimensionLine getMeasuringDimensionLineAt(float x, float y,
boolean magnetismEnabled) {
float margin = PIXEL_MARGIN / getScale();
for (HomePieceOfFurniture piece : this.home.getFurniture()) {
if (isPieceOfFurnitureVisibleAtSelectedLevel(piece)) {
DimensionLine dimensionLine = getDimensionLineBetweenPointsAt(piece.getPoints(), x, y, margin, magnetismEnabled);
if (dimensionLine != null) {
return dimensionLine;
}
}
}
for (GeneralPath roomPath : getRoomPathsFromWalls()) {
if (roomPath.intersects(x - margin, y - margin, 2 * margin, 2 * margin)) {
DimensionLine dimensionLine = getDimensionLineBetweenPointsAt(
getPathPoints(roomPath, true), x, y, margin, magnetismEnabled);
if (dimensionLine != null) {
return dimensionLine;
}
}
}
for (Room room : this.home.getRooms()) {
if (room.isAtLevel(this.home.getSelectedLevel())) {
DimensionLine dimensionLine = getDimensionLineBetweenPointsAt(room.getPoints(), x, y, margin, magnetismEnabled);
if (dimensionLine != null) {
return dimensionLine;
}
}
}
return null;
}
/**
* Returns the dimension line that measures the side of the given polygon at (<code>x</code>, <code>y</code>) point,
* or <code>null</code> if it doesn't exist.
*/
private DimensionLine getDimensionLineBetweenPointsAt(float [][] points, float x, float y,
float margin, boolean magnetismEnabled) {
for (int i = 0; i < points.length; i++) {
int nextPointIndex = (i + 1) % points.length;
// Ignore sides with a length smaller than 0.1 cm
double distanceBetweenPointsSq = Point2D.distanceSq(points [i][0], points [i][1],
points [nextPointIndex][0], points [nextPointIndex][1]);
if (distanceBetweenPointsSq > 0.01
&& Line2D.ptSegDistSq(points [i][0], points [i][1],
points [nextPointIndex][0], points [nextPointIndex][1],
x, y) <= margin * margin) {
double angle = Math.atan2(points [i][1] - points [nextPointIndex][1],
points [nextPointIndex][0] - points [i][0]);
boolean reverse = angle < -Math.PI / 2 || angle > Math.PI / 2;
float xStart;
float yStart;
float xEnd;
float yEnd;
if (reverse) {
// Avoid reversed text on the dimension line
xStart = points [nextPointIndex][0];
yStart = points [nextPointIndex][1];
xEnd = points [i][0];
yEnd = points [i][1];
} else {
xStart = points [i][0];
yStart = points [i][1];
xEnd = points [nextPointIndex][0];
yEnd = points [nextPointIndex][1];
}
if (magnetismEnabled) {
float magnetizedLength = this.preferences.getLengthUnit().getMagnetizedLength(
(float)Math.sqrt(distanceBetweenPointsSq), getView().getPixelLength());
if (reverse) {
xEnd = points [nextPointIndex][0] - (float)(magnetizedLength * Math.cos(angle));
yEnd = points [nextPointIndex][1] + (float)(magnetizedLength * Math.sin(angle));
} else {
xEnd = points [i][0] + (float)(magnetizedLength * Math.cos(angle));
yEnd = points [i][1] - (float)(magnetizedLength * Math.sin(angle));
}
}
return new DimensionLine(xStart, yStart, xEnd, yEnd, 0);
}
}
return null;
}
/**
* Controls the creation of a new level.
*/
public void addLevel() {
List<Selectable> oldSelection = this.home.getSelectedItems();
final Selectable [] oldSelectedItems =
oldSelection.toArray(new Selectable [oldSelection.size()]);
final Level oldSelectedLevel = this.home.getSelectedLevel();
List<Level> levels = this.home.getLevels();
float newWallHeight = this.preferences.getNewWallHeight();
float newFloorThickness = this.preferences.getNewFloorThickness();
final Level level0;
if (levels.isEmpty()) {
// Create level 0
String level0Name = this.preferences.getLocalizedString(PlanController.class, "levelName", 0);
level0 = createLevel(level0Name, 0, newFloorThickness, newWallHeight);
level0.setBackgroundImage(this.home.getBackgroundImage());
moveHomeItemsToLevel(level0);
levels = this.home.getLevels();
} else {
level0 = null;
}
String newLevelName = this.preferences.getLocalizedString(PlanController.class, "levelName", levels.size());
float newLevelElevation = levels.get(levels.size() - 1).getElevation()
+ newWallHeight + newFloorThickness;
final Level newLevel = createLevel(newLevelName, newLevelElevation, newFloorThickness, newWallHeight);
setSelectedLevel(newLevel);
UndoableEdit undoableEdit = new AbstractUndoableEdit() {
@Override
public void undo() throws CannotUndoException {
super.undo();
setSelectedLevel(oldSelectedLevel);
home.deleteLevel(newLevel);
if (level0 != null) {
home.setBackgroundImage(level0.getBackgroundImage());
moveHomeItemsToLevel(oldSelectedLevel);
home.deleteLevel(level0);
}
selectAndShowItems(Arrays.asList(oldSelectedItems));
}
@Override
public void redo() throws CannotRedoException {
super.redo();
if (level0 != null) {
home.addLevel(level0);
moveHomeItemsToLevel(level0);
level0.setBackgroundImage(home.getBackgroundImage());
}
home.addLevel(newLevel);
setSelectedLevel(newLevel);
}
@Override
public String getPresentationName() {
return preferences.getLocalizedString(PlanController.class, "undoAddLevel");
}
};
this.undoSupport.postEdit(undoableEdit);
}
/**
* Returns a new level added to home.
*/
protected Level createLevel(String name, float elevation, float floorThickness, float height) {
Level newLevel = new Level(name, elevation, floorThickness, height);
this.home.addLevel(newLevel);
return newLevel;
}
/**
* Moves to the given level all existing furniture, walls, rooms, dimension lines
* and labels.
*/
private void moveHomeItemsToLevel(Level level) {
for (HomePieceOfFurniture piece : this.home.getFurniture()) {
piece.setLevel(level);
}
for (Wall wall : this.home.getWalls()) {
wall.setLevel(level);
}
for (Room room : this.home.getRooms()) {
room.setLevel(level);
}
for (DimensionLine dimensionLine : this.home.getDimensionLines()) {
dimensionLine.setLevel(level);
}
for (Label label : this.home.getLabels()) {
label.setLevel(level);
}
}
public void modifySelectedLevel() {
if (this.home.getSelectedLevel() != null) {
new LevelController(this.home, this.preferences, this.viewFactory,
this.undoSupport).displayView(getView());
}
}
/**
* Deletes the selected level and the items that belongs to it.
*/
public void deleteSelectedLevel() {
// Start a compound edit that delete walls, furniture, rooms, dimension lines and labels from home
undoSupport.beginUpdate();
List<HomePieceOfFurniture> levelFurniture = new ArrayList<HomePieceOfFurniture>();
final Level oldSelectedLevel = this.home.getSelectedLevel();
for (HomePieceOfFurniture piece : this.home.getFurniture()) {
if (piece.getLevel() == oldSelectedLevel) {
levelFurniture.add(piece);
}
}
// Delete furniture with inherited method
deleteFurniture(levelFurniture);
List<Selectable> levelOtherItems = new ArrayList<Selectable>();
addLevelItemsAtSelectedLevel(this.home.getWalls(), levelOtherItems);
addLevelItemsAtSelectedLevel(this.home.getRooms(), levelOtherItems);
addLevelItemsAtSelectedLevel(this.home.getDimensionLines(), levelOtherItems);
addLevelItemsAtSelectedLevel(this.home.getLabels(), levelOtherItems);
// First post to undo support that walls, rooms and dimension lines are deleted,
// otherwise data about joined walls and rooms index can't be stored
postDeleteItems(levelOtherItems, this.home.isBasePlanLocked());
// Then delete items from plan
doDeleteItems(levelOtherItems);
this.home.deleteLevel(oldSelectedLevel);
List<Level> levels = this.home.getLevels();
final Level remainingLevel;
final Float remainingLevelElevation;
if (levels.size() == 1) {
remainingLevel = levels.get(0);
remainingLevelElevation = remainingLevel.getElevation();
remainingLevel.setElevation(0);
} else {
remainingLevel = null;
remainingLevelElevation = null;
}
undoSupport.postEdit(new AbstractUndoableEdit() {
@Override
public void undo() throws CannotUndoException {
super.undo();
if (remainingLevel != null) {
remainingLevel.setElevation(remainingLevelElevation);
}
home.addLevel(oldSelectedLevel);
setSelectedLevel(oldSelectedLevel);
}
@Override
public void redo() throws CannotRedoException {
super.redo();
home.deleteLevel(oldSelectedLevel);
if (remainingLevel != null) {
remainingLevel.setElevation(0);
}
}
@Override
public String getPresentationName() {
return preferences.getLocalizedString(PlanController.class, "undoDeleteSelectedLevel");
}
});
// End compound edit
undoSupport.endUpdate();
}
private void addLevelItemsAtSelectedLevel(Collection<? extends Selectable> items,
List<Selectable> levelItems) {
Level selectedLevel = this.home.getSelectedLevel();
for (Selectable item : items) {
if (item instanceof Elevatable
&& ((Elevatable)item).getLevel() == selectedLevel) {
levelItems.add(item);
}
}
}
/**
* Returns a new wall instance between (<code>xStart</code>,
* <code>yStart</code>) and (<code>xEnd</code>, <code>yEnd</code>)
* end points. The new wall is added to home and its start point is joined
* to the start of <code>wallStartAtStart</code> or
* the end of <code>wallEndAtStart</code>.
*/
protected Wall createWall(float xStart, float yStart,
float xEnd, float yEnd,
Wall wallStartAtStart,
Wall wallEndAtStart) {
// Create a new wall
Wall newWall = new Wall(xStart, yStart, xEnd, yEnd,
this.preferences.getNewWallThickness(),
this.preferences.getNewWallHeight());
this.home.addWall(newWall);
if (wallStartAtStart != null) {
newWall.setWallAtStart(wallStartAtStart);
wallStartAtStart.setWallAtStart(newWall);
} else if (wallEndAtStart != null) {
newWall.setWallAtStart(wallEndAtStart);
wallEndAtStart.setWallAtEnd(newWall);
}
return newWall;
}
/**
* Joins the end point of <code>wall</code> to the start of
* <code>wallStartAtEnd</code> or the end of <code>wallEndAtEnd</code>.
*/
private void joinNewWallEndToWall(Wall wall,
Wall wallStartAtEnd, Wall wallEndAtEnd) {
if (wallStartAtEnd != null) {
wall.setWallAtEnd(wallStartAtEnd);
wallStartAtEnd.setWallAtStart(wall);
// Make wall end at the exact same position as wallAtEnd start point
wall.setXEnd(wallStartAtEnd.getXStart());
wall.setYEnd(wallStartAtEnd.getYStart());
} else if (wallEndAtEnd != null) {
wall.setWallAtEnd(wallEndAtEnd);
wallEndAtEnd.setWallAtEnd(wall);
// Make wall end at the exact same position as wallAtEnd end point
wall.setXEnd(wallEndAtEnd.getXEnd());
wall.setYEnd(wallEndAtEnd.getYEnd());
}
}
/**
* Returns the wall at (<code>x</code>, <code>y</code>) point,
* which has a start point not joined to any wall.
*/
private Wall getWallStartAt(float x, float y, Wall ignoredWall) {
float margin = WALL_ENDS_PIXEL_MARGIN / getScale();
for (Wall wall : this.home.getWalls()) {
if (wall != ignoredWall
&& wall.isAtLevel(this.home.getSelectedLevel())
&& wall.getWallAtStart() == null
&& wall.containsWallStartAt(x, y, margin))
return wall;
}
return null;
}
/**
* Returns the wall at (<code>x</code>, <code>y</code>) point,
* which has a end point not joined to any wall.
*/
private Wall getWallEndAt(float x, float y, Wall ignoredWall) {
float margin = WALL_ENDS_PIXEL_MARGIN / getScale();
for (Wall wall : this.home.getWalls()) {
if (wall != ignoredWall
&& wall.isAtLevel(this.home.getSelectedLevel())
&& wall.getWallAtEnd() == null
&& wall.containsWallEndAt(x, y, margin))
return wall;
}
return null;
}
/**
* Returns the selected wall with a start point
* at (<code>x</code>, <code>y</code>).
*/
private Wall getResizedWallStartAt(float x, float y) {
List<Selectable> selectedItems = this.home.getSelectedItems();
if (selectedItems.size() == 1
&& selectedItems.get(0) instanceof Wall
&& isItemResizable(selectedItems.get(0))) {
Wall wall = (Wall)selectedItems.get(0);
float margin = INDICATOR_PIXEL_MARGIN / getScale();
if (wall.isAtLevel(this.home.getSelectedLevel())
&& wall.containsWallStartAt(x, y, margin)) {
return wall;
}
}
return null;
}
/**
* Returns the selected wall with an end point at (<code>x</code>, <code>y</code>).
*/
private Wall getResizedWallEndAt(float x, float y) {
List<Selectable> selectedItems = this.home.getSelectedItems();
if (selectedItems.size() == 1
&& selectedItems.get(0) instanceof Wall
&& isItemResizable(selectedItems.get(0))) {
Wall wall = (Wall)selectedItems.get(0);
float margin = INDICATOR_PIXEL_MARGIN / getScale();
if (wall.isAtLevel(this.home.getSelectedLevel())
&& wall.containsWallEndAt(x, y, margin)) {
return wall;
}
}
return null;
}
/**
* Returns a new room instance with the given points.
* The new room is added to home.
*/
protected Room createRoom(float [][] roomPoints) {
Room newRoom = new Room(roomPoints);
this.home.addRoom(newRoom);
return newRoom;
}
/**
* Returns the selected room with a point at (<code>x</code>, <code>y</code>).
*/
private Room getResizedRoomAt(float x, float y) {
List<Selectable> selectedItems = this.home.getSelectedItems();
if (selectedItems.size() == 1
&& selectedItems.get(0) instanceof Room) {
Room room = (Room)selectedItems.get(0);
float margin = INDICATOR_PIXEL_MARGIN / getScale();
if (room.isAtLevel(this.home.getSelectedLevel())
&& room.getPointIndexAt(x, y, margin) != -1) {
return room;
}
}
return null;
}
/**
* Returns the selected room with its name center point at (<code>x</code>, <code>y</code>).
*/
private Room getRoomNameAt(float x, float y) {
List<Selectable> selectedItems = this.home.getSelectedItems();
if (selectedItems.size() == 1
&& selectedItems.get(0) instanceof Room
&& isItemMovable(selectedItems.get(0))) {
Room room = (Room)selectedItems.get(0);
float margin = INDICATOR_PIXEL_MARGIN / getScale();
if (room.isAtLevel(this.home.getSelectedLevel())
&& room.getName() != null
&& room.getName().trim().length() > 0
&& room.isNameCenterPointAt(x, y, margin)) {
return room;
}
}
return null;
}
/**
* Returns the selected room with its area center point at (<code>x</code>, <code>y</code>).
*/
private Room getRoomAreaAt(float x, float y) {
List<Selectable> selectedItems = this.home.getSelectedItems();
if (selectedItems.size() == 1
&& selectedItems.get(0) instanceof Room
&& isItemMovable(selectedItems.get(0))) {
Room room = (Room)selectedItems.get(0);
float margin = INDICATOR_PIXEL_MARGIN / getScale();
if (room.isAtLevel(this.home.getSelectedLevel())
&& room.isAreaVisible()
&& room.isAreaCenterPointAt(x, y, margin)) {
return room;
}
}
return null;
}
/**
* Returns a new dimension instance joining (<code>xStart</code>,
* <code>yStart</code>) and (<code>xEnd</code>, <code>yEnd</code>) points.
* The new dimension line is added to home.
*/
protected DimensionLine createDimensionLine(float xStart, float yStart,
float xEnd, float yEnd,
float offset) {
DimensionLine newDimensionLine = new DimensionLine(xStart, yStart, xEnd, yEnd, offset);
this.home.addDimensionLine(newDimensionLine);
return newDimensionLine;
}
/**
* Returns the selected dimension line with an end extension line
* at (<code>x</code>, <code>y</code>).
*/
private DimensionLine getResizedDimensionLineStartAt(float x, float y) {
List<Selectable> selectedItems = this.home.getSelectedItems();
if (selectedItems.size() == 1
&& selectedItems.get(0) instanceof DimensionLine
&& isItemResizable(selectedItems.get(0))) {
DimensionLine dimensionLine = (DimensionLine)selectedItems.get(0);
float margin = INDICATOR_PIXEL_MARGIN / getScale();
if (dimensionLine.isAtLevel(this.home.getSelectedLevel())
&& dimensionLine.containsStartExtensionLinetAt(x, y, margin)) {
return dimensionLine;
}
}
return null;
}
/**
* Returns the selected dimension line with an end extension line
* at (<code>x</code>, <code>y</code>).
*/
private DimensionLine getResizedDimensionLineEndAt(float x, float y) {
List<Selectable> selectedItems = this.home.getSelectedItems();
if (selectedItems.size() == 1
&& selectedItems.get(0) instanceof DimensionLine
&& isItemResizable(selectedItems.get(0))) {
DimensionLine dimensionLine = (DimensionLine)selectedItems.get(0);
float margin = INDICATOR_PIXEL_MARGIN / getScale();
if (dimensionLine.isAtLevel(this.home.getSelectedLevel())
&& dimensionLine.containsEndExtensionLineAt(x, y, margin)) {
return dimensionLine;
}
}
return null;
}
/**
* Returns the selected dimension line with a point
* at (<code>x</code>, <code>y</code>) at its middle.
*/
private DimensionLine getOffsetDimensionLineAt(float x, float y) {
List<Selectable> selectedItems = this.home.getSelectedItems();
if (selectedItems.size() == 1
&& selectedItems.get(0) instanceof DimensionLine
&& isItemResizable(selectedItems.get(0))) {
DimensionLine dimensionLine = (DimensionLine)selectedItems.get(0);
float margin = INDICATOR_PIXEL_MARGIN / getScale();
if (dimensionLine.isAtLevel(this.home.getSelectedLevel())
&& dimensionLine.isMiddlePointAt(x, y, margin)) {
return dimensionLine;
}
}
return null;
}
/**
* Returns the selected item at (<code>x</code>, <code>y</code>) point.
*/
private boolean isItemSelectedAt(float x, float y) {
float margin = PIXEL_MARGIN / getScale();
for (Selectable item : this.home.getSelectedItems()) {
if (item.containsPoint(x, y, margin)) {
return true;
}
}
return false;
}
/**
* Returns the selectable item at (<code>x</code>, <code>y</code>) point.
*/
public Selectable getSelectableItemAt(float x, float y) {
List<Selectable> selectableItems = getSelectableItemsAt(x, y, true);
if (selectableItems.size() != 0) {
return selectableItems.get(0);
} else {
return null;
}
}
/**
* Returns the selectable items at (<code>x</code>, <code>y</code>) point.
*/
public List<Selectable> getSelectableItemsAt(float x, float y) {
return getSelectableItemsAt(x, y, false);
}
/**
* Returns the selectable items at (<code>x</code>, <code>y</code>) point.
*/
private List<Selectable> getSelectableItemsAt(float x, float y,
boolean stopAtFirstItem) {
List<Selectable> items = new ArrayList<Selectable>();
float margin = PIXEL_MARGIN / getScale();
float textMargin = PIXEL_MARGIN / 2 / getScale();
ObserverCamera camera = this.home.getObserverCamera();
if (camera != null
&& camera == this.home.getCamera()
&& camera.containsPoint(x, y, margin)) {
items.add(camera);
if (stopAtFirstItem) {
return items;
}
}
boolean basePlanLocked = this.home.isBasePlanLocked();
Level selectedLevel = this.home.getSelectedLevel();
for (Label label : this.home.getLabels()) {
if (!basePlanLocked
|| !isItemPartOfBasePlan(label)) {
if (label.isAtLevel(selectedLevel)
&& label.containsPoint(x, y, margin)) {
items.add(label);
if (stopAtFirstItem) {
return items;
}
} else if (isItemTextAt(label, label.getText(), label.getStyle(),
label.getX(), label.getY(), x, y, textMargin)) {
items.add(label);
if (stopAtFirstItem) {
return items;
}
}
}
}
for (DimensionLine dimensionLine : this.home.getDimensionLines()) {
if ((!basePlanLocked
|| !isItemPartOfBasePlan(dimensionLine))
&& dimensionLine.isAtLevel(selectedLevel)
&& dimensionLine.containsPoint(x, y, margin)) {
items.add(dimensionLine);
if (stopAtFirstItem) {
return items;
}
}
}
List<HomePieceOfFurniture> furniture = this.home.getFurniture();
// Search in home furniture in reverse order to give priority to last drawn piece
// at highest elevation in case it covers an other piece
List<HomePieceOfFurniture> foundFurniture = new ArrayList<HomePieceOfFurniture>();
HomePieceOfFurniture foundPiece = null;
for (int i = furniture.size() - 1; i >= 0; i--) {
HomePieceOfFurniture piece = furniture.get(i);
if ((!basePlanLocked
|| !isItemPartOfBasePlan(piece))
&& isPieceOfFurnitureVisibleAtSelectedLevel(piece)) {
if (piece.containsPoint(x, y, margin)) {
foundFurniture.add(piece);
if (foundPiece == null
|| piece.getGroundElevation() > foundPiece.getGroundElevation()) {
foundPiece = piece;
}
} else if (foundPiece == null) {
// Search if piece name contains point in case it is drawn outside of the piece
String pieceName = piece.getName();
if (pieceName != null
&& piece.isNameVisible()
&& isItemTextAt(piece, pieceName, piece.getNameStyle(),
piece.getX() + piece.getNameXOffset(),
piece.getY() + piece.getNameYOffset(), x, y, textMargin)) {
foundFurniture.add(piece);
foundPiece = piece;
}
}
}
}
if (foundPiece != null
&& stopAtFirstItem) {
return Arrays.asList(new Selectable [] {foundPiece});
} else {
Collections.sort(foundFurniture, new Comparator<HomePieceOfFurniture>() {
public int compare(HomePieceOfFurniture p1, HomePieceOfFurniture p2) {
return -Float.compare(p1.getGroundElevation(), p2.getGroundElevation());
}
});
items.addAll(foundFurniture);
for (Wall wall : this.home.getWalls()) {
if ((!basePlanLocked
|| !isItemPartOfBasePlan(wall))
&& wall.isAtLevel(selectedLevel)
&& wall.containsPoint(x, y, margin)) {
items.add(wall);
if (stopAtFirstItem) {
return items;
}
}
}
List<Room> rooms = this.home.getRooms();
// Search in home rooms in reverse order to give priority to last drawn room
// at highest elevation in case it covers an other piece
Room foundRoom = null;
for (int i = rooms.size() - 1; i >= 0; i--) {
Room room = rooms.get(i);
if (!basePlanLocked
|| !isItemPartOfBasePlan(room)) {
if (room.isAtLevel(selectedLevel)) {
if (room.containsPoint(x, y, margin)) {
items.add(room);
if (foundRoom == null
|| room.isCeilingVisible() && !foundRoom.isCeilingVisible()) {
foundRoom = room;
}
} else {
// Search if room name contains point in case it is drawn outside of the room
String roomName = room.getName();
if (roomName != null
&& isItemTextAt(room, roomName, room.getNameStyle(),
room.getXCenter() + room.getNameXOffset(),
room.getYCenter() + room.getNameYOffset(), x, y, textMargin)) {
items.add(room);
foundRoom = room;
}
// Search if room area contains point in case its text is drawn outside of the room
if (room.isAreaVisible()) {
String areaText = this.preferences.getLengthUnit().getAreaFormatWithUnit().format(room.getArea());
if (isItemTextAt(room, areaText, room.getAreaStyle(),
room.getXCenter() + room.getAreaXOffset(),
room.getYCenter() + room.getAreaYOffset(), x, y, textMargin)) {
items.add(room);
foundRoom = room;
}
}
}
}
}
}
if (foundRoom != null
&& stopAtFirstItem) {
return Arrays.asList(new Selectable [] {foundRoom});
} else {
Compass compass = this.home.getCompass();
if ((!basePlanLocked
|| !isItemPartOfBasePlan(compass))
&& compass.containsPoint(x, y, textMargin)) {
items.add(compass);
}
return items;
}
}
}
/**
* Returns <code>true</code> if the <code>text</code> of an <code>item</code> displayed
* at the point (<code>xText</code>, <code>yText</code>) contains the point (<code>x</code>, <code>y</code>).
*/
private boolean isItemTextAt(Selectable item, String text, TextStyle textStyle, float xText, float yText,
float x, float y, float textMargin) {
if (textStyle == null) {
textStyle = this.preferences.getDefaultTextStyle(item.getClass());
}
float [][] textBounds = getView().getTextBounds(text, textStyle, xText, yText, 0);
return getPath(textBounds).intersects(x - textMargin, y - textMargin, 2 * textMargin, 2 * textMargin);
}
/**
* Returns the items that intersects with the rectangle of (<code>x0</code>,
* <code>y0</code>), (<code>x1</code>, <code>y1</code>) opposite corners.
*/
protected List<Selectable> getSelectableItemsIntersectingRectangle(float x0, float y0, float x1, float y1) {
List<Selectable> items = new ArrayList<Selectable>();
boolean basePlanLocked = this.home.isBasePlanLocked();
for (Selectable item : getVisibleItemsAtSelectedLevel()) {
if ((!basePlanLocked
|| !isItemPartOfBasePlan(item))
&& item.intersectsRectangle(x0, y0, x1, y1)) {
items.add(item);
}
}
ObserverCamera camera = this.home.getObserverCamera();
if (camera != null && camera.intersectsRectangle(x0, y0, x1, y1)) {
items.add(camera);
}
return items;
}
/**
* Returns the selected piece of furniture with a point
* at (<code>x</code>, <code>y</code>) that can be used to rotate the piece.
*/
private HomePieceOfFurniture getRotatedPieceOfFurnitureAt(float x, float y) {
List<Selectable> selectedItems = this.home.getSelectedItems();
if (selectedItems.size() == 1
&& selectedItems.get(0) instanceof HomePieceOfFurniture
&& isItemMovable(selectedItems.get(0))) {
HomePieceOfFurniture piece = (HomePieceOfFurniture)selectedItems.get(0);
float scaleInverse = 1 / getScale();
float margin = INDICATOR_PIXEL_MARGIN * scaleInverse;
if (isPieceOfFurnitureVisibleAtSelectedLevel(piece)
&& piece.isTopLeftPointAt(x, y, margin)
// Keep a free zone around piece center
&& Math.abs(x - piece.getX()) > scaleInverse
&& Math.abs(y - piece.getY()) > scaleInverse) {
return piece;
}
}
return null;
}
/**
* Returns the selected piece of furniture with a point
* at (<code>x</code>, <code>y</code>) that can be used to elevate the piece.
*/
private HomePieceOfFurniture getElevatedPieceOfFurnitureAt(float x, float y) {
List<Selectable> selectedItems = this.home.getSelectedItems();
if (selectedItems.size() == 1
&& selectedItems.get(0) instanceof HomePieceOfFurniture
&& isItemMovable(selectedItems.get(0))) {
HomePieceOfFurniture piece = (HomePieceOfFurniture)selectedItems.get(0);
float scaleInverse = 1 / getScale();
float margin = INDICATOR_PIXEL_MARGIN * scaleInverse;
if (isPieceOfFurnitureVisibleAtSelectedLevel(piece)
&& piece.isTopRightPointAt(x, y, margin)
// Keep a free zone around piece center
&& Math.abs(x - piece.getX()) > scaleInverse
&& Math.abs(y - piece.getY()) > scaleInverse) {
return piece;
}
}
return null;
}
/**
* Returns the selected piece of furniture with a point
* at (<code>x</code>, <code>y</code>) that can be used to resize the height
* of the piece.
*/
private HomePieceOfFurniture getHeightResizedPieceOfFurnitureAt(float x, float y) {
List<Selectable> selectedItems = this.home.getSelectedItems();
if (selectedItems.size() == 1
&& selectedItems.get(0) instanceof HomePieceOfFurniture) {
HomePieceOfFurniture piece = (HomePieceOfFurniture)selectedItems.get(0);
float scaleInverse = 1 / getScale();
float margin = INDICATOR_PIXEL_MARGIN * scaleInverse;
if (isPieceOfFurnitureVisibleAtSelectedLevel(piece)
&& piece.isResizable()
&& isItemResizable(piece)
&& piece.isBottomLeftPointAt(x, y, margin)
// Keep a free zone around piece center
&& Math.abs(x - piece.getX()) > scaleInverse
&& Math.abs(y - piece.getY()) > scaleInverse) {
return piece;
}
}
return null;
}
/**
* Returns the selected piece of furniture with a point
* at (<code>x</code>, <code>y</code>) that can be used to resize
* the width and the depth of the piece.
*/
private HomePieceOfFurniture getWidthAndDepthResizedPieceOfFurnitureAt(float x, float y) {
List<Selectable> selectedItems = this.home.getSelectedItems();
if (selectedItems.size() == 1
&& selectedItems.get(0) instanceof HomePieceOfFurniture
&& isItemResizable(selectedItems.get(0))) {
HomePieceOfFurniture piece = (HomePieceOfFurniture)selectedItems.get(0);
float scaleInverse = 1 / getScale();
float margin = INDICATOR_PIXEL_MARGIN * scaleInverse;
if (isPieceOfFurnitureVisibleAtSelectedLevel(piece)
&& piece.isResizable()
&& isItemResizable(piece)
&& piece.isBottomRightPointAt(x, y, margin)
// Keep a free zone around piece center
&& Math.abs(x - piece.getX()) > scaleInverse
&& Math.abs(y - piece.getY()) > scaleInverse) {
return piece;
}
}
return null;
}
/**
* Returns the selected light with a point at (<code>x</code>, <code>y</code>)
* that can be used to resize the power of the light.
*/
private HomeLight getModifiedLightPowerAt(float x, float y) {
List<Selectable> selectedItems = this.home.getSelectedItems();
if (selectedItems.size() == 1
&& selectedItems.get(0) instanceof HomeLight) {
HomeLight light = (HomeLight)selectedItems.get(0);
float scaleInverse = 1 / getScale();
float margin = INDICATOR_PIXEL_MARGIN * scaleInverse;
if (isPieceOfFurnitureVisibleAtSelectedLevel(light)
&& light.isBottomLeftPointAt(x, y, margin)
// Keep a free zone around piece center
&& Math.abs(x - light.getX()) > scaleInverse
&& Math.abs(y - light.getY()) > scaleInverse) {
return light;
}
}
return null;
}
/**
* Returns the selected piece of furniture with its
* name center point at (<code>x</code>, <code>y</code>).
*/
private HomePieceOfFurniture getPieceOfFurnitureNameAt(float x, float y) {
List<Selectable> selectedItems = this.home.getSelectedItems();
if (selectedItems.size() == 1
&& selectedItems.get(0) instanceof HomePieceOfFurniture
&& isItemMovable(selectedItems.get(0))) {
HomePieceOfFurniture piece = (HomePieceOfFurniture)selectedItems.get(0);
float scaleInverse = 1 / getScale();
float margin = INDICATOR_PIXEL_MARGIN * scaleInverse;
if (isPieceOfFurnitureVisibleAtSelectedLevel(piece)
&& piece.isNameVisible()
&& piece.getName().trim().length() > 0
&& piece.isNameCenterPointAt(x, y, margin)) {
return piece;
}
}
return null;
}
/**
* Returns the selected camera with a point at (<code>x</code>, <code>y</code>)
* that can be used to change the camera yaw angle.
*/
private Camera getYawRotatedCameraAt(float x, float y) {
List<Selectable> selectedItems = this.home.getSelectedItems();
if (selectedItems.size() == 1
&& selectedItems.get(0) instanceof Camera
&& isItemResizable(selectedItems.get(0))) {
ObserverCamera camera = (ObserverCamera)selectedItems.get(0);
float margin = INDICATOR_PIXEL_MARGIN / getScale();
float [][] cameraPoints = camera.getPoints();
// Check if (x,y) matches the point between the first and the last points
// of the rectangle surrounding camera
float xMiddleFirstAndLastPoint = (cameraPoints [0][0] + cameraPoints [3][0]) / 2;
float yMiddleFirstAndLastPoint = (cameraPoints [0][1] + cameraPoints [3][1]) / 2;
if (Math.abs(x - xMiddleFirstAndLastPoint) <= margin
&& Math.abs(y - yMiddleFirstAndLastPoint) <= margin) {
return camera;
}
}
return null;
}
/**
* Returns the selected camera with a point at (<code>x</code>, <code>y</code>)
* that can be used to change the camera pitch angle.
*/
private Camera getPitchRotatedCameraAt(float x, float y) {
List<Selectable> selectedItems = this.home.getSelectedItems();
if (selectedItems.size() == 1
&& selectedItems.get(0) instanceof Camera
&& isItemResizable(selectedItems.get(0))) {
ObserverCamera camera = (ObserverCamera)selectedItems.get(0);
float margin = INDICATOR_PIXEL_MARGIN / getScale();
float [][] cameraPoints = camera.getPoints();
// Check if (x,y) matches the point between the second and the third points
// of the rectangle surrounding camera
float xMiddleFirstAndLastPoint = (cameraPoints [1][0] + cameraPoints [2][0]) / 2;
float yMiddleFirstAndLastPoint = (cameraPoints [1][1] + cameraPoints [2][1]) / 2;
if (Math.abs(x - xMiddleFirstAndLastPoint) <= margin
&& Math.abs(y - yMiddleFirstAndLastPoint) <= margin) {
return camera;
}
}
return null;
}
/**
* Returns the selected camera with a point at (<code>x</code>, <code>y</code>)
* that can be used to change the camera elevation.
*/
private Camera getElevatedCameraAt(float x, float y) {
List<Selectable> selectedItems = this.home.getSelectedItems();
if (selectedItems.size() == 1
&& selectedItems.get(0) instanceof Camera
&& isItemResizable(selectedItems.get(0))) {
ObserverCamera camera = (ObserverCamera)selectedItems.get(0);
float margin = INDICATOR_PIXEL_MARGIN / getScale();
float [][] cameraPoints = camera.getPoints();
// Check if (x,y) matches the point between the first and the second points
// of the rectangle surrounding camera
float xMiddleFirstAndSecondPoint = (cameraPoints [0][0] + cameraPoints [1][0]) / 2;
float yMiddleFirstAndSecondPoint = (cameraPoints [0][1] + cameraPoints [1][1]) / 2;
if (Math.abs(x - xMiddleFirstAndSecondPoint) <= margin
&& Math.abs(y - yMiddleFirstAndSecondPoint) <= margin) {
return camera;
}
}
return null;
}
/**
* Returns the selected compass with a point
* at (<code>x</code>, <code>y</code>) that can be used to rotate it.
*/
private Compass getRotatedCompassAt(float x, float y) {
List<Selectable> selectedItems = this.home.getSelectedItems();
if (selectedItems.size() == 1
&& selectedItems.get(0) instanceof Compass
&& isItemMovable(selectedItems.get(0))) {
Compass compass = (Compass)selectedItems.get(0);
float margin = INDICATOR_PIXEL_MARGIN / getScale();
float [][] compassPoints = compass.getPoints();
// Check if (x,y) matches the point between the third and the fourth points (South point)
// of the rectangle surrounding compass
float xMiddleThirdAndFourthPoint = (compassPoints [2][0] + compassPoints [3][0]) / 2;
float yMiddleThirdAndFourthPoint = (compassPoints [2][1] + compassPoints [3][1]) / 2;
if (Math.abs(x - xMiddleThirdAndFourthPoint) <= margin
&& Math.abs(y - yMiddleThirdAndFourthPoint) <= margin) {
return compass;
}
}
return null;
}
/**
* Returns the selected compass with a point
* at (<code>x</code>, <code>y</code>) that can be used to resize it.
*/
private Compass getResizedCompassAt(float x, float y) {
List<Selectable> selectedItems = this.home.getSelectedItems();
if (selectedItems.size() == 1
&& selectedItems.get(0) instanceof Compass
&& isItemMovable(selectedItems.get(0))) {
Compass compass = (Compass)selectedItems.get(0);
float margin = INDICATOR_PIXEL_MARGIN / getScale();
float [][] compassPoints = compass.getPoints();
// Check if (x,y) matches the point between the second and the third points (East point)
// of the rectangle surrounding compass
float xMiddleSecondAndThirdPoint = (compassPoints [1][0] + compassPoints [2][0]) / 2;
float yMiddleSecondAndThirdPoint = (compassPoints [1][1] + compassPoints [2][1]) / 2;
if (Math.abs(x - xMiddleSecondAndThirdPoint) <= margin
&& Math.abs(y - yMiddleSecondAndThirdPoint) <= margin) {
return compass;
}
}
return null;
}
/**
* Deletes <code>items</code> in plan and record it as an undoable operation.
*/
public void deleteItems(List<? extends Selectable> items) {
List<Selectable> deletedItems = new ArrayList<Selectable>(items.size());
for (Selectable item : items) {
if (isItemDeletable(item)) {
deletedItems.add(item);
}
}
if (!deletedItems.isEmpty()) {
// Start a compound edit that deletes walls, furniture and dimension lines from home
this.undoSupport.beginUpdate();
final List<Selectable> selectedItems = new ArrayList<Selectable>(items);
// Add a undoable edit that will select the undeleted items at undo
this.undoSupport.postEdit(new AbstractUndoableEdit() {
@Override
public void undo() throws CannotRedoException {
super.undo();
selectAndShowItems(selectedItems);
}
});
// Delete furniture with inherited method
deleteFurniture(Home.getFurnitureSubList(deletedItems));
List<Selectable> deletedOtherItems =
new ArrayList<Selectable>(Home.getWallsSubList(deletedItems));
deletedOtherItems.addAll(Home.getRoomsSubList(deletedItems));
deletedOtherItems.addAll(Home.getDimensionLinesSubList(deletedItems));
deletedOtherItems.addAll(Home.getLabelsSubList(deletedItems));
// First post to undo support that walls, rooms and dimension lines are deleted,
// otherwise data about joined walls and rooms index can't be stored
postDeleteItems(deletedOtherItems, this.home.isBasePlanLocked());
// Then delete items from plan
doDeleteItems(deletedOtherItems);
// End compound edit
this.undoSupport.endUpdate();
}
}
/**
* Posts an undoable delete items operation about <code>deletedItems</code>.
*/
private void postDeleteItems(final List<? extends Selectable> deletedItems,
final boolean basePlanLocked) {
// Manage walls
List<Wall> deletedWalls = Home.getWallsSubList(deletedItems);
// Get joined walls data for undo operation
final JoinedWall [] joinedDeletedWalls = JoinedWall.getJoinedWalls(deletedWalls);
// Manage rooms and their index
List<Room> deletedRooms = Home.getRoomsSubList(deletedItems);
List<Room> homeRooms = this.home.getRooms();
// Sort the deleted rooms in the ascending order of their index in home
Map<Integer, Room> sortedMap = new TreeMap<Integer, Room>();
for (Room room : deletedRooms) {
sortedMap.put(homeRooms.indexOf(room), room);
}
final Room [] rooms = sortedMap.values().toArray(new Room [sortedMap.size()]);
final int [] roomsIndex = new int [rooms.length];
int i = 0;
for (int index : sortedMap.keySet()) {
roomsIndex [i++] = index;
}
// Manage dimension lines
List<DimensionLine> deletedDimensionLines = Home.getDimensionLinesSubList(deletedItems);
final DimensionLine [] dimensionLines = deletedDimensionLines.toArray(
new DimensionLine [deletedDimensionLines.size()]);
// Manage labels
List<Label> deletedLabels = Home.getLabelsSubList(deletedItems);
final Label [] labels = deletedLabels.toArray(new Label [deletedLabels.size()]);
final Level level = this.home.getSelectedLevel();
UndoableEdit undoableEdit = new AbstractUndoableEdit() {
@Override
public void undo() throws CannotUndoException {
super.undo();
doAddWalls(joinedDeletedWalls, basePlanLocked);
doAddRooms(rooms, roomsIndex, level, basePlanLocked);
doAddDimensionLines(dimensionLines, level, basePlanLocked);
doAddLabels(labels, level, basePlanLocked);
selectAndShowItems(deletedItems);
}
@Override
public void redo() throws CannotRedoException {
super.redo();
selectItems(deletedItems);
doDeleteWalls(joinedDeletedWalls, basePlanLocked);
doDeleteRooms(rooms, basePlanLocked);
doDeleteDimensionLines(dimensionLines, basePlanLocked);
doDeleteLabels(labels, basePlanLocked);
}
@Override
public String getPresentationName() {
return preferences.getLocalizedString(
PlanController.class, "undoDeleteSelectionName");
}
};
this.undoSupport.postEdit(undoableEdit);
}
/**
* Deletes <code>items</code> from home.
*/
private void doDeleteItems(List<Selectable> items) {
boolean basePlanLocked = this.home.isBasePlanLocked();
for (Selectable item : items) {
if (item instanceof Wall) {
home.deleteWall((Wall)item);
} else if (item instanceof DimensionLine) {
home.deleteDimensionLine((DimensionLine)item);
} else if (item instanceof Room) {
home.deleteRoom((Room)item);
} else if (item instanceof Label) {
home.deleteLabel((Label)item);
} else if (item instanceof HomePieceOfFurniture) {
home.deletePieceOfFurniture((HomePieceOfFurniture)item);
}
// Unlock base plan if item is a part of it
basePlanLocked &= !isItemPartOfBasePlan(item);
}
this.home.setBasePlanLocked(basePlanLocked);
}
/**
* Moves and shows selected items in plan component of (<code>dx</code>,
* <code>dy</code>) units and record it as undoable operation.
*/
private void moveAndShowSelectedItems(float dx, float dy) {
List<Selectable> selectedItems = this.home.getSelectedItems();
List<Selectable> movedItems = new ArrayList<Selectable>(selectedItems.size());
for (Selectable item : selectedItems) {
if (isItemMovable(item)) {
movedItems.add(item);
}
}
if (!movedItems.isEmpty()) {
moveItems(movedItems, dx, dy);
selectAndShowItems(movedItems);
if (movedItems.size() != 1
|| !(movedItems.get(0) instanceof Camera)) {
// Post move undo only for items different from the camera
postItemsMove(movedItems, selectedItems, dx, dy);
}
}
}
/**
* Moves <code>items</code> of (<code>dx</code>, <code>dy</code>) units.
*/
public void moveItems(List<? extends Selectable> items, float dx, float dy) {
for (Selectable item : items) {
if (item instanceof Wall) {
Wall wall = (Wall)item;
moveWallStartPoint(wall,
wall.getXStart() + dx, wall.getYStart() + dy,
!items.contains(wall.getWallAtStart()));
moveWallEndPoint(wall,
wall.getXEnd() + dx, wall.getYEnd() + dy,
!items.contains(wall.getWallAtEnd()));
} else {
item.move(dx, dy);
}
}
}
/**
* Moves <code>wall</code> start point to (<code>xStart</code>, <code>yStart</code>)
* and the wall point joined to its start point if <code>moveWallAtStart</code> is true.
*/
private void moveWallStartPoint(Wall wall, float xStart, float yStart,
boolean moveWallAtStart) {
float oldXStart = wall.getXStart();
float oldYStart = wall.getYStart();
wall.setXStart(xStart);
wall.setYStart(yStart);
Wall wallAtStart = wall.getWallAtStart();
// If wall is joined to a wall at its start
// and this wall doesn't belong to the list of moved walls
if (wallAtStart != null && moveWallAtStart) {
// Move the wall start point or end point
if (wallAtStart.getWallAtStart() == wall
&& (wallAtStart.getWallAtEnd() != wall
|| (wallAtStart.getXStart() == oldXStart
&& wallAtStart.getYStart() == oldYStart))) {
wallAtStart.setXStart(xStart);
wallAtStart.setYStart(yStart);
} else if (wallAtStart.getWallAtEnd() == wall
&& (wallAtStart.getWallAtStart() != wall
|| (wallAtStart.getXEnd() == oldXStart
&& wallAtStart.getYEnd() == oldYStart))) {
wallAtStart.setXEnd(xStart);
wallAtStart.setYEnd(yStart);
}
}
}
/**
* Moves <code>wall</code> end point to (<code>xEnd</code>, <code>yEnd</code>)
* and the wall point joined to its end if <code>moveWallAtEnd</code> is true.
*/
private void moveWallEndPoint(Wall wall, float xEnd, float yEnd,
boolean moveWallAtEnd) {
float oldXEnd = wall.getXEnd();
float oldYEnd = wall.getYEnd();
wall.setXEnd(xEnd);
wall.setYEnd(yEnd);
Wall wallAtEnd = wall.getWallAtEnd();
// If wall is joined to a wall at its end
// and this wall doesn't belong to the list of moved walls
if (wallAtEnd != null && moveWallAtEnd) {
// Move the wall start point or end point
if (wallAtEnd.getWallAtStart() == wall
&& (wallAtEnd.getWallAtEnd() != wall
|| (wallAtEnd.getXStart() == oldXEnd
&& wallAtEnd.getYStart() == oldYEnd))) {
wallAtEnd.setXStart(xEnd);
wallAtEnd.setYStart(yEnd);
} else if (wallAtEnd.getWallAtEnd() == wall
&& (wallAtEnd.getWallAtStart() != wall
|| (wallAtEnd.getXEnd() == oldXEnd
&& wallAtEnd.getYEnd() == oldYEnd))) {
wallAtEnd.setXEnd(xEnd);
wallAtEnd.setYEnd(yEnd);
}
}
}
/**
* Moves <code>wall</code> start point to (<code>x</code>, <code>y</code>)
* if <code>editingStartPoint</code> is true or <code>wall</code> end point
* to (<code>x</code>, <code>y</code>) if <code>editingStartPoint</code> is false.
*/
private void moveWallPoint(Wall wall, float x, float y, boolean startPoint) {
if (startPoint) {
moveWallStartPoint(wall, x, y, true);
} else {
moveWallEndPoint(wall, x, y, true);
}
}
/**
* Moves <code>room</code> point at the given index to (<code>x</code>, <code>y</code>).
*/
private void moveRoomPoint(Room room, float x, float y, int pointIndex) {
room.setPoint(x, y, pointIndex);
}
/**
* Moves <code>dimensionLine</code> start point to (<code>x</code>, <code>y</code>)
* if <code>editingStartPoint</code> is true or <code>dimensionLine</code> end point
* to (<code>x</code>, <code>y</code>) if <code>editingStartPoint</code> is false.
*/
private void moveDimensionLinePoint(DimensionLine dimensionLine, float x, float y, boolean startPoint) {
if (startPoint) {
dimensionLine.setXStart(x);
dimensionLine.setYStart(y);
} else {
dimensionLine.setXEnd(x);
dimensionLine.setYEnd(y);
}
}
/**
* Swaps start and end points of the given dimension line.
*/
private void reverseDimensionLine(DimensionLine dimensionLine) {
float swappedX = dimensionLine.getXStart();
float swappedY = dimensionLine.getYStart();
dimensionLine.setXStart(dimensionLine.getXEnd());
dimensionLine.setYStart(dimensionLine.getYEnd());
dimensionLine.setXEnd(swappedX);
dimensionLine.setYEnd(swappedY);
dimensionLine.setOffset(-dimensionLine.getOffset());
}
/**
* Selects <code>items</code> and make them visible at screen.
*/
protected void selectAndShowItems(List<? extends Selectable> items) {
selectItems(items);
selectLevelFromSelectedItems();
getView().makeSelectionVisible();
}
/**
* Selects <code>items</code>.
*/
protected void selectItems(List<? extends Selectable> items) {
// Remove selectionListener when selection is done from this controller
// to control when selection should be made visible
this.home.removeSelectionListener(this.selectionListener);
this.home.setSelectedItems(items);
this.home.addSelectionListener(this.selectionListener);
}
/**
* Selects the given <code>item</code>.
*/
public void selectItem(Selectable item) {
selectItems(Arrays.asList(new Selectable [] {item}));
}
/**
* Deselects all walls in plan.
*/
private void deselectAll() {
List<Selectable> emptyList = Collections.emptyList();
selectItems(emptyList);
}
/**
* Adds <code>items</code> to home and post an undoable operation.
*/
public void addItems(final List<? extends Selectable> items) {
// Start a compound edit that adds walls, furniture, rooms, dimension lines and labels to home
this.undoSupport.beginUpdate();
addFurniture(Home.getFurnitureSubList(items));
addWalls(Home.getWallsSubList(items));
addRooms(Home.getRoomsSubList(items));
addDimensionLines(Home.getDimensionLinesSubList(items));
addLabels(Home.getLabelsSubList(items));
this.home.setSelectedItems(items);
// Add a undoable edit that will select all the items at redo
undoSupport.postEdit(new AbstractUndoableEdit() {
@Override
public void redo() throws CannotRedoException {
super.redo();
home.setSelectedItems(items);
}
@Override
public String getPresentationName() {
return preferences.getLocalizedString(PlanController.class, "undAddItemsName");
}
});
// End compound edit
undoSupport.endUpdate();
}
/**
* Adds furniture to home and updates door and window flags if they intersect with walls and magnestism is enabled.
*/
@Override
public void addFurniture(List<HomePieceOfFurniture> furniture) {
super.addFurniture(furniture);
if (this.preferences.isMagnetismEnabled()) {
Area wallsArea = getWallsArea();
for (HomePieceOfFurniture piece : furniture) {
if (piece instanceof HomeDoorOrWindow) {
float [][] piecePoints = piece.getPoints();
Area pieceAreaIntersection = new Area(getPath(piecePoints));
pieceAreaIntersection.intersect(wallsArea);
if (!pieceAreaIntersection.isEmpty()
&& new Room(piecePoints).getArea() / getArea(pieceAreaIntersection) > 0.999) {
((HomeDoorOrWindow) piece).setBoundToWall(true);
}
}
}
}
}
/**
* Adds <code>walls</code> to home and post an undoable new wall operation.
*/
public void addWalls(List<Wall> walls) {
for (Wall wall : walls) {
this.home.addWall(wall);
}
postCreateWalls(walls, this.home.getSelectedItems(), home.isBasePlanLocked());
}
/**
* Posts an undoable new wall operation, about <code>newWalls</code>.
*/
private void postCreateWalls(List<Wall> newWalls,
List<Selectable> oldSelection,
final boolean oldBasePlanLocked) {
if (newWalls.size() > 0) {
boolean basePlanLocked = this.home.isBasePlanLocked();
if (basePlanLocked) {
for (Wall wall : newWalls) {
// Unlock base plan if wall is a part of it
basePlanLocked &= !isItemPartOfBasePlan(wall);
}
this.home.setBasePlanLocked(basePlanLocked);
}
final boolean newBasePlanLocked = basePlanLocked;
// Retrieve data about joined walls to newWalls
final JoinedWall [] joinedNewWalls = JoinedWall.getJoinedWalls(newWalls);
final Selectable [] oldSelectedItems =
oldSelection.toArray(new Selectable [oldSelection.size()]);
UndoableEdit undoableEdit = new AbstractUndoableEdit() {
@Override
public void undo() throws CannotUndoException {
super.undo();
doDeleteWalls(joinedNewWalls, oldBasePlanLocked);
selectAndShowItems(Arrays.asList(oldSelectedItems));
}
@Override
public void redo() throws CannotRedoException {
super.redo();
doAddWalls(joinedNewWalls, newBasePlanLocked);
selectAndShowItems(JoinedWall.getWalls(joinedNewWalls));
}
@Override
public String getPresentationName() {
return preferences.getLocalizedString(
PlanController.class, "undoCreateWallsName");
}
};
this.undoSupport.postEdit(undoableEdit);
}
}
/**
* Adds the walls in <code>joinedWalls</code> to plan component, joins
* them to other walls if necessary.
*/
private void doAddWalls(JoinedWall [] joinedWalls, boolean basePlanLocked) {
// First add all walls to home
for (JoinedWall joinedNewWall : joinedWalls) {
Wall wall = joinedNewWall.getWall();
this.home.addWall(wall);
wall.setLevel(joinedNewWall.getLevel());
}
this.home.setBasePlanLocked(basePlanLocked);
// Then join them to each other if necessary
for (JoinedWall joinedNewWall : joinedWalls) {
Wall wall = joinedNewWall.getWall();
Wall wallAtStart = joinedNewWall.getWallAtStart();
if (wallAtStart != null) {
wall.setWallAtStart(wallAtStart);
if (joinedNewWall.isJoinedAtEndOfWallAtStart()) {
wallAtStart.setWallAtEnd(wall);
} else if (joinedNewWall.isJoinedAtStartOfWallAtStart()) {
wallAtStart.setWallAtStart(wall);
}
}
Wall wallAtEnd = joinedNewWall.getWallAtEnd();
if (wallAtEnd != null) {
wall.setWallAtEnd(wallAtEnd);
if (joinedNewWall.isJoinedAtStartOfWallAtEnd()) {
wallAtEnd.setWallAtStart(wall);
} else if (joinedNewWall.isJoinedAtEndOfWallAtEnd()) {
wallAtEnd.setWallAtEnd(wall);
}
}
}
}
/**
* Deletes walls referenced in <code>joinedDeletedWalls</code>.
*/
private void doDeleteWalls(JoinedWall [] joinedDeletedWalls,
boolean basePlanLocked) {
for (JoinedWall joinedWall : joinedDeletedWalls) {
this.home.deleteWall(joinedWall.getWall());
}
this.home.setBasePlanLocked(basePlanLocked);
}
/**
* Add <code>newRooms</code> to home and post an undoable new room line operation.
*/
public void addRooms(List<Room> rooms) {
final Room [] newRooms = rooms.toArray(new Room [rooms.size()]);
// Get indices of rooms added to home
final int [] roomsIndex = new int [rooms.size()];
int endIndex = home.getRooms().size();
for (int i = 0; i < roomsIndex.length; i++) {
roomsIndex [i] = endIndex++;
this.home.addRoom(newRooms [i], roomsIndex [i]);
}
postCreateRooms(newRooms, roomsIndex, this.home.getSelectedItems(), this.home.isBasePlanLocked());
}
/**
* Posts an undoable new room operation, about <code>newRooms</code>.
*/
private void postCreateRooms(final Room [] newRooms,
final int [] roomsIndex,
List<Selectable> oldSelection,
final boolean oldBasePlanLocked) {
if (newRooms.length > 0) {
boolean basePlanLocked = this.home.isBasePlanLocked();
if (basePlanLocked) {
for (Room room : newRooms) {
// Unlock base plan if room is a part of it
basePlanLocked &= !isItemPartOfBasePlan(room);
}
this.home.setBasePlanLocked(basePlanLocked);
}
final boolean newBasePlanLocked = basePlanLocked;
final Selectable [] oldSelectedItems =
oldSelection.toArray(new Selectable [oldSelection.size()]);
final Level roomsLevel = this.home.getSelectedLevel();
UndoableEdit undoableEdit = new AbstractUndoableEdit() {
@Override
public void undo() throws CannotUndoException {
super.undo();
doDeleteRooms(newRooms, oldBasePlanLocked);
selectAndShowItems(Arrays.asList(oldSelectedItems));
}
@Override
public void redo() throws CannotRedoException {
super.redo();
doAddRooms(newRooms, roomsIndex, roomsLevel, newBasePlanLocked);
selectAndShowItems(Arrays.asList(newRooms));
}
@Override
public String getPresentationName() {
return preferences.getLocalizedString(
PlanController.class, "undoCreateRoomsName");
}
};
this.undoSupport.postEdit(undoableEdit);
}
}
/**
* Posts an undoable new room operation, about <code>newRooms</code>.
*/
private void postCreateRooms(List<Room> rooms,
List<Selectable> oldSelection,
boolean basePlanLocked) {
// Search the index of rooms in home list of rooms
Room [] newRooms = rooms.toArray(new Room [rooms.size()]);
int [] roomsIndex = new int [rooms.size()];
List<Room> homeRooms = this.home.getRooms();
for (int i = 0; i < roomsIndex.length; i++) {
roomsIndex [i] = homeRooms.lastIndexOf(newRooms [i]);
}
postCreateRooms(newRooms, roomsIndex, oldSelection, basePlanLocked);
}
/**
* Adds the <code>rooms</code> to plan component.
*/
private void doAddRooms(Room [] rooms,
int [] roomsIndex,
Level roomsLevel,
boolean basePlanLocked) {
for (int i = 0; i < roomsIndex.length; i++) {
this.home.addRoom (rooms [i], roomsIndex [i]);
rooms [i].setLevel(roomsLevel);
}
this.home.setBasePlanLocked(basePlanLocked);
}
/**
* Deletes <code>rooms</code>.
*/
private void doDeleteRooms(Room [] rooms,
boolean basePlanLocked) {
for (Room room : rooms) {
this.home.deleteRoom(room);
}
this.home.setBasePlanLocked(basePlanLocked);
}
/**
* Add <code>dimensionLines</code> to home and post an undoable new dimension line operation.
*/
public void addDimensionLines(List<DimensionLine> dimensionLines) {
for (DimensionLine dimensionLine : dimensionLines) {
this.home.addDimensionLine(dimensionLine);
}
postCreateDimensionLines(dimensionLines,
this.home.getSelectedItems(), this.home.isBasePlanLocked());
}
/**
* Posts an undoable new dimension line operation, about <code>newDimensionLines</code>.
*/
private void postCreateDimensionLines(List<DimensionLine> newDimensionLines,
List<Selectable> oldSelection,
final boolean oldBasePlanLocked) {
if (newDimensionLines.size() > 0) {
boolean basePlanLocked = this.home.isBasePlanLocked();
if (basePlanLocked) {
for (DimensionLine dimensionLine : newDimensionLines) {
// Unlock base plan if dimension line is a part of it
basePlanLocked &= !isItemPartOfBasePlan(dimensionLine);
}
this.home.setBasePlanLocked(basePlanLocked);
}
final boolean newBasePlanLocked = basePlanLocked;
final DimensionLine [] dimensionLines = newDimensionLines.toArray(
new DimensionLine [newDimensionLines.size()]);
final Selectable [] oldSelectedItems =
oldSelection.toArray(new Selectable [oldSelection.size()]);
final Level dimensionLinesLevel = this.home.getSelectedLevel();
UndoableEdit undoableEdit = new AbstractUndoableEdit() {
@Override
public void undo() throws CannotUndoException {
super.undo();
doDeleteDimensionLines(dimensionLines, oldBasePlanLocked);
selectAndShowItems(Arrays.asList(oldSelectedItems));
}
@Override
public void redo() throws CannotRedoException {
super.redo();
doAddDimensionLines(dimensionLines, dimensionLinesLevel, newBasePlanLocked);
selectAndShowItems(Arrays.asList(dimensionLines));
}
@Override
public String getPresentationName() {
return preferences.getLocalizedString(
PlanController.class, "undoCreateDimensionLinesName");
}
};
this.undoSupport.postEdit(undoableEdit);
}
}
/**
* Adds the dimension lines in <code>dimensionLines</code> to plan component.
*/
private void doAddDimensionLines(DimensionLine [] dimensionLines,
Level dimensionLinesLevel, boolean basePlanLocked) {
for (DimensionLine dimensionLine : dimensionLines) {
this.home.addDimensionLine(dimensionLine);
dimensionLine.setLevel(dimensionLinesLevel);
}
this.home.setBasePlanLocked(basePlanLocked);
}
/**
* Deletes dimension lines in <code>dimensionLines</code>.
*/
private void doDeleteDimensionLines(DimensionLine [] dimensionLines,
boolean basePlanLocked) {
for (DimensionLine dimensionLine : dimensionLines) {
this.home.deleteDimensionLine(dimensionLine);
}
this.home.setBasePlanLocked(basePlanLocked);
}
/**
* Add <code>labels</code> to home and post an undoable new label operation.
*/
public void addLabels(List<Label> labels) {
for (Label label : labels) {
this.home.addLabel(label);
}
postCreateLabels(labels, this.home.getSelectedItems(), this.home.isBasePlanLocked());
}
/**
* Posts an undoable new label operation, about <code>newLabels</code>.
*/
private void postCreateLabels(List<Label> newLabels,
List<Selectable> oldSelection,
final boolean oldBasePlanLocked) {
if (newLabels.size() > 0) {
boolean basePlanLocked = this.home.isBasePlanLocked();
if (basePlanLocked) {
for (Label label : newLabels) {
// Unlock base plan if label is a part of it
basePlanLocked &= !isItemPartOfBasePlan(label);
}
this.home.setBasePlanLocked(basePlanLocked);
}
final boolean newBasePlanLocked = basePlanLocked;
final Label [] labels = newLabels.toArray(new Label [newLabels.size()]);
final Selectable [] oldSelectedItems =
oldSelection.toArray(new Selectable [oldSelection.size()]);
final Level labelsLevel = this.home.getSelectedLevel();
UndoableEdit undoableEdit = new AbstractUndoableEdit() {
@Override
public void undo() throws CannotUndoException {
super.undo();
doDeleteLabels(labels, oldBasePlanLocked);
selectAndShowItems(Arrays.asList(oldSelectedItems));
}
@Override
public void redo() throws CannotRedoException {
super.redo();
doAddLabels(labels, labelsLevel, newBasePlanLocked);
selectAndShowItems(Arrays.asList(labels));
}
@Override
public String getPresentationName() {
return preferences.getLocalizedString(
PlanController.class, "undoCreateLabelsName");
}
};
this.undoSupport.postEdit(undoableEdit);
}
}
/**
* Adds the labels in <code>labels</code> to plan component.
*/
private void doAddLabels(Label [] labels, Level labelsLevel, boolean basePlanLocked) {
for (Label label : labels) {
this.home.addLabel(label);
label.setLevel(labelsLevel);
}
this.home.setBasePlanLocked(basePlanLocked);
}
/**
* Deletes labels in <code>labels</code>.
*/
private void doDeleteLabels(Label [] labels, boolean basePlanLocked) {
for (Label label : labels) {
this.home.deleteLabel(label);
}
this.home.setBasePlanLocked(basePlanLocked);
}
/**
* Posts an undoable operation of a (<code>dx</code>, <code>dy</code>) move
* of <code>movedItems</code>.
*/
private void postItemsMove(List<? extends Selectable> movedItems,
List<? extends Selectable> oldSelection,
final float dx, final float dy) {
if (dx != 0 || dy != 0) {
// Store the moved items in an array
final Selectable [] itemsArray =
movedItems.toArray(new Selectable [movedItems.size()]);
final Selectable [] oldSelectedItems =
oldSelection.toArray(new Selectable [oldSelection.size()]);
UndoableEdit undoableEdit = new AbstractUndoableEdit() {
@Override
public void undo() throws CannotUndoException {
super.undo();
doMoveAndShowItems(itemsArray, oldSelectedItems, -dx, -dy);
}
@Override
public void redo() throws CannotRedoException {
super.redo();
doMoveAndShowItems(itemsArray, itemsArray, dx, dy);
}
@Override
public String getPresentationName() {
return preferences.getLocalizedString(
PlanController.class, "undoMoveSelectionName");
}
};
this.undoSupport.postEdit(undoableEdit);
}
}
/**
* Moves <code>movedItems</code> of (<code>dx</code>, <code>dy</code>) pixels,
* selects them and make them visible.
*/
private void doMoveAndShowItems(Selectable [] movedItems,
Selectable [] selectedItems,
float dx, float dy) {
moveItems(Arrays.asList(movedItems), dx, dy);
selectAndShowItems(Arrays.asList(selectedItems));
}
/**
* Posts an undoable operation of a (<code>dx</code>, <code>dy</code>) move
* of <code>movedPieceOfFurniture</code>.
*/
private void postPieceOfFurnitureMove(final HomePieceOfFurniture piece,
final float dx, final float dy,
final float oldAngle,
final float oldDepth,
final float oldElevation,
final boolean oldDoorOrWindowBoundToWall) {
final float newAngle = piece.getAngle();
final float newDepth = piece.getDepth();
final float newElevation = piece.getElevation();
if (dx != 0 || dy != 0
|| newAngle != oldAngle
|| newDepth != oldDepth
|| newElevation != oldElevation) {
UndoableEdit undoableEdit = new AbstractUndoableEdit() {
@Override
public void undo() throws CannotUndoException {
super.undo();
piece.move(-dx, -dy);
piece.setAngle(oldAngle);
if (piece.isResizable()
&& isItemResizable(piece)) {
piece.setDepth(oldDepth);
}
piece.setElevation(oldElevation);
if (piece instanceof HomeDoorOrWindow) {
((HomeDoorOrWindow)piece).setBoundToWall(oldDoorOrWindowBoundToWall);
}
selectAndShowItems(Arrays.asList(new HomePieceOfFurniture [] {piece}));
}
@Override
public void redo() throws CannotRedoException {
super.redo();
piece.move(dx, dy);
piece.setAngle(newAngle);
if (piece.isResizable()
&& isItemResizable(piece)) {
piece.setDepth(newDepth);
}
piece.setElevation(newElevation);
selectAndShowItems(Arrays.asList(new HomePieceOfFurniture [] {piece}));
}
@Override
public String getPresentationName() {
return preferences.getLocalizedString(
PlanController.class, "undoMoveSelectionName");
}
};
this.undoSupport.postEdit(undoableEdit);
}
}
/**
* Posts an undoable operation about duplication <code>items</code>.
*/
private void postItemsDuplication(final List<Selectable> items,
final List<Selectable> oldSelectedItems) {
boolean basePlanLocked = this.home.isBasePlanLocked();
// Delete furniture and add it again in a compound edit
List<HomePieceOfFurniture> furniture = Home.getFurnitureSubList(items);
for (HomePieceOfFurniture piece : furniture) {
this.home.deletePieceOfFurniture(piece);
}
// Post duplicated items in a compound edit
this.undoSupport.beginUpdate();
// Add a undoable edit that will select previous items at undo
this.undoSupport.postEdit(new AbstractUndoableEdit() {
@Override
public void undo() throws CannotRedoException {
super.undo();
selectAndShowItems(oldSelectedItems);
}
});
addFurniture(furniture);
List<Selectable> emptyList = Collections.emptyList();
postCreateWalls(Home.getWallsSubList(items), emptyList, basePlanLocked);
postCreateRooms(Home.getRoomsSubList(items), emptyList, basePlanLocked);
postCreateDimensionLines(Home.getDimensionLinesSubList(items), emptyList, basePlanLocked);
postCreateLabels(Home.getLabelsSubList(items), emptyList, basePlanLocked);
// Add a undoable edit that will select all the items at redo
this.undoSupport.postEdit(new AbstractUndoableEdit() {
@Override
public void redo() throws CannotRedoException {
super.redo();
selectAndShowItems(items);
}
@Override
public String getPresentationName() {
return preferences.getLocalizedString(
PlanController.class, "undoDuplicateSelectionName");
}
});
// End compound edit
this.undoSupport.endUpdate();
selectItems(items);
}
/**
* Posts an undoable operation about <code>wall</code> resizing.
*/
private void postWallResize(final Wall wall, final float oldX, final float oldY,
final boolean startPoint) {
final float newX;
final float newY;
if (startPoint) {
newX = wall.getXStart();
newY = wall.getYStart();
} else {
newX = wall.getXEnd();
newY = wall.getYEnd();
}
if (newX != oldX || newY != oldY) {
UndoableEdit undoableEdit = new AbstractUndoableEdit() {
@Override
public void undo() throws CannotUndoException {
super.undo();
moveWallPoint(wall, oldX, oldY, startPoint);
selectAndShowItems(Arrays.asList(new Wall [] {wall}));
}
@Override
public void redo() throws CannotRedoException {
super.redo();
moveWallPoint(wall, newX, newY, startPoint);
selectAndShowItems(Arrays.asList(new Wall [] {wall}));
}
@Override
public String getPresentationName() {
return preferences.getLocalizedString(
PlanController.class, "undoWallResizeName");
}
};
this.undoSupport.postEdit(undoableEdit);
}
}
/**
* Posts an undoable operation about <code>room</code> resizing.
*/
private void postRoomResize(final Room room, final float oldX, final float oldY,
final int pointIndex) {
float [] roomPoint = room.getPoints() [pointIndex];
final float newX = roomPoint [0];
final float newY = roomPoint [1];
if (newX != oldX || newY != oldY) {
UndoableEdit undoableEdit = new AbstractUndoableEdit() {
@Override
public void undo() throws CannotUndoException {
super.undo();
moveRoomPoint(room, oldX, oldY, pointIndex);
selectAndShowItems(Arrays.asList(new Room [] {room}));
}
@Override
public void redo() throws CannotRedoException {
super.redo();
moveRoomPoint(room, newX, newY, pointIndex);
selectAndShowItems(Arrays.asList(new Room [] {room}));
}
@Override
public String getPresentationName() {
return preferences.getLocalizedString(
PlanController.class, "undoRoomResizeName");
}
};
this.undoSupport.postEdit(undoableEdit);
}
}
/**
* Posts an undoable operation about <code>room</code> name offset change.
*/
private void postRoomNameOffset(final Room room, final float oldNameXOffset,
final float oldNameYOffset) {
final float newNameXOffset = room.getNameXOffset();
final float newNameYOffset = room.getNameYOffset();
if (newNameXOffset != oldNameXOffset
|| newNameYOffset != oldNameYOffset) {
UndoableEdit undoableEdit = new AbstractUndoableEdit() {
@Override
public void undo() throws CannotUndoException {
super.undo();
room.setNameXOffset(oldNameXOffset);
room.setNameYOffset(oldNameYOffset);
selectAndShowItems(Arrays.asList(new Room [] {room}));
}
@Override
public void redo() throws CannotRedoException {
super.redo();
room.setNameXOffset(newNameXOffset);
room.setNameYOffset(newNameYOffset);
selectAndShowItems(Arrays.asList(new Room [] {room}));
}
@Override
public String getPresentationName() {
return preferences.getLocalizedString(
PlanController.class, "undoRoomNameOffsetName");
}
};
this.undoSupport.postEdit(undoableEdit);
}
}
/**
* Posts an undoable operation about <code>room</code> area offset change.
*/
private void postRoomAreaOffset(final Room room, final float oldAreaXOffset,
final float oldAreaYOffset) {
final float newAreaXOffset = room.getAreaXOffset();
final float newAreaYOffset = room.getAreaYOffset();
if (newAreaXOffset != oldAreaXOffset
|| newAreaYOffset != oldAreaYOffset) {
UndoableEdit undoableEdit = new AbstractUndoableEdit() {
@Override
public void undo() throws CannotUndoException {
super.undo();
room.setAreaXOffset(oldAreaXOffset);
room.setAreaYOffset(oldAreaYOffset);
selectAndShowItems(Arrays.asList(new Room [] {room}));
}
@Override
public void redo() throws CannotRedoException {
super.redo();
room.setAreaXOffset(newAreaXOffset);
room.setAreaYOffset(newAreaYOffset);
selectAndShowItems(Arrays.asList(new Room [] {room}));
}
@Override
public String getPresentationName() {
return preferences.getLocalizedString(
PlanController.class, "undoRoomAreaOffsetName");
}
};
this.undoSupport.postEdit(undoableEdit);
}
}
/**
* Post to undo support an angle change on <code>piece</code>.
*/
private void postPieceOfFurnitureRotation(final HomePieceOfFurniture piece,
final float oldAngle,
final boolean oldDoorOrWindowBoundToWall) {
final float newAngle = piece.getAngle();
if (newAngle != oldAngle) {
UndoableEdit undoableEdit = new AbstractUndoableEdit() {
@Override
public void undo() throws CannotUndoException {
super.undo();
piece.setAngle(oldAngle);
if (piece instanceof HomeDoorOrWindow) {
((HomeDoorOrWindow)piece).setBoundToWall(oldDoorOrWindowBoundToWall);
}
selectAndShowItems(Arrays.asList(new HomePieceOfFurniture [] {piece}));
}
@Override
public void redo() throws CannotRedoException {
super.redo();
piece.setAngle(newAngle);
selectAndShowItems(Arrays.asList(new HomePieceOfFurniture [] {piece}));
}
@Override
public String getPresentationName() {
return preferences.getLocalizedString(
PlanController.class, "undoPieceOfFurnitureRotationName");
}
};
this.undoSupport.postEdit(undoableEdit);
}
}
/**
* Post to undo support an elevation change on <code>piece</code>.
*/
private void postPieceOfFurnitureElevation(final HomePieceOfFurniture piece, final float oldElevation) {
final float newElevation = piece.getElevation();
if (newElevation != oldElevation) {
UndoableEdit undoableEdit = new AbstractUndoableEdit() {
@Override
public void undo() throws CannotUndoException {
super.undo();
piece.setElevation(oldElevation);
selectAndShowItems(Arrays.asList(new HomePieceOfFurniture [] {piece}));
}
@Override
public void redo() throws CannotRedoException {
super.redo();
piece.setElevation(newElevation);
selectAndShowItems(Arrays.asList(new HomePieceOfFurniture [] {piece}));
}
@Override
public String getPresentationName() {
return preferences.getLocalizedString(PlanController.class,
oldElevation < newElevation
? "undoPieceOfFurnitureRaiseName"
: "undoPieceOfFurnitureLowerName");
}
};
this.undoSupport.postEdit(undoableEdit);
}
}
/**
* Post to undo support a height change on <code>piece</code>.
*/
private void postPieceOfFurnitureHeightResize(final ResizedPieceOfFurniture resizedPiece) {
if (resizedPiece.getPieceOfFurniture().getHeight() != resizedPiece.getHeight()) {
postPieceOfFurnitureResize(resizedPiece, "undoPieceOfFurnitureHeightResizeName");
}
}
/**
* Post to undo support a width and depth change on <code>piece</code>.
*/
private void postPieceOfFurnitureWidthAndDepthResize(final ResizedPieceOfFurniture resizedPiece) {
HomePieceOfFurniture piece = resizedPiece.getPieceOfFurniture();
if (piece.getWidth() != resizedPiece.getWidth()
|| piece.getDepth() != resizedPiece.getDepth()) {
postPieceOfFurnitureResize(resizedPiece, "undoPieceOfFurnitureWidthAndDepthResizeName");
}
}
/**
* Post to undo support a size change on <code>piece</code>.
*/
private void postPieceOfFurnitureResize(final ResizedPieceOfFurniture resizedPiece,
final String presentationNameKey) {
HomePieceOfFurniture piece = resizedPiece.getPieceOfFurniture();
final float newX = piece.getX();
final float newY = piece.getY();
final float newWidth = piece.getWidth();
final float newDepth = piece.getDepth();
final float newHeight = piece.getHeight();
final boolean doorOrWindowBoundToWall = piece instanceof HomeDoorOrWindow
&& ((HomeDoorOrWindow)piece).isBoundToWall();
UndoableEdit undoableEdit = new AbstractUndoableEdit() {
@Override
public void undo() throws CannotUndoException {
super.undo();
resizedPiece.reset();
selectAndShowItems(Arrays.asList(new HomePieceOfFurniture [] {resizedPiece.getPieceOfFurniture()}));
}
@Override
public void redo() throws CannotRedoException {
super.redo();
HomePieceOfFurniture piece = resizedPiece.getPieceOfFurniture();
piece.setX(newX);
piece.setY(newY);
piece.setWidth(newWidth);
piece.setDepth(newDepth);
piece.setHeight(newHeight);
if (piece instanceof HomeDoorOrWindow) {
((HomeDoorOrWindow)piece).setBoundToWall(doorOrWindowBoundToWall);
}
selectAndShowItems(Arrays.asList(new HomePieceOfFurniture [] {piece}));
}
@Override
public String getPresentationName() {
return preferences.getLocalizedString(
PlanController.class, presentationNameKey);
}
};
this.undoSupport.postEdit(undoableEdit);
}
/**
* Post to undo support a power modification on <code>light</code>.
*/
private void postLightPowerModification(final HomeLight light, final float oldPower) {
final float newPower = light.getPower();
if (newPower != oldPower) {
UndoableEdit undoableEdit = new AbstractUndoableEdit() {
@Override
public void undo() throws CannotUndoException {
super.undo();
light.setPower(oldPower);
selectAndShowItems(Arrays.asList(new HomePieceOfFurniture [] {light}));
}
@Override
public void redo() throws CannotRedoException {
super.redo();
light.setPower(newPower);
selectAndShowItems(Arrays.asList(new HomePieceOfFurniture [] {light}));
}
@Override
public String getPresentationName() {
return preferences.getLocalizedString(
PlanController.class, "undoLightPowerModificationName");
}
};
this.undoSupport.postEdit(undoableEdit);
}
}
/**
* Posts an undoable operation about <code>piece</code> name offset change.
*/
private void postPieceOfFurnitureNameOffset(final HomePieceOfFurniture piece,
final float oldNameXOffset,
final float oldNameYOffset) {
final float newNameXOffset = piece.getNameXOffset();
final float newNameYOffset = piece.getNameYOffset();
if (newNameXOffset != oldNameXOffset
|| newNameYOffset != oldNameYOffset) {
UndoableEdit undoableEdit = new AbstractUndoableEdit() {
@Override
public void undo() throws CannotUndoException {
super.undo();
piece.setNameXOffset(oldNameXOffset);
piece.setNameYOffset(oldNameYOffset);
selectAndShowItems(Arrays.asList(new HomePieceOfFurniture [] {piece}));
}
@Override
public void redo() throws CannotRedoException {
super.redo();
piece.setNameXOffset(newNameXOffset);
piece.setNameYOffset(newNameYOffset);
selectAndShowItems(Arrays.asList(new HomePieceOfFurniture [] {piece}));
}
@Override
public String getPresentationName() {
return preferences.getLocalizedString(
PlanController.class, "undoPieceOfFurnitureNameOffsetName");
}
};
this.undoSupport.postEdit(undoableEdit);
}
}
/**
* Posts an undoable operation about <code>dimensionLine</code> resizing.
*/
private void postDimensionLineResize(final DimensionLine dimensionLine, final float oldX, final float oldY,
final boolean startPoint, final boolean reversed) {
final float newX;
final float newY;
if (startPoint) {
newX = dimensionLine.getXStart();
newY = dimensionLine.getYStart();
} else {
newX = dimensionLine.getXEnd();
newY = dimensionLine.getYEnd();
}
if (newX != oldX || newY != oldY || reversed) {
UndoableEdit undoableEdit = new AbstractUndoableEdit() {
@Override
public void undo() throws CannotUndoException {
super.undo();
if (reversed) {
reverseDimensionLine(dimensionLine);
moveDimensionLinePoint(dimensionLine, oldX, oldY, !startPoint);
} else {
moveDimensionLinePoint(dimensionLine, oldX, oldY, startPoint);
}
selectAndShowItems(Arrays.asList(new DimensionLine [] {dimensionLine}));
}
@Override
public void redo() throws CannotRedoException {
super.redo();
moveDimensionLinePoint(dimensionLine, newX, newY, startPoint);
if (reversed) {
reverseDimensionLine(dimensionLine);
}
selectAndShowItems(Arrays.asList(new DimensionLine [] {dimensionLine}));
}
@Override
public String getPresentationName() {
return preferences.getLocalizedString(
PlanController.class, "undoDimensionLineResizeName");
}
};
this.undoSupport.postEdit(undoableEdit);
}
}
/**
* Posts an undoable operation about <code>dimensionLine</code> offset change.
*/
private void postDimensionLineOffset(final DimensionLine dimensionLine, final float oldOffset) {
final float newOffset = dimensionLine.getOffset();
if (newOffset != oldOffset) {
UndoableEdit undoableEdit = new AbstractUndoableEdit() {
@Override
public void undo() throws CannotUndoException {
super.undo();
dimensionLine.setOffset(oldOffset);
selectAndShowItems(Arrays.asList(new DimensionLine [] {dimensionLine}));
}
@Override
public void redo() throws CannotRedoException {
super.redo();
dimensionLine.setOffset(newOffset);
selectAndShowItems(Arrays.asList(new DimensionLine [] {dimensionLine}));
}
@Override
public String getPresentationName() {
return preferences.getLocalizedString(
PlanController.class, "undoDimensionLineOffsetName");
}
};
this.undoSupport.postEdit(undoableEdit);
}
}
/**
* Post to undo support a north direction change on <code>compass</code>.
*/
private void postCompassRotation(final Compass compass,
final float oldNorthDirection) {
final float newNorthDirection = compass.getNorthDirection();
if (newNorthDirection != oldNorthDirection) {
UndoableEdit undoableEdit = new AbstractUndoableEdit() {
@Override
public void undo() throws CannotUndoException {
super.undo();
compass.setNorthDirection(oldNorthDirection);
selectAndShowItems(Arrays.asList(new Compass [] {compass}));
}
@Override
public void redo() throws CannotRedoException {
super.redo();
compass.setNorthDirection(newNorthDirection);
selectAndShowItems(Arrays.asList(new Compass [] {compass}));
}
@Override
public String getPresentationName() {
return preferences.getLocalizedString(
PlanController.class, "undoCompassRotationName");
}
};
this.undoSupport.postEdit(undoableEdit);
}
}
/**
* Post to undo support a size change on <code>compass</code>.
*/
private void postCompassResize(final Compass compass,
final float oldDiameter) {
final float newDiameter = compass.getDiameter();
if (newDiameter != oldDiameter) {
UndoableEdit undoableEdit = new AbstractUndoableEdit() {
@Override
public void undo() throws CannotUndoException {
super.undo();
compass.setDiameter(oldDiameter);
selectAndShowItems(Arrays.asList(new Compass [] {compass}));
}
@Override
public void redo() throws CannotRedoException {
super.redo();
compass.setDiameter(newDiameter);
selectAndShowItems(Arrays.asList(new Compass [] {compass}));
}
@Override
public String getPresentationName() {
return preferences.getLocalizedString(
PlanController.class, "undoCompassResizeName");
}
};
this.undoSupport.postEdit(undoableEdit);
}
}
/**
* Returns the points of a general path which contains only one path.
*/
private float [][] getPathPoints(GeneralPath path,
boolean removeAlignedPoints) {
List<float []> pathPoints = new ArrayList<float[]>();
float [] previousPathPoint = null;
for (PathIterator it = path.getPathIterator(null); !it.isDone(); ) {
float [] pathPoint = new float[2];
if (it.currentSegment(pathPoint) != PathIterator.SEG_CLOSE
&& (previousPathPoint == null
|| !Arrays.equals(pathPoint, previousPathPoint))) {
boolean replacePoint = false;
if (removeAlignedPoints
&& pathPoints.size() > 1) {
// Check if pathPoint is aligned with the last line added to pathPoints
float [] lastLineStartPoint = pathPoints.get(pathPoints.size() - 2);
float [] lastLineEndPoint = previousPathPoint;
replacePoint = Line2D.ptLineDistSq(lastLineStartPoint [0], lastLineStartPoint [1],
lastLineEndPoint [0], lastLineEndPoint [1],
pathPoint [0], pathPoint [1]) < 0.0001;
}
if (replacePoint) {
pathPoints.set(pathPoints.size() - 1, pathPoint);
} else {
pathPoints.add(pathPoint);
}
previousPathPoint = pathPoint;
}
it.next();
}
// Remove last point if it's equal to first point
if (pathPoints.size() > 1
&& Arrays.equals(pathPoints.get(0), pathPoints.get(pathPoints.size() - 1))) {
pathPoints.remove(pathPoints.size() - 1);
}
return pathPoints.toArray(new float [pathPoints.size()][]);
}
/**
* Returns the list of closed paths that may define rooms from
* the current set of home walls.
*/
private List<GeneralPath> getRoomPathsFromWalls() {
if (this.roomPathsCache == null) {
// Iterate over all the paths the walls area contains
Area wallsArea = getWallsArea();
List<GeneralPath> roomPaths = getAreaPaths(wallsArea);
Area insideWallsArea = new Area(wallsArea);
for (GeneralPath roomPath : roomPaths) {
insideWallsArea.add(new Area(roomPath));
}
this.roomPathsCache = roomPaths;
this.insideWallsAreaCache = insideWallsArea;
}
return this.roomPathsCache;
}
/**
* Returns the paths described by the given <code>area</code>.
*/
private List<GeneralPath> getAreaPaths(Area area) {
List<GeneralPath> roomPaths = new ArrayList<GeneralPath>();
GeneralPath roomPath = new GeneralPath();
for (PathIterator it = area.getPathIterator(null, 0.5f); !it.isDone(); ) {
float [] roomPoint = new float[2];
switch (it.currentSegment(roomPoint)) {
case PathIterator.SEG_MOVETO :
roomPath.moveTo(roomPoint [0], roomPoint [1]);
break;
case PathIterator.SEG_LINETO :
roomPath.lineTo(roomPoint [0], roomPoint [1]);
break;
case PathIterator.SEG_CLOSE :
roomPath.closePath();
roomPaths.add(roomPath);
roomPath = new GeneralPath();
break;
}
it.next();
}
return roomPaths;
}
/**
* Returns the area that includes walls and inside walls area.
*/
private Area getInsideWallsArea() {
if (this.insideWallsAreaCache == null) {
getRoomPathsFromWalls();
}
return this.insideWallsAreaCache;
}
/**
* Returns the area covered by walls.
*/
private Area getWallsArea() {
if (this.wallsAreaCache == null) {
// Compute walls area
Area wallsArea = new Area();
Level selectedLevel = this.home.getSelectedLevel();
for (Wall wall : home.getWalls()) {
if (wall.isAtLevel(selectedLevel)) {
wallsArea.add(new Area(getPath(wall.getPoints())));
}
}
this.wallsAreaCache = wallsArea;
}
return this.wallsAreaCache;
}
/**
* Returns the shape matching the coordinates in <code>points</code> array.
*/
private GeneralPath getPath(float [][] points) {
GeneralPath path = new GeneralPath();
path.moveTo(points [0][0], points [0][1]);
for (int i = 1; i < points.length; i++) {
path.lineTo(points [i][0], points [i][1]);
}
path.closePath();
return path;
}
/**
* Returns the path matching a given area.
*/
private GeneralPath getPath(Area area) {
GeneralPath path = new GeneralPath();
float [] point = new float [2];
for (PathIterator it = area.getPathIterator(null, 0.5f); !it.isDone(); ) {
switch (it.currentSegment(point)) {
case PathIterator.SEG_MOVETO :
path.moveTo(point [0], point [1]);
break;
case PathIterator.SEG_LINETO :
path.lineTo(point [0], point [1]);
break;
}
it.next();
}
return path;
}
/**
* Selects the level of the first elevatable item in the current selection
* if no selected item is visible at the selected level.
*/
private void selectLevelFromSelectedItems() {
Level selectedLevel = this.home.getSelectedLevel();
List<Selectable> selectedItems = this.home.getSelectedItems();
for (Object item : selectedItems) {
if (item instanceof Elevatable
&& ((Elevatable)item).isAtLevel(selectedLevel)) {
return;
}
}
for (Object item : selectedItems) {
if (item instanceof Elevatable) {
setSelectedLevel(((Elevatable)item).getLevel());
break;
}
}
}
/**
* Stores the size of a resized piece of furniture.
*/
private static class ResizedPieceOfFurniture {
private final HomePieceOfFurniture piece;
private final float x;
private final float y;
private final float width;
private final float depth;
private final float height;
private final boolean doorOrWindowBoundToWall;
private final float [] groupFurnitureX;
private final float [] groupFurnitureY;
private final float [] groupFurnitureWidth;
private final float [] groupFurnitureDepth;
private final float [] groupFurnitureHeight;
public ResizedPieceOfFurniture(HomePieceOfFurniture piece) {
this.piece = piece;
this.x = piece.getX();
this.y = piece.getY();
this.width = piece.getWidth();
this.depth = piece.getDepth();
this.height = piece.getHeight();
this.doorOrWindowBoundToWall = piece instanceof HomeDoorOrWindow
&& ((HomeDoorOrWindow)piece).isBoundToWall();
if (piece instanceof HomeFurnitureGroup) {
List<HomePieceOfFurniture> groupFurniture = getGroupFurniture((HomeFurnitureGroup)piece);
this.groupFurnitureX = new float [groupFurniture.size()];
this.groupFurnitureY = new float [groupFurniture.size()];
this.groupFurnitureWidth = new float [groupFurniture.size()];
this.groupFurnitureDepth = new float [groupFurniture.size()];
this.groupFurnitureHeight = new float [groupFurniture.size()];
for (int i = 0; i < groupFurniture.size(); i++) {
HomePieceOfFurniture groupPiece = groupFurniture.get(i);
this.groupFurnitureX [i] = groupPiece.getX();
this.groupFurnitureY [i] = groupPiece.getY();
this.groupFurnitureWidth [i] = groupPiece.getWidth();
this.groupFurnitureDepth [i] = groupPiece.getDepth();
this.groupFurnitureHeight [i] = groupPiece.getHeight();
}
} else {
this.groupFurnitureX = null;
this.groupFurnitureY = null;
this.groupFurnitureWidth = null;
this.groupFurnitureDepth = null;
this.groupFurnitureHeight = null;
}
}
public HomePieceOfFurniture getPieceOfFurniture() {
return this.piece;
}
public float getWidth() {
return this.width;
}
public float getDepth() {
return this.depth;
}
public float getHeight() {
return this.height;
}
public boolean isDoorOrWindowBoundToWall() {
return this.doorOrWindowBoundToWall;
}
public void reset() {
this.piece.setX(this.x);
this.piece.setY(this.y);
this.piece.setWidth(this.width);
this.piece.setDepth(this.depth);
this.piece.setHeight(this.height);
if (this.piece instanceof HomeDoorOrWindow) {
((HomeDoorOrWindow)this.piece).setBoundToWall(this.doorOrWindowBoundToWall);
}
if (this.piece instanceof HomeFurnitureGroup) {
List<HomePieceOfFurniture> groupFurniture = getGroupFurniture((HomeFurnitureGroup)this.piece);
for (int i = 0; i < groupFurniture.size(); i++) {
HomePieceOfFurniture groupPiece = groupFurniture.get(i);
if (this.piece.isResizable()) {
// Restore group furniture location and size because resizing a group isn't reversible
groupPiece.setX(this.groupFurnitureX [i]);
groupPiece.setY(this.groupFurnitureY [i]);
groupPiece.setWidth(this.groupFurnitureWidth [i]);
groupPiece.setDepth(this.groupFurnitureDepth [i]);
groupPiece.setHeight(this.groupFurnitureHeight [i]);
}
}
}
}
/**
* Returns all the children of the given <code>furnitureGroup</code>.
*/
private List<HomePieceOfFurniture> getGroupFurniture(HomeFurnitureGroup furnitureGroup) {
List<HomePieceOfFurniture> pieces = new ArrayList<HomePieceOfFurniture>();
for (HomePieceOfFurniture piece : furnitureGroup.getFurniture()) {
pieces.add(piece);
if (piece instanceof HomeFurnitureGroup) {
pieces.addAll(getGroupFurniture((HomeFurnitureGroup)piece));
}
}
return pieces;
}
}
/**
* Stores the walls at start and at end of a given wall. This data are useful
* to add a collection of walls after an undo/redo delete operation.
*/
private static final class JoinedWall {
private final Wall wall;
private final Wall wallAtStart;
private final Wall wallAtEnd;
private final Level level;
private final boolean joinedAtStartOfWallAtStart;
private final boolean joinedAtEndOfWallAtStart;
private final boolean joinedAtStartOfWallAtEnd;
private final boolean joinedAtEndOfWallAtEnd;
public JoinedWall(Wall wall) {
this.wall = wall;
this.level = wall.getLevel();
this.wallAtStart = wall.getWallAtStart();
this.joinedAtEndOfWallAtStart =
this.wallAtStart != null
&& this.wallAtStart.getWallAtEnd() == wall;
this.joinedAtStartOfWallAtStart =
this.wallAtStart != null
&& this.wallAtStart.getWallAtStart() == wall;
this.wallAtEnd = wall.getWallAtEnd();
this.joinedAtEndOfWallAtEnd =
this.wallAtEnd != null
&& wallAtEnd.getWallAtEnd() == wall;
this.joinedAtStartOfWallAtEnd =
this.wallAtEnd != null
&& wallAtEnd.getWallAtStart() == wall;
}
public Wall getWall() {
return this.wall;
}
public Level getLevel() {
return this.level;
}
public Wall getWallAtEnd() {
return this.wallAtEnd;
}
public Wall getWallAtStart() {
return this.wallAtStart;
}
public boolean isJoinedAtEndOfWallAtStart() {
return this.joinedAtEndOfWallAtStart;
}
public boolean isJoinedAtStartOfWallAtStart() {
return this.joinedAtStartOfWallAtStart;
}
public boolean isJoinedAtEndOfWallAtEnd() {
return this.joinedAtEndOfWallAtEnd;
}
public boolean isJoinedAtStartOfWallAtEnd() {
return this.joinedAtStartOfWallAtEnd;
}
/**
* A helper method that builds an array of <code>JoinedWall</code> objects
* for a given list of walls.
*/
public static JoinedWall [] getJoinedWalls(List<Wall> walls) {
JoinedWall [] joinedWalls = new JoinedWall [walls.size()];
for (int i = 0; i < joinedWalls.length; i++) {
joinedWalls [i] = new JoinedWall(walls.get(i));
}
return joinedWalls;
}
/**
* A helper method that builds a list of <code>Wall</code> objects
* for a given array of <code>JoinedWall</code> objects.
*/
public static List<Wall> getWalls(JoinedWall [] joinedWalls) {
Wall [] walls = new Wall [joinedWalls.length];
for (int i = 0; i < joinedWalls.length; i++) {
walls [i] = joinedWalls [i].getWall();
}
return Arrays.asList(walls);
}
}
/**
* A point which coordinates are computed with an angle magnetism algorithm.
*/
private static class PointWithAngleMagnetism {
private static final int STEP_COUNT = 24; // 15 degrees step
private float x;
private float y;
private float angle;
/**
* Create a point that applies angle magnetism to point (<code>x</code>,
* <code>y</code>). Point end coordinates may be different from
* x or y, to match the closest point belonging to one of the radius of a
* circle centered at (<code>xStart</code>, <code>yStart</code>), each
* radius being a multiple of 15 degrees. The length of the line joining
* (<code>xStart</code>, <code>yStart</code>) to the computed point is
* approximated depending on the current <code>unit</code> and scale.
*/
public PointWithAngleMagnetism(float xStart, float yStart, float x, float y,
LengthUnit unit, float maxLengthDelta) {
this.x = x;
this.y = y;
if (xStart == x) {
// Apply magnetism to the length of the line joining start point to magnetized point
float magnetizedLength = unit.getMagnetizedLength(Math.abs(yStart - y), maxLengthDelta);
this.y = yStart + (float)(magnetizedLength * Math.signum(y - yStart));
} else if (yStart == y) {
// Apply magnetism to the length of the line joining start point to magnetized point
float magnetizedLength = unit.getMagnetizedLength(Math.abs(xStart - x), maxLengthDelta);
this.x = xStart + (float)(magnetizedLength * Math.signum(x - xStart));
} else { // xStart != x && yStart != y
double angleStep = 2 * Math.PI / STEP_COUNT;
// Caution : pixel coordinate space is indirect !
double angle = Math.atan2(yStart - y, x - xStart);
// Compute previous angle closest to a step angle (multiple of angleStep)
double previousStepAngle = Math.floor(angle / angleStep) * angleStep;
double angle1;
double tanAngle1;
double angle2;
double tanAngle2;
// Compute the tan of previousStepAngle and the next step angle
if (Math.tan(angle) > 0) {
angle1 = previousStepAngle;
tanAngle1 = Math.tan(previousStepAngle);
angle2 = previousStepAngle + angleStep;
tanAngle2 = Math.tan(previousStepAngle + angleStep);
} else {
// If slope is negative inverse the order of the two angles
angle1 = previousStepAngle + angleStep;
tanAngle1 = Math.tan(previousStepAngle + angleStep);
angle2 = previousStepAngle;
tanAngle2 = Math.tan(previousStepAngle);
}
// Search in the first quarter of the trigonometric circle,
// the point (xEnd1,yEnd1) or (xEnd2,yEnd2) closest to point
// (xEnd,yEnd) that belongs to angle 1 or angle 2 radius
double firstQuarterTanAngle1 = Math.abs(tanAngle1);
double firstQuarterTanAngle2 = Math.abs(tanAngle2);
float xEnd1 = Math.abs(xStart - x);
float yEnd2 = Math.abs(yStart - y);
float xEnd2 = 0;
// If angle 2 is greater than 0 rad
if (firstQuarterTanAngle2 > 1E-10) {
// Compute the abscissa of point 2 that belongs to angle 1 radius at
// y2 ordinate
xEnd2 = (float)(yEnd2 / firstQuarterTanAngle2);
}
float yEnd1 = 0;
// If angle 1 is smaller than PI / 2 rad
if (firstQuarterTanAngle1 < 1E10) {
// Compute the ordinate of point 1 that belongs to angle 1 radius at
// x1 abscissa
yEnd1 = (float)(xEnd1 * firstQuarterTanAngle1);
}
// Apply magnetism to the smallest distance
double magnetismAngle;
if (Math.abs(xEnd2 - xEnd1) < Math.abs(yEnd1 - yEnd2)) {
magnetismAngle = angle2;
this.x = xStart + (float)((yStart - y) / tanAngle2);
} else {
magnetismAngle = angle1;
this.y = yStart - (float)((x - xStart) * tanAngle1);
}
// Apply magnetism to the length of the line joining start point
// to magnetized point
float magnetizedLength = unit.getMagnetizedLength((float)Point2D.distance(xStart, yStart,
this.x, this.y), maxLengthDelta);
this.x = xStart + (float)(magnetizedLength * Math.cos(magnetismAngle));
this.y = yStart - (float)(magnetizedLength * Math.sin(magnetismAngle));
this.angle = (float)magnetismAngle;
}
}
/**
* Returns the abscissa of end point computed with magnetism.
*/
public float getX() {
return this.x;
}
/**
* Sets the abscissa of end point computed with magnetism
*/
protected void setX(float x) {
this.x = x;
}
/**
* Returns the ordinate of end point computed with magnetism.
*/
public float getY() {
return this.y;
}
/**
* Sets the ordinate of end point computed with magnetism.
*/
protected void setY(float y) {
this.y = y;
}
protected float getAngle() {
return this.angle;
}
}
/**
* A point with coordinates computed with angle and wall points magnetism.
*/
private class WallPointWithAngleMagnetism extends PointWithAngleMagnetism {
public WallPointWithAngleMagnetism(float x, float y) {
this(null, x, y, x, y);
}
public WallPointWithAngleMagnetism(Wall editedWall, float xWall, float yWall, float x, float y) {
super(xWall, yWall, x, y, preferences.getLengthUnit(), getView().getPixelLength());
float margin = PIXEL_MARGIN / getScale();
// Search which wall start or end point is close to (x, y)
// ignoring the start and end point of alignedWall
float deltaXToClosestWall = Float.POSITIVE_INFINITY;
float deltaYToClosestWall = Float.POSITIVE_INFINITY;
float xClosestWall = 0;
float yClosestWall = 0;
for (Wall wall : getDetectableWallsAtSelectedLevel()) {
if (wall != editedWall) {
if (Math.abs(getX() - wall.getXStart()) < margin
&& (editedWall == null
|| !equalsWallPoint(wall.getXStart(), wall.getYStart(), editedWall))) {
if (Math.abs(deltaYToClosestWall) > Math.abs(getY() - wall.getYStart())) {
xClosestWall = wall.getXStart();
deltaYToClosestWall = getY() - yClosestWall;
}
} else if (Math.abs(getX() - wall.getXEnd()) < margin
&& (editedWall == null
|| !equalsWallPoint(wall.getXEnd(), wall.getYEnd(), editedWall))) {
if (Math.abs(deltaYToClosestWall) > Math.abs(getY() - wall.getYEnd())) {
xClosestWall = wall.getXEnd();
deltaYToClosestWall = getY() - yClosestWall;
}
}
if (Math.abs(getY() - wall.getYStart()) < margin
&& (editedWall == null
|| !equalsWallPoint(wall.getXStart(), wall.getYStart(), editedWall))) {
if (Math.abs(deltaXToClosestWall) > Math.abs(getX() - wall.getXStart())) {
yClosestWall = wall.getYStart();
deltaXToClosestWall = getX() - xClosestWall;
}
} else if (Math.abs(getY() - wall.getYEnd()) < margin
&& (editedWall == null
|| !equalsWallPoint(wall.getXEnd(), wall.getYEnd(), editedWall))) {
if (Math.abs(deltaXToClosestWall) > Math.abs(getX() - wall.getXEnd())) {
yClosestWall = wall.getYEnd();
deltaXToClosestWall = getX() - xClosestWall;
}
}
}
}
if (editedWall != null) {
double alpha = -Math.tan(getAngle());
double beta = Math.abs(alpha) < 1E10
? yWall - alpha * xWall
: Double.POSITIVE_INFINITY;
if (deltaXToClosestWall != Float.POSITIVE_INFINITY && Math.abs(alpha) > 1E-10) {
float newX = (float)((yClosestWall - beta) / alpha);
if (Point2D.distanceSq(getX(), getY(), newX, yClosestWall) <= margin * margin) {
setX(newX);
setY(yClosestWall);
return;
}
}
if (deltaYToClosestWall != Float.POSITIVE_INFINITY
&& beta != Double.POSITIVE_INFINITY) {
float newY = (float)(alpha * xClosestWall + beta);
if (Point2D.distanceSq(getX(), getY(), xClosestWall, newY) <= margin * margin) {
setX(xClosestWall);
setY(newY);
}
}
} else {
if (deltaXToClosestWall != Float.POSITIVE_INFINITY) {
setY(yClosestWall);
}
if (deltaYToClosestWall != Float.POSITIVE_INFINITY) {
setX(xClosestWall);
}
}
}
/**
* Returns <code>true</code> if <code>wall</code> start or end point
* equals the point (<code>x</code>, <code>y</code>).
*/
private boolean equalsWallPoint(float x, float y, Wall wall) {
return x == wall.getXStart() && y == wall.getYStart()
|| x == wall.getXEnd() && y == wall.getYEnd();
}
}
/**
* A point with coordinates computed with angle and room points magnetism.
*/
private class RoomPointWithAngleMagnetism extends PointWithAngleMagnetism {
public RoomPointWithAngleMagnetism(float x, float y) {
this(null, -1, x, y, x, y);
}
public RoomPointWithAngleMagnetism(Room editedRoom, int editedPointIndex, float xRoom, float yRoom, float x, float y) {
super(xRoom, yRoom, x, y, preferences.getLengthUnit(), getView().getPixelLength());
float planScale = getScale();
float margin = PIXEL_MARGIN / planScale;
// Search which room points are close to (x, y)
// ignoring the start and end point of alignedRoom
float deltaXToClosestObject = Float.POSITIVE_INFINITY;
float deltaYToClosestObject = Float.POSITIVE_INFINITY;
float xClosestObject = 0;
float yClosestObject = 0;
for (Room room : getDetectableRoomsAtSelectedLevel()) {
float [][] roomPoints = room.getPoints();
for (int i = 0; i < roomPoints.length; i++) {
if (editedPointIndex == -1 || (i != editedPointIndex && roomPoints.length > 2)) {
if (Math.abs(getX() - roomPoints [i][0]) < margin
&& Math.abs(deltaYToClosestObject) > Math.abs(getY() - roomPoints [i][1])) {
xClosestObject = roomPoints [i][0];
deltaYToClosestObject = getY() - roomPoints [i][1];
}
if (Math.abs(getY() - roomPoints [i][1]) < margin
&& Math.abs(deltaXToClosestObject) > Math.abs(getX() - roomPoints [i][0])) {
yClosestObject = roomPoints [i][1];
deltaXToClosestObject = getX() - roomPoints [i][0];
}
}
}
}
// Search which wall points are close to (x, y)
for (Wall wall : getDetectableWallsAtSelectedLevel()) {
float [][] wallPoints = wall.getPoints();
// Take into account only points at start and end of the wall
wallPoints = new float [][] {wallPoints [0], wallPoints [wallPoints.length / 2 - 1],
wallPoints [wallPoints.length / 2], wallPoints [wallPoints.length - 1]};
for (int i = 0; i < wallPoints.length; i++) {
if (Math.abs(getX() - wallPoints [i][0]) < margin
&& Math.abs(deltaYToClosestObject) > Math.abs(getY() - wallPoints [i][1])) {
xClosestObject = wallPoints [i][0];
deltaYToClosestObject = getY() - wallPoints [i][1];
}
if (Math.abs(getY() - wallPoints [i][1]) < margin
&& Math.abs(deltaXToClosestObject) > Math.abs(getX() - wallPoints [i][0])) {
yClosestObject = wallPoints [i][1];
deltaXToClosestObject = getX() - wallPoints [i][0];
}
}
}
if (editedRoom != null) {
double alpha = -Math.tan(getAngle());
double beta = Math.abs(alpha) < 1E10
? yRoom - alpha * xRoom
: Double.POSITIVE_INFINITY;
if (deltaXToClosestObject != Float.POSITIVE_INFINITY && Math.abs(alpha) > 1E-10) {
float newX = (float)((yClosestObject - beta) / alpha);
if (Point2D.distanceSq(getX(), getY(), newX, yClosestObject) <= margin * margin) {
setX(newX);
setY(yClosestObject);
return;
}
}
if (deltaYToClosestObject != Float.POSITIVE_INFINITY
&& beta != Double.POSITIVE_INFINITY) {
float newY = (float)(alpha * xClosestObject + beta);
if (Point2D.distanceSq(getX(), getY(), xClosestObject, newY) <= margin * margin) {
setX(xClosestObject);
setY(newY);
}
}
} else {
if (deltaXToClosestObject != Float.POSITIVE_INFINITY) {
setY(yClosestObject);
}
if (deltaYToClosestObject != Float.POSITIVE_INFINITY) {
setX(xClosestObject);
}
}
}
}
/**
* A point which coordinates are equal to the closest point of a wall or a room.
*/
private class PointMagnetizedToClosestWallOrRoomPoint {
private float x;
private float y;
private boolean magnetized;
/**
* Creates a point that applies magnetism to point (<code>x</code>, <code>y</code>).
* If this point is close to a point of a wall corner or of a room, it will be initialiazed to its coordinates.
*/
public PointMagnetizedToClosestWallOrRoomPoint(float x, float y) {
this(null, -1, x, y);
}
public PointMagnetizedToClosestWallOrRoomPoint(Room editedRoom, int editedPointIndex, float x, float y) {
float margin = PIXEL_MARGIN / getScale();
// Find the closest wall point to (x,y)
double smallestDistance = Double.MAX_VALUE;
for (GeneralPath roomPath : getRoomPathsFromWalls()) {
smallestDistance = updateMagnetizedPoint(-1, x, y,
smallestDistance, getPathPoints(roomPath, false));
}
for (Room room : getDetectableRoomsAtSelectedLevel()) {
smallestDistance = updateMagnetizedPoint(room == editedRoom ? editedPointIndex : - 1,
x, y, smallestDistance, room.getPoints());
}
this.magnetized = smallestDistance <= margin * margin;
if (!this.magnetized) {
// Don't magnetism if closest wall point is too far
this.x = x;
this.y = y;
}
}
private double updateMagnetizedPoint(int editedPointIndex,
float x, float y,
double smallestDistance,
float [][] points) {
for (int i = 0; i < points.length; i++) {
if (i != editedPointIndex) {
double distance = Point2D.distanceSq(points [i][0], points [i][1], x, y);
if (distance < smallestDistance) {
this.x = points [i][0];
this.y = points [i][1];
smallestDistance = distance;
}
}
}
return smallestDistance;
}
/**
* Returns the abscissa of end point computed with magnetism.
*/
public float getX() {
return this.x;
}
/**
* Returns the ordinate of end point computed with magnetism.
*/
public float getY() {
return this.y;
}
public boolean isMagnetized() {
return this.magnetized;
}
}
/**
* Controller state classes super class.
*/
protected static abstract class ControllerState {
public void enter() {
}
public void exit() {
}
public abstract Mode getMode();
public void setMode(Mode mode) {
}
public boolean isModificationState() {
return false;
}
public void deleteSelection() {
}
public void escape() {
}
public void moveSelection(float dx, float dy) {
}
public void toggleMagnetism(boolean magnetismToggled) {
}
public void setDuplicationActivated(boolean duplicationActivated) {
}
public void setEditionActivated(boolean editionActivated) {
}
public void updateEditableProperty(EditableProperty editableField, Object value) {
}
public void pressMouse(float x, float y, int clickCount,
boolean shiftDown, boolean duplicationActivated) {
}
public void releaseMouse(float x, float y) {
}
public void moveMouse(float x, float y) {
}
public void zoom(float factor) {
}
}
// ControllerState subclasses
/**
* Abstract state able to manage the transition to other modes.
*/
private abstract class AbstractModeChangeState extends ControllerState {
@Override
public void setMode(Mode mode) {
if (mode == Mode.SELECTION) {
setState(getSelectionState());
} else if (mode == Mode.PANNING) {
setState(getPanningState());
} else if (mode == Mode.WALL_CREATION) {
setState(getWallCreationState());
} else if (mode == Mode.ROOM_CREATION) {
setState(getRoomCreationState());
} else if (mode == Mode.DIMENSION_LINE_CREATION) {
setState(getDimensionLineCreationState());
} else if (mode == Mode.LABEL_CREATION) {
setState(getLabelCreationState());
}
}
@Override
public void deleteSelection() {
deleteItems(home.getSelectedItems());
// Compute again feedback
moveMouse(getXLastMouseMove(), getYLastMouseMove());
}
@Override
public void moveSelection(float dx, float dy) {
moveAndShowSelectedItems(dx, dy);
// Compute again feedback
moveMouse(getXLastMouseMove(), getYLastMouseMove());
}
@Override
public void zoom(float factor) {
setScale(getScale() * factor);
}
}
/**
* Default selection state. This state manages transition to other modes,
* the deletion of selected items, and the move of selected items with arrow keys.
*/
private class SelectionState extends AbstractModeChangeState {
private final SelectionListener selectionListener = new SelectionListener() {
public void selectionChanged(SelectionEvent selectionEvent) {
List<Selectable> selectedItems = home.getSelectedItems();
getView().setResizeIndicatorVisible(selectedItems.size() == 1
&& (isItemResizable(selectedItems.get(0))
|| isItemMovable(selectedItems.get(0))));
}
};
@Override
public Mode getMode() {
return Mode.SELECTION;
}
@Override
public void enter() {
if (getView() != null) {
moveMouse(getXLastMouseMove(), getYLastMouseMove());
home.addSelectionListener(this.selectionListener);
this.selectionListener.selectionChanged(null);
}
}
@Override
public void moveMouse(float x, float y) {
if (getYawRotatedCameraAt(x, y) != null
|| getPitchRotatedCameraAt(x, y) != null) {
getView().setCursor(PlanView.CursorType.ROTATION);
} else if (getElevatedCameraAt(x, y) != null) {
getView().setCursor(PlanView.CursorType.ELEVATION);
} else if (getRoomNameAt(x, y) != null
|| getRoomAreaAt(x, y) != null
|| getResizedDimensionLineStartAt(x, y) != null
|| getResizedDimensionLineEndAt(x, y) != null
|| getWidthAndDepthResizedPieceOfFurnitureAt(x, y) != null
|| getResizedWallStartAt(x, y) != null
|| getResizedWallEndAt(x, y) != null
|| getResizedRoomAt(x, y) != null) {
getView().setCursor(PlanView.CursorType.RESIZE);
} else if (getModifiedLightPowerAt(x, y) != null) {
getView().setCursor(PlanView.CursorType.POWER);
} else if (getOffsetDimensionLineAt(x, y) != null
|| getHeightResizedPieceOfFurnitureAt(x, y) != null) {
getView().setCursor(PlanView.CursorType.HEIGHT);
} else if (getRotatedPieceOfFurnitureAt(x, y) != null) {
getView().setCursor(PlanView.CursorType.ROTATION);
} else if (getElevatedPieceOfFurnitureAt(x, y) != null) {
getView().setCursor(PlanView.CursorType.ELEVATION);
} else if (getPieceOfFurnitureNameAt(x, y) != null) {
getView().setCursor(PlanView.CursorType.RESIZE);
} else if (getRotatedCompassAt(x, y) != null) {
getView().setCursor(PlanView.CursorType.ROTATION);
} else if (getResizedCompassAt(x, y) != null) {
getView().setCursor(PlanView.CursorType.RESIZE);
} else {
// If a selected item is under cursor position
if (isItemSelectedAt(x, y)) {
getView().setCursor(PlanView.CursorType.MOVE);
} else {
getView().setCursor(PlanView.CursorType.SELECTION);
}
}
}
@Override
public void pressMouse(float x, float y, int clickCount,
boolean shiftDown, boolean duplicationActivated) {
if (clickCount == 1) {
if (getYawRotatedCameraAt(x, y) != null) {
setState(getCameraYawRotationState());
} else if (getPitchRotatedCameraAt(x, y) != null) {
setState(getCameraPitchRotationState());
} else if (getElevatedCameraAt(x, y) != null) {
setState(getCameraElevationState());
} else if (getRoomNameAt(x, y) != null) {
setState(getRoomNameOffsetState());
} else if (getRoomAreaAt(x, y) != null) {
setState(getRoomAreaOffsetState());
} else if (getResizedDimensionLineStartAt(x, y) != null
|| getResizedDimensionLineEndAt(x, y) != null) {
setState(getDimensionLineResizeState());
} else if (getWidthAndDepthResizedPieceOfFurnitureAt(x, y) != null) {
setState(getPieceOfFurnitureResizeState());
} else if (getResizedWallStartAt(x, y) != null
|| getResizedWallEndAt(x, y) != null) {
setState(getWallResizeState());
} else if (getResizedRoomAt(x, y) != null) {
setState(getRoomResizeState());
} else if (getOffsetDimensionLineAt(x, y) != null) {
setState(getDimensionLineOffsetState());
} else if (getModifiedLightPowerAt(x, y) != null) {
setState(getLightPowerModificationState());
} else if (getHeightResizedPieceOfFurnitureAt(x, y) != null) {
setState(getPieceOfFurnitureHeightState());
} else if (getRotatedPieceOfFurnitureAt(x, y) != null) {
setState(getPieceOfFurnitureRotationState());
} else if (getElevatedPieceOfFurnitureAt(x, y) != null) {
setState(getPieceOfFurnitureElevationState());
} else if (getPieceOfFurnitureNameAt(x, y) != null) {
setState(getPieceOfFurnitureNameOffsetState());
} else if (getRotatedCompassAt(x, y) != null) {
setState(getCompassRotationState());
} else if (getResizedCompassAt(x, y) != null) {
setState(getCompassResizeState());
} else {
Selectable item = getSelectableItemAt(x, y);
// If shift isn't pressed, and an item is under cursor position
if (!shiftDown && item != null) {
// Change state to SelectionMoveState
setState(getSelectionMoveState());
} else {
// Otherwise change state to RectangleSelectionState
setState(getRectangleSelectionState());
}
}
} else if (clickCount == 2) {
Selectable item = getSelectableItemAt(x, y);
// If shift isn't pressed, and an item is under cursor position
if (!shiftDown && item != null) {
// Modify selected item on a double click
if (item instanceof Wall) {
modifySelectedWalls();
} else if (item instanceof HomePieceOfFurniture) {
modifySelectedFurniture();
} else if (item instanceof Room) {
modifySelectedRooms();
} else if (item instanceof Label) {
modifySelectedLabels();
} else if (item instanceof Compass) {
modifyCompass();
} else if (item instanceof ObserverCamera) {
modifyObserverCamera();
}
}
}
}
@Override
public void exit() {
if (getView() != null) {
home.removeSelectionListener(this.selectionListener);
getView().setResizeIndicatorVisible(false);
}
}
}
/**
* Move selection state. This state manages the move of current selected items
* with mouse and the selection of one item, if mouse isn't moved while button
* is depressed. If duplication is activated during the move of the mouse,
* moved items are duplicated first.
*/
private class SelectionMoveState extends ControllerState {
private float xLastMouseMove;
private float yLastMouseMove;
private boolean mouseMoved;
private List<Selectable> oldSelection;
private List<Selectable> movedItems;
private List<Selectable> duplicatedItems;
private HomePieceOfFurniture movedPieceOfFurniture;
private float angleMovedPieceOfFurniture;
private float depthMovedPieceOfFurniture;
private float elevationMovedPieceOfFurniture;
private float xMovedPieceOfFurniture;
private float yMovedPieceOfFurniture;
private boolean movedDoorOrWindowBoundToWall;
private boolean magnetismEnabled;
private boolean duplicationActivated;
@Override
public Mode getMode() {
return Mode.SELECTION;
}
@Override
public boolean isModificationState() {
return true;
}
@Override
public void enter() {
this.xLastMouseMove = getXLastMousePress();
this.yLastMouseMove = getYLastMousePress();
this.mouseMoved = false;
List<Selectable> selectableItemsUnderCursor =
getSelectableItemsAt(getXLastMousePress(), getYLastMousePress());
this.oldSelection = home.getSelectedItems();
toggleMagnetism(wasShiftDownLastMousePress());
// If no selectable item under the cursor belongs to selection
if (Collections.disjoint(selectableItemsUnderCursor, this.oldSelection)) {
// Select only the item with highest priority under cursor position
selectItem(getSelectableItemAt(getXLastMousePress(), getYLastMousePress()));
}
List<Selectable> selectedItems = home.getSelectedItems();
this.movedItems = new ArrayList<Selectable>(selectedItems.size());
for (Selectable item : selectedItems) {
if (isItemMovable(item)) {
this.movedItems.add(item);
}
}
if (this.movedItems.size() == 1
&& this.movedItems.get(0) instanceof HomePieceOfFurniture) {
this.movedPieceOfFurniture = (HomePieceOfFurniture)this.movedItems.get(0);
this.xMovedPieceOfFurniture = this.movedPieceOfFurniture.getX();
this.yMovedPieceOfFurniture = this.movedPieceOfFurniture.getY();
this.angleMovedPieceOfFurniture = this.movedPieceOfFurniture.getAngle();
this.depthMovedPieceOfFurniture = this.movedPieceOfFurniture.getDepth();
this.elevationMovedPieceOfFurniture = this.movedPieceOfFurniture.getElevation();
this.movedDoorOrWindowBoundToWall = this.movedPieceOfFurniture instanceof HomeDoorOrWindow
&& ((HomeDoorOrWindow)this.movedPieceOfFurniture).isBoundToWall();
}
this.duplicatedItems = null;
this.duplicationActivated = wasDuplicationActivatedLastMousePress();
getView().setCursor(PlanView.CursorType.MOVE);
}
@Override
public void moveMouse(float x, float y) {
if (!this.mouseMoved) {
toggleDuplication(this.duplicationActivated);
}
if (this.movedPieceOfFurniture != null) {
// Reset to default piece values and adjust piece of furniture location, angle and depth
this.movedPieceOfFurniture.setX(this.xMovedPieceOfFurniture);
this.movedPieceOfFurniture.setY(this.yMovedPieceOfFurniture);
this.movedPieceOfFurniture.setAngle(this.angleMovedPieceOfFurniture);
if (this.movedPieceOfFurniture.isResizable()
&& isItemResizable(this.movedPieceOfFurniture)) {
this.movedPieceOfFurniture.setDepth(this.depthMovedPieceOfFurniture);
}
this.movedPieceOfFurniture.setElevation(this.elevationMovedPieceOfFurniture);
this.movedPieceOfFurniture.move(x - getXLastMousePress(), y - getYLastMousePress());
if (this.magnetismEnabled) {
Wall magnetWall = adjustPieceOfFurnitureOnWallAt(this.movedPieceOfFurniture, x, y, false);
if (adjustPieceOfFurnitureElevation(this.movedPieceOfFurniture) == null) {
adjustPieceOfFurnitureSideBySideAt(this.movedPieceOfFurniture, false, magnetWall != null);
}
if (magnetWall != null) {
getView().setDimensionLinesFeedback(getDimensionLinesAlongWall(this.movedPieceOfFurniture, magnetWall));
} else {
getView().setDimensionLinesFeedback(null);
}
}
} else {
moveItems(this.movedItems, x - this.xLastMouseMove, y - this.yLastMouseMove);
}
if (!this.mouseMoved) {
selectItems(this.movedItems);
}
getView().makePointVisible(x, y);
this.xLastMouseMove = x;
this.yLastMouseMove = y;
this.mouseMoved = true;
}
@Override
public void releaseMouse(float x, float y) {
if (this.mouseMoved) {
// Post in undo support a move or duplicate operation if selection isn't a camera
if (this.movedItems.size() > 0
&& !(this.movedItems.get(0) instanceof Camera)) {
if (this.duplicatedItems != null) {
postItemsDuplication(this.movedItems, this.duplicatedItems);
} else if (this.movedPieceOfFurniture != null) {
postPieceOfFurnitureMove(this.movedPieceOfFurniture,
this.movedPieceOfFurniture.getX() - this.xMovedPieceOfFurniture,
this.movedPieceOfFurniture.getY() - this.yMovedPieceOfFurniture,
this.angleMovedPieceOfFurniture,
this.depthMovedPieceOfFurniture,
this.elevationMovedPieceOfFurniture,
this.movedDoorOrWindowBoundToWall);
} else {
postItemsMove(this.movedItems, this.oldSelection,
this.xLastMouseMove - getXLastMousePress(),
this.yLastMouseMove - getYLastMousePress());
}
}
} else {
// If mouse didn't move, select only the item at (x,y)
Selectable itemUnderCursor = getSelectableItemAt(x, y);
if (itemUnderCursor != null) {
// Select only the item under cursor position
selectItem(itemUnderCursor);
}
}
// Change the state to SelectionState
setState(getSelectionState());
}
@Override
public void toggleMagnetism(boolean magnetismToggled) {
// Compute active magnetism
this.magnetismEnabled = preferences.isMagnetismEnabled()
^ magnetismToggled;
// Compute again piece move as if mouse moved
if (this.movedPieceOfFurniture != null) {
moveMouse(getXLastMouseMove(), getYLastMouseMove());
if (!this.magnetismEnabled) {
getView().deleteFeedback();
}
}
}
@Override
public void escape() {
if (this.mouseMoved) {
if (this.duplicatedItems != null) {
// Delete moved items and select original items
doDeleteItems(this.movedItems);
selectItems(this.duplicatedItems);
} else {
// Put items back to their initial location
if (this.movedPieceOfFurniture != null) {
this.movedPieceOfFurniture.setX(this.xMovedPieceOfFurniture);
this.movedPieceOfFurniture.setY(this.yMovedPieceOfFurniture);
this.movedPieceOfFurniture.setAngle(this.angleMovedPieceOfFurniture);
if (this.movedPieceOfFurniture.isResizable()
&& isItemResizable(this.movedPieceOfFurniture)) {
this.movedPieceOfFurniture.setDepth(this.depthMovedPieceOfFurniture);
}
this.movedPieceOfFurniture.setElevation(this.elevationMovedPieceOfFurniture);
if (this.movedPieceOfFurniture instanceof HomeDoorOrWindow) {
((HomeDoorOrWindow)this.movedPieceOfFurniture).setBoundToWall(
this.movedDoorOrWindowBoundToWall);
}
} else {
moveItems(this.movedItems,
getXLastMousePress() - this.xLastMouseMove,
getYLastMousePress() - this.yLastMouseMove);
}
}
}
// Change the state to SelectionState
setState(getSelectionState());
}
@Override
public void setDuplicationActivated(boolean duplicationActivated) {
if (this.mouseMoved) {
toggleDuplication(duplicationActivated);
}
this.duplicationActivated = duplicationActivated;
}
private void toggleDuplication(boolean duplicationActivated) {
if (this.movedItems.size() > 1
|| (this.movedItems.size() == 1
&& !(this.movedItems.get(0) instanceof Camera)
&& !(this.movedItems.get(0) instanceof Compass))) {
if (duplicationActivated
&& this.duplicatedItems == null) {
// Duplicate original items and add them to home
this.duplicatedItems = this.movedItems;
this.movedItems = Home.duplicate(this.movedItems);
for (Selectable item : this.movedItems) {
if (item instanceof Wall) {
home.addWall((Wall)item);
} else if (item instanceof Room) {
home.addRoom((Room)item);
} else if (item instanceof DimensionLine) {
home.addDimensionLine((DimensionLine)item);
} else if (item instanceof HomePieceOfFurniture) {
home.addPieceOfFurniture((HomePieceOfFurniture)item);
} else if (item instanceof Label) {
home.addLabel((Label)item);
}
}
// Put original items back to their initial location
if (this.movedPieceOfFurniture != null) {
this.movedPieceOfFurniture.setX(this.xMovedPieceOfFurniture);
this.movedPieceOfFurniture.setY(this.yMovedPieceOfFurniture);
this.movedPieceOfFurniture.setAngle(this.angleMovedPieceOfFurniture);
if (this.movedPieceOfFurniture.isResizable()
&& isItemResizable(this.movedPieceOfFurniture)) {
this.movedPieceOfFurniture.setDepth(this.depthMovedPieceOfFurniture);
}
this.movedPieceOfFurniture.setElevation(this.elevationMovedPieceOfFurniture);
this.movedPieceOfFurniture = (HomePieceOfFurniture)this.movedItems.get(0);
} else {
moveItems(this.duplicatedItems,
getXLastMousePress() - this.xLastMouseMove,
getYLastMousePress() - this.yLastMouseMove);
}
getView().setCursor(PlanView.CursorType.DUPLICATION);
} else if (!duplicationActivated
&& this.duplicatedItems != null) {
// Delete moved items
doDeleteItems(this.movedItems);
// Move original items to the current location
moveItems(this.duplicatedItems,
this.xLastMouseMove - getXLastMousePress(),
this.yLastMouseMove - getYLastMousePress());
this.movedItems = this.duplicatedItems;
this.duplicatedItems = null;
if (this.movedPieceOfFurniture != null) {
this.movedPieceOfFurniture = (HomePieceOfFurniture)this.movedItems.get(0);
}
getView().setCursor(PlanView.CursorType.MOVE);
}
selectItems(this.movedItems);
}
}
@Override
public void exit() {
getView().deleteFeedback();
this.movedItems = null;
this.duplicatedItems = null;
this.movedPieceOfFurniture = null;
}
}
/**
* Selection with rectangle state. This state manages selection when mouse
* press is done outside of an item or when mouse press is done with shift key
* down.
*/
private class RectangleSelectionState extends ControllerState {
private List<Selectable> selectedItemsMousePressed;
private boolean mouseMoved;
@Override
public Mode getMode() {
return Mode.SELECTION;
}
@Override
public boolean isModificationState() {
return true;
}
@Override
public void enter() {
Selectable itemUnderCursor =
getSelectableItemAt(getXLastMousePress(), getYLastMousePress());
// If no item under cursor and shift wasn't down, deselect all
if (itemUnderCursor == null && !wasShiftDownLastMousePress()) {
deselectAll();
}
// Store current selection
this.selectedItemsMousePressed =
new ArrayList<Selectable>(home.getSelectedItems());
this.mouseMoved = false;
}
@Override
public void moveMouse(float x, float y) {
this.mouseMoved = true;
updateSelectedItems(getXLastMousePress(), getYLastMousePress(),
x, y, this.selectedItemsMousePressed);
// Update rectangle feedback
PlanView planView = getView();
planView.setRectangleFeedback(
getXLastMousePress(), getYLastMousePress(), x, y);
planView.makePointVisible(x, y);
}
@Override
public void releaseMouse(float x, float y) {
// If cursor didn't move
if (!this.mouseMoved) {
Selectable itemUnderCursor = getSelectableItemAt(x, y);
// Toggle selection of the item under cursor
if (itemUnderCursor != null) {
if (this.selectedItemsMousePressed.contains(itemUnderCursor)) {
this.selectedItemsMousePressed.remove(itemUnderCursor);
} else {
// Remove any camera from current selection
for (Iterator<Selectable> iter = this.selectedItemsMousePressed.iterator(); iter.hasNext();) {
if (iter.next() instanceof Camera) {
iter.remove();
}
}
// Let the camera belong to selection only if no item are selected
if (!(itemUnderCursor instanceof Camera)
|| this.selectedItemsMousePressed.size() == 0) {
this.selectedItemsMousePressed.add(itemUnderCursor);
}
}
selectItems(this.selectedItemsMousePressed);
}
}
// Change state to SelectionState
setState(getSelectionState());
}
@Override
public void escape() {
setState(getSelectionState());
}
@Override
public void exit() {
getView().deleteFeedback();
this.selectedItemsMousePressed = null;
}
/**
* Updates selection from <code>selectedItemsMousePressed</code> and the
* items that intersects the rectangle at coordinates (<code>x0</code>,
* <code>y0</code>) and (<code>x1</code>, <code>y1</code>).
*/
private void updateSelectedItems(float x0, float y0,
float x1, float y1,
List<Selectable> selectedItemsMousePressed) {
List<Selectable> selectedItems;
boolean shiftDown = wasShiftDownLastMousePress();
if (shiftDown) {
selectedItems = new ArrayList<Selectable>(selectedItemsMousePressed);
} else {
selectedItems = new ArrayList<Selectable>();
}
// For all the items that intersect with rectangle
for (Selectable item : getSelectableItemsIntersectingRectangle(x0, y0, x1, y1)) {
// Don't let the camera be able to be selected with a rectangle
if (!(item instanceof Camera)) {
// If shift was down at mouse press
if (shiftDown) {
// Toggle selection of item
if (selectedItemsMousePressed.contains(item)) {
selectedItems.remove(item);
} else {
selectedItems.add(item);
}
} else if (!selectedItemsMousePressed.contains(item)) {
// Else select the wall
selectedItems.add(item);
}
}
}
// Update selection
selectItems(selectedItems);
}
}
/**
* Panning state.
*/
private class PanningState extends ControllerState {
private Integer xLastMouseMove;
private Integer yLastMouseMove;
@Override
public Mode getMode() {
return Mode.PANNING;
}
@Override
public void setMode(Mode mode) {
if (mode == Mode.SELECTION) {
setState(getSelectionState());
} else if (mode == Mode.WALL_CREATION) {
setState(getWallCreationState());
} else if (mode == Mode.ROOM_CREATION) {
setState(getRoomCreationState());
} else if (mode == Mode.DIMENSION_LINE_CREATION) {
setState(getDimensionLineCreationState());
} else if (mode == Mode.LABEL_CREATION) {
setState(getLabelCreationState());
}
}
@Override
public void enter() {
getView().setCursor(PlanView.CursorType.PANNING);
}
@Override
public void moveSelection(float dx, float dy) {
getView().moveView(dx * 10, dy * 10);
}
@Override
public void pressMouse(float x, float y, int clickCount, boolean shiftDown, boolean duplicationActivated) {
if (clickCount == 1) {
this.xLastMouseMove = getView().convertXModelToScreen(x);
this.yLastMouseMove = getView().convertYModelToScreen(y);
} else {
this.xLastMouseMove = null;
this.yLastMouseMove = null;
}
}
@Override
public void moveMouse(float x, float y) {
if (this.xLastMouseMove != null) {
int newX = getView().convertXModelToScreen(x);
int newY = getView().convertYModelToScreen(y);
getView().moveView((this.xLastMouseMove - newX) / getScale(), (this.yLastMouseMove - newY) / getScale());
this.xLastMouseMove = newX;
this.yLastMouseMove = newY;
}
}
@Override
public void releaseMouse(float x, float y) {
this.xLastMouseMove = null;
}
@Override
public void escape() {
this.xLastMouseMove = null;
}
@Override
public void zoom(float factor) {
setScale(getScale() * factor);
}
}
/**
* Drag and drop state. This state manages the dragging of items
* transfered from outside of plan view with the mouse.
*/
private class DragAndDropState extends ControllerState {
private float xLastMouseMove;
private float yLastMouseMove;
private HomePieceOfFurniture draggedPieceOfFurniture;
private float xDraggedPieceOfFurniture;
private float yDraggedPieceOfFurniture;
private float angleDraggedPieceOfFurniture;
private float depthDraggedPieceOfFurniture;
private float elevationDraggedPieceOfFurniture;
@Override
public Mode getMode() {
return Mode.SELECTION;
}
@Override
public boolean isModificationState() {
// This state is used before a modification is performed
return false;
}
@Override
public void enter() {
this.xLastMouseMove = 0;
this.yLastMouseMove = 0;
getView().setDraggedItemsFeedback(draggedItems);
if (draggedItems.size() == 1
&& draggedItems.get(0) instanceof HomePieceOfFurniture) {
this.draggedPieceOfFurniture = (HomePieceOfFurniture)draggedItems.get(0);
this.xDraggedPieceOfFurniture = this.draggedPieceOfFurniture.getX();
this.yDraggedPieceOfFurniture = this.draggedPieceOfFurniture.getY();
this.angleDraggedPieceOfFurniture = this.draggedPieceOfFurniture.getAngle();
this.depthDraggedPieceOfFurniture = this.draggedPieceOfFurniture.getDepth();
this.elevationDraggedPieceOfFurniture = this.draggedPieceOfFurniture.getElevation();
}
}
@Override
public void moveMouse(float x, float y) {
List<Selectable> draggedItemsFeedback = new ArrayList<Selectable>(draggedItems);
// Update in plan view the location of the feedback of the dragged items
moveItems(draggedItems, x - this.xLastMouseMove, y - this.yLastMouseMove);
if (this.draggedPieceOfFurniture != null
&& preferences.isMagnetismEnabled()) {
// Reset to default piece values and adjust piece of furniture location, angle and depth
this.draggedPieceOfFurniture.setX(this.xDraggedPieceOfFurniture);
this.draggedPieceOfFurniture.setY(this.yDraggedPieceOfFurniture);
this.draggedPieceOfFurniture.setAngle(this.angleDraggedPieceOfFurniture);
if (this.draggedPieceOfFurniture.isResizable()) {
this.draggedPieceOfFurniture.setDepth(this.depthDraggedPieceOfFurniture);
}
this.draggedPieceOfFurniture.setElevation(this.elevationDraggedPieceOfFurniture);
this.draggedPieceOfFurniture.move(x, y);
Wall magnetWall = adjustPieceOfFurnitureOnWallAt(this.draggedPieceOfFurniture, x, y, true);
if (adjustPieceOfFurnitureElevation(this.draggedPieceOfFurniture) == null) {
adjustPieceOfFurnitureSideBySideAt(this.draggedPieceOfFurniture, magnetWall == null, magnetWall != null);
}
if (magnetWall != null) {
getView().setDimensionLinesFeedback(getDimensionLinesAlongWall(this.draggedPieceOfFurniture, magnetWall));
} else {
getView().setDimensionLinesFeedback(null);
}
}
getView().setDraggedItemsFeedback(draggedItemsFeedback);
this.xLastMouseMove = x;
this.yLastMouseMove = y;
}
@Override
public void exit() {
this.draggedPieceOfFurniture = null;
getView().deleteFeedback();
}
}
/**
* Wall creation state. This state manages transition to other modes,
* and initial wall creation.
*/
private class WallCreationState extends AbstractModeChangeState {
private boolean magnetismEnabled;
@Override
public Mode getMode() {
return Mode.WALL_CREATION;
}
@Override
public void enter() {
getView().setCursor(PlanView.CursorType.DRAW);
toggleMagnetism(wasShiftDownLastMousePress());
}
@Override
public void moveMouse(float x, float y) {
if (this.magnetismEnabled) {
WallPointWithAngleMagnetism point = new WallPointWithAngleMagnetism(x, y);
x = point.getX();
y = point.getY();
}
getView().setAlignmentFeedback(Wall.class, null, x, y, false);
}
@Override
public void pressMouse(float x, float y, int clickCount,
boolean shiftDown, boolean duplicationActivated) {
// Change state to WallDrawingState
setState(getWallDrawingState());
}
@Override
public void setEditionActivated(boolean editionActivated) {
if (editionActivated) {
setState(getWallDrawingState());
PlanController.this.setEditionActivated(editionActivated);
}
}
@Override
public void toggleMagnetism(boolean magnetismToggled) {
// Compute active magnetism
this.magnetismEnabled = preferences.isMagnetismEnabled()
^ magnetismToggled;
moveMouse(getXLastMouseMove(), getYLastMouseMove());
}
@Override
public void exit() {
getView().deleteFeedback();
}
}
/**
* Wall modification state.
*/
private abstract class AbstractWallState extends ControllerState {
private String wallLengthToolTipFeedback;
private String wallAngleToolTipFeedback;
private String wallArcExtentToolTipFeedback;
private String wallThicknessToolTipFeedback;
@Override
public void enter() {
this.wallLengthToolTipFeedback = preferences.getLocalizedString(
PlanController.class, "wallLengthToolTipFeedback");
this.wallAngleToolTipFeedback = preferences.getLocalizedString(
PlanController.class, "wallAngleToolTipFeedback");
this.wallArcExtentToolTipFeedback = preferences.getLocalizedString(
PlanController.class, "wallArcExtentToolTipFeedback");
this.wallThicknessToolTipFeedback = preferences.getLocalizedString(
PlanController.class, "wallThicknessToolTipFeedback");
}
protected String getToolTipFeedbackText(Wall wall, boolean ignoreArcExtent) {
Float arcExtent = wall.getArcExtent();
if (!ignoreArcExtent && arcExtent != null) {
return "<html>" + String.format(this.wallArcExtentToolTipFeedback, Math.round(Math.toDegrees(arcExtent)));
} else {
float startPointToEndPointDistance = wall.getStartPointToEndPointDistance();
return "<html>" + String.format(this.wallLengthToolTipFeedback,
preferences.getLengthUnit().getFormatWithUnit().format(startPointToEndPointDistance))
+ "<br>" + String.format(this.wallAngleToolTipFeedback, getWallAngleInDegrees(wall, startPointToEndPointDistance))
+ "<br>" + String.format(this.wallThicknessToolTipFeedback,
preferences.getLengthUnit().getFormatWithUnit().format(wall.getThickness()));
}
}
/**
* Returns wall angle in degrees.
*/
protected Integer getWallAngleInDegrees(Wall wall) {
return getWallAngleInDegrees(wall, wall.getStartPointToEndPointDistance());
}
private Integer getWallAngleInDegrees(Wall wall, float startPointToEndPointDistance) {
Wall wallAtStart = wall.getWallAtStart();
if (wallAtStart != null) {
float wallAtStartSegmentDistance = wallAtStart.getStartPointToEndPointDistance();
if (startPointToEndPointDistance != 0 && wallAtStartSegmentDistance != 0) {
// Compute the angle between the wall and its wall at start
float xWallVector = (wall.getXEnd() - wall.getXStart()) / startPointToEndPointDistance;
float yWallVector = (wall.getYEnd() - wall.getYStart()) / startPointToEndPointDistance;
float xWallAtStartVector = (wallAtStart.getXEnd() - wallAtStart.getXStart()) / wallAtStartSegmentDistance;
float yWallAtStartVector = (wallAtStart.getYEnd() - wallAtStart.getYStart()) / wallAtStartSegmentDistance;
if (wallAtStart.getWallAtStart() == wall) {
// Reverse wall at start direction
xWallAtStartVector = -xWallAtStartVector;
yWallAtStartVector = -yWallAtStartVector;
}
int wallAngle = (int)Math.round(180 - Math.toDegrees(Math.atan2(
yWallVector * xWallAtStartVector - xWallVector * yWallAtStartVector,
xWallVector * xWallAtStartVector + yWallVector * yWallAtStartVector)));
if (wallAngle > 180) {
wallAngle -= 360;
}
return wallAngle;
}
}
if (startPointToEndPointDistance == 0) {
return 0;
} else {
return (int)Math.round(Math.toDegrees(Math.atan2(
wall.getYStart() - wall.getYEnd(), wall.getXEnd() - wall.getXStart())));
}
}
protected void showWallAngleFeedback(Wall wall, boolean ignoreArcExtent) {
Float arcExtent = wall.getArcExtent();
if (!ignoreArcExtent && arcExtent != null) {
if (arcExtent < 0) {
getView().setAngleFeedback(wall.getXArcCircleCenter(), wall.getYArcCircleCenter(),
wall.getXStart(), wall.getYStart(), wall.getXEnd(), wall.getYEnd());
} else {
getView().setAngleFeedback(wall.getXArcCircleCenter(), wall.getYArcCircleCenter(),
wall.getXEnd(), wall.getYEnd(), wall.getXStart(), wall.getYStart());
}
} else {
Wall wallAtStart = wall.getWallAtStart();
if (wallAtStart != null) {
if (wallAtStart.getWallAtStart() == wall) {
if (getWallAngleInDegrees(wall) > 0) {
getView().setAngleFeedback(wall.getXStart(), wall.getYStart(),
wallAtStart.getXEnd(), wallAtStart.getYEnd(), wall.getXEnd(), wall.getYEnd());
} else {
getView().setAngleFeedback(wall.getXStart(), wall.getYStart(),
wall.getXEnd(), wall.getYEnd(), wallAtStart.getXEnd(), wallAtStart.getYEnd());
}
} else {
if (getWallAngleInDegrees(wall) > 0) {
getView().setAngleFeedback(wall.getXStart(), wall.getYStart(),
wallAtStart.getXStart(), wallAtStart.getYStart(),
wall.getXEnd(), wall.getYEnd());
} else {
getView().setAngleFeedback(wall.getXStart(), wall.getYStart(),
wall.getXEnd(), wall.getYEnd(),
wallAtStart.getXStart(), wallAtStart.getYStart());
}
}
}
}
}
}
/**
* Wall drawing state. This state manages wall creation at each mouse press.
*/
private class WallDrawingState extends AbstractWallState {
private float xStart;
private float yStart;
private float xLastEnd;
private float yLastEnd;
private Wall wallStartAtStart;
private Wall wallEndAtStart;
private Wall newWall;
private Wall wallStartAtEnd;
private Wall wallEndAtEnd;
private Wall lastWall;
private List<Selectable> oldSelection;
private boolean oldBasePlanLocked;
private List<Wall> newWalls;
private boolean magnetismEnabled;
private boolean roundWall;
private long lastWallCreationTime;
private Float wallArcExtent;
@Override
public Mode getMode() {
return Mode.WALL_CREATION;
}
@Override
public boolean isModificationState() {
return true;
}
@Override
public void setMode(Mode mode) {
// Escape current creation and change state to matching mode
escape();
if (mode == Mode.SELECTION) {
setState(getSelectionState());
} else if (mode == Mode.PANNING) {
setState(getPanningState());
} else if (mode == Mode.ROOM_CREATION) {
setState(getRoomCreationState());
} else if (mode == Mode.DIMENSION_LINE_CREATION) {
setState(getDimensionLineCreationState());
} else if (mode == Mode.LABEL_CREATION) {
setState(getLabelCreationState());
}
}
@Override
public void enter() {
super.enter();
this.oldSelection = home.getSelectedItems();
this.oldBasePlanLocked = home.isBasePlanLocked();
toggleMagnetism(wasShiftDownLastMousePress());
this.xStart = getXLastMouseMove();
this.yStart = getYLastMouseMove();
// If the start or end line of a wall close to (xStart, yStart) is
// free, it will the wall at start of the new wall
this.wallEndAtStart = getWallEndAt(this.xStart, this.yStart, null);
if (this.wallEndAtStart != null) {
this.wallStartAtStart = null;
this.xStart = this.wallEndAtStart.getXEnd();
this.yStart = this.wallEndAtStart.getYEnd();
} else {
this.wallStartAtStart = getWallStartAt(
this.xStart, this.yStart, null);
if (this.wallStartAtStart != null) {
this.xStart = this.wallStartAtStart.getXStart();
this.yStart = this.wallStartAtStart.getYStart();
} else if (this.magnetismEnabled) {
WallPointWithAngleMagnetism point = new WallPointWithAngleMagnetism(this.xStart, this.yStart);
this.xStart = point.getX();
this.yStart = point.getY();
}
}
this.newWall = null;
this.wallStartAtEnd = null;
this.wallEndAtEnd = null;
this.lastWall = null;
this.newWalls = new ArrayList<Wall>();
this.lastWallCreationTime = -1;
deselectAll();
setDuplicationActivated(wasDuplicationActivatedLastMousePress());
PlanView planView = getView();
planView.setAlignmentFeedback(Wall.class, null, this.xStart, this.yStart, false);
}
@Override
public void moveMouse(float x, float y) {
PlanView planView = getView();
// Compute the coordinates where wall end point should be moved
float xEnd;
float yEnd;
if (this.magnetismEnabled) {
WallPointWithAngleMagnetism point = new WallPointWithAngleMagnetism(this.newWall, this.xStart, this.yStart, x, y);
xEnd = point.getX();
yEnd = point.getY();
} else {
xEnd = x;
yEnd = y;
}
// If current wall doesn't exist
if (this.newWall == null) {
// Create a new one
this.newWall = createWall(this.xStart, this.yStart,
xEnd, yEnd, this.wallStartAtStart, this.wallEndAtStart);
this.newWalls.add(this.newWall);
} else if (this.wallArcExtent != null) {
// Compute current wall arc extent from the circumscribed circle of the triangle
// with vertices (xStart, yStart) (xEnd, yEnd) (x, y)
float [] arcCenter = getCircumscribedCircleCenter(this.newWall.getXStart(), this.newWall.getYStart(),
this.newWall.getXEnd(), this.newWall.getYEnd(), x, y);
double startPointToBissectorLine1Distance = Point2D.distance(this.newWall.getXStart(), this.newWall.getYStart(),
this.newWall.getXEnd(), this.newWall.getYEnd()) / 2;
double arcCenterToWallDistance = Float.isInfinite(arcCenter [0]) || Float.isInfinite(arcCenter [1])
? Float.POSITIVE_INFINITY
: Line2D.ptLineDist(this.newWall.getXStart(), this.newWall.getYStart(),
this.newWall.getXEnd(), this.newWall.getYEnd(), arcCenter [0], arcCenter [1]);
int mousePosition = Line2D.relativeCCW(this.newWall.getXStart(), this.newWall.getYStart(),
this.newWall.getXEnd(), this.newWall.getYEnd(), x, y);
int centerPosition = Line2D.relativeCCW(this.newWall.getXStart(), this.newWall.getYStart(),
this.newWall.getXEnd(), this.newWall.getYEnd(), arcCenter [0], arcCenter [1]);
if (centerPosition == mousePosition) {
this.wallArcExtent = (float)(Math.PI + 2 * Math.atan2(arcCenterToWallDistance, startPointToBissectorLine1Distance));
} else {
this.wallArcExtent = (float)(2 * Math.atan2(startPointToBissectorLine1Distance, arcCenterToWallDistance));
}
this.wallArcExtent = Math.min(this.wallArcExtent, 3 * (float)Math.PI / 2);
this.wallArcExtent *= mousePosition;
if (this.magnetismEnabled) {
this.wallArcExtent = (float)Math.toRadians(Math.round(Math.toDegrees(this.wallArcExtent)));
}
this.newWall.setArcExtent(this.wallArcExtent);
} else {
// Otherwise update its end point
this.newWall.setXEnd(xEnd);
this.newWall.setYEnd(yEnd);
}
planView.setToolTipFeedback(getToolTipFeedbackText(this.newWall, false), x, y);
planView.setAlignmentFeedback(Wall.class, this.newWall, xEnd, yEnd, false);
showWallAngleFeedback(this.newWall, false);
// If the start or end line of a wall close to (xEnd, yEnd) is
// free, it will the wall at end of the new wall.
this.wallStartAtEnd = getWallStartAt(xEnd, yEnd, this.newWall);
if (this.wallStartAtEnd != null) {
this.wallEndAtEnd = null;
// Select the wall with a free start to display a feedback to user
selectItem(this.wallStartAtEnd);
} else {
this.wallEndAtEnd = getWallEndAt(xEnd, yEnd, this.newWall);
if (this.wallEndAtEnd != null) {
// Select the wall with a free end to display a feedback to user
selectItem(this.wallEndAtEnd);
} else {
deselectAll();
}
}
// Ensure point at (x,y) is visible
planView.makePointVisible(x, y);
// Update move coordinates
this.xLastEnd = xEnd;
this.yLastEnd = yEnd;
}
/**
* Returns the circumscribed circle of the triangle with vertices (x1, y1) (x2, y2) (x, y).
*/
private float [] getCircumscribedCircleCenter(float x1, float y1, float x2, float y2, float x, float y) {
float [][] bissectorLine1 = getBissectorLine(x1, y1, x2, y2);
float [][] bissectorLine2 = getBissectorLine(x1, y1, x, y);
float [] arcCenter = computeIntersection(bissectorLine1 [0], bissectorLine1 [1],
bissectorLine2 [0], bissectorLine2 [1]);
return arcCenter;
}
private float [][] getBissectorLine(float x1, float y1, float x2, float y2) {
float xMiddlePoint = (x1 + x2) / 2;
float yMiddlePoint = (y1 + y2) / 2;
float bissectorLineAlpha = (x1 - x2) / (y2 - y1);
if (bissectorLineAlpha > 1E10) {
// Vertical line
return new float [][] {{xMiddlePoint, yMiddlePoint}, {xMiddlePoint, yMiddlePoint + 1}};
} else {
return new float [][] {{xMiddlePoint, yMiddlePoint}, {xMiddlePoint + 1, bissectorLineAlpha + yMiddlePoint}};
}
}
@Override
public void pressMouse(float x, float y, int clickCount,
boolean shiftDown, boolean duplicationActivated) {
if (clickCount == 2) {
Selectable selectableItem = getSelectableItemAt(x, y);
if (this.newWalls.size() == 0
&& selectableItem instanceof Room) {
createWallsAroundRoom((Room)selectableItem);
} else {
if (this.roundWall && this.newWall != null) {
// Let's end wall creation of round walls after a double click
endWallCreation();
}
if (this.lastWall != null) {
// Join last wall to the selected wall at its end
joinNewWallEndToWall(this.lastWall,
this.wallStartAtEnd, this.wallEndAtEnd);
}
}
validateDrawnWalls();
} else {
// Create a new wall only when it will have a distance between start and end points > 0
if (this.newWall != null
&& this.newWall.getStartPointToEndPointDistance() > 0) {
if (this.roundWall && this.wallArcExtent == null) {
this.wallArcExtent = (float)Math.PI;
this.newWall.setArcExtent(this.wallArcExtent);
getView().setToolTipFeedback(getToolTipFeedbackText(this.newWall, false), x, y);
} else {
getView().deleteToolTipFeedback();
selectItem(this.newWall);
endWallCreation();
}
}
}
}
/**
* Creates walls around the given <code>room</code>.
*/
private void createWallsAroundRoom(Room room) {
if (room.isSingular()) {
float [][] roomPoints = room.getPoints();
List<float []> pointsList = new ArrayList<float[]>(Arrays.asList(roomPoints));
// It points are not clockwise reverse their order
if (!room.isClockwise()) {
Collections.reverse(pointsList);
}
// Remove equal points
for (int i = 0; i < pointsList.size(); ) {
float [] point = pointsList.get(i);
float [] nextPoint = pointsList.get((i + 1) % pointsList.size());
if (point [0] == nextPoint [0]
&& point [1] == nextPoint [1]) {
pointsList.remove(i);
} else {
i++;
}
}
roomPoints = pointsList.toArray(new float [pointsList.size()][]);
float halfWallThickness = preferences.getNewWallThickness() / 2;
float [][] largerRoomPoints = new float [roomPoints.length][];
for (int i = 0; i < roomPoints.length; i++) {
float [] point = roomPoints [i];
float [] previousPoint = roomPoints [(i + roomPoints.length - 1) % roomPoints.length];
float [] nextPoint = roomPoints [(i + 1) % roomPoints.length];
// Compute the angle of the line with a direction orthogonal to line (previousPoint, point)
double previousAngle = Math.atan2(point [0] - previousPoint [0], previousPoint [1] - point [1]);
// Compute the points of the line joining previous and current point
// at a distance equal to the half wall thickness
float deltaX = (float)(Math.cos(previousAngle) * halfWallThickness);
float deltaY = (float)(Math.sin(previousAngle) * halfWallThickness);
float [] point1 = {previousPoint [0] - deltaX, previousPoint [1] - deltaY};
float [] point2 = {point [0] - deltaX, point [1] - deltaY};
// Compute the angle of the line with a direction orthogonal to line (point, nextPoint)
double nextAngle = Math.atan2(nextPoint [0] - point [0], point [1] - nextPoint [1]);
// Compute the points of the line joining current and next point
// at a distance equal to the half wall thickness
deltaX = (float)(Math.cos(nextAngle) * halfWallThickness);
deltaY = (float)(Math.sin(nextAngle) * halfWallThickness);
float [] point3 = {point [0] - deltaX, point [1] - deltaY};
float [] point4 = {nextPoint [0] - deltaX, nextPoint [1] - deltaY};
largerRoomPoints [i] = computeIntersection(point1, point2, point3, point4);
}
// Create walls joining points of largerRoomPoints
Wall lastWall = null;
for (int i = 0; i < largerRoomPoints.length; i++) {
float [] point = largerRoomPoints [i];
float [] nextPoint = largerRoomPoints [(i + 1) % roomPoints.length];
Wall wall = createWall(point [0], point [1], nextPoint [0], nextPoint [1], null, lastWall);
this.newWalls.add(wall);
lastWall = wall;
}
joinNewWallEndToWall(lastWall, this.newWalls.get(0), null);
}
}
private void validateDrawnWalls() {
if (this.newWalls.size() > 0) {
// Post walls creation to undo support
postCreateWalls(this.newWalls, this.oldSelection, this.oldBasePlanLocked);
selectItems(this.newWalls);
}
// Change state to WallCreationState
setState(getWallCreationState());
}
private void endWallCreation() {
this.lastWall =
this.wallEndAtStart = this.newWall;
this.wallStartAtStart = null;
this.xStart = this.newWall.getXEnd();
this.yStart = this.newWall.getYEnd();
this.newWall = null;
this.wallArcExtent = null;
}
@Override
public void setEditionActivated(boolean editionActivated) {
PlanView planView = getView();
if (editionActivated) {
planView.deleteFeedback();
if (this.newWalls.size() == 0
&& this.wallEndAtStart == null
&& this.wallStartAtStart == null) {
// Edit xStart and yStart
planView.setToolTipEditedProperties(new EditableProperty [] {EditableProperty.X,
EditableProperty.Y},
new Object [] {this.xStart, this.yStart},
this.xStart, this.yStart);
} else {
if (this.newWall == null) {
// May happen if edition is activated after the user clicked to finish one wall
createNextWall();
}
if (this.wallArcExtent == null) {
// Edit length, angle and thickness
planView.setToolTipEditedProperties(new EditableProperty [] {EditableProperty.LENGTH,
EditableProperty.ANGLE,
EditableProperty.THICKNESS},
new Object [] {this.newWall.getLength(),
getWallAngleInDegrees(this.newWall),
this.newWall.getThickness()},
this.newWall.getXEnd(), this.newWall.getYEnd());
} else {
// Edit arc extent
planView.setToolTipEditedProperties(new EditableProperty [] {EditableProperty.ARC_EXTENT},
new Object [] {new Integer((int)Math.round(Math.toDegrees(this.wallArcExtent)))},
this.newWall.getXEnd(), this.newWall.getYEnd());
}
}
} else {
if (this.newWall == null) {
// Create a new wall once user entered the start point of the first wall
float defaultLength = preferences.getLengthUnit() == LengthUnit.INCH
? LengthUnit.footToCentimeter(10) : 300;
this.xLastEnd = this.xStart + defaultLength;
this.yLastEnd = this.yStart;
this.newWall = createWall(this.xStart, this.yStart,
this.xLastEnd, this.yLastEnd, this.wallStartAtStart, this.wallEndAtStart);
this.newWalls.add(this.newWall);
// Activate automatically second step to let user enter the
// length, angle and thickness of the new wall
planView.deleteFeedback();
setEditionActivated(true);
} else if (this.roundWall && this.wallArcExtent == null) {
this.wallArcExtent = (float)Math.PI;
this.newWall.setArcExtent(this.wallArcExtent);
setEditionActivated(true);
} else if (System.currentTimeMillis() - this.lastWallCreationTime < 300) {
// If the user deactivated edition less than 300 ms after activation,
// validate drawn walls after removing the last added wall
if (this.newWalls.size() > 1) {
this.newWalls.remove(this.newWall);
home.deleteWall(this.newWall);
}
validateDrawnWalls();
} else {
endWallCreation();
if (this.newWalls.size() > 2 && this.wallStartAtEnd != null) {
// Join last wall to the first wall at its end and validate drawn walls
joinNewWallEndToWall(this.lastWall, this.wallStartAtEnd, null);
validateDrawnWalls();
return;
}
createNextWall();
// Reactivate automatically second step
planView.deleteToolTipFeedback();
setEditionActivated(true);
}
}
}
private void createNextWall() {
Wall previousWall = this.wallEndAtStart != null
? this.wallEndAtStart
: this.wallStartAtStart;
// Create a new wall with an angle equal to previous wall angle - 90�
double previousWallAngle = Math.PI - Math.atan2(previousWall.getYStart() - previousWall.getYEnd(),
previousWall.getXStart() - previousWall.getXEnd());
previousWallAngle -= Math.PI / 2;
float previousWallSegmentDistance = previousWall.getStartPointToEndPointDistance();
this.xLastEnd = (float)(this.xStart + previousWallSegmentDistance * Math.cos(previousWallAngle));
this.yLastEnd = (float)(this.yStart - previousWallSegmentDistance * Math.sin(previousWallAngle));
this.newWall = createWall(this.xStart, this.yStart,
this.xLastEnd, this.yLastEnd, this.wallStartAtStart, previousWall);
this.newWall.setThickness(previousWall.getThickness());
this.newWalls.add(this.newWall);
this.lastWallCreationTime = System.currentTimeMillis();
deselectAll();
}
@Override
public void updateEditableProperty(EditableProperty editableProperty, Object value) {
PlanView planView = getView();
if (this.newWall == null) {
float maximumLength = preferences.getLengthUnit().getMaximumLength();
// Update start point of the first wall
switch (editableProperty) {
case X :
this.xStart = value != null ? ((Number)value).floatValue() : 0;
this.xStart = Math.max(-maximumLength, Math.min(this.xStart, maximumLength));
break;
case Y :
this.yStart = value != null ? ((Number)value).floatValue() : 0;
this.yStart = Math.max(-maximumLength, Math.min(this.yStart, maximumLength));
break;
}
planView.setAlignmentFeedback(Wall.class, null, this.xStart, this.yStart, true);
planView.makePointVisible(this.xStart, this.yStart);
} else {
if (editableProperty == EditableProperty.THICKNESS) {
float thickness = value != null ? Math.abs(((Number)value).floatValue()) : 0;
thickness = Math.max(0.01f, Math.min(thickness, 1000));
this.newWall.setThickness(thickness);
} else if (editableProperty == EditableProperty.ARC_EXTENT) {
double arcExtent = Math.toRadians(value != null ? ((Number)value).doubleValue() : 0);
this.wallArcExtent = (float)(Math.signum(arcExtent) * Math.min(Math.abs(arcExtent), 3 * Math.PI / 2));
this.newWall.setArcExtent(this.wallArcExtent);
showWallAngleFeedback(this.newWall, false);
} else {
// Update end point of the current wall
switch (editableProperty) {
case LENGTH :
float length = value != null ? ((Number)value).floatValue() : 0;
length = Math.max(0.001f, Math.min(length, preferences.getLengthUnit().getMaximumLength()));
double wallAngle = Math.PI - Math.atan2(this.yStart - this.yLastEnd, this.xStart - this.xLastEnd);
this.xLastEnd = (float)(this.xStart + length * Math.cos(wallAngle));
this.yLastEnd = (float)(this.yStart - length * Math.sin(wallAngle));
break;
case ANGLE :
wallAngle = Math.toRadians(value != null ? ((Number)value).doubleValue() : 0);
Wall previousWall = this.newWall.getWallAtStart();
if (previousWall != null
&& previousWall.getStartPointToEndPointDistance() > 0) {
wallAngle -= Math.atan2(previousWall.getYStart() - previousWall.getYEnd(),
previousWall.getXStart() - previousWall.getXEnd());
}
float startPointToEndPointDistance = this.newWall.getStartPointToEndPointDistance();
this.xLastEnd = (float)(this.xStart + startPointToEndPointDistance * Math.cos(wallAngle));
this.yLastEnd = (float)(this.yStart - startPointToEndPointDistance * Math.sin(wallAngle));
break;
default :
return;
}
// Update new wall
this.newWall.setXEnd(this.xLastEnd);
this.newWall.setYEnd(this.yLastEnd);
planView.setAlignmentFeedback(Wall.class, this.newWall, this.xLastEnd, this.yLastEnd, false);
showWallAngleFeedback(this.newWall, false);
// Ensure wall points are visible
planView.makePointVisible(this.xStart, this.yStart);
planView.makePointVisible(this.xLastEnd, this.yLastEnd);
// Search if the free start point of the first wall matches the end point of the current wall
if (this.newWalls.size() > 2
&& this.newWalls.get(0).getWallAtStart() == null
&& this.newWalls.get(0).containsWallStartAt(this.xLastEnd, this.yLastEnd, 1E-3f)) {
this.wallStartAtEnd = this.newWalls.get(0);
selectItem(this.wallStartAtEnd);
} else {
this.wallStartAtEnd = null;
deselectAll();
}
}
}
}
@Override
public void toggleMagnetism(boolean magnetismToggled) {
// Compute active magnetism
this.magnetismEnabled = preferences.isMagnetismEnabled()
^ magnetismToggled;
// If the new wall already exists,
// compute again its end as if mouse moved
if (this.newWall != null) {
moveMouse(getXLastMouseMove(), getYLastMouseMove());
}
}
@Override
public void setDuplicationActivated(boolean duplicationActivated) {
// Reuse duplication activation for round circle creation
this.roundWall = duplicationActivated;
}
@Override
public void escape() {
if (this.newWall != null) {
// Delete current created wall
home.deleteWall(this.newWall);
this.newWalls.remove(this.newWall);
}
validateDrawnWalls();
}
@Override
public void exit() {
PlanView planView = getView();
planView.deleteFeedback();
this.wallStartAtStart = null;
this.wallEndAtStart = null;
this.newWall = null;
this.wallArcExtent = null;
this.wallStartAtEnd = null;
this.wallEndAtEnd = null;
this.lastWall = null;
this.oldSelection = null;
this.newWalls = null;
}
}
/**
* Wall resize state. This state manages wall resizing.
*/
private class WallResizeState extends AbstractWallState {
private Wall selectedWall;
private boolean startPoint;
private float oldX;
private float oldY;
private float deltaXToResizePoint;
private float deltaYToResizePoint;
private boolean magnetismEnabled;
@Override
public Mode getMode() {
return Mode.SELECTION;
}
@Override
public boolean isModificationState() {
return true;
}
@Override
public void enter() {
super.enter();
this.selectedWall = (Wall)home.getSelectedItems().get(0);
this.startPoint = this.selectedWall
== getResizedWallStartAt(getXLastMousePress(), getYLastMousePress());
if (this.startPoint) {
this.oldX = this.selectedWall.getXStart();
this.oldY = this.selectedWall.getYStart();
} else {
this.oldX = this.selectedWall.getXEnd();
this.oldY = this.selectedWall.getYEnd();
}
this.deltaXToResizePoint = getXLastMousePress() - this.oldX;
this.deltaYToResizePoint = getYLastMousePress() - this.oldY;
toggleMagnetism(wasShiftDownLastMousePress());
PlanView planView = getView();
planView.setResizeIndicatorVisible(true);
planView.setToolTipFeedback(getToolTipFeedbackText(this.selectedWall, true),
getXLastMousePress(), getYLastMousePress());
planView.setAlignmentFeedback(Wall.class, this.selectedWall, this.oldX, this.oldY, false);
showWallAngleFeedback(this.selectedWall, true);
}
@Override
public void moveMouse(float x, float y) {
PlanView planView = getView();
float newX = x - this.deltaXToResizePoint;
float newY = y - this.deltaYToResizePoint;
if (this.magnetismEnabled) {
WallPointWithAngleMagnetism point = new WallPointWithAngleMagnetism(this.selectedWall,
this.startPoint
? this.selectedWall.getXEnd()
: this.selectedWall.getXStart(),
this.startPoint
? this.selectedWall.getYEnd()
: this.selectedWall.getYStart(), newX, newY);
newX = point.getX();
newY = point.getY();
}
moveWallPoint(this.selectedWall, newX, newY, this.startPoint);
planView.setToolTipFeedback(getToolTipFeedbackText(this.selectedWall, true), x, y);
planView.setAlignmentFeedback(Wall.class, this.selectedWall, newX, newY, false);
showWallAngleFeedback(this.selectedWall, true);
// Ensure point at (x,y) is visible
planView.makePointVisible(x, y);
}
@Override
public void releaseMouse(float x, float y) {
postWallResize(this.selectedWall, this.oldX, this.oldY, this.startPoint);
setState(getSelectionState());
}
@Override
public void toggleMagnetism(boolean magnetismToggled) {
// Compute active magnetism
this.magnetismEnabled = preferences.isMagnetismEnabled()
^ magnetismToggled;
moveMouse(getXLastMouseMove(), getYLastMouseMove());
}
@Override
public void escape() {
moveWallPoint(this.selectedWall, this.oldX, this.oldY, this.startPoint);
setState(getSelectionState());
}
@Override
public void exit() {
PlanView planView = getView();
planView.setResizeIndicatorVisible(false);
planView.deleteFeedback();
this.selectedWall = null;
}
}
/**
* Furniture rotation state. This states manages the rotation of a piece of furniture.
*/
private class PieceOfFurnitureRotationState extends ControllerState {
private static final int STEP_COUNT = 24;
private boolean magnetismEnabled;
private HomePieceOfFurniture selectedPiece;
private float angleMousePress;
private float oldAngle;
private boolean doorOrWindowBoundToWall;
private String rotationToolTipFeedback;
@Override
public Mode getMode() {
return Mode.SELECTION;
}
@Override
public boolean isModificationState() {
return true;
}
@Override
public void enter() {
this.rotationToolTipFeedback = preferences.getLocalizedString(
PlanController.class, "rotationToolTipFeedback");
this.selectedPiece = (HomePieceOfFurniture)home.getSelectedItems().get(0);
this.angleMousePress = (float)Math.atan2(this.selectedPiece.getY() - getYLastMousePress(),
getXLastMousePress() - this.selectedPiece.getX());
this.oldAngle = this.selectedPiece.getAngle();
this.doorOrWindowBoundToWall = this.selectedPiece instanceof HomeDoorOrWindow
&& ((HomeDoorOrWindow)this.selectedPiece).isBoundToWall();
this.magnetismEnabled = preferences.isMagnetismEnabled()
^ wasShiftDownLastMousePress();
PlanView planView = getView();
planView.setResizeIndicatorVisible(true);
planView.setToolTipFeedback(getToolTipFeedbackText(this.oldAngle),
getXLastMousePress(), getYLastMousePress());
}
@Override
public void moveMouse(float x, float y) {
if (x != this.selectedPiece.getX() || y != this.selectedPiece.getY()) {
// Compute the new angle of the piece
float angleMouseMove = (float)Math.atan2(this.selectedPiece.getY() - y,
x - this.selectedPiece.getX());
float newAngle = this.oldAngle - angleMouseMove + this.angleMousePress;
if (this.magnetismEnabled) {
float angleStep = 2 * (float)Math.PI / STEP_COUNT;
// Compute angles closest to a step angle (multiple of angleStep)
newAngle = Math.round(newAngle / angleStep) * angleStep;
}
// Update piece new angle
this.selectedPiece.setAngle(newAngle);
// Ensure point at (x,y) is visible
PlanView planView = getView();
planView.makePointVisible(x, y);
planView.setToolTipFeedback(getToolTipFeedbackText(newAngle), x, y);
}
}
@Override
public void releaseMouse(float x, float y) {
postPieceOfFurnitureRotation(this.selectedPiece, this.oldAngle, this.doorOrWindowBoundToWall);
setState(getSelectionState());
}
@Override
public void toggleMagnetism(boolean magnetismToggled) {
// Compute active magnetism
this.magnetismEnabled = preferences.isMagnetismEnabled()
^ magnetismToggled;
// Compute again angle as if mouse moved
moveMouse(getXLastMouseMove(), getYLastMouseMove());
}
@Override
public void escape() {
this.selectedPiece.setAngle(this.oldAngle);
if (this.selectedPiece instanceof HomeDoorOrWindow) {
((HomeDoorOrWindow)this.selectedPiece).setBoundToWall(this.doorOrWindowBoundToWall);
}
setState(getSelectionState());
}
@Override
public void exit() {
PlanView planView = getView();
planView.setResizeIndicatorVisible(false);
planView.deleteFeedback();
this.selectedPiece = null;
}
private String getToolTipFeedbackText(float angle) {
return String.format(this.rotationToolTipFeedback,
(Math.round(Math.toDegrees(angle)) + 360) % 360);
}
}
/**
* Furniture elevation state. This states manages the elevation change of a piece of furniture.
*/
private class PieceOfFurnitureElevationState extends ControllerState {
private boolean magnetismEnabled;
private float deltaYToElevationPoint;
private HomePieceOfFurniture selectedPiece;
private float oldElevation;
private String elevationToolTipFeedback;
@Override
public Mode getMode() {
return Mode.SELECTION;
}
@Override
public boolean isModificationState() {
return true;
}
@Override
public void enter() {
this.elevationToolTipFeedback = preferences.getLocalizedString(
PlanController.class, "elevationToolTipFeedback");
this.selectedPiece = (HomePieceOfFurniture)home.getSelectedItems().get(0);
float [] elevationPoint = this.selectedPiece.getPoints() [1];
this.deltaYToElevationPoint = getYLastMousePress() - elevationPoint [1];
this.oldElevation = this.selectedPiece.getElevation();
this.magnetismEnabled = preferences.isMagnetismEnabled()
^ wasShiftDownLastMousePress();
PlanView planView = getView();
planView.setResizeIndicatorVisible(true);
planView.setToolTipFeedback(getToolTipFeedbackText(this.oldElevation),
getXLastMousePress(), getYLastMousePress());
}
@Override
public void moveMouse(float x, float y) {
// Compute the new elevation of the piece
PlanView planView = getView();
float [] topRightPoint = this.selectedPiece.getPoints() [1];
float deltaY = y - this.deltaYToElevationPoint - topRightPoint[1];
float newElevation = this.oldElevation - deltaY;
newElevation = Math.min(Math.max(newElevation, 0f), preferences.getLengthUnit().getMaximumElevation());
if (this.magnetismEnabled) {
newElevation = preferences.getLengthUnit().getMagnetizedLength(newElevation, planView.getPixelLength());
}
// Update piece new dimension
this.selectedPiece.setElevation(newElevation);
// Ensure point at (x,y) is visible
planView.makePointVisible(x, y);
planView.setToolTipFeedback(getToolTipFeedbackText(newElevation), x, y);
}
@Override
public void releaseMouse(float x, float y) {
postPieceOfFurnitureElevation(this.selectedPiece, this.oldElevation);
setState(getSelectionState());
}
@Override
public void toggleMagnetism(boolean magnetismToggled) {
// Compute active magnetism
this.magnetismEnabled = preferences.isMagnetismEnabled()
^ magnetismToggled;
// Compute again angle as if mouse moved
moveMouse(getXLastMouseMove(), getYLastMouseMove());
}
@Override
public void escape() {
this.selectedPiece.setElevation(this.oldElevation);
setState(getSelectionState());
}
@Override
public void exit() {
PlanView planView = getView();
planView.setResizeIndicatorVisible(false);
planView.deleteFeedback();
this.selectedPiece = null;
}
private String getToolTipFeedbackText(float height) {
return String.format(this.elevationToolTipFeedback,
preferences.getLengthUnit().getFormatWithUnit().format(height));
}
}
/**
* Furniture height state. This states manages the height resizing of a piece of furniture.
*/
private class PieceOfFurnitureHeightState extends ControllerState {
private boolean magnetismEnabled;
private float deltaYToResizePoint;
private ResizedPieceOfFurniture resizedPiece;
private float [] topLeftPoint;
private float [] resizePoint;
private String resizeToolTipFeedback;
@Override
public Mode getMode() {
return Mode.SELECTION;
}
@Override
public boolean isModificationState() {
return true;
}
@Override
public void enter() {
this.resizeToolTipFeedback = preferences.getLocalizedString(
PlanController.class, "heightResizeToolTipFeedback");
HomePieceOfFurniture selectedPiece = (HomePieceOfFurniture)home.getSelectedItems().get(0);
this.resizedPiece = new ResizedPieceOfFurniture(selectedPiece);
float [][] resizedPiecePoints = selectedPiece.getPoints();
this.resizePoint = resizedPiecePoints [3];
this.deltaYToResizePoint = getYLastMousePress() - this.resizePoint [1];
this.topLeftPoint = resizedPiecePoints [0];
this.magnetismEnabled = preferences.isMagnetismEnabled()
^ wasShiftDownLastMousePress();
PlanView planView = getView();
planView.setResizeIndicatorVisible(true);
planView.setToolTipFeedback(getToolTipFeedbackText(selectedPiece.getHeight()),
getXLastMousePress(), getYLastMousePress());
}
@Override
public void moveMouse(float x, float y) {
// Compute the new height of the piece
PlanView planView = getView();
HomePieceOfFurniture selectedPiece = this.resizedPiece.getPieceOfFurniture();
float deltaY = y - this.deltaYToResizePoint - this.resizePoint [1];
float newHeight = this.resizedPiece.getHeight() - deltaY;
newHeight = Math.max(newHeight, 0f);
if (this.magnetismEnabled) {
newHeight = preferences.getLengthUnit().getMagnetizedLength(newHeight, planView.getPixelLength());
}
newHeight = Math.min(Math.max(newHeight, preferences.getLengthUnit().getMinimumLength()),
preferences.getLengthUnit().getMaximumLength());
// Update piece new dimension
selectedPiece.setHeight(newHeight);
// Manage proportional constraint
if (!selectedPiece.isDeformable()) {
float ratio = newHeight / this.resizedPiece.getHeight();
float newWidth = this.resizedPiece.getWidth() * ratio;
float newDepth = this.resizedPiece.getDepth() * ratio;
// Update piece new location
float angle = selectedPiece.getAngle();
double cos = Math.cos(angle);
double sin = Math.sin(angle);
float newX = (float)(this.topLeftPoint [0] + (newWidth * cos - newDepth * sin) / 2f);
float newY = (float)(this.topLeftPoint [1] + (newWidth * sin + newDepth * cos) / 2f);
selectedPiece.setX(newX);
selectedPiece.setY(newY);
selectedPiece.setWidth(newWidth);
selectedPiece.setDepth(newDepth);
}
// Ensure point at (x,y) is visible
planView.makePointVisible(x, y);
planView.setToolTipFeedback(getToolTipFeedbackText(newHeight), x, y);
}
@Override
public void releaseMouse(float x, float y) {
postPieceOfFurnitureHeightResize(this.resizedPiece);
setState(getSelectionState());
}
@Override
public void toggleMagnetism(boolean magnetismToggled) {
// Compute active magnetism
this.magnetismEnabled = preferences.isMagnetismEnabled()
^ magnetismToggled;
// Compute again angle as if mouse moved
moveMouse(getXLastMouseMove(), getYLastMouseMove());
}
@Override
public void escape() {
this.resizedPiece.reset();
setState(getSelectionState());
}
@Override
public void exit() {
PlanView planView = getView();
planView.setResizeIndicatorVisible(false);
planView.deleteFeedback();
this.resizedPiece = null;
}
private String getToolTipFeedbackText(float height) {
return String.format(this.resizeToolTipFeedback,
preferences.getLengthUnit().getFormatWithUnit().format(height));
}
}
/**
* Furniture resize state. This states manages the resizing of a piece of furniture.
*/
private class PieceOfFurnitureResizeState extends ControllerState {
private boolean magnetismEnabled;
private float deltaXToResizePoint;
private float deltaYToResizePoint;
private ResizedPieceOfFurniture resizedPiece;
private float [] topLeftPoint;
private String widthResizeToolTipFeedback;
private String depthResizeToolTipFeedback;
@Override
public Mode getMode() {
return Mode.SELECTION;
}
@Override
public boolean isModificationState() {
return true;
}
@Override
public void enter() {
this.widthResizeToolTipFeedback = preferences.getLocalizedString(
PlanController.class, "widthResizeToolTipFeedback");
this.depthResizeToolTipFeedback = preferences.getLocalizedString(
PlanController.class, "depthResizeToolTipFeedback");
HomePieceOfFurniture selectedPiece = (HomePieceOfFurniture)home.getSelectedItems().get(0);
this.resizedPiece = new ResizedPieceOfFurniture(selectedPiece);
float [][] resizedPiecePoints = selectedPiece.getPoints();
float [] resizePoint = resizedPiecePoints [2];
this.deltaXToResizePoint = getXLastMousePress() - resizePoint [0];
this.deltaYToResizePoint = getYLastMousePress() - resizePoint [1];
this.topLeftPoint = resizedPiecePoints [0];
this.magnetismEnabled = preferences.isMagnetismEnabled()
^ wasShiftDownLastMousePress();
PlanView planView = getView();
planView.setResizeIndicatorVisible(true);
planView.setToolTipFeedback(getToolTipFeedbackText(selectedPiece.getWidth(), selectedPiece.getDepth()),
getXLastMousePress(), getYLastMousePress());
}
@Override
public void moveMouse(float x, float y) {
// Compute the new location and dimension of the piece to let
// its bottom right point be at mouse location
PlanView planView = getView();
HomePieceOfFurniture selectedPiece = this.resizedPiece.getPieceOfFurniture();
float angle = selectedPiece.getAngle();
double cos = Math.cos(angle);
double sin = Math.sin(angle);
float deltaX = x - this.deltaXToResizePoint - this.topLeftPoint [0];
float deltaY = y - this.deltaYToResizePoint - this.topLeftPoint [1];
float newWidth = (float)(deltaY * sin + deltaX * cos);
if (this.magnetismEnabled) {
newWidth = preferences.getLengthUnit().getMagnetizedLength(newWidth, planView.getPixelLength());
}
newWidth = Math.min(Math.max(newWidth, preferences.getLengthUnit().getMinimumLength()),
preferences.getLengthUnit().getMaximumLength());
float newDepth;
if (!this.resizedPiece.isDoorOrWindowBoundToWall()
|| !selectedPiece.isDeformable()
|| !this.magnetismEnabled) {
// Update piece depth if it's not a door a window
// or if it's a a door a window unbound to a wall when magnetism is enabled
newDepth = (float)(deltaY * cos - deltaX * sin);
if (this.magnetismEnabled) {
newDepth = preferences.getLengthUnit().getMagnetizedLength(newDepth, planView.getPixelLength());
}
newDepth = Math.min(Math.max(newDepth, preferences.getLengthUnit().getMinimumLength()),
preferences.getLengthUnit().getMaximumLength());
} else {
newDepth = this.resizedPiece.getDepth();
}
// Manage proportional constraint
float newHeight = this.resizedPiece.getHeight();
if (!selectedPiece.isDeformable()) {
float [][] resizedPiecePoints = selectedPiece.getPoints();
float ratio;
if (Line2D.relativeCCW(resizedPiecePoints [0][0], resizedPiecePoints [0][1], resizedPiecePoints [2][0], resizedPiecePoints [2][1], x, y) >= 0) {
ratio = newWidth / this.resizedPiece.getWidth();
newDepth = this.resizedPiece.getDepth() * ratio;
} else {
ratio = newDepth / this.resizedPiece.getDepth();
newWidth = this.resizedPiece.getWidth() * ratio;
}
newHeight = this.resizedPiece.getHeight() * ratio;
}
// Update piece new location
float newX = (float)(this.topLeftPoint [0] + (newWidth * cos - newDepth * sin) / 2f);
float newY = (float)(this.topLeftPoint [1] + (newWidth * sin + newDepth * cos) / 2f);
selectedPiece.setX(newX);
selectedPiece.setY(newY);
// Update piece size
selectedPiece.setWidth(newWidth);
selectedPiece.setDepth(newDepth);
selectedPiece.setHeight(newHeight);
if (this.resizedPiece.isDoorOrWindowBoundToWall()) {
// Maintain boundToWall flag
((HomeDoorOrWindow)selectedPiece).setBoundToWall(this.magnetismEnabled);
}
// Ensure point at (x,y) is visible
planView.makePointVisible(x, y);
planView.setToolTipFeedback(getToolTipFeedbackText(newWidth, newDepth), x, y);
}
@Override
public void releaseMouse(float x, float y) {
postPieceOfFurnitureWidthAndDepthResize(this.resizedPiece);
setState(getSelectionState());
}
@Override
public void toggleMagnetism(boolean magnetismToggled) {
// Compute active magnetism
this.magnetismEnabled = preferences.isMagnetismEnabled()
^ magnetismToggled;
// Compute again angle as if mouse moved
moveMouse(getXLastMouseMove(), getYLastMouseMove());
}
@Override
public void escape() {
this.resizedPiece.reset();
setState(getSelectionState());
}
@Override
public void exit() {
PlanView planView = getView();
planView.setResizeIndicatorVisible(false);
planView.deleteFeedback();
this.resizedPiece = null;
}
private String getToolTipFeedbackText(float width, float depth) {
String toolTipFeedbackText = "<html>" + String.format(this.widthResizeToolTipFeedback,
preferences.getLengthUnit().getFormatWithUnit().format(width));
if (!(this.resizedPiece.getPieceOfFurniture() instanceof HomeDoorOrWindow)
|| !((HomeDoorOrWindow)this.resizedPiece.getPieceOfFurniture()).isBoundToWall()) {
toolTipFeedbackText += "<br>" + String.format(this.depthResizeToolTipFeedback,
preferences.getLengthUnit().getFormatWithUnit().format(depth));
}
return toolTipFeedbackText;
}
}
/**
* Light power state. This states manages the power modification of a light.
*/
private class LightPowerModificationState extends ControllerState {
private float deltaXToModificationPoint;
private HomeLight selectedLight;
private float oldPower;
private String lightPowerToolTipFeedback;
@Override
public Mode getMode() {
return Mode.SELECTION;
}
@Override
public boolean isModificationState() {
return true;
}
@Override
public void enter() {
this.lightPowerToolTipFeedback = preferences.getLocalizedString(
PlanController.class, "lightPowerToolTipFeedback");
this.selectedLight = (HomeLight)home.getSelectedItems().get(0);
float [] resizePoint = this.selectedLight.getPoints() [3];
this.deltaXToModificationPoint = getXLastMousePress() - resizePoint [0];
this.oldPower = this.selectedLight.getPower();
PlanView planView = getView();
planView.setResizeIndicatorVisible(true);
planView.setToolTipFeedback(getToolTipFeedbackText(this.oldPower),
getXLastMousePress(), getYLastMousePress());
}
@Override
public void moveMouse(float x, float y) {
// Compute the new height of the piece
PlanView planView = getView();
float [] bottomLeftPoint = this.selectedLight.getPoints() [3];
float deltaX = x - this.deltaXToModificationPoint - bottomLeftPoint [0];
float newPower = this.oldPower + deltaX / 100f * getScale();
newPower = Math.min(Math.max(newPower, 0f), 1f);
// Update light power
this.selectedLight.setPower(newPower);
// Ensure point at (x,y) is visible
planView.makePointVisible(x, y);
planView.setToolTipFeedback(getToolTipFeedbackText(newPower), x, y);
}
@Override
public void releaseMouse(float x, float y) {
postLightPowerModification(this.selectedLight, this.oldPower);
setState(getSelectionState());
}
@Override
public void escape() {
this.selectedLight.setPower(this.oldPower);
setState(getSelectionState());
}
@Override
public void exit() {
PlanView planView = getView();
planView.setResizeIndicatorVisible(false);
planView.deleteFeedback();
this.selectedLight = null;
}
private String getToolTipFeedbackText(float power) {
return String.format(this.lightPowerToolTipFeedback, Math.round(power * 100));
}
}
/**
* Furniture name offset state. This state manages the name offset of a piece of furniture.
*/
private class PieceOfFurnitureNameOffsetState extends ControllerState {
private HomePieceOfFurniture selectedPiece;
private float oldNameXOffset;
private float oldNameYOffset;
private float xLastMouseMove;
private float yLastMouseMove;
@Override
public Mode getMode() {
return Mode.SELECTION;
}
@Override
public boolean isModificationState() {
return true;
}
@Override
public void enter() {
this.selectedPiece = (HomePieceOfFurniture)home.getSelectedItems().get(0);
this.oldNameXOffset = this.selectedPiece.getNameXOffset();
this.oldNameYOffset = this.selectedPiece.getNameYOffset();
this.xLastMouseMove = getXLastMousePress();
this.yLastMouseMove = getYLastMousePress();
PlanView planView = getView();
planView.setResizeIndicatorVisible(true);
}
@Override
public void moveMouse(float x, float y) {
this.selectedPiece.setNameXOffset(this.selectedPiece.getNameXOffset() + x - this.xLastMouseMove);
this.selectedPiece.setNameYOffset(this.selectedPiece.getNameYOffset() + y - this.yLastMouseMove);
this.xLastMouseMove = x;
this.yLastMouseMove = y;
// Ensure point at (x,y) is visible
getView().makePointVisible(x, y);
}
@Override
public void releaseMouse(float x, float y) {
postPieceOfFurnitureNameOffset(this.selectedPiece, this.oldNameXOffset, this.oldNameYOffset);
setState(getSelectionState());
}
@Override
public void escape() {
this.selectedPiece.setNameXOffset(this.oldNameXOffset);
this.selectedPiece.setNameYOffset(this.oldNameYOffset);
setState(getSelectionState());
}
@Override
public void exit() {
getView().setResizeIndicatorVisible(false);
this.selectedPiece = null;
}
}
/**
* Camera yaw change state. This states manages the change of the observer camera yaw angle.
*/
private class CameraYawRotationState extends ControllerState {
private ObserverCamera selectedCamera;
private float oldYaw;
private float xLastMouseMove;
private float yLastMouseMove;
private float angleLastMouseMove;
private String rotationToolTipFeedback;
@Override
public Mode getMode() {
return Mode.SELECTION;
}
@Override
public boolean isModificationState() {
return true;
}
@Override
public void enter() {
this.rotationToolTipFeedback = preferences.getLocalizedString(
PlanController.class, "cameraYawRotationToolTipFeedback");
this.selectedCamera = (ObserverCamera)home.getSelectedItems().get(0);
this.oldYaw = this.selectedCamera.getYaw();
this.xLastMouseMove = getXLastMousePress();
this.yLastMouseMove = getYLastMousePress();
this.angleLastMouseMove = (float)Math.atan2(this.selectedCamera.getY() - this.yLastMouseMove,
this.xLastMouseMove - this.selectedCamera.getX());
PlanView planView = getView();
planView.setResizeIndicatorVisible(true);
planView.setToolTipFeedback(getToolTipFeedbackText(this.oldYaw),
getXLastMousePress(), getYLastMousePress());
}
@Override
public void moveMouse(float x, float y) {
if (x != this.selectedCamera.getX() || y != this.selectedCamera.getY()) {
// Compute the new angle of the camera
float angleMouseMove = (float)Math.atan2(this.selectedCamera.getY() - y,
x - this.selectedCamera.getX());
// Compute yaw angle with a delta that takes into account the direction
// of the rotation (clock wise or counter clock wise)
float deltaYaw = angleLastMouseMove - angleMouseMove;
float orientation = Math.signum((y - this.selectedCamera.getY()) * (this.xLastMouseMove - this.selectedCamera.getX())
- (this.yLastMouseMove - this.selectedCamera.getY()) * (x- this.selectedCamera.getX()));
if (orientation < 0 && deltaYaw > 0) {
deltaYaw -= (float)(Math.PI * 2f);
} else if (orientation > 0 && deltaYaw < 0) {
deltaYaw += (float)(Math.PI * 2f);
}
// Update camera new yaw angle
float newYaw = this.selectedCamera.getYaw() + deltaYaw;
this.selectedCamera.setYaw(newYaw);
getView().setToolTipFeedback(getToolTipFeedbackText(newYaw), x, y);
this.xLastMouseMove = x;
this.yLastMouseMove = y;
this.angleLastMouseMove = angleMouseMove;
}
}
@Override
public void releaseMouse(float x, float y) {
setState(getSelectionState());
}
@Override
public void escape() {
this.selectedCamera.setYaw(this.oldYaw);
setState(getSelectionState());
}
@Override
public void exit() {
PlanView planView = getView();
planView.setResizeIndicatorVisible(false);
planView.deleteFeedback();
this.selectedCamera = null;
}
private String getToolTipFeedbackText(float angle) {
return String.format(this.rotationToolTipFeedback,
(Math.round(Math.toDegrees(angle)) + 360) % 360);
}
}
/**
* Camera pitch rotation state. This states manages the change of the observer camera pitch angle.
*/
private class CameraPitchRotationState extends ControllerState {
private ObserverCamera selectedCamera;
private float oldPitch;
private String rotationToolTipFeedback;
@Override
public Mode getMode() {
return Mode.SELECTION;
}
@Override
public boolean isModificationState() {
return true;
}
@Override
public void enter() {
this.rotationToolTipFeedback = preferences.getLocalizedString(
PlanController.class, "cameraPitchRotationToolTipFeedback");
this.selectedCamera = (ObserverCamera)home.getSelectedItems().get(0);
this.oldPitch = this.selectedCamera.getPitch();
PlanView planView = getView();
planView.setResizeIndicatorVisible(true);
planView.setToolTipFeedback(getToolTipFeedbackText(this.oldPitch),
getXLastMousePress(), getYLastMousePress());
}
@Override
public void moveMouse(float x, float y) {
// Compute the new angle of the camera
float newPitch = (float)(this.oldPitch
+ (y - getYLastMousePress()) * Math.cos(this.selectedCamera.getYaw()) * Math.PI / 360
- (x - getXLastMousePress()) * Math.sin(this.selectedCamera.getYaw()) * Math.PI / 360);
// Check new angle is between -60� and 90�
newPitch = Math.max(newPitch, -(float)Math.PI / 3);
newPitch = Math.min(newPitch, (float)Math.PI / 36 * 15);
// Update camera pitch angle
this.selectedCamera.setPitch(newPitch);
getView().setToolTipFeedback(getToolTipFeedbackText(newPitch), x, y);
}
@Override
public void releaseMouse(float x, float y) {
setState(getSelectionState());
}
@Override
public void escape() {
this.selectedCamera.setPitch(this.oldPitch);
setState(getSelectionState());
}
@Override
public void exit() {
PlanView planView = getView();
planView.setResizeIndicatorVisible(false);
planView.deleteFeedback();
this.selectedCamera = null;
}
private String getToolTipFeedbackText(float angle) {
return String.format(this.rotationToolTipFeedback,
Math.round(Math.toDegrees(angle)) % 360);
}
}
/**
* Camera elevation state. This states manages the change of the observer camera elevation.
*/
private class CameraElevationState extends ControllerState {
private ObserverCamera selectedCamera;
private float oldElevation;
private String cameraElevationToolTipFeedback;
private String observerHeightToolTipFeedback;
@Override
public Mode getMode() {
return Mode.SELECTION;
}
@Override
public boolean isModificationState() {
return true;
}
@Override
public void enter() {
this.cameraElevationToolTipFeedback = preferences.getLocalizedString(
PlanController.class, "cameraElevationToolTipFeedback");
this.observerHeightToolTipFeedback = preferences.getLocalizedString(
PlanController.class, "observerHeightToolTipFeedback");
this.selectedCamera = (ObserverCamera)home.getSelectedItems().get(0);
this.oldElevation = this.selectedCamera.getZ();
PlanView planView = getView();
planView.setResizeIndicatorVisible(true);
planView.setToolTipFeedback(getToolTipFeedbackText(this.oldElevation),
getXLastMousePress(), getYLastMousePress());
}
@Override
public void moveMouse(float x, float y) {
// Compute the new elevation of the camera
float newElevation = (float)(this.oldElevation - (y - getYLastMousePress()));
List<Level> levels = home.getLevels();
float minimumElevation = levels.size() == 0 ? 10 : 10 + levels.get(0).getElevation();
// Check new elevation is between min and max
newElevation = Math.min(Math.max(newElevation, minimumElevation), preferences.getLengthUnit().getMaximumElevation());
// Update camera elevation
this.selectedCamera.setZ(newElevation);
getView().setToolTipFeedback(getToolTipFeedbackText(newElevation), x, y);
}
@Override
public void releaseMouse(float x, float y) {
setState(getSelectionState());
}
@Override
public void escape() {
this.selectedCamera.setZ(this.oldElevation);
setState(getSelectionState());
}
@Override
public void exit() {
PlanView planView = getView();
planView.setResizeIndicatorVisible(false);
planView.deleteFeedback();
this.selectedCamera = null;
}
private String getToolTipFeedbackText(float elevation) {
String toolTipFeedbackText = "<html>" + String.format(this.cameraElevationToolTipFeedback,
preferences.getLengthUnit().getFormatWithUnit().format(elevation));
if (!this.selectedCamera.isFixedSize() && elevation >= 70 && elevation <= 218.75f) {
toolTipFeedbackText += "<br>" + String.format(this.observerHeightToolTipFeedback,
preferences.getLengthUnit().getFormatWithUnit().format(elevation * 15 / 14));
}
return toolTipFeedbackText;
}
}
/**
* Dimension line creation state. This state manages transition to
* other modes, and initial dimension line creation.
*/
private class DimensionLineCreationState extends AbstractModeChangeState {
private boolean magnetismEnabled;
@Override
public Mode getMode() {
return Mode.DIMENSION_LINE_CREATION;
}
@Override
public void enter() {
getView().setCursor(PlanView.CursorType.DRAW);
toggleMagnetism(wasShiftDownLastMousePress());
}
@Override
public void moveMouse(float x, float y) {
getView().setAlignmentFeedback(DimensionLine.class, null, x, y, false);
DimensionLine dimensionLine = getMeasuringDimensionLineAt(x, y, this.magnetismEnabled);
if (dimensionLine != null) {
getView().setDimensionLinesFeedback(Arrays.asList(new DimensionLine [] {dimensionLine}));
} else {
getView().setDimensionLinesFeedback(null);
}
}
@Override
public void pressMouse(float x, float y, int clickCount,
boolean shiftDown, boolean duplicationActivated) {
// Ignore double clicks (may happen when state is activated returning from DimensionLineDrawingState)
if (clickCount == 1) {
// Change state to DimensionLineDrawingState
setState(getDimensionLineDrawingState());
}
}
@Override
public void setEditionActivated(boolean editionActivated) {
if (editionActivated) {
setState(getDimensionLineDrawingState());
PlanController.this.setEditionActivated(editionActivated);
}
}
@Override
public void toggleMagnetism(boolean magnetismToggled) {
// Compute active magnetism
this.magnetismEnabled = preferences.isMagnetismEnabled()
^ magnetismToggled;
moveMouse(getXLastMouseMove(), getYLastMouseMove());
}
@Override
public void exit() {
getView().deleteFeedback();
}
}
/**
* Dimension line drawing state. This state manages dimension line creation at mouse press.
*/
private class DimensionLineDrawingState extends ControllerState {
private float xStart;
private float yStart;
private boolean editingStartPoint;
private DimensionLine newDimensionLine;
private List<Selectable> oldSelection;
private boolean oldBasePlanLocked;
private boolean magnetismEnabled;
private boolean offsetChoice;
@Override
public Mode getMode() {
return Mode.DIMENSION_LINE_CREATION;
}
@Override
public boolean isModificationState() {
return true;
}
@Override
public void setMode(Mode mode) {
// Escape current creation and change state to matching mode
escape();
if (mode == Mode.SELECTION) {
setState(getSelectionState());
} else if (mode == Mode.PANNING) {
setState(getPanningState());
} else if (mode == Mode.WALL_CREATION) {
setState(getWallCreationState());
} else if (mode == Mode.ROOM_CREATION) {
setState(getRoomCreationState());
} else if (mode == Mode.LABEL_CREATION) {
setState(getLabelCreationState());
}
}
@Override
public void enter() {
this.oldSelection = home.getSelectedItems();
this.oldBasePlanLocked = home.isBasePlanLocked();
this.xStart = getXLastMouseMove();
this.yStart = getYLastMouseMove();
this.editingStartPoint = false;
this.offsetChoice = false;
this.newDimensionLine = null;
deselectAll();
toggleMagnetism(wasShiftDownLastMousePress());
DimensionLine dimensionLine = getMeasuringDimensionLineAt(
getXLastMousePress(), getYLastMousePress(), this.magnetismEnabled);
if (dimensionLine != null) {
getView().setDimensionLinesFeedback(Arrays.asList(new DimensionLine [] {dimensionLine}));
}
getView().setAlignmentFeedback(DimensionLine.class,
null, getXLastMousePress(), getYLastMousePress(), false);
}
@Override
public void moveMouse(float x, float y) {
PlanView planView = getView();
planView.deleteFeedback();
if (this.offsetChoice) {
float distanceToDimensionLine = (float)Line2D.ptLineDist(
this.newDimensionLine.getXStart(), this.newDimensionLine.getYStart(),
this.newDimensionLine.getXEnd(), this.newDimensionLine.getYEnd(), x, y);
if (this.newDimensionLine.getLength() > 0) {
int relativeCCW = Line2D.relativeCCW(
this.newDimensionLine.getXStart(), this.newDimensionLine.getYStart(),
this.newDimensionLine.getXEnd(), this.newDimensionLine.getYEnd(), x, y);
this.newDimensionLine.setOffset(
-Math.signum(relativeCCW) * distanceToDimensionLine);
}
} else {
// Compute the coordinates where dimension line end point should be moved
float newX;
float newY;
if (this.magnetismEnabled) {
PointWithAngleMagnetism point = new PointWithAngleMagnetism(
this.xStart, this.yStart, x, y,
preferences.getLengthUnit(), planView.getPixelLength());
newX = point.getX();
newY = point.getY();
} else {
newX = x;
newY = y;
}
// If current dimension line doesn't exist
if (this.newDimensionLine == null) {
// Create a new one
this.newDimensionLine = createDimensionLine(this.xStart, this.yStart, newX, newY, 0);
getView().setDimensionLinesFeedback(null);
} else {
// Otherwise update its end points
if (this.editingStartPoint) {
this.newDimensionLine.setXStart(newX);
this.newDimensionLine.setYStart(newY);
} else {
this.newDimensionLine.setXEnd(newX);
this.newDimensionLine.setYEnd(newY);
}
}
updateReversedDimensionLine();
planView.setAlignmentFeedback(DimensionLine.class,
this.newDimensionLine, newX, newY, false);
}
// Ensure point at (x,y) is visible
planView.makePointVisible(x, y);
}
/**
* Swaps start and end point of the created dimension line if needed
* to ensure its text is never upside down.
*/
private void updateReversedDimensionLine() {
double angle = getDimensionLineAngle();
boolean reverse = angle < -Math.PI / 2 || angle > Math.PI / 2;
if (reverse ^ this.editingStartPoint) {
reverseDimensionLine(this.newDimensionLine);
this.editingStartPoint = !this.editingStartPoint;
}
}
private double getDimensionLineAngle() {
if (this.newDimensionLine.getLength() == 0) {
return 0;
} else {
if (this.editingStartPoint) {
return Math.atan2(this.yStart - this.newDimensionLine.getYStart(),
this.newDimensionLine.getXStart() - this.xStart);
} else {
return Math.atan2(this.yStart - this.newDimensionLine.getYEnd(),
this.newDimensionLine.getXEnd() - this.xStart);
}
}
}
@Override
public void pressMouse(float x, float y, int clickCount,
boolean shiftDown, boolean duplicationActivated) {
if (this.newDimensionLine == null
&& clickCount == 2) {
// Try to guess the item to measure
DimensionLine dimensionLine = getMeasuringDimensionLineAt(x, y, this.magnetismEnabled);
this.newDimensionLine = createDimensionLine(
dimensionLine.getXStart(), dimensionLine.getYStart(),
dimensionLine.getXEnd(), dimensionLine.getYEnd(),
dimensionLine.getOffset());
}
// Create a new dimension line only when it will have a length > 0
// meaning after the first mouse move
if (this.newDimensionLine != null) {
if (this.offsetChoice) {
validateDrawnDimensionLine();
} else {
// Switch to offset choice
this.offsetChoice = true;
PlanView planView = getView();
planView.setCursor(PlanView.CursorType.HEIGHT);
planView.deleteFeedback();
}
}
}
private void validateDrawnDimensionLine() {
selectItem(this.newDimensionLine);
// Post dimension line creation to undo support
postCreateDimensionLines(Arrays.asList(new DimensionLine [] {this.newDimensionLine}),
this.oldSelection, this.oldBasePlanLocked);
this.newDimensionLine = null;
// Change state to DimensionLineCreationState
setState(getDimensionLineCreationState());
}
@Override
public void setEditionActivated(boolean editionActivated) {
PlanView planView = getView();
if (editionActivated) {
planView.deleteFeedback();
if (this.newDimensionLine == null) {
// Edit xStart and yStart
planView.setToolTipEditedProperties(new EditableProperty [] {EditableProperty.X,
EditableProperty.Y},
new Object [] {this.xStart, this.yStart},
this.xStart, this.yStart);
} else if (this.offsetChoice) {
// Edit offset
planView.setToolTipEditedProperties(new EditableProperty [] {EditableProperty.OFFSET},
new Object [] {this.newDimensionLine.getOffset()},
this.newDimensionLine.getXEnd(), this.newDimensionLine.getYEnd());
} else {
// Edit length and angle
planView.setToolTipEditedProperties(new EditableProperty [] {EditableProperty.LENGTH,
EditableProperty.ANGLE},
new Object [] {this.newDimensionLine.getLength(),
(int)Math.round(Math.toDegrees(getDimensionLineAngle()))},
this.newDimensionLine.getXEnd(), this.newDimensionLine.getYEnd());
}
} else {
if (this.newDimensionLine == null) {
// Create a new dimension line once user entered its start point
float defaultLength = preferences.getLengthUnit() == LengthUnit.INCH
? LengthUnit.footToCentimeter(3) : 100;
this.newDimensionLine = createDimensionLine(this.xStart, this.yStart,
this.xStart + defaultLength, this.yStart, 0);
// Activate automatically second step to let user enter the
// length and angle of the new dimension line
planView.deleteFeedback();
setEditionActivated(true);
} else if (this.offsetChoice) {
validateDrawnDimensionLine();
} else {
this.offsetChoice = true;
setEditionActivated(true);
}
}
}
@Override
public void updateEditableProperty(EditableProperty editableProperty, Object value) {
PlanView planView = getView();
float maximumLength = preferences.getLengthUnit().getMaximumLength();
if (this.newDimensionLine == null) {
// Update start point of the dimension line
switch (editableProperty) {
case X :
this.xStart = value != null ? ((Number)value).floatValue() : 0;
this.xStart = Math.max(-maximumLength, Math.min(this.xStart, maximumLength));
break;
case Y :
this.yStart = value != null ? ((Number)value).floatValue() : 0;
this.yStart = Math.max(-maximumLength, Math.min(this.yStart, maximumLength));
break;
}
planView.setAlignmentFeedback(DimensionLine.class, null, this.xStart, this.yStart, true);
planView.makePointVisible(this.xStart, this.yStart);
} else if (this.offsetChoice) {
if (editableProperty == EditableProperty.OFFSET) {
// Update new dimension line offset
float offset = value != null ? ((Number)value).floatValue() : 0;
offset = Math.max(-maximumLength, Math.min(offset, maximumLength));
this.newDimensionLine.setOffset(offset);
}
} else {
float newX;
float newY;
// Update end point of the dimension line
switch (editableProperty) {
case LENGTH :
float length = value != null ? ((Number)value).floatValue() : 0;
length = Math.max(0.001f, Math.min(length, maximumLength));
double dimensionLineAngle = getDimensionLineAngle();
newX = (float)(this.xStart + length * Math.cos(dimensionLineAngle));
newY = (float)(this.yStart - length * Math.sin(dimensionLineAngle));
break;
case ANGLE :
dimensionLineAngle = Math.toRadians(value != null ? ((Number)value).floatValue() : 0);
float dimensionLineLength = this.newDimensionLine.getLength();
newX = (float)(this.xStart + dimensionLineLength * Math.cos(dimensionLineAngle));
newY = (float)(this.yStart - dimensionLineLength * Math.sin(dimensionLineAngle));
break;
default :
return;
}
// Update new dimension line
if (this.editingStartPoint) {
this.newDimensionLine.setXStart(newX);
this.newDimensionLine.setYStart(newY);
} else {
this.newDimensionLine.setXEnd(newX);
this.newDimensionLine.setYEnd(newY);
}
updateReversedDimensionLine();
planView.setAlignmentFeedback(DimensionLine.class, this.newDimensionLine, newX, newY, false);
// Ensure dimension line end points are visible
planView.makePointVisible(this.xStart, this.yStart);
planView.makePointVisible(newX, newY);
}
}
@Override
public void toggleMagnetism(boolean magnetismToggled) {
// Compute active magnetism
this.magnetismEnabled = preferences.isMagnetismEnabled()
^ magnetismToggled;
// If the new dimension line already exists,
// compute again its end as if mouse moved
if (this.newDimensionLine != null && !this.offsetChoice) {
moveMouse(getXLastMouseMove(), getYLastMouseMove());
}
}
@Override
public void escape() {
if (this.newDimensionLine != null) {
// Delete current created dimension line
home.deleteDimensionLine(this.newDimensionLine);
}
// Change state to DimensionLineCreationState
setState(getDimensionLineCreationState());
}
@Override
public void exit() {
getView().deleteFeedback();
this.newDimensionLine = null;
this.oldSelection = null;
}
}
/**
* Dimension line resize state. This state manages dimension line resizing.
*/
private class DimensionLineResizeState extends ControllerState {
private DimensionLine selectedDimensionLine;
private boolean editingStartPoint;
private float oldX;
private float oldY;
private boolean reversedDimensionLine;
private float deltaXToResizePoint;
private float deltaYToResizePoint;
private float distanceFromResizePointToDimensionBaseLine;
private boolean magnetismEnabled;
@Override
public Mode getMode() {
return Mode.SELECTION;
}
@Override
public boolean isModificationState() {
return true;
}
@Override
public void enter() {
PlanView planView = getView();
planView.setResizeIndicatorVisible(true);
this.selectedDimensionLine = (DimensionLine)home.getSelectedItems().get(0);
this.editingStartPoint = this.selectedDimensionLine
== getResizedDimensionLineStartAt(getXLastMousePress(), getYLastMousePress());
if (this.editingStartPoint) {
this.oldX = this.selectedDimensionLine.getXStart();
this.oldY = this.selectedDimensionLine.getYStart();
} else {
this.oldX = this.selectedDimensionLine.getXEnd();
this.oldY = this.selectedDimensionLine.getYEnd();
}
this.reversedDimensionLine = false;
float xResizePoint;
float yResizePoint;
// Compute the closest resize point placed on the extension line and the distance
// between that point and the dimension line base
float alpha1 = (float)(this.selectedDimensionLine.getYEnd() - this.selectedDimensionLine.getYStart())
/ (this.selectedDimensionLine.getXEnd() - this.selectedDimensionLine.getXStart());
// If line is vertical
if (Math.abs(alpha1) > 1E5) {
xResizePoint = getXLastMousePress();
if (this.editingStartPoint) {
yResizePoint = this.selectedDimensionLine.getYStart();
} else {
yResizePoint = this.selectedDimensionLine.getYEnd();
}
} else if (this.selectedDimensionLine.getYStart() == this.selectedDimensionLine.getYEnd()) {
if (this.editingStartPoint) {
xResizePoint = this.selectedDimensionLine.getXStart();
} else {
xResizePoint = this.selectedDimensionLine.getXEnd();
}
yResizePoint = getYLastMousePress();
} else {
float beta1 = getYLastMousePress() - alpha1 * getXLastMousePress();
float alpha2 = -1 / alpha1;
float beta2;
if (this.editingStartPoint) {
beta2 = this.selectedDimensionLine.getYStart() - alpha2 * this.selectedDimensionLine.getXStart();
} else {
beta2 = this.selectedDimensionLine.getYEnd() - alpha2 * this.selectedDimensionLine.getXEnd();
}
xResizePoint = (beta2 - beta1) / (alpha1 - alpha2);
yResizePoint = alpha1 * xResizePoint + beta1;
}
this.deltaXToResizePoint = getXLastMousePress() - xResizePoint;
this.deltaYToResizePoint = getYLastMousePress() - yResizePoint;
if (this.editingStartPoint) {
this.distanceFromResizePointToDimensionBaseLine = (float)Point2D.distance(xResizePoint, yResizePoint,
this.selectedDimensionLine.getXStart(), this.selectedDimensionLine.getYStart());
planView.setAlignmentFeedback(DimensionLine.class, this.selectedDimensionLine,
this.selectedDimensionLine.getXStart(), this.selectedDimensionLine.getYStart(), false);
} else {
this.distanceFromResizePointToDimensionBaseLine = (float)Point2D.distance(xResizePoint, yResizePoint,
this.selectedDimensionLine.getXEnd(), this.selectedDimensionLine.getYEnd());
planView.setAlignmentFeedback(DimensionLine.class, this.selectedDimensionLine,
this.selectedDimensionLine.getXEnd(), this.selectedDimensionLine.getYEnd(), false);
}
toggleMagnetism(wasShiftDownLastMousePress());
}
@Override
public void moveMouse(float x, float y) {
PlanView planView = getView();
float xResizePoint = x - this.deltaXToResizePoint;
float yResizePoint = y - this.deltaYToResizePoint;
if (this.editingStartPoint) {
// Compute the new start point of the dimension line knowing that the distance
// from resize point to dimension line base is constant,
// and that the end point of the dimension line doesn't move
double distanceFromResizePointToDimensionLineEnd = Point2D.distance(xResizePoint, yResizePoint,
this.selectedDimensionLine.getXEnd(), this.selectedDimensionLine.getYEnd());
double distanceFromDimensionLineStartToDimensionLineEnd = Math.sqrt(
distanceFromResizePointToDimensionLineEnd * distanceFromResizePointToDimensionLineEnd
- this.distanceFromResizePointToDimensionBaseLine * this.distanceFromResizePointToDimensionBaseLine);
if (distanceFromDimensionLineStartToDimensionLineEnd > 0) {
double dimensionLineRelativeAngle = -Math.atan2(this.distanceFromResizePointToDimensionBaseLine,
distanceFromDimensionLineStartToDimensionLineEnd);
if (this.selectedDimensionLine.getOffset() >= 0) {
dimensionLineRelativeAngle = -dimensionLineRelativeAngle;
}
double resizePointToDimensionLineEndAngle = Math.atan2(yResizePoint - this.selectedDimensionLine.getYEnd(),
xResizePoint - this.selectedDimensionLine.getXEnd());
double dimensionLineStartToDimensionLineEndAngle = dimensionLineRelativeAngle + resizePointToDimensionLineEndAngle;
float xNewStartPoint = this.selectedDimensionLine.getXEnd() + (float)(distanceFromDimensionLineStartToDimensionLineEnd
* Math.cos(dimensionLineStartToDimensionLineEndAngle));
float yNewStartPoint = this.selectedDimensionLine.getYEnd() + (float)(distanceFromDimensionLineStartToDimensionLineEnd
* Math.sin(dimensionLineStartToDimensionLineEndAngle));
if (this.magnetismEnabled) {
PointWithAngleMagnetism point = new PointWithAngleMagnetism(
this.selectedDimensionLine.getXEnd(),
this.selectedDimensionLine.getYEnd(), xNewStartPoint, yNewStartPoint,
preferences.getLengthUnit(), planView.getPixelLength());
xNewStartPoint = point.getX();
yNewStartPoint = point.getY();
}
moveDimensionLinePoint(this.selectedDimensionLine, xNewStartPoint, yNewStartPoint, this.editingStartPoint);
updateReversedDimensionLine();
planView.setAlignmentFeedback(DimensionLine.class, this.selectedDimensionLine,
xNewStartPoint, yNewStartPoint, false);
} else {
planView.deleteFeedback();
}
} else {
// Compute the new end point of the dimension line knowing that the distance
// from resize point to dimension line base is constant,
// and that the start point of the dimension line doesn't move
double distanceFromResizePointToDimensionLineStart = Point2D.distance(xResizePoint, yResizePoint,
this.selectedDimensionLine.getXStart(), this.selectedDimensionLine.getYStart());
double distanceFromDimensionLineStartToDimensionLineEnd = Math.sqrt(
distanceFromResizePointToDimensionLineStart * distanceFromResizePointToDimensionLineStart
- this.distanceFromResizePointToDimensionBaseLine * this.distanceFromResizePointToDimensionBaseLine);
if (distanceFromDimensionLineStartToDimensionLineEnd > 0) {
double dimensionLineRelativeAngle = Math.atan2(this.distanceFromResizePointToDimensionBaseLine,
distanceFromDimensionLineStartToDimensionLineEnd);
if (this.selectedDimensionLine.getOffset() >= 0) {
dimensionLineRelativeAngle = -dimensionLineRelativeAngle;
}
double resizePointToDimensionLineStartAngle = Math.atan2(yResizePoint - this.selectedDimensionLine.getYStart(),
xResizePoint - this.selectedDimensionLine.getXStart());
double dimensionLineStartToDimensionLineEndAngle = dimensionLineRelativeAngle + resizePointToDimensionLineStartAngle;
float xNewEndPoint = this.selectedDimensionLine.getXStart() + (float)(distanceFromDimensionLineStartToDimensionLineEnd
* Math.cos(dimensionLineStartToDimensionLineEndAngle));
float yNewEndPoint = this.selectedDimensionLine.getYStart() + (float)(distanceFromDimensionLineStartToDimensionLineEnd
* Math.sin(dimensionLineStartToDimensionLineEndAngle));
if (this.magnetismEnabled) {
PointWithAngleMagnetism point = new PointWithAngleMagnetism(
this.selectedDimensionLine.getXStart(),
this.selectedDimensionLine.getYStart(), xNewEndPoint, yNewEndPoint,
preferences.getLengthUnit(), planView.getPixelLength());
xNewEndPoint = point.getX();
yNewEndPoint = point.getY();
}
moveDimensionLinePoint(this.selectedDimensionLine, xNewEndPoint, yNewEndPoint, this.editingStartPoint);
updateReversedDimensionLine();
planView.setAlignmentFeedback(DimensionLine.class, this.selectedDimensionLine,
xNewEndPoint, yNewEndPoint, false);
} else {
planView.deleteFeedback();
}
}
// Ensure point at (x,y) is visible
getView().makePointVisible(x, y);
}
/**
* Swaps start and end point of the dimension line if needed
* to ensure its text is never upside down.
*/
private void updateReversedDimensionLine() {
double angle = getDimensionLineAngle();
if (angle < -Math.PI / 2 || angle > Math.PI / 2) {
reverseDimensionLine(this.selectedDimensionLine);
this.editingStartPoint = !this.editingStartPoint;
this.reversedDimensionLine = !this.reversedDimensionLine;
}
}
private double getDimensionLineAngle() {
if (this.selectedDimensionLine.getLength() == 0) {
return 0;
} else {
return Math.atan2(this.selectedDimensionLine.getYStart() - this.selectedDimensionLine.getYEnd(),
this.selectedDimensionLine.getXEnd() - this.selectedDimensionLine.getXStart());
}
}
@Override
public void releaseMouse(float x, float y) {
postDimensionLineResize(this.selectedDimensionLine, this.oldX, this.oldY,
this.editingStartPoint, this.reversedDimensionLine);
setState(getSelectionState());
}
@Override
public void toggleMagnetism(boolean magnetismToggled) {
// Compute active magnetism
this.magnetismEnabled = preferences.isMagnetismEnabled()
^ magnetismToggled;
moveMouse(getXLastMouseMove(), getYLastMouseMove());
}
@Override
public void escape() {
if (this.reversedDimensionLine) {
reverseDimensionLine(this.selectedDimensionLine);
this.editingStartPoint = !this.editingStartPoint;
}
moveDimensionLinePoint(this.selectedDimensionLine, this.oldX, this.oldY, this.editingStartPoint);
setState(getSelectionState());
}
@Override
public void exit() {
PlanView planView = getView();
planView.deleteFeedback();
planView.setResizeIndicatorVisible(false);
this.selectedDimensionLine = null;
}
}
/**
* Dimension line offset state. This state manages dimension line offset.
*/
private class DimensionLineOffsetState extends ControllerState {
private DimensionLine selectedDimensionLine;
private float oldOffset;
private float deltaXToOffsetPoint;
private float deltaYToOffsetPoint;
@Override
public Mode getMode() {
return Mode.SELECTION;
}
@Override
public boolean isModificationState() {
return true;
}
@Override
public void enter() {
this.selectedDimensionLine = (DimensionLine)home.getSelectedItems().get(0);
this.oldOffset = this.selectedDimensionLine.getOffset();
double angle = Math.atan2(this.selectedDimensionLine.getYEnd() - this.selectedDimensionLine.getYStart(),
this.selectedDimensionLine.getXEnd() - this.selectedDimensionLine.getXStart());
float dx = (float)-Math.sin(angle) * this.oldOffset;
float dy = (float)Math.cos(angle) * this.oldOffset;
float xMiddle = (this.selectedDimensionLine.getXStart() + this.selectedDimensionLine.getXEnd()) / 2 + dx;
float yMiddle = (this.selectedDimensionLine.getYStart() + this.selectedDimensionLine.getYEnd()) / 2 + dy;
this.deltaXToOffsetPoint = getXLastMousePress() - xMiddle;
this.deltaYToOffsetPoint = getYLastMousePress() - yMiddle;
PlanView planView = getView();
planView.setResizeIndicatorVisible(true);
}
@Override
public void moveMouse(float x, float y) {
float newX = x - this.deltaXToOffsetPoint;
float newY = y - this.deltaYToOffsetPoint;
float distanceToDimensionLine =
(float)Line2D.ptLineDist(this.selectedDimensionLine.getXStart(), this.selectedDimensionLine.getYStart(),
this.selectedDimensionLine.getXEnd(), this.selectedDimensionLine.getYEnd(), newX, newY);
int relativeCCW = Line2D.relativeCCW(this.selectedDimensionLine.getXStart(), this.selectedDimensionLine.getYStart(),
this.selectedDimensionLine.getXEnd(), this.selectedDimensionLine.getYEnd(), newX, newY);
this.selectedDimensionLine.setOffset(
-Math.signum(relativeCCW) * distanceToDimensionLine);
// Ensure point at (x,y) is visible
getView().makePointVisible(x, y);
}
@Override
public void releaseMouse(float x, float y) {
postDimensionLineOffset(this.selectedDimensionLine, this.oldOffset);
setState(getSelectionState());
}
@Override
public void escape() {
this.selectedDimensionLine.setOffset(this.oldOffset);
setState(getSelectionState());
}
@Override
public void exit() {
getView().setResizeIndicatorVisible(false);
this.selectedDimensionLine = null;
}
}
/**
* Room creation state. This state manages transition to
* other modes, and initial room creation.
*/
private class RoomCreationState extends AbstractModeChangeState {
private boolean magnetismEnabled;
@Override
public Mode getMode() {
return Mode.ROOM_CREATION;
}
@Override
public void enter() {
getView().setCursor(PlanView.CursorType.DRAW);
toggleMagnetism(wasShiftDownLastMousePress());
}
@Override
public void moveMouse(float x, float y) {
if (this.magnetismEnabled) {
// Find the closest wall or room point to current mouse location
PointMagnetizedToClosestWallOrRoomPoint point = new PointMagnetizedToClosestWallOrRoomPoint(x, y);
if (point.isMagnetized()) {
getView().setAlignmentFeedback(Room.class, null, point.getX(),
point.getY(), point.isMagnetized());
} else {
RoomPointWithAngleMagnetism pointWithAngleMagnetism = new RoomPointWithAngleMagnetism(
getXLastMouseMove(), getYLastMouseMove());
getView().setAlignmentFeedback(Room.class, null, pointWithAngleMagnetism.getX(),
pointWithAngleMagnetism.getY(), point.isMagnetized());
}
} else {
getView().setAlignmentFeedback(Room.class, null, x, y, false);
}
}
@Override
public void pressMouse(float x, float y, int clickCount,
boolean shiftDown, boolean duplicationActivated) {
// Change state to RoomDrawingState
setState(getRoomDrawingState());
}
@Override
public void setEditionActivated(boolean editionActivated) {
if (editionActivated) {
setState(getRoomDrawingState());
PlanController.this.setEditionActivated(editionActivated);
}
}
@Override
public void toggleMagnetism(boolean magnetismToggled) {
// Compute active magnetism
this.magnetismEnabled = preferences.isMagnetismEnabled()
^ magnetismToggled;
// Compute again feedback point as if mouse moved
moveMouse(getXLastMouseMove(), getYLastMouseMove());
}
@Override
public void exit() {
getView().deleteFeedback();
}
}
/**
* Room modification state.
*/
private abstract class AbstractRoomState extends ControllerState {
private String roomSideLengthToolTipFeedback;
private String roomSideAngleToolTipFeedback;
@Override
public void enter() {
this.roomSideLengthToolTipFeedback = preferences.getLocalizedString(
PlanController.class, "roomSideLengthToolTipFeedback");
this.roomSideAngleToolTipFeedback = preferences.getLocalizedString(
PlanController.class, "roomSideAngleToolTipFeedback");
}
protected String getToolTipFeedbackText(Room room, int pointIndex) {
float length = getRoomSideLength(room, pointIndex);
int angle = getRoomSideAngle(room, pointIndex);
return "<html>" + String.format(this.roomSideLengthToolTipFeedback,
preferences.getLengthUnit().getFormatWithUnit().format(length))
+ "<br>" + String.format(this.roomSideAngleToolTipFeedback, angle);
}
protected float getRoomSideLength(Room room, int pointIndex) {
float [][] points = room.getPoints();
float [] previousPoint = points [(pointIndex + points.length - 1) % points.length];
return (float)Point2D.distance(previousPoint [0], previousPoint [1],
points [pointIndex][0], points [pointIndex][1]);
}
/**
* Returns room side angle at the given point index in degrees.
*/
protected Integer getRoomSideAngle(Room room, int pointIndex) {
float [][] points = room.getPoints();
float [] point = points [pointIndex];
float [] previousPoint = points [(pointIndex + points.length - 1) % points.length];
float [] previousPreviousPoint = points [(pointIndex + points.length - 2) % points.length];
float sideLength = (float)Point2D.distance(
previousPoint [0], previousPoint [1],
points [pointIndex][0], points [pointIndex][1]);
float previousSideLength = (float)Point2D.distance(
previousPreviousPoint [0], previousPreviousPoint [1],
previousPoint [0], previousPoint [1]);
if (previousPreviousPoint != point
&& sideLength != 0 && previousSideLength != 0) {
// Compute the angle between the side finishing at pointIndex
// and the previous side
float xSideVector = (point [0] - previousPoint [0]) / sideLength;
float ySideVector = (point [1] - previousPoint [1]) / sideLength;
float xPreviousSideVector = (previousPoint [0] - previousPreviousPoint [0]) / previousSideLength;
float yPreviousSideVector = (previousPoint [1] - previousPreviousPoint [1]) / previousSideLength;
int sideAngle = (int)Math.round(180 - Math.toDegrees(Math.atan2(
ySideVector * xPreviousSideVector - xSideVector * yPreviousSideVector,
xSideVector * xPreviousSideVector + ySideVector * yPreviousSideVector)));
if (sideAngle > 180) {
sideAngle -= 360;
}
return sideAngle;
}
if (sideLength == 0) {
return 0;
} else {
return (int)Math.round(Math.toDegrees(Math.atan2(
previousPoint [1] - point [1],
point [0] - previousPoint [0])));
}
}
protected void showRoomAngleFeedback(Room room, int pointIndex) {
float [][] points = room.getPoints();
if (points.length > 2) {
float [] previousPoint = points [(pointIndex + points.length - 1) % points.length];
float [] previousPreviousPoint = points [(pointIndex + points.length - 2) % points.length];
if (getRoomSideAngle(room, pointIndex) > 0) {
getView().setAngleFeedback(previousPoint [0], previousPoint [1],
previousPreviousPoint [0], previousPreviousPoint [1],
points [pointIndex][0], points [pointIndex][1]);
} else {
getView().setAngleFeedback(previousPoint [0], previousPoint [1],
points [pointIndex][0], points [pointIndex][1],
previousPreviousPoint [0], previousPreviousPoint [1]);
}
}
}
}
/**
* Room drawing state. This state manages room creation at mouse press.
*/
private class RoomDrawingState extends AbstractRoomState {
private float xPreviousPoint;
private float yPreviousPoint;
private Room newRoom;
private float [] newPoint;
private List<Selectable> oldSelection;
private boolean oldBasePlanLocked;
private boolean magnetismEnabled;
private long lastPointCreationTime;
@Override
public Mode getMode() {
return Mode.ROOM_CREATION;
}
@Override
public boolean isModificationState() {
return true;
}
@Override
public void setMode(Mode mode) {
// Escape current creation and change state to matching mode
escape();
if (mode == Mode.SELECTION) {
setState(getSelectionState());
} else if (mode == Mode.PANNING) {
setState(getPanningState());
} else if (mode == Mode.WALL_CREATION) {
setState(getWallCreationState());
} else if (mode == Mode.DIMENSION_LINE_CREATION) {
setState(getDimensionLineCreationState());
} else if (mode == Mode.LABEL_CREATION) {
setState(getLabelCreationState());
}
}
@Override
public void enter() {
super.enter();
this.oldSelection = home.getSelectedItems();
this.oldBasePlanLocked = home.isBasePlanLocked();
this.newRoom = null;
toggleMagnetism(wasShiftDownLastMousePress());
if (this.magnetismEnabled) {
// Find the closest wall or room point to current mouse location
PointMagnetizedToClosestWallOrRoomPoint point = new PointMagnetizedToClosestWallOrRoomPoint(
getXLastMouseMove(), getYLastMouseMove());
if (point.isMagnetized()) {
this.xPreviousPoint = point.getX();
this.yPreviousPoint = point.getY();
} else {
RoomPointWithAngleMagnetism pointWithAngleMagnetism = new RoomPointWithAngleMagnetism(
getXLastMouseMove(), getYLastMouseMove());
this.xPreviousPoint = pointWithAngleMagnetism.getX();
this.yPreviousPoint = pointWithAngleMagnetism.getY();
}
getView().setAlignmentFeedback(Room.class, null,
this.xPreviousPoint, this.yPreviousPoint, point.isMagnetized());
} else {
this.xPreviousPoint = getXLastMousePress();
this.yPreviousPoint = getYLastMousePress();
getView().setAlignmentFeedback(Room.class, null,
this.xPreviousPoint, this.yPreviousPoint, false);
}
deselectAll();
}
@Override
public void moveMouse(float x, float y) {
PlanView planView = getView();
// Compute the coordinates where current edit room point should be moved
float xEnd = x;
float yEnd = y;
boolean magnetizedPoint = false;
if (this.magnetismEnabled) {
// Find the closest wall or room point to current mouse location
PointMagnetizedToClosestWallOrRoomPoint point = this.newRoom != null
? new PointMagnetizedToClosestWallOrRoomPoint(this.newRoom, this.newRoom.getPointCount() - 1, x, y)
: new PointMagnetizedToClosestWallOrRoomPoint(x, y);
magnetizedPoint = point.isMagnetized();
if (magnetizedPoint) {
xEnd = point.getX();
yEnd = point.getY();
} else {
// Use magnetism if closest wall point is too far
int editedPointIndex = this.newRoom != null
? this.newRoom.getPointCount() - 1
: -1;
RoomPointWithAngleMagnetism pointWithAngleMagnetism = new RoomPointWithAngleMagnetism(
this.newRoom, editedPointIndex, this.xPreviousPoint, this.yPreviousPoint, x, y);
xEnd = pointWithAngleMagnetism.getX();
yEnd = pointWithAngleMagnetism.getY();
}
}
// If current room doesn't exist
if (this.newRoom == null) {
// Create a new one
this.newRoom = createAndSelectRoom(this.xPreviousPoint, this.yPreviousPoint, xEnd, yEnd);
} else if (this.newPoint != null) {
// Add a point to current room
float [][] points = this.newRoom.getPoints();
this.xPreviousPoint = points [points.length - 1][0];
this.yPreviousPoint = points [points.length - 1][1];
this.newRoom.addPoint(xEnd, yEnd);
this.newPoint = null;
} else {
// Otherwise update its last point
this.newRoom.setPoint(xEnd, yEnd, this.newRoom.getPointCount() - 1);
}
planView.setToolTipFeedback(
getToolTipFeedbackText(this.newRoom, this.newRoom.getPointCount() - 1), x, y);
planView.setAlignmentFeedback(Room.class, this.newRoom,
xEnd, yEnd, magnetizedPoint);
showRoomAngleFeedback(this.newRoom, this.newRoom.getPointCount() - 1);
// Ensure point at (x,y) is visible
planView.makePointVisible(x, y);
}
/**
* Returns a new room instance with one side between (<code>xStart</code>,
* <code>yStart</code>) and (<code>xEnd</code>, <code>yEnd</code>) points.
* The new room is added to home and selected
*/
private Room createAndSelectRoom(float xStart, float yStart,
float xEnd, float yEnd) {
Room newRoom = createRoom(new float [][] {{xStart, yStart}, {xEnd, yEnd}});
// Let's consider that points outside of home will create by default a room with no ceiling
Area insideWallsArea = getInsideWallsArea();
newRoom.setCeilingVisible(insideWallsArea.contains(xStart, yStart));
selectItem(newRoom);
return newRoom;
}
@Override
public void pressMouse(float x, float y, int clickCount,
boolean shiftDown, boolean duplicationActivated) {
if (clickCount == 2) {
if (this.newRoom == null) {
// Try to guess the room that contains the point (x,y)
this.newRoom = createRoomAt(x, y);
if (this.newRoom != null) {
selectItem(this.newRoom);
}
}
validateDrawnRoom();
} else {
endRoomSide();
}
}
private void validateDrawnRoom() {
if (this.newRoom != null) {
float [][] points = this.newRoom.getPoints();
if (points.length < 3) {
// Delete current created room if it doesn't have more than 2 clicked points
home.deleteRoom(this.newRoom);
} else {
// Post room creation to undo support
postCreateRooms(Arrays.asList(new Room [] {this.newRoom}),
this.oldSelection, this.oldBasePlanLocked);
}
}
// Change state to RoomCreationState
setState(getRoomCreationState());
}
private void endRoomSide() {
// Create a new room side only when its length is greater than zero
if (this.newRoom != null
&& getRoomSideLength(this.newRoom, this.newRoom.getPointCount() - 1) > 0) {
this.newPoint = new float [2];
// Let's consider that any point outside of home will create
// by default a room with no ceiling
if (this.newRoom.isCeilingVisible()) {
float [][] roomPoints = this.newRoom.getPoints();
float [] lastPoint = roomPoints [roomPoints.length - 1];
if (!getInsideWallsArea().contains(lastPoint [0], lastPoint [1])) {
this.newRoom.setCeilingVisible(false);
}
}
}
}
/**
* Returns the room matching the closed path that contains the point at the given
* coordinates or <code>null</code> if there's no closed path at this point.
*/
private Room createRoomAt(float x, float y) {
for (GeneralPath roomPath : getRoomPathsFromWalls()) {
if (roomPath.contains(x, y)) {
// Add to roomPath a half of the footprint on floor of all the doors and windows
// with an elevation equal to zero that intersects with roomPath
for (HomePieceOfFurniture piece : getVisibleDoorsAndWindowsAtGround(home.getFurniture())) {
float [][] doorPoints = piece.getPoints();
int intersectionCount = 0;
for (int i = 0; i < doorPoints.length; i++) {
if (roomPath.contains(doorPoints [i][0], doorPoints [i][1])) {
intersectionCount++;
}
}
if (intersectionCount == 2
&& doorPoints.length == 4) {
// Find the intersection of the door with home walls
Area wallsDoorIntersection = new Area(getWallsArea());
wallsDoorIntersection.intersect(new Area(getPath(doorPoints)));
// Reduce the size of intersection to its half
float [][] intersectionPoints = getPathPoints(getPath(wallsDoorIntersection), false);
Shape halfDoorPath = null;
if (intersectionPoints.length == 4) {
float epsilon = 0.05f;
for (int i = 0; i < intersectionPoints.length; i++) {
// Check point in room with rectangle intersection test otherwise we miss some points
if (roomPath.intersects(intersectionPoints [i][0] - epsilon / 2,
intersectionPoints [i][1] - epsilon / 2, epsilon, epsilon)) {
int inPoint1 = i;
int inPoint2;
int outPoint1;
int outPoint2;
if (roomPath.intersects(intersectionPoints [i + 1][0] - epsilon / 2,
intersectionPoints [i + 1][1] - epsilon / 2, epsilon, epsilon)) {
inPoint2 = i + 1;
outPoint2 = (i + 2) % 4;
outPoint1 = (i + 3) % 4;
} else {
outPoint1 = (i + 1) % 4;
outPoint2 = (i + 2) % 4;
inPoint2 = (i + 3) % 4;
}
intersectionPoints [outPoint1][0] = (intersectionPoints [outPoint1][0]
+ intersectionPoints [inPoint1][0]) / 2;
intersectionPoints [outPoint1][1] = (intersectionPoints [outPoint1][1]
+ intersectionPoints [inPoint1][1]) / 2;
intersectionPoints [outPoint2][0] = (intersectionPoints [outPoint2][0]
+ intersectionPoints [inPoint2][0]) / 2;
intersectionPoints [outPoint2][1] = (intersectionPoints [outPoint2][1]
+ intersectionPoints [inPoint2][1]) / 2;
GeneralPath path = getPath(intersectionPoints);
// Enlarge the intersection path to ensure its union with room builds only one path
Rectangle2D bounds2D = path.getBounds2D();
AffineTransform transform = AffineTransform.getTranslateInstance(bounds2D.getCenterX(), bounds2D.getCenterY());
double min = Math.min(bounds2D.getWidth(), bounds2D.getHeight());
double scale = (min + epsilon) / min;
transform.scale(scale, scale);
transform.translate(-bounds2D.getCenterX(), -bounds2D.getCenterY());
halfDoorPath = path.createTransformedShape(transform);
break;
}
}
}
if (halfDoorPath != null) {
Area halfDoorRoomUnion = new Area(halfDoorPath);
halfDoorRoomUnion.add(new Area(roomPath));
roomPath = getPath(halfDoorRoomUnion);
}
}
}
return createRoom(getPathPoints(roomPath, false));
}
}
return null;
}
/**
* Returns all the visible doors and windows with a null elevation in the given <code>furniture</code>.
*/
private List<HomePieceOfFurniture> getVisibleDoorsAndWindowsAtGround(List<HomePieceOfFurniture> furniture) {
List<HomePieceOfFurniture> doorsAndWindows = new ArrayList<HomePieceOfFurniture>(furniture.size());
for (HomePieceOfFurniture piece : furniture) {
if (isPieceOfFurnitureVisibleAtSelectedLevel(piece)
&& piece.getElevation() == 0) {
if (piece instanceof HomeFurnitureGroup) {
doorsAndWindows.addAll(getVisibleDoorsAndWindowsAtGround(((HomeFurnitureGroup)piece).getFurniture()));
} else if (piece.isDoorOrWindow()) {
doorsAndWindows.add(piece);
}
}
}
return doorsAndWindows;
}
@Override
public void setEditionActivated(boolean editionActivated) {
PlanView planView = getView();
if (editionActivated) {
planView.deleteFeedback();
if (this.newRoom == null) {
// Edit previous point
planView.setToolTipEditedProperties(new EditableProperty [] {EditableProperty.X,
EditableProperty.Y},
new Object [] {this.xPreviousPoint, this.yPreviousPoint},
this.xPreviousPoint, this.yPreviousPoint);
} else {
if (this.newPoint != null) {
// May happen if edition is activated after the user clicked to add a new point
createNextSide();
}
// Edit length and angle
float [][] points = this.newRoom.getPoints();
planView.setToolTipEditedProperties(new EditableProperty [] {EditableProperty.LENGTH,
EditableProperty.ANGLE},
new Object [] {getRoomSideLength(this.newRoom, points.length - 1),
getRoomSideAngle(this.newRoom, points.length - 1)},
points [points.length - 1][0], points [points.length - 1][1]);
}
} else {
if (this.newRoom == null) {
// Create a new side once user entered the start point of the room
float defaultLength = preferences.getLengthUnit() == LengthUnit.INCH
? LengthUnit.footToCentimeter(10) : 300;
this.newRoom = createAndSelectRoom(this.xPreviousPoint, this.yPreviousPoint,
this.xPreviousPoint + defaultLength, this.yPreviousPoint);
// Activate automatically second step to let user enter the
// length and angle of the new side
planView.deleteFeedback();
setEditionActivated(true);
} else if (System.currentTimeMillis() - this.lastPointCreationTime < 300) {
// If the user deactivated edition less than 300 ms after activation,
// escape current side creation
escape();
} else {
endRoomSide();
float [][] points = this.newRoom.getPoints();
// If last edited point matches first point validate drawn room
if (points.length > 2
&& this.newRoom.getPointIndexAt(points [points.length - 1][0], points [points.length - 1][1], 0.001f) == 0) {
// Remove last currently edited point.
this.newRoom.removePoint(this.newRoom.getPointCount() - 1);
validateDrawnRoom();
return;
}
createNextSide();
// Reactivate automatically second step
planView.deleteToolTipFeedback();
setEditionActivated(true);
}
}
}
private void createNextSide() {
// Add a point to current room
float [][] points = this.newRoom.getPoints();
this.xPreviousPoint = points [points.length - 1][0];
this.yPreviousPoint = points [points.length - 1][1];
// Create a new side with an angle equal to previous side angle - 90�
double previousSideAngle = Math.PI - Math.atan2(points [points.length - 2][1] - points [points.length - 1][1],
points [points.length - 2][0] - points [points.length - 1][0]);
previousSideAngle -= Math.PI / 2;
float previousSideLength = getRoomSideLength(this.newRoom, points.length - 1);
this.newRoom.addPoint(
(float)(this.xPreviousPoint + previousSideLength * Math.cos(previousSideAngle)),
(float)(this.yPreviousPoint - previousSideLength * Math.sin(previousSideAngle)));
this.newPoint = null;
this.lastPointCreationTime = System.currentTimeMillis();
}
@Override
public void updateEditableProperty(EditableProperty editableProperty, Object value) {
PlanView planView = getView();
if (this.newRoom == null) {
float maximumLength = preferences.getLengthUnit().getMaximumLength();
// Update start point of the first wall
switch (editableProperty) {
case X :
this.xPreviousPoint = value != null ? ((Number)value).floatValue() : 0;
this.xPreviousPoint = Math.max(-maximumLength, Math.min(this.xPreviousPoint, maximumLength));
break;
case Y :
this.yPreviousPoint = value != null ? ((Number)value).floatValue() : 0;
this.yPreviousPoint = Math.max(-maximumLength, Math.min(this.yPreviousPoint, maximumLength));
break;
}
planView.setAlignmentFeedback(Room.class, null, this.xPreviousPoint, this.yPreviousPoint, true);
planView.makePointVisible(this.xPreviousPoint, this.yPreviousPoint);
} else {
float [][] roomPoints = this.newRoom.getPoints();
float [] previousPoint = roomPoints [roomPoints.length - 2];
float [] point = roomPoints [roomPoints.length - 1];
float newX;
float newY;
// Update end point of the current room
switch (editableProperty) {
case LENGTH :
float length = value != null ? ((Number)value).floatValue() : 0;
length = Math.max(0.001f, Math.min(length, preferences.getLengthUnit().getMaximumLength()));
double wallAngle = Math.PI - Math.atan2(previousPoint [1] - point [1],
previousPoint [0] - point [0]);
newX = (float)(previousPoint [0] + length * Math.cos(wallAngle));
newY = (float)(previousPoint [1] - length * Math.sin(wallAngle));
break;
case ANGLE :
wallAngle = Math.toRadians(value != null ? ((Number)value).floatValue() : 0);
if (roomPoints.length > 2) {
wallAngle -= Math.atan2(roomPoints [roomPoints.length - 3][1] - previousPoint [1],
roomPoints [roomPoints.length - 3][0] - previousPoint [0]);
}
float wallLength = getRoomSideLength(this.newRoom, roomPoints.length - 1);
newX = (float)(previousPoint [0] + wallLength * Math.cos(wallAngle));
newY = (float)(previousPoint [1] - wallLength * Math.sin(wallAngle));
break;
default :
return;
}
this.newRoom.setPoint(newX, newY, roomPoints.length - 1);
// Update new room
planView.setAlignmentFeedback(Room.class, this.newRoom, newX, newY, false);
showRoomAngleFeedback(this.newRoom, roomPoints.length - 1);
// Ensure room side points are visible
planView.makePointVisible(previousPoint [0], previousPoint [1]);
planView.makePointVisible(newX, newY);
}
}
@Override
public void toggleMagnetism(boolean magnetismToggled) {
// Compute active magnetism
this.magnetismEnabled = preferences.isMagnetismEnabled()
^ magnetismToggled;
// If the new room already exists,
// compute again its last point as if mouse moved
if (this.newRoom != null) {
moveMouse(getXLastMouseMove(), getYLastMouseMove());
}
}
@Override
public void escape() {
if (this.newRoom != null
&& this.newPoint == null) {
// Remove last currently edited point.
this.newRoom.removePoint(this.newRoom.getPointCount() - 1);
}
validateDrawnRoom();
}
@Override
public void exit() {
getView().deleteFeedback();
this.newRoom = null;
this.newPoint = null;
this.oldSelection = null;
}
}
/**
* Room resize state. This state manages room resizing.
*/
private class RoomResizeState extends AbstractRoomState {
private Room selectedRoom;
private int roomPointIndex;
private float oldX;
private float oldY;
private float deltaXToResizePoint;
private float deltaYToResizePoint;
private boolean magnetismEnabled;
@Override
public Mode getMode() {
return Mode.SELECTION;
}
@Override
public boolean isModificationState() {
return true;
}
@Override
public void enter() {
super.enter();
this.selectedRoom = (Room)home.getSelectedItems().get(0);
float margin = INDICATOR_PIXEL_MARGIN / getScale();
this.roomPointIndex = this.selectedRoom.getPointIndexAt(
getXLastMousePress(), getYLastMousePress(), margin);
float [][] roomPoints = this.selectedRoom.getPoints();
this.oldX = roomPoints [this.roomPointIndex][0];
this.oldY = roomPoints [this.roomPointIndex][1];
this.deltaXToResizePoint = getXLastMousePress() - this.oldX;
this.deltaYToResizePoint = getYLastMousePress() - this.oldY;
toggleMagnetism(wasShiftDownLastMousePress());
PlanView planView = getView();
planView.setResizeIndicatorVisible(true);
planView.setToolTipFeedback(getToolTipFeedbackText(this.selectedRoom, this.roomPointIndex),
getXLastMousePress(), getYLastMousePress());
showRoomAngleFeedback(this.selectedRoom, this.roomPointIndex);
}
@Override
public void moveMouse(float x, float y) {
PlanView planView = getView();
float newX = x - this.deltaXToResizePoint;
float newY = y - this.deltaYToResizePoint;
boolean magnetizedPoint = false;
if (this.magnetismEnabled) {
// Find the closest wall or room point to current mouse location
PointMagnetizedToClosestWallOrRoomPoint point = new PointMagnetizedToClosestWallOrRoomPoint(
this.selectedRoom, this.roomPointIndex, newX, newY);
magnetizedPoint = point.isMagnetized();
if (magnetizedPoint) {
newX = point.getX();
newY = point.getY();
} else {
// Use magnetism if closest wall point is too far
float [][] roomPoints = this.selectedRoom.getPoints();
int previousPointIndex = this.roomPointIndex == 0
? roomPoints.length - 1
: this.roomPointIndex - 1;
float xPreviousPoint = roomPoints [previousPointIndex][0];
float yPreviousPoint = roomPoints [previousPointIndex][1];
RoomPointWithAngleMagnetism pointWithAngleMagnetism = new RoomPointWithAngleMagnetism(
this.selectedRoom, this.roomPointIndex, xPreviousPoint, yPreviousPoint, newX, newY);
newX = pointWithAngleMagnetism.getX();
newY = pointWithAngleMagnetism.getY();
}
}
moveRoomPoint(this.selectedRoom, newX, newY, this.roomPointIndex);
planView.setToolTipFeedback(getToolTipFeedbackText(this.selectedRoom, this.roomPointIndex), x, y);
planView.setAlignmentFeedback(Room.class, this.selectedRoom, newX, newY, magnetizedPoint);
showRoomAngleFeedback(this.selectedRoom, this.roomPointIndex);
// Ensure point at (x,y) is visible
planView.makePointVisible(x, y);
}
@Override
public void releaseMouse(float x, float y) {
postRoomResize(this.selectedRoom, this.oldX, this.oldY, this.roomPointIndex);
setState(getSelectionState());
}
@Override
public void toggleMagnetism(boolean magnetismToggled) {
// Compute active magnetism
this.magnetismEnabled = preferences.isMagnetismEnabled()
^ magnetismToggled;
moveMouse(getXLastMouseMove(), getYLastMouseMove());
}
@Override
public void escape() {
moveRoomPoint(this.selectedRoom, this.oldX, this.oldY, this.roomPointIndex);
setState(getSelectionState());
}
@Override
public void exit() {
PlanView planView = getView();
planView.setResizeIndicatorVisible(false);
planView.deleteFeedback();
this.selectedRoom = null;
}
}
/**
* Room name offset state. This state manages room name offset.
*/
private class RoomNameOffsetState extends ControllerState {
private Room selectedRoom;
private float oldNameXOffset;
private float oldNameYOffset;
private float xLastMouseMove;
private float yLastMouseMove;
@Override
public Mode getMode() {
return Mode.SELECTION;
}
@Override
public boolean isModificationState() {
return true;
}
@Override
public void enter() {
this.selectedRoom = (Room)home.getSelectedItems().get(0);
this.oldNameXOffset = this.selectedRoom.getNameXOffset();
this.oldNameYOffset = this.selectedRoom.getNameYOffset();
this.xLastMouseMove = getXLastMousePress();
this.yLastMouseMove = getYLastMousePress();
PlanView planView = getView();
planView.setResizeIndicatorVisible(true);
}
@Override
public void moveMouse(float x, float y) {
this.selectedRoom.setNameXOffset(this.selectedRoom.getNameXOffset() + x - this.xLastMouseMove);
this.selectedRoom.setNameYOffset(this.selectedRoom.getNameYOffset() + y - this.yLastMouseMove);
this.xLastMouseMove = x;
this.yLastMouseMove = y;
// Ensure point at (x,y) is visible
getView().makePointVisible(x, y);
}
@Override
public void releaseMouse(float x, float y) {
postRoomNameOffset(this.selectedRoom, this.oldNameXOffset, this.oldNameYOffset);
setState(getSelectionState());
}
@Override
public void escape() {
this.selectedRoom.setNameXOffset(this.oldNameXOffset);
this.selectedRoom.setNameYOffset(this.oldNameYOffset);
setState(getSelectionState());
}
@Override
public void exit() {
getView().setResizeIndicatorVisible(false);
this.selectedRoom = null;
}
}
/**
* Room area offset state. This state manages room area offset.
*/
private class RoomAreaOffsetState extends ControllerState {
private Room selectedRoom;
private float oldAreaXOffset;
private float oldAreaYOffset;
private float xLastMouseMove;
private float yLastMouseMove;
@Override
public Mode getMode() {
return Mode.SELECTION;
}
@Override
public boolean isModificationState() {
return true;
}
@Override
public void enter() {
this.selectedRoom = (Room)home.getSelectedItems().get(0);
this.oldAreaXOffset = this.selectedRoom.getAreaXOffset();
this.oldAreaYOffset = this.selectedRoom.getAreaYOffset();
this.xLastMouseMove = getXLastMousePress();
this.yLastMouseMove = getYLastMousePress();
PlanView planView = getView();
planView.setResizeIndicatorVisible(true);
}
@Override
public void moveMouse(float x, float y) {
this.selectedRoom.setAreaXOffset(this.selectedRoom.getAreaXOffset() + x - this.xLastMouseMove);
this.selectedRoom.setAreaYOffset(this.selectedRoom.getAreaYOffset() + y - this.yLastMouseMove);
this.xLastMouseMove = x;
this.yLastMouseMove = y;
// Ensure point at (x,y) is visible
getView().makePointVisible(x, y);
}
@Override
public void releaseMouse(float x, float y) {
postRoomAreaOffset(this.selectedRoom, this.oldAreaXOffset, this.oldAreaYOffset);
setState(getSelectionState());
}
@Override
public void escape() {
this.selectedRoom.setAreaXOffset(this.oldAreaXOffset);
this.selectedRoom.setAreaYOffset(this.oldAreaYOffset);
setState(getSelectionState());
}
@Override
public void exit() {
getView().setResizeIndicatorVisible(false);
this.selectedRoom = null;
}
}
/**
* Label creation state. This state manages transition to
* other modes, and initial label creation.
*/
private class LabelCreationState extends AbstractModeChangeState {
@Override
public Mode getMode() {
return Mode.LABEL_CREATION;
}
@Override
public void enter() {
getView().setCursor(PlanView.CursorType.DRAW);
}
@Override
public void pressMouse(float x, float y, int clickCount,
boolean shiftDown, boolean duplicationActivated) {
createLabel(x, y);
}
}
/**
* Compass rotation state. This states manages the rotation of the compass.
*/
private class CompassRotationState extends ControllerState {
private Compass selectedCompass;
private float angleMousePress;
private float oldNorthDirection;
private String rotationToolTipFeedback;
@Override
public Mode getMode() {
return Mode.SELECTION;
}
@Override
public boolean isModificationState() {
return true;
}
@Override
public void enter() {
this.rotationToolTipFeedback = preferences.getLocalizedString(
PlanController.class, "rotationToolTipFeedback");
this.selectedCompass = (Compass)home.getSelectedItems().get(0);
this.angleMousePress = (float)Math.atan2(this.selectedCompass.getY() - getYLastMousePress(),
getXLastMousePress() - this.selectedCompass.getX());
this.oldNorthDirection = this.selectedCompass.getNorthDirection();
PlanView planView = getView();
planView.setResizeIndicatorVisible(true);
planView.setToolTipFeedback(getToolTipFeedbackText(this.oldNorthDirection),
getXLastMousePress(), getYLastMousePress());
}
@Override
public void moveMouse(float x, float y) {
if (x != this.selectedCompass.getX() || y != this.selectedCompass.getY()) {
// Compute the new north direction of the compass
float angleMouseMove = (float)Math.atan2(this.selectedCompass.getY() - y,
x - this.selectedCompass.getX());
float newNorthDirection = this.oldNorthDirection - angleMouseMove + this.angleMousePress;
float angleStep = (float)Math.PI / 180;
// Compute angles closest to a degree with a value between 0 and 2 PI
newNorthDirection = Math.round(newNorthDirection / angleStep) * angleStep;
newNorthDirection = (float)((newNorthDirection + 2 * Math.PI) % (2 * Math.PI));
// Update compass new north direction
this.selectedCompass.setNorthDirection(newNorthDirection);
// Ensure point at (x,y) is visible
PlanView planView = getView();
planView.makePointVisible(x, y);
planView.setToolTipFeedback(getToolTipFeedbackText(newNorthDirection), x, y);
}
}
@Override
public void releaseMouse(float x, float y) {
postCompassRotation(this.selectedCompass, this.oldNorthDirection);
setState(getSelectionState());
}
@Override
public void escape() {
this.selectedCompass.setNorthDirection(this.oldNorthDirection);
setState(getSelectionState());
}
@Override
public void exit() {
PlanView planView = getView();
planView.setResizeIndicatorVisible(false);
planView.deleteFeedback();
this.selectedCompass = null;
}
private String getToolTipFeedbackText(float angle) {
return String.format(this.rotationToolTipFeedback, Math.round(Math.toDegrees(angle)));
}
}
/**
* Compass resize state. This states manages the resizing of the compass.
*/
private class CompassResizeState extends ControllerState {
private Compass selectedCompass;
private float oldDiameter;
private float deltaXToResizePoint;
private float deltaYToResizePoint;
private String resizeToolTipFeedback;
@Override
public Mode getMode() {
return Mode.SELECTION;
}
@Override
public boolean isModificationState() {
return true;
}
@Override
public void enter() {
this.resizeToolTipFeedback = preferences.getLocalizedString(
PlanController.class, "diameterToolTipFeedback");
this.selectedCompass = (Compass)home.getSelectedItems().get(0);
float [][] compassPoints = this.selectedCompass.getPoints();
float xMiddleSecondAndThirdPoint = (compassPoints [1][0] + compassPoints [2][0]) / 2;
float yMiddleSecondAndThirdPoint = (compassPoints [1][1] + compassPoints [2][1]) / 2;
this.deltaXToResizePoint = getXLastMousePress() - xMiddleSecondAndThirdPoint;
this.deltaYToResizePoint = getYLastMousePress() - yMiddleSecondAndThirdPoint;
this.oldDiameter = this.selectedCompass.getDiameter();
PlanView planView = getView();
planView.setResizeIndicatorVisible(true);
planView.setToolTipFeedback(getToolTipFeedbackText(this.oldDiameter),
getXLastMousePress(), getYLastMousePress());
}
@Override
public void moveMouse(float x, float y) {
// Compute the new diameter of the compass
PlanView planView = getView();
float newDiameter = (float)Point2D.distance(this.selectedCompass.getX(), this.selectedCompass.getY(),
x - this.deltaXToResizePoint, y - this.deltaYToResizePoint) * 2;
newDiameter = preferences.getLengthUnit().getMagnetizedLength(newDiameter, planView.getPixelLength());
newDiameter = Math.min(Math.max(newDiameter, preferences.getLengthUnit().getMinimumLength()),
preferences.getLengthUnit().getMaximumLength() / 10);
// Update piece size
this.selectedCompass.setDiameter(newDiameter);
// Ensure point at (x,y) is visible
planView.makePointVisible(x, y);
planView.setToolTipFeedback(getToolTipFeedbackText(newDiameter), x, y);
}
@Override
public void releaseMouse(float x, float y) {
postCompassResize(this.selectedCompass, this.oldDiameter);
setState(getSelectionState());
}
@Override
public void escape() {
this.selectedCompass.setDiameter(this.oldDiameter);
setState(getSelectionState());
}
@Override
public void exit() {
PlanView planView = getView();
planView.setResizeIndicatorVisible(false);
planView.deleteFeedback();
this.selectedCompass = null;
}
private String getToolTipFeedbackText(float diameter) {
return String.format(this.resizeToolTipFeedback,
preferences.getLengthUnit().getFormatWithUnit().format(diameter));
}
}
}
| false | true | private Wall adjustPieceOfFurnitureOnWallAt(HomePieceOfFurniture piece,
float x, float y, boolean forceOrientation) {
float margin = PIXEL_MARGIN / getScale();
Level selectedLevel = this.home.getSelectedLevel();
float [][] piecePoints = piece.getPoints();
Area wallsArea = getWallsArea();
Collection<Wall> walls = this.home.getWalls();
Wall referenceWall = null;
if (forceOrientation
|| !piece.isDoorOrWindow()) {
// Search if point (x, y) is contained in home walls with no margin
for (Wall wall : walls) {
if (wall.isAtLevel(selectedLevel)
&& wall.containsPoint(x, y, 0)
&& wall.getStartPointToEndPointDistance() > 0) {
referenceWall = getReferenceWall(wall, x, y);
break;
}
}
if (referenceWall == null) {
// If not found search if point (x, y) is contained in home walls with a margin
for (Wall wall : walls) {
if (wall.isAtLevel(selectedLevel)
&& wall.containsPoint(x, y, margin)
&& wall.getStartPointToEndPointDistance() > 0) {
referenceWall = getReferenceWall(wall, x, y);
break;
}
}
}
}
if (referenceWall == null) {
// Search if the border of a wall at floor level intersects with the given piece
Area pieceAreaWithMargin = new Area(getRotatedRectangle(
piece.getX() - piece.getWidth() / 2 - margin, piece.getY() - piece.getDepth() / 2 - margin,
piece.getWidth() + 2 * margin, piece.getDepth() + 2 * margin, piece.getAngle()));
float intersectionWithReferenceWallSurface = 0;
for (Wall wall : walls) {
if (wall.isAtLevel(selectedLevel)
&& wall.getStartPointToEndPointDistance() > 0) {
float [][] wallPoints = wall.getPoints();
Area wallAreaIntersection = new Area(getPath(wallPoints));
wallAreaIntersection.intersect(pieceAreaWithMargin);
if (!wallAreaIntersection.isEmpty()) {
float surface = getArea(wallAreaIntersection);
if (surface > intersectionWithReferenceWallSurface) {
surface = intersectionWithReferenceWallSurface;
if (forceOrientation) {
referenceWall = getReferenceWall(wall, x, y);
} else {
Rectangle2D intersectionBounds = wallAreaIntersection.getBounds2D();
referenceWall = getReferenceWall(wall, (float)intersectionBounds.getCenterX(), (float)intersectionBounds.getCenterY());
}
}
}
}
}
}
if (referenceWall != null
&& (referenceWall.getArcExtent() == null
|| !piece.isDoorOrWindow())) {
float xPiece = x;
float yPiece = y;
float pieceAngle = piece.getAngle();
float halfWidth = piece.getWidth() / 2;
float halfDepth = piece.getDepth() / 2;
double wallAngle = Math.atan2(referenceWall.getYEnd() - referenceWall.getYStart(),
referenceWall.getXEnd() - referenceWall.getXStart());
float [][] wallPoints = referenceWall.getPoints();
boolean magnetizedAtRight = wallAngle > -Math.PI / 2 && wallAngle <= Math.PI / 2;
double cosWallAngle = Math.cos(wallAngle);
double sinWallAngle = Math.sin(wallAngle);
double distanceToLeftSide = Line2D.ptLineDist(
wallPoints [0][0], wallPoints [0][1], wallPoints [1][0], wallPoints [1][1], x, y);
double distanceToRightSide = Line2D.ptLineDist(
wallPoints [2][0], wallPoints [2][1], wallPoints [3][0], wallPoints [3][1], x, y);
boolean adjustOrientation = forceOrientation
|| piece.isDoorOrWindow()
|| referenceWall.containsPoint(x, y, PIXEL_MARGIN / getScale());
if (adjustOrientation) {
double distanceToPieceLeftSide = Line2D.ptLineDist(
piecePoints [0][0], piecePoints [0][1], piecePoints [3][0], piecePoints [3][1], x, y);
double distanceToPieceRightSide = Line2D.ptLineDist(
piecePoints [1][0], piecePoints [1][1], piecePoints [2][0], piecePoints [2][1], x, y);
double distanceToPieceSide = pieceAngle > (3 * Math.PI / 2 + 1E-6) || pieceAngle < (Math.PI / 2 + 1E-6)
? distanceToPieceLeftSide
: distanceToPieceRightSide;
pieceAngle = (float)(distanceToRightSide < distanceToLeftSide
? wallAngle
: wallAngle + Math.PI);
if (piece.isDoorOrWindow()) {
final float thicknessEpsilon = 0.00025f;
float wallDistance = thicknessEpsilon / 2;
if (piece instanceof HomeDoorOrWindow) {
HomeDoorOrWindow doorOrWindow = (HomeDoorOrWindow)piece;
if (piece.isResizable()
&& isItemResizable(piece)) {
piece.setDepth(thicknessEpsilon
+ referenceWall.getThickness() / doorOrWindow.getWallThickness());
halfDepth = piece.getDepth() / 2;
}
wallDistance += piece.getDepth() * doorOrWindow.getWallDistance();
}
if (distanceToRightSide < distanceToLeftSide) {
xPiece += sinWallAngle * ( (distanceToLeftSide + wallDistance) - halfDepth);
yPiece += cosWallAngle * (-(distanceToLeftSide + wallDistance) + halfDepth);
} else {
xPiece += sinWallAngle * (-(distanceToRightSide + wallDistance) + halfDepth);
yPiece += cosWallAngle * ( (distanceToRightSide + wallDistance) - halfDepth);
}
if (magnetizedAtRight) {
xPiece += cosWallAngle * (halfWidth - distanceToPieceSide);
yPiece += sinWallAngle * (halfWidth - distanceToPieceSide);
} else {
// Ensure adjusted window is at the right of the cursor
xPiece += -cosWallAngle * (halfWidth - distanceToPieceSide);
yPiece += -sinWallAngle * (halfWidth - distanceToPieceSide);
}
} else {
if (distanceToRightSide < distanceToLeftSide) {
int pointIndicator = Line2D.relativeCCW(
wallPoints [2][0], wallPoints [2][1], wallPoints [3][0], wallPoints [3][1], x, y);
xPiece += pointIndicator * sinWallAngle * distanceToRightSide - sinWallAngle * halfDepth;
yPiece += -pointIndicator * cosWallAngle * distanceToRightSide + cosWallAngle * halfDepth;
} else {
int pointIndicator = Line2D.relativeCCW(
wallPoints [0][0], wallPoints [0][1], wallPoints [1][0], wallPoints [1][1], x, y);
xPiece += -pointIndicator * sinWallAngle * distanceToLeftSide + sinWallAngle * halfDepth;
yPiece += pointIndicator * cosWallAngle * distanceToLeftSide - cosWallAngle * halfDepth;
}
if (magnetizedAtRight) {
xPiece += cosWallAngle * (halfWidth - distanceToPieceSide);
yPiece += sinWallAngle * (halfWidth - distanceToPieceSide);
} else {
// Ensure adjusted piece is at the right of the cursor
xPiece += -cosWallAngle * (halfWidth - distanceToPieceSide);
yPiece += -sinWallAngle * (halfWidth - distanceToPieceSide);
}
}
} else {
// Search the distance required to align piece on the left or right side of the reference wall
Line2D centerLine = new Line2D.Float(referenceWall.getXStart(), referenceWall.getYStart(),
referenceWall.getXEnd(), referenceWall.getYEnd());
Shape pieceBoundingBox = getRotatedRectangle(0, 0, piece.getWidth(), piece.getDepth(), (float)(pieceAngle - wallAngle));
double rotatedBoundingBoxDepth = pieceBoundingBox.getBounds2D().getHeight();
double distance = centerLine.relativeCCW(piece.getX(), piece.getY())
* (-referenceWall.getThickness() / 2 + centerLine.ptLineDist(piece.getX(), piece.getY()) - rotatedBoundingBoxDepth / 2);
if (Math.signum(centerLine.relativeCCW(x, y)) != Math.signum(centerLine.relativeCCW(piece.getX(), piece.getY()))) {
distance -= Math.signum(centerLine.relativeCCW(x, y)) * (rotatedBoundingBoxDepth + referenceWall.getThickness());
}
xPiece = piece.getX() + (float)(-distance * sinWallAngle);
yPiece = piece.getY() + (float)(distance * cosWallAngle);
}
if (!piece.isDoorOrWindow()
&& (referenceWall.getArcExtent() == null // Ignore reoriented piece when (x, y) is inside a round wall
|| !adjustOrientation
|| Line2D.relativeCCW(referenceWall.getXStart(), referenceWall.getYStart(),
referenceWall.getXEnd(), referenceWall.getYEnd(), x, y) > 0)) {
// Search if piece intersects some other walls and avoid it intersects the closest one
Area wallsAreaIntersection = new Area(wallsArea);
Area adjustedPieceArea = new Area(getRotatedRectangle(xPiece - halfWidth,
yPiece - halfDepth, piece.getWidth(), piece.getDepth(), pieceAngle));
wallsAreaIntersection.subtract(new Area(getPath(wallPoints)));
wallsAreaIntersection.intersect(adjustedPieceArea);
if (!wallsAreaIntersection.isEmpty()) {
// Search the wall intersection path the closest to (x, y)
GeneralPath closestWallIntersectionPath = getClosestPath(getAreaPaths(wallsAreaIntersection), x, y);
if (closestWallIntersectionPath != null) {
// In case the adjusted piece crosses a wall, search the area intersecting that wall
// + other parts which crossed the wall (the farthest ones from (x,y))
adjustedPieceArea.subtract(wallsArea);
if (adjustedPieceArea.isEmpty()) {
return null;
} else {
List<GeneralPath> adjustedPieceAreaPaths = getAreaPaths(adjustedPieceArea);
// Ignore too complex cases when the piece intersect many walls and is not parallel to a wall
double angleDifference = (wallAngle - pieceAngle + 2 * Math.PI) % Math.PI;
if (angleDifference < 1E-5
|| Math.PI - angleDifference < 1E-5
|| adjustedPieceAreaPaths.size() < 2) {
GeneralPath adjustedPiecePathInArea = getClosestPath(adjustedPieceAreaPaths, x, y);
Area adjustingArea = new Area(closestWallIntersectionPath);
for (GeneralPath path : adjustedPieceAreaPaths) {
if (path != adjustedPiecePathInArea) {
adjustingArea.add(new Area(path));
}
}
AffineTransform rotation = AffineTransform.getRotateInstance(-wallAngle);
Rectangle2D adjustingAreaBounds = adjustingArea.createTransformedArea(rotation).getBounds2D();
Rectangle2D adjustedPiecePathInAreaBounds = adjustedPiecePathInArea.createTransformedShape(rotation).getBounds2D();
if (!adjustingAreaBounds.contains(adjustedPiecePathInAreaBounds)) {
double adjustLeftBorder = Math.signum(adjustedPiecePathInAreaBounds.getCenterX() - adjustingAreaBounds.getCenterX());
xPiece += adjustingAreaBounds.getWidth() * cosWallAngle * adjustLeftBorder;
yPiece += adjustingAreaBounds.getWidth() * sinWallAngle * adjustLeftBorder;
}
}
}
}
}
}
piece.setAngle(pieceAngle);
piece.setX(xPiece);
piece.setY(yPiece);
if (piece instanceof HomeDoorOrWindow) {
((HomeDoorOrWindow) piece).setBoundToWall(true);
}
return referenceWall;
}
return null;
}
| private Wall adjustPieceOfFurnitureOnWallAt(HomePieceOfFurniture piece,
float x, float y, boolean forceOrientation) {
float margin = PIXEL_MARGIN / getScale();
Level selectedLevel = this.home.getSelectedLevel();
float [][] piecePoints = piece.getPoints();
Area wallsArea = getWallsArea();
Collection<Wall> walls = this.home.getWalls();
Wall referenceWall = null;
if (forceOrientation
|| !piece.isDoorOrWindow()) {
// Search if point (x, y) is contained in home walls with no margin
for (Wall wall : walls) {
if (wall.isAtLevel(selectedLevel)
&& wall.containsPoint(x, y, 0)
&& wall.getStartPointToEndPointDistance() > 0) {
referenceWall = getReferenceWall(wall, x, y);
break;
}
}
if (referenceWall == null) {
// If not found search if point (x, y) is contained in home walls with a margin
for (Wall wall : walls) {
if (wall.isAtLevel(selectedLevel)
&& wall.containsPoint(x, y, margin)
&& wall.getStartPointToEndPointDistance() > 0) {
referenceWall = getReferenceWall(wall, x, y);
break;
}
}
}
}
if (referenceWall == null) {
// Search if the border of a wall at floor level intersects with the given piece
Area pieceAreaWithMargin = new Area(getRotatedRectangle(
piece.getX() - piece.getWidth() / 2 - margin, piece.getY() - piece.getDepth() / 2 - margin,
piece.getWidth() + 2 * margin, piece.getDepth() + 2 * margin, piece.getAngle()));
float intersectionWithReferenceWallSurface = 0;
for (Wall wall : walls) {
if (wall.isAtLevel(selectedLevel)
&& wall.getStartPointToEndPointDistance() > 0) {
float [][] wallPoints = wall.getPoints();
Area wallAreaIntersection = new Area(getPath(wallPoints));
wallAreaIntersection.intersect(pieceAreaWithMargin);
if (!wallAreaIntersection.isEmpty()) {
float surface = getArea(wallAreaIntersection);
if (surface > intersectionWithReferenceWallSurface) {
intersectionWithReferenceWallSurface = surface;
if (forceOrientation) {
referenceWall = getReferenceWall(wall, x, y);
} else {
Rectangle2D intersectionBounds = wallAreaIntersection.getBounds2D();
referenceWall = getReferenceWall(wall, (float)intersectionBounds.getCenterX(), (float)intersectionBounds.getCenterY());
}
}
}
}
}
}
if (referenceWall != null
&& (referenceWall.getArcExtent() == null
|| !piece.isDoorOrWindow())) {
float xPiece = x;
float yPiece = y;
float pieceAngle = piece.getAngle();
float halfWidth = piece.getWidth() / 2;
float halfDepth = piece.getDepth() / 2;
double wallAngle = Math.atan2(referenceWall.getYEnd() - referenceWall.getYStart(),
referenceWall.getXEnd() - referenceWall.getXStart());
float [][] wallPoints = referenceWall.getPoints();
boolean magnetizedAtRight = wallAngle > -Math.PI / 2 && wallAngle <= Math.PI / 2;
double cosWallAngle = Math.cos(wallAngle);
double sinWallAngle = Math.sin(wallAngle);
double distanceToLeftSide = Line2D.ptLineDist(
wallPoints [0][0], wallPoints [0][1], wallPoints [1][0], wallPoints [1][1], x, y);
double distanceToRightSide = Line2D.ptLineDist(
wallPoints [2][0], wallPoints [2][1], wallPoints [3][0], wallPoints [3][1], x, y);
boolean adjustOrientation = forceOrientation
|| piece.isDoorOrWindow()
|| referenceWall.containsPoint(x, y, PIXEL_MARGIN / getScale());
if (adjustOrientation) {
double distanceToPieceLeftSide = Line2D.ptLineDist(
piecePoints [0][0], piecePoints [0][1], piecePoints [3][0], piecePoints [3][1], x, y);
double distanceToPieceRightSide = Line2D.ptLineDist(
piecePoints [1][0], piecePoints [1][1], piecePoints [2][0], piecePoints [2][1], x, y);
double distanceToPieceSide = pieceAngle > (3 * Math.PI / 2 + 1E-6) || pieceAngle < (Math.PI / 2 + 1E-6)
? distanceToPieceLeftSide
: distanceToPieceRightSide;
pieceAngle = (float)(distanceToRightSide < distanceToLeftSide
? wallAngle
: wallAngle + Math.PI);
if (piece.isDoorOrWindow()) {
final float thicknessEpsilon = 0.00025f;
float wallDistance = thicknessEpsilon / 2;
if (piece instanceof HomeDoorOrWindow) {
HomeDoorOrWindow doorOrWindow = (HomeDoorOrWindow)piece;
if (piece.isResizable()
&& isItemResizable(piece)) {
piece.setDepth(thicknessEpsilon
+ referenceWall.getThickness() / doorOrWindow.getWallThickness());
halfDepth = piece.getDepth() / 2;
}
wallDistance += piece.getDepth() * doorOrWindow.getWallDistance();
}
if (distanceToRightSide < distanceToLeftSide) {
xPiece += sinWallAngle * ( (distanceToLeftSide + wallDistance) - halfDepth);
yPiece += cosWallAngle * (-(distanceToLeftSide + wallDistance) + halfDepth);
} else {
xPiece += sinWallAngle * (-(distanceToRightSide + wallDistance) + halfDepth);
yPiece += cosWallAngle * ( (distanceToRightSide + wallDistance) - halfDepth);
}
if (magnetizedAtRight) {
xPiece += cosWallAngle * (halfWidth - distanceToPieceSide);
yPiece += sinWallAngle * (halfWidth - distanceToPieceSide);
} else {
// Ensure adjusted window is at the right of the cursor
xPiece += -cosWallAngle * (halfWidth - distanceToPieceSide);
yPiece += -sinWallAngle * (halfWidth - distanceToPieceSide);
}
} else {
if (distanceToRightSide < distanceToLeftSide) {
int pointIndicator = Line2D.relativeCCW(
wallPoints [2][0], wallPoints [2][1], wallPoints [3][0], wallPoints [3][1], x, y);
xPiece += pointIndicator * sinWallAngle * distanceToRightSide - sinWallAngle * halfDepth;
yPiece += -pointIndicator * cosWallAngle * distanceToRightSide + cosWallAngle * halfDepth;
} else {
int pointIndicator = Line2D.relativeCCW(
wallPoints [0][0], wallPoints [0][1], wallPoints [1][0], wallPoints [1][1], x, y);
xPiece += -pointIndicator * sinWallAngle * distanceToLeftSide + sinWallAngle * halfDepth;
yPiece += pointIndicator * cosWallAngle * distanceToLeftSide - cosWallAngle * halfDepth;
}
if (magnetizedAtRight) {
xPiece += cosWallAngle * (halfWidth - distanceToPieceSide);
yPiece += sinWallAngle * (halfWidth - distanceToPieceSide);
} else {
// Ensure adjusted piece is at the right of the cursor
xPiece += -cosWallAngle * (halfWidth - distanceToPieceSide);
yPiece += -sinWallAngle * (halfWidth - distanceToPieceSide);
}
}
} else {
// Search the distance required to align piece on the left or right side of the reference wall
Line2D centerLine = new Line2D.Float(referenceWall.getXStart(), referenceWall.getYStart(),
referenceWall.getXEnd(), referenceWall.getYEnd());
Shape pieceBoundingBox = getRotatedRectangle(0, 0, piece.getWidth(), piece.getDepth(), (float)(pieceAngle - wallAngle));
double rotatedBoundingBoxDepth = pieceBoundingBox.getBounds2D().getHeight();
double distance = centerLine.relativeCCW(piece.getX(), piece.getY())
* (-referenceWall.getThickness() / 2 + centerLine.ptLineDist(piece.getX(), piece.getY()) - rotatedBoundingBoxDepth / 2);
if (Math.signum(centerLine.relativeCCW(x, y)) != Math.signum(centerLine.relativeCCW(piece.getX(), piece.getY()))) {
distance -= Math.signum(centerLine.relativeCCW(x, y)) * (rotatedBoundingBoxDepth + referenceWall.getThickness());
}
xPiece = piece.getX() + (float)(-distance * sinWallAngle);
yPiece = piece.getY() + (float)(distance * cosWallAngle);
}
if (!piece.isDoorOrWindow()
&& (referenceWall.getArcExtent() == null // Ignore reoriented piece when (x, y) is inside a round wall
|| !adjustOrientation
|| Line2D.relativeCCW(referenceWall.getXStart(), referenceWall.getYStart(),
referenceWall.getXEnd(), referenceWall.getYEnd(), x, y) > 0)) {
// Search if piece intersects some other walls and avoid it intersects the closest one
Area wallsAreaIntersection = new Area(wallsArea);
Area adjustedPieceArea = new Area(getRotatedRectangle(xPiece - halfWidth,
yPiece - halfDepth, piece.getWidth(), piece.getDepth(), pieceAngle));
wallsAreaIntersection.subtract(new Area(getPath(wallPoints)));
wallsAreaIntersection.intersect(adjustedPieceArea);
if (!wallsAreaIntersection.isEmpty()) {
// Search the wall intersection path the closest to (x, y)
GeneralPath closestWallIntersectionPath = getClosestPath(getAreaPaths(wallsAreaIntersection), x, y);
if (closestWallIntersectionPath != null) {
// In case the adjusted piece crosses a wall, search the area intersecting that wall
// + other parts which crossed the wall (the farthest ones from (x,y))
adjustedPieceArea.subtract(wallsArea);
if (adjustedPieceArea.isEmpty()) {
return null;
} else {
List<GeneralPath> adjustedPieceAreaPaths = getAreaPaths(adjustedPieceArea);
// Ignore too complex cases when the piece intersect many walls and is not parallel to a wall
double angleDifference = (wallAngle - pieceAngle + 2 * Math.PI) % Math.PI;
if (angleDifference < 1E-5
|| Math.PI - angleDifference < 1E-5
|| adjustedPieceAreaPaths.size() < 2) {
GeneralPath adjustedPiecePathInArea = getClosestPath(adjustedPieceAreaPaths, x, y);
Area adjustingArea = new Area(closestWallIntersectionPath);
for (GeneralPath path : adjustedPieceAreaPaths) {
if (path != adjustedPiecePathInArea) {
adjustingArea.add(new Area(path));
}
}
AffineTransform rotation = AffineTransform.getRotateInstance(-wallAngle);
Rectangle2D adjustingAreaBounds = adjustingArea.createTransformedArea(rotation).getBounds2D();
Rectangle2D adjustedPiecePathInAreaBounds = adjustedPiecePathInArea.createTransformedShape(rotation).getBounds2D();
if (!adjustingAreaBounds.contains(adjustedPiecePathInAreaBounds)) {
double adjustLeftBorder = Math.signum(adjustedPiecePathInAreaBounds.getCenterX() - adjustingAreaBounds.getCenterX());
xPiece += adjustingAreaBounds.getWidth() * cosWallAngle * adjustLeftBorder;
yPiece += adjustingAreaBounds.getWidth() * sinWallAngle * adjustLeftBorder;
}
}
}
}
}
}
piece.setAngle(pieceAngle);
piece.setX(xPiece);
piece.setY(yPiece);
if (piece instanceof HomeDoorOrWindow) {
((HomeDoorOrWindow) piece).setBoundToWall(true);
}
return referenceWall;
}
return null;
}
|
diff --git a/uk.ac.diamond.scisoft.analysis.rcp/src/uk/ac/diamond/scisoft/analysis/rcp/hdf5/HDF5TreeExplorer.java b/uk.ac.diamond.scisoft.analysis.rcp/src/uk/ac/diamond/scisoft/analysis/rcp/hdf5/HDF5TreeExplorer.java
index fbb7579..01e6a24 100644
--- a/uk.ac.diamond.scisoft.analysis.rcp/src/uk/ac/diamond/scisoft/analysis/rcp/hdf5/HDF5TreeExplorer.java
+++ b/uk.ac.diamond.scisoft.analysis.rcp/src/uk/ac/diamond/scisoft/analysis/rcp/hdf5/HDF5TreeExplorer.java
@@ -1,677 +1,677 @@
/*
* Copyright © 2011 Diamond Light Source Ltd.
* Contact : [email protected]
*
* This is free software: you can redistribute it and/or modify it under the
* terms of the GNU General Public License version 3 as published by the Free
* Software Foundation.
*
* This software is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this software. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.ac.diamond.scisoft.analysis.rcp.hdf5;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang.ArrayUtils;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.TreePath;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Cursor;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.ui.IWorkbenchPartSite;
import org.eclipse.ui.PartInitException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import uk.ac.diamond.scisoft.analysis.dataset.AbstractDataset;
import uk.ac.diamond.scisoft.analysis.dataset.ILazyDataset;
import uk.ac.diamond.scisoft.analysis.dataset.IndexIterator;
import uk.ac.diamond.scisoft.analysis.hdf5.HDF5Attribute;
import uk.ac.diamond.scisoft.analysis.hdf5.HDF5Dataset;
import uk.ac.diamond.scisoft.analysis.hdf5.HDF5File;
import uk.ac.diamond.scisoft.analysis.hdf5.HDF5Group;
import uk.ac.diamond.scisoft.analysis.hdf5.HDF5Node;
import uk.ac.diamond.scisoft.analysis.hdf5.HDF5NodeLink;
import uk.ac.diamond.scisoft.analysis.io.DataHolder;
import uk.ac.diamond.scisoft.analysis.io.HDF5Loader;
import uk.ac.diamond.scisoft.analysis.rcp.explorers.AbstractExplorer;
import uk.ac.diamond.scisoft.analysis.rcp.explorers.MetadataSelection;
import uk.ac.diamond.scisoft.analysis.rcp.inspector.AxisChoice;
import uk.ac.diamond.scisoft.analysis.rcp.inspector.AxisSelection;
import uk.ac.diamond.scisoft.analysis.rcp.inspector.DatasetSelection;
import uk.ac.diamond.scisoft.analysis.rcp.inspector.DatasetSelection.InspectorType;
import uk.ac.diamond.scisoft.analysis.rcp.results.navigator.AsciiTextView;
import uk.ac.gda.monitor.IMonitor;
public class HDF5TreeExplorer extends AbstractExplorer implements ISelectionProvider {
private static final Logger logger = LoggerFactory.getLogger(HDF5TreeExplorer.class);
HDF5File tree = null;
private HDF5TableTree tableTree = null;
private Display display;
private ILazyDataset cData; // chosen dataset
List<AxisSelection> axes; // list of axes for each dimension
private String filename;
/**
* Separator between (full) file name and node path
*/
public static final String HDF5FILENAME_NODEPATH_SEPARATOR = "#";
public static class HDF5Selection extends DatasetSelection {
private String fileName;
private String node;
public HDF5Selection(InspectorType type, String filename, String node, List<AxisSelection> axes, ILazyDataset... dataset) {
super(type, axes, dataset);
this.fileName = filename;
this.node = node;
}
@Override
public boolean equals(Object other) {
if (super.equals(other) && other instanceof HDF5Selection) {
HDF5Selection that = (HDF5Selection) other;
if (fileName == null && that.fileName == null)
return node.equals(that.node);
if (fileName != null && fileName.equals(that.fileName))
return node.equals(that.node);
}
return false;
}
@Override
public int hashCode() {
int hash = super.hashCode();
hash = hash * 17 + node.hashCode();
return hash;
}
@Override
public String toString() {
return node + " = " + super.toString();
}
public String getFileName() {
return fileName;
}
public String getNode() {
return node;
}
}
private HDF5Selection hdf5Selection;
private Set<ISelectionChangedListener> cListeners;
private Listener contextListener = null;
private DataHolder holder;
public HDF5TreeExplorer(Composite parent, IWorkbenchPartSite partSite, ISelectionChangedListener valueSelect) {
super(parent, partSite, valueSelect);
display = parent.getDisplay();
setLayout(new FillLayout());
if (metaValueListener != null) {
contextListener = new Listener() {
@Override
public void handleEvent(Event event) {
handleContextClick();
}
};
}
tableTree = new HDF5TableTree(this, null, new Listener() {
@Override
public void handleEvent(Event event) {
if (event.button == 1)
handleDoubleClick();
}
}, contextListener);
cListeners = new HashSet<ISelectionChangedListener>();
axes = new ArrayList<AxisSelection>();
}
/**
* populate a selection object
*/
public void selectHDF5Node(HDF5NodeLink link, InspectorType type) {
if (link == null)
return;
if (handleSelectedNode(link)) {
// provide selection
setSelection(new HDF5Selection(type, filename, link.getFullName(), axes, cData));
} else
logger.error("Could not process update of selected node: {}", link.getName());
}
private boolean handleSelectedNode(HDF5NodeLink link) {
if (processTextNode(link)) {
return false;
}
if (!processSelectedNode(link))
return false;
if (cData == null)
return false;
return true;
}
/**
* Handle a node given by the path
* @param path
*/
public void handleNode(String path) {
HDF5NodeLink link = tree.findNodeLink(path);
if (link != null) {
if (handleSelectedNode(link)) {
// provide selection
setSelection(new HDF5Selection(InspectorType.LINE, filename, link.getName(), axes, cData));
return;
}
logger.debug("Could not handle selected node: {}", link.getName());
}
logger.debug("Could not find selected node: {}", path);
}
private void handleContextClick() {
IStructuredSelection selection = tableTree.getSelection();
try {
// check if selection is valid for plotting
if (selection != null) {
Object obj = selection.getFirstElement();
String metaName = null;
if (obj instanceof HDF5NodeLink) {
metaName = ((HDF5NodeLink) obj).getFullName();
} else if (obj instanceof HDF5Attribute) {
metaName = ((HDF5Attribute) obj).getFullName();
}
if (metaName != null) {
SelectionChangedEvent ce = new SelectionChangedEvent(this, new MetadataSelection(metaName));
metaValueListener.selectionChanged(ce);
}
}
} catch (Exception e) {
logger.error("Error processing selection: {}", e.getMessage());
}
}
private void handleDoubleClick() {
final Cursor cursor = getCursor();
Cursor tempCursor = getDisplay().getSystemCursor(SWT.CURSOR_WAIT);
if (tempCursor != null)
setCursor(tempCursor);
IStructuredSelection selection = tableTree.getSelection();
try {
// check if selection is valid for plotting
if (selection != null && selection.getFirstElement() instanceof HDF5NodeLink) {
HDF5NodeLink link = (HDF5NodeLink) selection.getFirstElement();
selectHDF5Node(link, InspectorType.LINE);
}
} catch (Exception e) {
logger.error("Error processing selection: {}", e.getMessage());
} finally {
if (tempCursor != null)
setCursor(cursor);
}
}
private boolean processTextNode(HDF5NodeLink link) {
HDF5Node node = link.getDestination();
if (!(node instanceof HDF5Dataset))
return false;
HDF5Dataset dataset = (HDF5Dataset) node;
if (!dataset.isString())
return false;
try {
getTextView().setData(dataset.getString());
return true;
} catch (Exception e) {
logger.error("Error processing text node {}: {}", link.getName(), e);
}
return false;
}
private static final String NXAXES = "axes";
private static final String NXAXIS = "axis";
private static final String NXLABEL = "label";
private static final String NXPRIMARY = "primary";
private static final String NXSIGNAL = "signal";
private static final String NXDATA = "NXdata";
private static final String SDS = "SDS";
private boolean processSelectedNode(HDF5NodeLink link) {
// two cases: axis and primary or axes
// iterate through each child to find axes and primary attributes
HDF5Node node = link.getDestination();
boolean foundData = false;
List<AxisChoice> choices = new ArrayList<AxisChoice>();
HDF5Attribute axesAttr = null;
HDF5Group gNode = null;
HDF5Dataset dNode = null;
// see if chosen node is a NXdata class
String nxClass = node.containsAttribute(HDF5File.NXCLASS) ? node.getAttribute(HDF5File.NXCLASS).getFirstElement() : null;
if (nxClass == null || nxClass.equals(SDS)) {
if (!(node instanceof HDF5Dataset))
return foundData;
dNode = (HDF5Dataset) node;
if (!dNode.isSupported())
return false;
foundData = true;
cData = dNode.getDataset();
axesAttr = dNode.getAttribute(NXAXES);
gNode = (HDF5Group) link.getSource(); // before hunting for axes
} else if (nxClass.equals(NXDATA)) {
assert node instanceof HDF5Group;
gNode = (HDF5Group) node;
// find data (signal=1) and check for axes attribute
Iterator<HDF5NodeLink> iter = gNode.getNodeLinkIterator();
while (iter.hasNext()) {
HDF5NodeLink l = iter.next();
if (l.isDestinationADataset()) {
dNode = (HDF5Dataset) l.getDestination();
if (dNode.containsAttribute(NXSIGNAL) && dNode.isSupported()) {
foundData = true;
cData = dNode.getDataset();
axesAttr = dNode.getAttribute(NXAXES);
break; // only one signal per NXdata item
}
}
}
}
if (!foundData)
return foundData;
// remove extraneous dimensions
cData.squeeze(true);
// set up slices
int rank = cData.getRank();
// scan children for SDS as possible axes (could be referenced by axes)
@SuppressWarnings("null")
Iterator<HDF5NodeLink> iter = gNode.getNodeLinkIterator();
while (iter.hasNext()) {
HDF5NodeLink l = iter.next();
if (l.isDestinationADataset()) {
HDF5Dataset d = (HDF5Dataset) l.getDestination();
if (!d.isSupported() || d.isString() || dNode == d || d.containsAttribute(NXSIGNAL))
continue;
ILazyDataset a = d.getDataset();
try {
int[] s = a.getShape().clone();
s = AbstractDataset.squeezeShape(s, true);
if (s.length != 0) // don't make a 0D dataset
a.squeeze(true);
AxisChoice choice = new AxisChoice(a);
HDF5Attribute attr = d.getAttribute(NXAXIS);
HDF5Attribute attr_label = d.getAttribute(NXLABEL);
if (attr != null) {
int[] intAxis = null;
if (attr.isString()) {
String[] str = attr.getFirstElement().split(",");
intAxis = new int[str.length];
for (int i = 0; i < str.length; i++)
intAxis[i] = Integer.parseInt(str[i]) - 1;
} else {
AbstractDataset attrd = attr.getValue();
intAxis = new int[attrd.getSize()];
IndexIterator it = attrd.getIterator();
int i = 0;
while (it.hasNext()) {
- intAxis[i++] = (int) attrd.getElementLongAbs(it.index);
+ intAxis[i++] = (int) attrd.getElementLongAbs(it.index) - 1;
}
}
if (attr_label != null) {
if (attr_label.isString()) {
choice.setDimension(intAxis, Integer.parseInt(attr_label.getFirstElement()) - 1);
} else {
choice.setDimension(intAxis, attr_label.getValue().getInt(0) - 1);
}
} else
choice.setDimension(intAxis);
} else {
if (attr_label != null) {
if (attr_label.isString()) {
choice.setDimension(new int[] { Integer.parseInt(attr_label.getFirstElement()) - 1 });
} else {
choice.setDimension(new int[] {attr_label.getValue().getInt(0) - 1 });
}
}
}
attr = d.getAttribute(NXPRIMARY);
if (attr != null) {
if (attr.isString()) {
Integer intPrimary = Integer.parseInt(attr.getFirstElement());
choice.setPrimary(intPrimary);
} else {
AbstractDataset attrd = attr.getValue();
choice.setPrimary(attrd.getInt(0));
}
}
choices.add(choice);
} catch (Exception e) {
logger.warn("Axis attributes in {} are invalid - {}", a.getName(), e.getMessage());
continue;
}
}
}
List<String> aNames = new ArrayList<String>();
if (axesAttr != null) { // check axes attribute for list axes
String axesStr = axesAttr.getFirstElement().trim();
if (axesStr.startsWith("[")) { // strip opening and closing brackets
axesStr = axesStr.substring(1, axesStr.length() - 1);
}
// check if axes referenced by data exists
String[] names = null;
names = axesStr.split("[:,]");
for (String s : names) {
boolean flg = false;
for (AxisChoice c : choices) {
if (c.equals(s)) {
flg = true;
break;
}
}
if (flg) {
aNames.add(s);
} else {
logger.warn("Referenced axis {} does not exist in NeXus tree node {}", new Object[] { s, node });
aNames.add(null);
}
}
}
// set up AxisSelector
// build up list of choice per dimension
axes.clear();
for (int i = 0; i < rank; i++) {
int dim = cData.getShape()[i];
AxisSelection aSel = new AxisSelection(dim);
axes.add(i, null); // expand list
for (AxisChoice c : choices) {
// check if dimension number and axis length matches
if (c.getDimension() == i) {
if (checkAxisDimensions(c))
aSel.addSelection(c, c.getPrimary());
}
}
for (AxisChoice c : choices) {
// add in others if axis length matches
if (aSel.containsAxis(c.getName())) {
continue;
}
int[] cAxis = c.getAxes();
if ((c.getDimension() != i) && ArrayUtils.contains(cAxis, i)) {
if (checkAxisDimensions(c))
aSel.addSelection(c, 0);
}
}
if (i < aNames.size()) {
for (AxisChoice c : choices) {
if (aSel.containsAxis(c.getName())) {
continue;
}
if (c.getName().equals(aNames.get(i))) {
if (checkAxisDimensions(c))
aSel.addSelection(c, 1);
}
}
}
for (AxisChoice c : choices) {
if (aSel.containsAxis(c.getName())) {
continue;
}
if (!checkAxisDimensions(c)) {
int[] choiceDims = c.getValues().getShape();
AbstractDataset axis = c.getValues();
for (int j = 0; j < choiceDims.length; j++) {
if (choiceDims[j] == dim) {
int[] start = new int[choiceDims.length];
int[] stop = new int[choiceDims.length];
Arrays.fill(stop, 1);
int[] step = stop.clone();
stop[j] = dim;
AbstractDataset sliceAxis = axis.getSlice(start, stop, step).flatten();
// Add dimension label to prevent axis name clashes for different dimensions
sliceAxis.setName(c.getName() + "_" + "dim:" + (i + 1));
AxisChoice tmpChoice = new AxisChoice(sliceAxis);
tmpChoice.setDimension(new int[] {i});
aSel.addSelection(tmpChoice, 0);
}
}
}
}
// add in an automatically generated axis with top order so it appears after primary axes
AbstractDataset axis = AbstractDataset.arange(dim, AbstractDataset.INT32);
axis.setName("dim:" + (i + 1));
AxisChoice newChoice = new AxisChoice(axis);
newChoice.setDimension(new int[] {i});
aSel.addSelection(newChoice, aSel.getMaxOrder() + 1);
aSel.reorderNames();
aSel.selectAxis(0);
axes.set(i, aSel);
}
return foundData;
}
/**
* Check that all the dimensions in the axis align with the dimensions of the data
*/
private boolean checkAxisDimensions(AxisChoice c) {
int[] cAxis = c.getAxes();
if (cAxis == null) {
logger.warn("Ignoring node {} as it doesn't have axis attribute",
new Object[] { c.getName() });
return false;
}
AbstractDataset axis = c.getValues();
if (cAxis.length != axis.getRank()) {
logger.warn("Ignoring axis {} as its axis attribute rank does not match axis data rank",
new Object[] { c.getName() });
return false;
}
int len = cData.getRank();
int[] aShape = axis.getShape();
int[] dShape = cData.getShape();
for (int a = 0; a < cAxis.length; a++) {
if (cAxis[a] >= len) {
logger.warn("Ignoring axis {} as its attribute points to non-existing dimension",
new Object[] { c.getName() });
return false;
}
int axisShape = aShape[a];
int dataShape = dShape[cAxis[a]];
if (axisShape != dataShape) {
logger.warn("Ignoring axis {} as its length ({}) does not match data size ({}) for dimension ({})",
new Object[] { c.getName(), axisShape, dataShape, cAxis[a] });
return false;
}
}
return true;
}
@Override
public void dispose() {
cListeners.clear();
super.dispose();
}
private AsciiTextView getTextView() {
AsciiTextView textView = null;
// check if Dataset Table View is open
try {
textView = (AsciiTextView) site.getPage().showView(AsciiTextView.ID);
} catch (PartInitException e) {
logger.error("All over now! Cannot find ASCII text view: {} ", e);
}
return textView;
}
@Override
public DataHolder loadFile(String fileName, IMonitor mon) throws Exception {
if (fileName == filename)
return holder;
return new HDF5Loader(fileName).loadFile(mon);
}
@Override
public void loadFileAndDisplay(String fileName, IMonitor mon) throws Exception {
tree = new HDF5Loader(fileName).loadTree(mon);
if (tree != null) {
holder = new DataHolder();
Map<String, ILazyDataset> map = HDF5Loader.createDatasetsMap(tree.getGroup());
for (String n : map.keySet()) {
holder.addDataset(n, map.get(n));
}
holder.setMetadata(HDF5Loader.createMetaData(tree));
setFilename(fileName);
if (display != null)
display.asyncExec(new Runnable() {
@Override
public void run() {
tableTree.setInput(tree.getNodeLink());
display.update();
}
});
}
}
/**
* @return loaded tree or null
*/
public HDF5File getHDF5Tree() {
return tree;
}
public void setHDF5Tree(HDF5File htree) {
tree = htree;
if (display != null)
display.asyncExec(new Runnable() {
@Override
public void run() {
tableTree.setInput(tree.getNodeLink());
display.update();
}
});
}
public void expandAll() {
tableTree.expandAll();
}
public void expandToLevel(int level) {
tableTree.expandToLevel(level);
}
public void expandToLevel(Object link, int level) {
tableTree.expandToLevel(link, level);
}
public TreePath[] getExpandedTreePaths() {
return tableTree.getExpandedTreePaths();
}
// selection provider interface
@Override
public void addSelectionChangedListener(ISelectionChangedListener listener) {
if (cListeners.add(listener)) {
return;
}
}
@Override
public ISelection getSelection() {
return hdf5Selection;
}
@Override
public void removeSelectionChangedListener(ISelectionChangedListener listener) {
if (cListeners.remove(listener))
return;
}
@Override
public void setSelection(ISelection selection) {
if (selection instanceof HDF5Selection)
hdf5Selection = (HDF5Selection) selection;
else
return;
SelectionChangedEvent e = new SelectionChangedEvent(this, hdf5Selection);
for (ISelectionChangedListener s : cListeners)
s.selectionChanged(e);
}
/**
* Set full name for file (including path)
* @param fileName
*/
public void setFilename(String fileName) {
filename = fileName;
}
public HDF5TableTree getTableTree(){
return tableTree;
}
}
| true | true | private boolean processSelectedNode(HDF5NodeLink link) {
// two cases: axis and primary or axes
// iterate through each child to find axes and primary attributes
HDF5Node node = link.getDestination();
boolean foundData = false;
List<AxisChoice> choices = new ArrayList<AxisChoice>();
HDF5Attribute axesAttr = null;
HDF5Group gNode = null;
HDF5Dataset dNode = null;
// see if chosen node is a NXdata class
String nxClass = node.containsAttribute(HDF5File.NXCLASS) ? node.getAttribute(HDF5File.NXCLASS).getFirstElement() : null;
if (nxClass == null || nxClass.equals(SDS)) {
if (!(node instanceof HDF5Dataset))
return foundData;
dNode = (HDF5Dataset) node;
if (!dNode.isSupported())
return false;
foundData = true;
cData = dNode.getDataset();
axesAttr = dNode.getAttribute(NXAXES);
gNode = (HDF5Group) link.getSource(); // before hunting for axes
} else if (nxClass.equals(NXDATA)) {
assert node instanceof HDF5Group;
gNode = (HDF5Group) node;
// find data (signal=1) and check for axes attribute
Iterator<HDF5NodeLink> iter = gNode.getNodeLinkIterator();
while (iter.hasNext()) {
HDF5NodeLink l = iter.next();
if (l.isDestinationADataset()) {
dNode = (HDF5Dataset) l.getDestination();
if (dNode.containsAttribute(NXSIGNAL) && dNode.isSupported()) {
foundData = true;
cData = dNode.getDataset();
axesAttr = dNode.getAttribute(NXAXES);
break; // only one signal per NXdata item
}
}
}
}
if (!foundData)
return foundData;
// remove extraneous dimensions
cData.squeeze(true);
// set up slices
int rank = cData.getRank();
// scan children for SDS as possible axes (could be referenced by axes)
@SuppressWarnings("null")
Iterator<HDF5NodeLink> iter = gNode.getNodeLinkIterator();
while (iter.hasNext()) {
HDF5NodeLink l = iter.next();
if (l.isDestinationADataset()) {
HDF5Dataset d = (HDF5Dataset) l.getDestination();
if (!d.isSupported() || d.isString() || dNode == d || d.containsAttribute(NXSIGNAL))
continue;
ILazyDataset a = d.getDataset();
try {
int[] s = a.getShape().clone();
s = AbstractDataset.squeezeShape(s, true);
if (s.length != 0) // don't make a 0D dataset
a.squeeze(true);
AxisChoice choice = new AxisChoice(a);
HDF5Attribute attr = d.getAttribute(NXAXIS);
HDF5Attribute attr_label = d.getAttribute(NXLABEL);
if (attr != null) {
int[] intAxis = null;
if (attr.isString()) {
String[] str = attr.getFirstElement().split(",");
intAxis = new int[str.length];
for (int i = 0; i < str.length; i++)
intAxis[i] = Integer.parseInt(str[i]) - 1;
} else {
AbstractDataset attrd = attr.getValue();
intAxis = new int[attrd.getSize()];
IndexIterator it = attrd.getIterator();
int i = 0;
while (it.hasNext()) {
intAxis[i++] = (int) attrd.getElementLongAbs(it.index);
}
}
if (attr_label != null) {
if (attr_label.isString()) {
choice.setDimension(intAxis, Integer.parseInt(attr_label.getFirstElement()) - 1);
} else {
choice.setDimension(intAxis, attr_label.getValue().getInt(0) - 1);
}
} else
choice.setDimension(intAxis);
} else {
if (attr_label != null) {
if (attr_label.isString()) {
choice.setDimension(new int[] { Integer.parseInt(attr_label.getFirstElement()) - 1 });
} else {
choice.setDimension(new int[] {attr_label.getValue().getInt(0) - 1 });
}
}
}
attr = d.getAttribute(NXPRIMARY);
if (attr != null) {
if (attr.isString()) {
Integer intPrimary = Integer.parseInt(attr.getFirstElement());
choice.setPrimary(intPrimary);
} else {
AbstractDataset attrd = attr.getValue();
choice.setPrimary(attrd.getInt(0));
}
}
choices.add(choice);
} catch (Exception e) {
logger.warn("Axis attributes in {} are invalid - {}", a.getName(), e.getMessage());
continue;
}
}
}
List<String> aNames = new ArrayList<String>();
if (axesAttr != null) { // check axes attribute for list axes
String axesStr = axesAttr.getFirstElement().trim();
if (axesStr.startsWith("[")) { // strip opening and closing brackets
axesStr = axesStr.substring(1, axesStr.length() - 1);
}
// check if axes referenced by data exists
String[] names = null;
names = axesStr.split("[:,]");
for (String s : names) {
boolean flg = false;
for (AxisChoice c : choices) {
if (c.equals(s)) {
flg = true;
break;
}
}
if (flg) {
aNames.add(s);
} else {
logger.warn("Referenced axis {} does not exist in NeXus tree node {}", new Object[] { s, node });
aNames.add(null);
}
}
}
// set up AxisSelector
// build up list of choice per dimension
axes.clear();
for (int i = 0; i < rank; i++) {
int dim = cData.getShape()[i];
AxisSelection aSel = new AxisSelection(dim);
axes.add(i, null); // expand list
for (AxisChoice c : choices) {
// check if dimension number and axis length matches
if (c.getDimension() == i) {
if (checkAxisDimensions(c))
aSel.addSelection(c, c.getPrimary());
}
}
for (AxisChoice c : choices) {
// add in others if axis length matches
if (aSel.containsAxis(c.getName())) {
continue;
}
int[] cAxis = c.getAxes();
if ((c.getDimension() != i) && ArrayUtils.contains(cAxis, i)) {
if (checkAxisDimensions(c))
aSel.addSelection(c, 0);
}
}
if (i < aNames.size()) {
for (AxisChoice c : choices) {
if (aSel.containsAxis(c.getName())) {
continue;
}
if (c.getName().equals(aNames.get(i))) {
if (checkAxisDimensions(c))
aSel.addSelection(c, 1);
}
}
}
for (AxisChoice c : choices) {
if (aSel.containsAxis(c.getName())) {
continue;
}
if (!checkAxisDimensions(c)) {
int[] choiceDims = c.getValues().getShape();
AbstractDataset axis = c.getValues();
for (int j = 0; j < choiceDims.length; j++) {
if (choiceDims[j] == dim) {
int[] start = new int[choiceDims.length];
int[] stop = new int[choiceDims.length];
Arrays.fill(stop, 1);
int[] step = stop.clone();
stop[j] = dim;
AbstractDataset sliceAxis = axis.getSlice(start, stop, step).flatten();
// Add dimension label to prevent axis name clashes for different dimensions
sliceAxis.setName(c.getName() + "_" + "dim:" + (i + 1));
AxisChoice tmpChoice = new AxisChoice(sliceAxis);
tmpChoice.setDimension(new int[] {i});
aSel.addSelection(tmpChoice, 0);
}
}
}
}
// add in an automatically generated axis with top order so it appears after primary axes
AbstractDataset axis = AbstractDataset.arange(dim, AbstractDataset.INT32);
axis.setName("dim:" + (i + 1));
AxisChoice newChoice = new AxisChoice(axis);
newChoice.setDimension(new int[] {i});
aSel.addSelection(newChoice, aSel.getMaxOrder() + 1);
aSel.reorderNames();
aSel.selectAxis(0);
axes.set(i, aSel);
}
return foundData;
}
| private boolean processSelectedNode(HDF5NodeLink link) {
// two cases: axis and primary or axes
// iterate through each child to find axes and primary attributes
HDF5Node node = link.getDestination();
boolean foundData = false;
List<AxisChoice> choices = new ArrayList<AxisChoice>();
HDF5Attribute axesAttr = null;
HDF5Group gNode = null;
HDF5Dataset dNode = null;
// see if chosen node is a NXdata class
String nxClass = node.containsAttribute(HDF5File.NXCLASS) ? node.getAttribute(HDF5File.NXCLASS).getFirstElement() : null;
if (nxClass == null || nxClass.equals(SDS)) {
if (!(node instanceof HDF5Dataset))
return foundData;
dNode = (HDF5Dataset) node;
if (!dNode.isSupported())
return false;
foundData = true;
cData = dNode.getDataset();
axesAttr = dNode.getAttribute(NXAXES);
gNode = (HDF5Group) link.getSource(); // before hunting for axes
} else if (nxClass.equals(NXDATA)) {
assert node instanceof HDF5Group;
gNode = (HDF5Group) node;
// find data (signal=1) and check for axes attribute
Iterator<HDF5NodeLink> iter = gNode.getNodeLinkIterator();
while (iter.hasNext()) {
HDF5NodeLink l = iter.next();
if (l.isDestinationADataset()) {
dNode = (HDF5Dataset) l.getDestination();
if (dNode.containsAttribute(NXSIGNAL) && dNode.isSupported()) {
foundData = true;
cData = dNode.getDataset();
axesAttr = dNode.getAttribute(NXAXES);
break; // only one signal per NXdata item
}
}
}
}
if (!foundData)
return foundData;
// remove extraneous dimensions
cData.squeeze(true);
// set up slices
int rank = cData.getRank();
// scan children for SDS as possible axes (could be referenced by axes)
@SuppressWarnings("null")
Iterator<HDF5NodeLink> iter = gNode.getNodeLinkIterator();
while (iter.hasNext()) {
HDF5NodeLink l = iter.next();
if (l.isDestinationADataset()) {
HDF5Dataset d = (HDF5Dataset) l.getDestination();
if (!d.isSupported() || d.isString() || dNode == d || d.containsAttribute(NXSIGNAL))
continue;
ILazyDataset a = d.getDataset();
try {
int[] s = a.getShape().clone();
s = AbstractDataset.squeezeShape(s, true);
if (s.length != 0) // don't make a 0D dataset
a.squeeze(true);
AxisChoice choice = new AxisChoice(a);
HDF5Attribute attr = d.getAttribute(NXAXIS);
HDF5Attribute attr_label = d.getAttribute(NXLABEL);
if (attr != null) {
int[] intAxis = null;
if (attr.isString()) {
String[] str = attr.getFirstElement().split(",");
intAxis = new int[str.length];
for (int i = 0; i < str.length; i++)
intAxis[i] = Integer.parseInt(str[i]) - 1;
} else {
AbstractDataset attrd = attr.getValue();
intAxis = new int[attrd.getSize()];
IndexIterator it = attrd.getIterator();
int i = 0;
while (it.hasNext()) {
intAxis[i++] = (int) attrd.getElementLongAbs(it.index) - 1;
}
}
if (attr_label != null) {
if (attr_label.isString()) {
choice.setDimension(intAxis, Integer.parseInt(attr_label.getFirstElement()) - 1);
} else {
choice.setDimension(intAxis, attr_label.getValue().getInt(0) - 1);
}
} else
choice.setDimension(intAxis);
} else {
if (attr_label != null) {
if (attr_label.isString()) {
choice.setDimension(new int[] { Integer.parseInt(attr_label.getFirstElement()) - 1 });
} else {
choice.setDimension(new int[] {attr_label.getValue().getInt(0) - 1 });
}
}
}
attr = d.getAttribute(NXPRIMARY);
if (attr != null) {
if (attr.isString()) {
Integer intPrimary = Integer.parseInt(attr.getFirstElement());
choice.setPrimary(intPrimary);
} else {
AbstractDataset attrd = attr.getValue();
choice.setPrimary(attrd.getInt(0));
}
}
choices.add(choice);
} catch (Exception e) {
logger.warn("Axis attributes in {} are invalid - {}", a.getName(), e.getMessage());
continue;
}
}
}
List<String> aNames = new ArrayList<String>();
if (axesAttr != null) { // check axes attribute for list axes
String axesStr = axesAttr.getFirstElement().trim();
if (axesStr.startsWith("[")) { // strip opening and closing brackets
axesStr = axesStr.substring(1, axesStr.length() - 1);
}
// check if axes referenced by data exists
String[] names = null;
names = axesStr.split("[:,]");
for (String s : names) {
boolean flg = false;
for (AxisChoice c : choices) {
if (c.equals(s)) {
flg = true;
break;
}
}
if (flg) {
aNames.add(s);
} else {
logger.warn("Referenced axis {} does not exist in NeXus tree node {}", new Object[] { s, node });
aNames.add(null);
}
}
}
// set up AxisSelector
// build up list of choice per dimension
axes.clear();
for (int i = 0; i < rank; i++) {
int dim = cData.getShape()[i];
AxisSelection aSel = new AxisSelection(dim);
axes.add(i, null); // expand list
for (AxisChoice c : choices) {
// check if dimension number and axis length matches
if (c.getDimension() == i) {
if (checkAxisDimensions(c))
aSel.addSelection(c, c.getPrimary());
}
}
for (AxisChoice c : choices) {
// add in others if axis length matches
if (aSel.containsAxis(c.getName())) {
continue;
}
int[] cAxis = c.getAxes();
if ((c.getDimension() != i) && ArrayUtils.contains(cAxis, i)) {
if (checkAxisDimensions(c))
aSel.addSelection(c, 0);
}
}
if (i < aNames.size()) {
for (AxisChoice c : choices) {
if (aSel.containsAxis(c.getName())) {
continue;
}
if (c.getName().equals(aNames.get(i))) {
if (checkAxisDimensions(c))
aSel.addSelection(c, 1);
}
}
}
for (AxisChoice c : choices) {
if (aSel.containsAxis(c.getName())) {
continue;
}
if (!checkAxisDimensions(c)) {
int[] choiceDims = c.getValues().getShape();
AbstractDataset axis = c.getValues();
for (int j = 0; j < choiceDims.length; j++) {
if (choiceDims[j] == dim) {
int[] start = new int[choiceDims.length];
int[] stop = new int[choiceDims.length];
Arrays.fill(stop, 1);
int[] step = stop.clone();
stop[j] = dim;
AbstractDataset sliceAxis = axis.getSlice(start, stop, step).flatten();
// Add dimension label to prevent axis name clashes for different dimensions
sliceAxis.setName(c.getName() + "_" + "dim:" + (i + 1));
AxisChoice tmpChoice = new AxisChoice(sliceAxis);
tmpChoice.setDimension(new int[] {i});
aSel.addSelection(tmpChoice, 0);
}
}
}
}
// add in an automatically generated axis with top order so it appears after primary axes
AbstractDataset axis = AbstractDataset.arange(dim, AbstractDataset.INT32);
axis.setName("dim:" + (i + 1));
AxisChoice newChoice = new AxisChoice(axis);
newChoice.setDimension(new int[] {i});
aSel.addSelection(newChoice, aSel.getMaxOrder() + 1);
aSel.reorderNames();
aSel.selectAxis(0);
axes.set(i, aSel);
}
return foundData;
}
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.