answer stringlengths 17 10.2M |
|---|
package gorden.album.utils;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.MediaStore.Images.Media;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import gorden.album.R;
import gorden.album.entity.Picture;
import gorden.album.entity.PictureDirectory;
import static android.provider.MediaStore.Images.Media.*;
import static android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
public class PictureScanner implements LoaderManager.LoaderCallbacks<Cursor> {
private AppCompatActivity mContext;
private OnPicturesLoadedListener loadedListener;
private boolean showGif;
private final String[] IMAGE_PROJECTION = {
_ID,
DISPLAY_NAME, // aaa.jpg
DATA, // /storage/emulated/0/pp/downloader/wallpaper/aaa.jpg
SIZE, //long 132492
WIDTH, //int 1920
HEIGHT, //int 1080
MIME_TYPE, // image/jpeg
DATE_ADDED}; //long 1450518608
private ArrayList<PictureDirectory> directories = new ArrayList<>();
private PictureScanner(AppCompatActivity mContext) {
this.mContext = mContext;
}
public static PictureScanner getInstance(AppCompatActivity mContext) {
return new PictureScanner(mContext);
}
public void scan(OnPicturesLoadedListener loadedListener, boolean showGif) {
this.loadedListener = loadedListener;
this.showGif = showGif;
LoaderManager loaderManager = mContext.getSupportLoaderManager();
loaderManager.initLoader(0, null, this);
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
return new CursorLoader(mContext, EXTERNAL_CONTENT_URI, IMAGE_PROJECTION, showGif ? null : MIME_TYPE + "!=?", showGif ? null : new String[]{"image/gif"}, IMAGE_PROJECTION[7] + " DESC");
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
directories.clear();
if (data != null) {
ArrayList<Picture> allPictures = new ArrayList<>();
while (data.moveToNext()) {
String imageId = data.getString(data.getColumnIndexOrThrow(IMAGE_PROJECTION[0]));
String imageName = data.getString(data.getColumnIndexOrThrow(IMAGE_PROJECTION[1]));
String imagePath = data.getString(data.getColumnIndexOrThrow(IMAGE_PROJECTION[2]));
long imageSize = data.getLong(data.getColumnIndexOrThrow(IMAGE_PROJECTION[3]));
int imageWidth = data.getInt(data.getColumnIndexOrThrow(IMAGE_PROJECTION[4]));
int imageHeight = data.getInt(data.getColumnIndexOrThrow(IMAGE_PROJECTION[5]));
String imageMimeType = data.getString(data.getColumnIndexOrThrow(IMAGE_PROJECTION[6]));
long imageAddTime = data.getLong(data.getColumnIndexOrThrow(IMAGE_PROJECTION[7]));
Picture picture = new Picture();
picture.id = imageId;
picture.name = imageName;
picture.addTime = imageAddTime;
picture.path = imagePath;
picture.size = imageSize;
picture.mimeType = imageMimeType;
picture.width = imageWidth;
picture.height = imageHeight;
if (!isEffective(picture)) continue;
allPictures.add(picture);
File imageFile = new File(imagePath);
File imageParentFile = imageFile.getParentFile();
PictureDirectory pictureDirectory = new PictureDirectory();
pictureDirectory.dirName = imageParentFile.getName();
pictureDirectory.dirPath = imageParentFile.getAbsolutePath();
if (!directories.contains(pictureDirectory)) {
ArrayList<Picture> images = new ArrayList<>();
images.add(picture);
pictureDirectory.coverPicture = picture;
pictureDirectory.pictures = images;
directories.add(pictureDirectory);
} else {
directories.get(directories.indexOf(pictureDirectory)).pictures.add(picture);
}
}
if (data.getCount() > 0 && allPictures.size() > 0) {
PictureDirectory allImagesFolder = new PictureDirectory();
allImagesFolder.dirName = mContext.getResources().getString(R.string.album_str_all_image);
allImagesFolder.dirPath = "/";
allImagesFolder.coverPicture = allPictures.get(0);
allImagesFolder.pictures = allPictures;
directories.add(0, allImagesFolder);
}
loadedListener.onPicturesLoaded(directories);
}
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
Log.e("PictureScanner", "onLoaderReset");
}
private boolean isEffective(Picture picture) {
return new File(picture.path).isFile() && picture.size > 0;//&& picture.width > 0
}
public interface OnPicturesLoadedListener {
void onPicturesLoaded(List<PictureDirectory> imageFolders);
}
} |
package edu.vu.isis.ammo.core.network;
import java.io.BufferedInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.Socket;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Enumeration;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.zip.CRC32;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import android.os.Looper;
/**
* Two long running threads and one short.
* The long threads are for sending and receiving messages.
* The short thread is to connect the socket.
* The sent messages are placed into a queue if the socket is connected.
*
* @author phreed
*
*/
public class TcpChannel {
private static final Logger logger = LoggerFactory.getLogger(TcpChannel.class);
private boolean isEnabled = false;
private Socket socket = null;
private ConnectorThread connectorThread;
private ReceiverThread receiverThread;
private SenderThread senderThread;
private int connectTimeout = 5 * 1000; // this should come from network preferences
private int socketTimeout = 5 * 1000; // milliseconds.
private String gatewayHost = null;
private int gatewayPort = -1;
private ByteOrder endian = ByteOrder.LITTLE_ENDIAN;
private final Object syncObj;
private TcpChannel(NetworkService driver) {
super();
logger.trace("Thread <{}>TcpChannel::<constructor>", Thread.currentThread().getId());
this.syncObj = this;
this.connectorThread = new ConnectorThread(this, driver);
this.senderThread = new SenderThread(this, driver);
this.receiverThread = new ReceiverThread(this, driver);
}
public static TcpChannel getInstance(NetworkService driver) {
logger.trace("Thread <{}>::getInstance", Thread.currentThread().getId());
TcpChannel instance = new TcpChannel(driver);
return instance;
}
public boolean isConnected() { return this.connectorThread.isConnected(); }
/**
* Was the status changed as a result of enabling the connection.
* @return
*/
public boolean isEnabled() { return this.isEnabled; }
public boolean enable() {
logger.trace("Thread <{}>::enable", Thread.currentThread().getId());
synchronized (this.syncObj) {
if (this.isEnabled == true)
return false;
this.isEnabled = true;
this.connectorThread.start();
this.senderThread.start();
this.receiverThread.start();
}
return true;
}
public boolean disable() {
logger.trace("Thread <{}>::disable", Thread.currentThread().getId());
synchronized (this.syncObj) {
if (this.isEnabled == false)
return false;
this.isEnabled = false;
this.connectorThread.stop();
this.senderThread.stop();
this.receiverThread.stop();
}
return true;
}
public boolean setConnectTimeout(int value) {
logger.trace("Thread <{}>::setConnectTimeout {}", Thread.currentThread().getId(), value);
this.connectTimeout = value;
return true;
}
public boolean setSocketTimeout(int value) {
logger.trace("Thread <{}>::setSocketTimeout {}", Thread.currentThread().getId(), value);
this.socketTimeout = value;
this.reset();
return true;
}
public boolean setHost(String host) {
logger.trace("Thread <{}>::setHost {}", Thread.currentThread().getId(), host);
if ( gatewayHost != null && gatewayHost.equals(host) ) return false;
this.gatewayHost = host;
this.reset();
return true;
}
public boolean setPort(int port) {
logger.trace("Thread <{}>::setPort {}", Thread.currentThread().getId(), port);
if (gatewayPort == port) return false;
this.gatewayPort = port;
this.reset();
return true;
}
public String toString() {
return "socket: host["+this.gatewayHost+"] port["+this.gatewayPort+"]";
}
/**
* forces a reconnection.
*/
public void reset() {
logger.trace("Thread <{}>::reset", Thread.currentThread().getId());
this.connectorThread.reset();
}
/**
* manages the connection.
* enable or disable expresses the operator intent.
* There is no reason to run the thread unless the channel is enabled.
*
* Any of the properties of the channel
* @author phreed
*
*/
private static class ConnectorThread extends Thread {
private static final Logger logger = LoggerFactory.getLogger(ConnectorThread.class);
private static final String DEFAULT_HOST = "10.0.2.2";
private static final int DEFAULT_PORT = 32896;
private static final int GATEWAY_RETRY_TIME = 20000; // 20 seconds
private TcpChannel parent;
private INetworkService.OnConnectHandler handler;
private final State state;
private ConnectorThread(TcpChannel parent, INetworkService.OnConnectHandler handler) {
logger.trace("Thread <{}>ConnectorThread::<constructor>", Thread.currentThread().getId());
this.parent = parent;
this.handler = handler;
this.state = new State();
}
private class State {
private int value;
static private final int CONNECTED = 0; // the socket is good an active
static private final int CONNECTING = 1; // trying to connect
static private final int DISCONNECTED = 2; // the socket is disconnected
static private final int STALE = 4; // indicating there is a message
static private final int LINK_WAIT = 5; // indicating the underlying link is down
private long version; // used to uniquely name the connection
public State() {
this.value = STALE;
this.version = Long.MIN_VALUE;
}
public synchronized void set(int state) {
logger.trace("Thread <{}>State::set {}", Thread.currentThread().getId(), state);
if (state == STALE) {
logger.error("set stale only from the special setStale method");
return;
}
if (state == CONNECTED)
version++;
this.value = state;
this.notifyAll();
}
public synchronized int get() { return this.value; }
public synchronized boolean isConnected() {
return this.value == CONNECTED;
}
public synchronized boolean failure(long version) {
if (version != this.version) return true;
if (this.value != CONNECTED) return true;
this.value = STALE;
this.notifyAll();
return true;
}
}
public boolean isConnected() {
return this.state.isConnected();
}
public long getVersion() {
return this.state.version;
}
/**
* reset forces the channel closed if open.
*/
public void reset() {
this.state.failure(this.state.version);
}
public void failure(long version) {
this.state.failure(version);
}
/**
* A value machine based.
* Most of the time this machine will be in a CONNECTED value.
* In that CONNECTED value the machine wait for the connection value to
* change or for an interrupt indicating that the thread is being shut down.
*
* The value machine takes care of the following constraints:
* We don't need to reconnect unless.
* 1) the connection has been lost
* 2) the connection has been marked stale
* 3) the connection is enabled.
* 4) an explicit reconnection was requested
*
* @return
*/
@Override
public void run() {
logger.trace("Thread <{}>ConnectorThread::run", Thread.currentThread().getId());
MAINTAIN_CONNECTION: while (true) {
switch (this.state.get()) {
case State.STALE:
disconnect();
this.state.set(State.LINK_WAIT);
break;
case State.LINK_WAIT:
if (isLinkUp()) {
this.state.set(State.DISCONNECTED);
}
// on else wait for link to come up TODO triggered through broadcast receiver
break;
case State.DISCONNECTED:
if ( !this.connect() ) {
this.state.set(State.CONNECTING);
} else {
this.state.set(State.CONNECTED);
}
break;
case State.CONNECTING: // keep trying
if ( this.connect() ) {
this.state.set(State.CONNECTED);
} else {
try {
Thread.sleep(GATEWAY_RETRY_TIME);
} catch (InterruptedException ex) {
logger.info("sleep interrupted - intentional disable, exiting thread ...");
this.state.set(State.STALE);
break MAINTAIN_CONNECTION;
}
}
break;
case State.CONNECTED:
handler.auth();
default: {
try {
synchronized (this.state) {
this.state.wait(); // wait for somebody to change the connection status
}
} catch (InterruptedException ex) {
logger.info("connection intentionally disabled {}", this.state );
this.state.set(State.STALE);
break MAINTAIN_CONNECTION;
}
}
}
}
try {
this.parent.socket.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
private boolean disconnect() {
logger.trace("Thread <{}>ConnectorThread::disconnect", Thread.currentThread().getId());
try {
if (this.parent.socket == null) return true;
this.parent.socket.close();
} catch (IOException e) {
return false;
}
return true;
}
private boolean isLinkUp() { return true; }
/**
* connects to the gateway
* @return
*/
private boolean connect() {
logger.trace("Thread <{}>ConnectorThread::connect", Thread.currentThread().getId());
String host = (parent.gatewayHost != null) ? parent.gatewayHost : DEFAULT_HOST;
int port = (parent.gatewayPort > 10) ? parent.gatewayPort : DEFAULT_PORT;
InetAddress ipaddr = null;
try {
ipaddr = InetAddress.getByName(host);
} catch (UnknownHostException e) {
logger.info("could not resolve host name");
return false;
}
parent.socket = new Socket();
InetSocketAddress sockAddr = new InetSocketAddress(ipaddr, port);
try {
parent.socket.connect(sockAddr, parent.connectTimeout);
} catch (IOException ex) {
logger.warn("connection to {}:{} failed : " + ex.getLocalizedMessage(), ipaddr, port);
parent.socket = null;
return false;
}
if (parent.socket == null) return false;
try {
parent.socket.setSoTimeout(parent.socketTimeout);
} catch (SocketException ex) {
return false;
}
logger.info("connection to {}:{} established ", ipaddr, port);
return true;
}
}
/**
* do your best to send the message.
*
* @param size
* @param checksum
* @param message
* @return
*/
public boolean sendRequest(int size, CRC32 checksum, byte[] payload, INetworkService.OnSendMessageHandler handler)
{
synchronized (this.syncObj) {
this.senderThread.putMsg(new GwMessage(size, checksum, payload, handler) );
return true;
}
}
public class GwMessage {
public final int size;
public final CRC32 checksum;
public final byte[] payload;
public final INetworkService.OnSendMessageHandler handler;
public GwMessage(int size, CRC32 checksum, byte[] payload, INetworkService.OnSendMessageHandler handler) {
this.size = size;
this.checksum = checksum;
this.payload = payload;
this.handler = handler;
}
}
/**
* A thread for receiving incoming messages on the socket.
* The main method is run().
*
*/
public static class SenderThread extends Thread {
private static final Logger logger = LoggerFactory.getLogger(SenderThread.class);
static private final int WAIT_CONNECT = 1; // waiting for connection
static private final int SENDING = 2; // indicating the next thing is the size
static private final int TAKING = 3; // indicating the next thing is the size
private final TcpChannel parent;
private final INetworkService.OnSendMessageHandler handler;
private final BlockingQueue<GwMessage> queue;
private SenderThread(TcpChannel parent, INetworkService.OnSendMessageHandler handler) {
logger.trace("Thread <{}>SenderThread::<constructor>", Thread.currentThread().getId());
this.parent = parent;
this.handler = handler;
this.queue = new LinkedBlockingQueue<GwMessage>(20);
}
public void putMsg(GwMessage msg) {
try {
this.queue.put(msg);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
/**
* Initiate a connection to the server and then wait for a response.
* All responses are of the form:
* size : int32
* checksum : int32
* bytes[] : <size>
* This is done via a simple value machine.
* If the checksum doesn't match the connection is dropped and restarted.
*
* Once the message has been read it is passed off to...
*/
@Override
public void run() {
logger.trace("Thread <{}>SenderThread::run", Thread.currentThread().getId());
int state = TAKING;
DataOutputStream dos = null;
try {
// one integer for size & four bytes for checksum
ByteBuffer buf = ByteBuffer.allocate(Integer.SIZE/Byte.SIZE + 4);
buf.order(parent.endian);
GwMessage msg = null;
long version = Long.MAX_VALUE;
while (true) {
switch (state) {
case WAIT_CONNECT:
try {
// if connected then proceed
// keep the working socket so that if something goes wrong
// the socket can be checked to see if it has changed
// in the interim.
synchronized (parent.connectorThread.state) {
while (! parent.connectorThread.isConnected()) {
try {
logger.trace("Thread <{}>SenderThread::value.wait",
Thread.currentThread().getId());
parent.connectorThread.state.wait();
} catch (InterruptedException ex) {
logger.warn("thread interupted {}",ex.getLocalizedMessage());
return ; // looks like the thread is being shut down.
}
}
long newversion = parent.connectorThread.getVersion();
if (newversion != version) {
dos = new DataOutputStream(this.parent.socket.getOutputStream());
version = newversion;
}
}
} catch (SocketException ex) {
logger.warn("socket disconnected while writing a message");
if (msg.handler != null) msg.handler.ack(false);
parent.connectorThread.failure(version);
} catch (IOException ex) {
logger.warn("io exception writing messages");
if (msg.handler != null) msg.handler.ack(false);
parent.connectorThread.failure(version);
}
state = SENDING;
break;
case TAKING:
msg = queue.take(); // THE MAIN BLOCKING CALL
state = WAIT_CONNECT;
break;
case SENDING:
// refresh dos to current socket (current means version match)
buf.rewind();
buf.putInt(msg.size);
long cvalue = msg.checksum.getValue();
byte[] checksum = new byte[] {
(byte)cvalue,
(byte)(cvalue >>> 8),
(byte)(cvalue >>> 16),
(byte)(cvalue >>> 24)
};
logger.debug("checksum [{}]", checksum);
buf.put(checksum, 0, 4);
try {
dos.write(buf.array());
dos.write(msg.payload);
dos.flush();
} catch (SocketException ex) {
logger.warn("socket disconnected while writing a message");
if (msg.handler != null) msg.handler.ack(false);
parent.connectorThread.failure(version);
state = TAKING;
break;
} catch (IOException ex) {
logger.warn("io exception writing messages");
if (msg.handler != null) msg.handler.ack(false);
parent.connectorThread.failure(version);
state = TAKING;
break;
}
// legitimately sent to gateway.
if (msg.handler != null) msg.handler.ack(true);
state = TAKING;
break;
}
}
} catch (InterruptedException ex) {
logger.warn("interupted writing messages");
}
logger.warn("sender thread exiting ...");
}
}
/**
* A thread for receiving incoming messages on the socket.
* The main method is run().
*
*/
public static class ReceiverThread extends Thread {
private static final Logger logger = LoggerFactory.getLogger(ReceiverThread.class);
final private INetworkService.OnReceiveMessageHandler handler;
private TcpChannel parent = null;
// private TcpChannel.ConnectorThread;
volatile private int state;
static private final int SHUTDOWN = 0; // the run is being stopped
static private final int START = 1; // indicating the next thing is the size
static private final int WAIT_CONNECT = 2; // waiting for connection
static private final int STARTED = 3; // indicating there is a message
static private final int SIZED = 4; // indicating the next thing is a checksum
static private final int CHECKED = 5; // indicating the bytes are being read
static private final int DELIVER = 6; // indicating the message has been read
private ReceiverThread(TcpChannel parent, INetworkService.OnReceiveMessageHandler handler ) {
logger.trace("Thread <{}>ReceiverThread::<constructor>", Thread.currentThread().getId());
this.parent = parent;
this.handler = handler;
}
public void close() {
logger.trace("Thread <{}>::close", Thread.currentThread().getId());
this.state = SHUTDOWN;
}
@Override
public void start() {
super.start();
logger.trace("Thread <{}>::start", Thread.currentThread().getId());
}
/**
* Initiate a connection to the server and then wait for a response.
* All responses are of the form:
* size : int32
* checksum : int32
* bytes[] : <size>
* This is done via a simple value machine.
* If the checksum doesn't match the connection is dropped and restarted.
*
* Once the message has been read it is passed off to...
*/
@Override
public void run() {
logger.trace("Thread <{}>ReceiverThread::run", Thread.currentThread().getId());
Looper.prepare();
state = WAIT_CONNECT;
int bytesToRead = 0; // indicates how many bytes should be read
int bytesRead = 0; // indicates how many bytes have been read
long checksum = 0;
byte[] message = null;
byte[] byteToReadBuffer = new byte[Integer.SIZE/Byte.SIZE];
byte[] checksumBuffer = new byte[Long.SIZE/Byte.SIZE];
BufferedInputStream bis = null;
long version = Long.MAX_VALUE;
while (true) {
switch (state) {
case WAIT_CONNECT: // look for the size
synchronized (parent.connectorThread.state) {
while (! parent.connectorThread.isConnected() ) {
try {
logger.trace("Thread <{}>ReceiverThread::value.wait",
Thread.currentThread().getId());
parent.connectorThread.state.wait();
} catch (InterruptedException ex) {
logger.warn("thread interupted {}",ex.getLocalizedMessage());
shutdown(bis); // looks like the thread is being shut down.
return;
}
}
version = parent.connectorThread.getVersion();
}
try {
InputStream insock = this.parent.socket.getInputStream();
bis = new BufferedInputStream(insock, 1024);
} catch (IOException ex) {
logger.error("could not open input stream on socket {}", ex.getLocalizedMessage());
parent.connectorThread.failure(version);
continue;
}
if (bis == null) continue;
case START:
try {
bis.read(byteToReadBuffer);
} catch (SocketTimeoutException ex) {
// logger.trace("timeout on socket");
continue;
} catch (IOException e) {
logger.error("read error ...");
parent.connectorThread.failure(version);
this.state = WAIT_CONNECT;
break; // read error - set our value back to wait for connect
}
this.state = STARTED;
break;
case STARTED: // look for the size
{
ByteBuffer bbuf = ByteBuffer.wrap(byteToReadBuffer);
bbuf.order(this.parent.endian);
bytesToRead = bbuf.getInt();
if (bytesToRead < 0) break; // bad read keep trying
if (bytesToRead > 100000) {
logger.warn("a message with "+bytesToRead);
}
this.state = SIZED;
}
break;
case SIZED: // look for the checksum
{
try {
bis.read(checksumBuffer, 0, 4);
} catch (SocketTimeoutException ex) {
logger.trace("timeout on socket");
continue;
} catch (IOException e) {
logger.trace("read error on socket");
parent.connectorThread.failure(version);
this.state = WAIT_CONNECT;
break;
}
ByteBuffer bbuf = ByteBuffer.wrap(checksumBuffer);
bbuf.order(this.parent.endian);
checksum = bbuf.getLong();
message = new byte[bytesToRead];
logger.info(checksumBuffer.toString(), checksum);
bytesRead = 0;
this.state = CHECKED;
}
break;
case CHECKED: // read the message
while (bytesRead < bytesToRead) {
try {
int temp = bis.read(message, 0, bytesToRead - bytesRead);
bytesRead += (temp >= 0) ? temp : 0;
} catch (SocketTimeoutException ex) {
logger.trace("timeout on socket");
continue;
} catch (IOException ex) {
logger.trace("read error on socket");
this.state = WAIT_CONNECT;
parent.connectorThread.failure(version);
break;
}
}
if (bytesRead < bytesToRead)
break;
this.state = DELIVER;
break;
case DELIVER: // deliver the message to the gateway
this.handler.deliver(message, checksum);
message = null;
this.state = START;
break;
}
}
}
private void shutdown(BufferedInputStream bis) {
logger.debug("no longer listening, thread closing");
try { bis.close(); } catch (IOException e) {}
return;
}
}
/**
* A routine to get the local ip address
* TODO use this someplace
*
* @return
*/
public String getLocalIpAddress() {
logger.trace("Thread <{}>::getLocalIpAddress", Thread.currentThread().getId());
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) {
return inetAddress.getHostAddress().toString();
}
}
}
} catch (SocketException ex) {
logger.error( ex.toString());
}
return null;
}
} |
package com.RSG.AndroidPlugin;
import android.os.Environment;
import android.os.BatteryManager;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.Context;
public class AndroidPlugin
{
// Needed to get the battery level.
private Context context;
public AndroidPlugin(Context context)
{
this.context = context;
}
// Return the battery level as a float between 0 and 1 (1 being fully charged, 0 fulled discharged)
public float GetBatteryPct(Context context)
{
Intent batteryStatus = GetBatteryStatusIntent();
int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
float batteryPct = level / (float)scale;
return batteryPct;
}
// Return whether or not we're currently on charge
public boolean IsBatteryCharging()
{
Intent batteryStatus = GetBatteryStatusIntent();
int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
return status == BatteryManager.BATTERY_STATUS_CHARGING ||
status == BatteryManager.BATTERY_STATUS_FULL;
}
private Intent GetBatteryStatusIntent()
{
IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus = context.registerReceiver(null, ifilter);
}
} |
package com.gravity.root;
import org.newdawn.slick.AppGameContainer;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.state.StateBasedGame;
/**
*
* @author dxiao
*/
public class PlatformerGame extends StateBasedGame {
//@formatter:off
private LevelInfo[] levels = {
new LevelInfo("Level 1", "Staircases are hard!", "assets/Levels/split_world.tmx", 1001),
new LevelInfo("Level 2", "More traditional Mario", "assets/Levels/level2.tmx", 1002),
new LevelInfo("Slingshot", "Slingshot Turorial", "assets/Levels/tutorial.tmx", 1003)
};
//@formatter:on
public PlatformerGame() {
super("Psychic Psycho Bunnies v1.0");
}
@Override
public void initStatesList(GameContainer gc) throws SlickException {
addState(new MainMenuState());
addState(new LevelSelectState(levels));
for (LevelInfo level : levels) {
addState(new GameplayState(level.title, level.mapfile, level.stateId));
}
addState(new CreditsState());
addState(new GameOverState());
addState(new GameWinState());
}
public static void main(String args[]) throws SlickException {
AppGameContainer app = new AppGameContainer(new PlatformerGame());
app.setDisplayMode(1024, 768, false);
app.setMaximumLogicUpdateInterval(100);
app.setMinimumLogicUpdateInterval(10);
app.setTargetFrameRate(60);
// app.setSmoothDeltas(true);
app.start();
}
} |
package com.kaltura.playersdk;
import java.util.Timer;
import java.util.TimerTask;
import android.content.Context;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Handler;
import android.widget.VideoView;
import com.kaltura.playersdk.events.OnPlayerStateChangeListener;
import com.kaltura.playersdk.events.OnPlayheadUpdateListener;
import com.kaltura.playersdk.events.OnProgressListener;
import com.kaltura.playersdk.types.PlayerStates;
public class PlayerView extends VideoView implements VideoPlayerInterface {
//TODO make configurable
public static int PLAYHEAD_UPDATE_INTERVAL = 200;
private String mVideoUrl;
private OnPlayerStateChangeListener mPlayerStateListener;
private MediaPlayer.OnPreparedListener mPreparedListener;
private OnPlayheadUpdateListener mPlayheadUpdateListener;
private OnProgressListener mProgressListener;
private int mStartPos = 0;
private Handler mHandler;
private Runnable runnable = new Runnable() {
@Override
public void run() {
try {
int position = getCurrentPosition();
if ( position != 0 && mPlayheadUpdateListener != null )
mPlayheadUpdateListener.onPlayheadUpdated(position);
} catch(IllegalStateException e){
e.printStackTrace();
}
mHandler.postDelayed(this, PLAYHEAD_UPDATE_INTERVAL);
}
};
public PlayerView(Context context) {
super(context);
super.setOnCompletionListener( new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mediaPlayer) {
pause();
seekTo( 0 );
updateStopState();
mPlayerStateListener.onStateChanged(PlayerStates.END);
}
});
super.setOnPreparedListener( new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mediaPlayer) {
mPlayerStateListener.onStateChanged(PlayerStates.START);
mediaPlayer.setOnSeekCompleteListener( new MediaPlayer.OnSeekCompleteListener() {
@Override
public void onSeekComplete(MediaPlayer mediaPlayer) {
mPlayerStateListener.onStateChanged(PlayerStates.SEEKED);
}
});
if ( mPreparedListener != null ) {
mPreparedListener.onPrepared(mediaPlayer);
}
mediaPlayer.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() {
@Override
public void onBufferingUpdate(MediaPlayer mp, int progress) {
if ( mProgressListener != null ) {
mProgressListener.onProgressUpdate(progress);
}
}
});
}
});
}
@Override
public void setStartingPoint(int point) {
mStartPos = point;
}
@Override
public String getVideoUrl() {
return mVideoUrl;
}
@Override
public void setVideoUrl(String url) {
mVideoUrl = url;
super.setVideoURI(Uri.parse(url));
}
@Override
public int getDuration() {
return super.getDuration();
}
public int getCurrentPosition() {
return super.getCurrentPosition();
}
@Override
public boolean getIsPlaying() {
return super.isPlaying();
}
@Override
public void play() {
if ( !this.isPlaying() ) {
super.start();
if ( mStartPos != 0 ) {
super.seekTo( mStartPos );
mStartPos = 0;
}
if ( mHandler == null ) {
mHandler = new Handler();
}
mHandler.postDelayed(runnable, PLAYHEAD_UPDATE_INTERVAL);
mPlayerStateListener.onStateChanged(PlayerStates.PLAY);
}
}
@Override
public void pause() {
if ( this.isPlaying() ) {
super.pause();
mPlayerStateListener.onStateChanged(PlayerStates.PAUSE);
}
}
@Override
public void stop() {
super.stopPlayback();
updateStopState();
}
private void updateStopState() {
if ( mHandler != null ) {
mHandler.removeCallbacks( runnable );
}
}
@Override
public void seek(int msec) {
mPlayerStateListener.onStateChanged(PlayerStates.SEEKING);
super.seekTo(msec);
}
@Override
public void registerPlayerStateChange( OnPlayerStateChangeListener listener) {
mPlayerStateListener = listener;
}
@Override
public void registerReadyToPlay( MediaPlayer.OnPreparedListener listener) {
mPreparedListener = listener;
}
@Override
public void registerError( MediaPlayer.OnErrorListener listener) {
super.setOnErrorListener(listener);
}
@Override
public void registerPlayheadUpdate( OnPlayheadUpdateListener listener ) {
mPlayheadUpdateListener = listener;
}
@Override
public void removePlayheadUpdateListener() {
mPlayheadUpdateListener = null;
}
@Override
public void registerProgressUpdate ( OnProgressListener listener ) {
mProgressListener = listener;
}
} |
package mil.nga.giat.mage.sdk.location;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import mil.nga.giat.mage.sdk.R;
import mil.nga.giat.mage.sdk.datastore.common.GeometryType;
import mil.nga.giat.mage.sdk.datastore.location.LocationGeometry;
import mil.nga.giat.mage.sdk.datastore.location.LocationHelper;
import mil.nga.giat.mage.sdk.datastore.location.LocationProperty;
import mil.nga.giat.mage.sdk.event.IEventDispatcher;
import mil.nga.giat.mage.sdk.exceptions.LocationException;
import mil.nga.giat.mage.sdk.utils.GeometryUtil;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.util.Log;
/**
* Query the device for the device's location. If userReportingFrequency is set
* to never, the Service will listen for changes to userReportingFrequency.
*
* TODO: implement {@link IEventDispatcher} for location updates?
*/
public class LocationService extends Service implements LocationListener, OnSharedPreferenceChangeListener {
private static final String LOG_NAME = LocationService.class.getName();
private final Context mContext;
// Minimum milliseconds between updates
private static final long MIN_TIME_BW_UPDATES = 0 * 1000;
protected final LocationManager locationManager;
protected boolean pollingRunning = false;
protected Collection<LocationListener> locationListeners = new ArrayList<LocationListener>();
protected synchronized boolean isPolling() {
return pollingRunning;
}
// False means don't re-read gps settings. True means re-read gps settings. Gets triggered from preference change
protected AtomicBoolean preferenceSemaphore = new AtomicBoolean(false);
// the last time a location was pulled form the phone.
protected long lastLocationPullTime = 0;
protected synchronized long getLastLocationPullTime() {
return lastLocationPullTime;
}
protected synchronized void setLastLocationPullTime(long lastLocationPullTime) {
this.lastLocationPullTime = lastLocationPullTime;
}
/**
* GPS Sensitivity Setting
*
* @return
*/
private final synchronized long getMinimumDistanceChangeForUpdates() {
final SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(mContext);
return Long.parseLong(sharedPreferences.getString(mContext.getString(R.string.gpsSensitivityKey), mContext.getString(R.string.gpsSensitivityDefaultValue)));
}
/**
* User Reporting Frequency Setting
*
* @return
*/
protected final synchronized long getUserReportingFrequency() {
final SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(mContext);
return Long.parseLong(sharedPreferences.getString(mContext.getString(R.string.userReportingFrequencyKey), mContext.getString(R.string.userReportingFrequencyDefaultValue)));
}
protected boolean locationUpdatesEnabled = false;
public synchronized boolean getLocationUpdatesEnabled() {
return locationUpdatesEnabled;
}
private final Handler mHandler = new Handler();
/**
* FIXME: Should this take a storage utility to save locations?
*
* @param context
*/
public LocationService(Context context) {
this.mContext = context;
this.locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
PreferenceManager.getDefaultSharedPreferences(mContext).registerOnSharedPreferenceChangeListener(this);
preferenceSemaphore.set(false);
}
public void registerOnLocationListener(LocationListener listener) {
locationListeners.add(listener);
}
public void unregisterOnLocationListener(LocationListener listener) {
locationListeners.remove(listener);
}
private void requestLocationUpdates() {
if (locationManager != null) {
final List<String> providers = locationManager.getAllProviders();
if (providers != null) {
if (providers.contains(LocationManager.GPS_PROVIDER)) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, getMinimumDistanceChangeForUpdates(), this);
locationUpdatesEnabled = true;
}
if (providers.contains(LocationManager.NETWORK_PROVIDER)) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, getMinimumDistanceChangeForUpdates(), this);
locationUpdatesEnabled = true;
}
}
}
}
private void removeLocationUpdates() {
locationManager.removeUpdates(this);
locationUpdatesEnabled = false;
}
/**
* Return a location or <code>null</code> is no location is available.
*
* @return A {@link Location}.
*/
public Location getLocation() {
Location location = null;
// if GPS Enabled get Location using GPS Services
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
} else if(locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
setLastLocationPullTime(System.currentTimeMillis());
return location;
}
/**
* Method to show settings alert dialog On pressing Settings button will
* launch Settings Options
*/
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
alertDialog.setTitle("GPS settings");
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
@Override
public void onLocationChanged(Location location) {
if (location.getProvider().equals(LocationManager.GPS_PROVIDER)) {
setLastLocationPullTime(System.currentTimeMillis());
saveLocation(location, "ACTIVE");
}
for (LocationListener listener : locationListeners) {
listener.onLocationChanged(location);
}
}
@Override
public void onProviderDisabled(String provider) {
for (LocationListener listener : locationListeners) {
listener.onProviderDisabled(provider);
}
}
@Override
public void onProviderEnabled(String provider) {
for (LocationListener listener : locationListeners) {
listener.onProviderEnabled(provider);
}
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
for (LocationListener listener : locationListeners) {
listener.onStatusChanged(provider, status, extras);
}
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
/**
* Call this to start the location service
*/
public void start() {
if(!isPolling()) {
pollingRunning = Boolean.TRUE;
createLocationPollingThread().start();
}
}
/**
* Call this to stop the location service
*/
public void stop() {
pollingRunning = Boolean.FALSE;
if (locationManager != null) {
synchronized (preferenceSemaphore) {
preferenceSemaphore.notifyAll();
}
removeLocationUpdates();
}
}
// TODO: Should this be in an AsyncTask?
private void saveLocation(Location location, String state) {
// TODO: check that location timestamp is not 0!
// INTEGRATION WITH LOCATION DATASTORE
LocationHelper locationHelper = LocationHelper.getInstance(mContext);
// build properties
Collection<LocationProperty> locationProperties = new ArrayList<LocationProperty>();
LocationProperty reportedTime = new LocationProperty("REPORTED_TIME", String.valueOf(System.currentTimeMillis()));
locationProperties.add(reportedTime);
// build geometry
String coordinages = GeometryUtil.generate(location.getLatitude(), location.getLongitude());
LocationGeometry locationGeometry = new LocationGeometry(coordinages, new GeometryType("point"));
// build location
mil.nga.giat.mage.sdk.datastore.location.Location loc = new mil.nga.giat.mage.sdk.datastore.location.Location("Feature", locationProperties, locationGeometry);
loc.setLocationGeometry(locationGeometry);
loc.setProperties(locationProperties);
// save the location
try {
locationHelper.createLocation(loc);
} catch (LocationException le) {
// TODO: is this good enough?
Log.w(LOG_NAME, "Unable to record current location locally!", le);
}
Log.d(LOG_NAME, "A Current Active User exists." + loc);
}
/**
* Polls for locations at time specified by the settings.
*
* @return
*/
private Thread createLocationPollingThread() {
return new Thread(new Runnable() {
public void run() {
Looper.prepare();
while (isPolling()) {
try {
long userReportingFrequency = getUserReportingFrequency();
// if we should pull, then do it.
if(userReportingFrequency > 0) {
// make sure the service is configured to report locations
if(!getLocationUpdatesEnabled()) {
mHandler.post(new Runnable() {
public void run() {
removeLocationUpdates();
requestLocationUpdates();
}
});
}
final Location location = getLocation();
if (location != null) {
mHandler.post(new Runnable() {
public void run() {
saveLocation(location, "STALE");
}
});
}
long currentTime = new Date().getTime();
long lLPullTime = getLastLocationPullTime();
// we only need to pull if a location has not been saved in the last 'pollingInterval' seconds.
// the location could have been saved from a motion event, or from the last time the parent loop ran
// use local variables in order to maintain data integrity across instructions.
while (((lLPullTime = getLastLocationPullTime()) + (userReportingFrequency = getUserReportingFrequency()) > (currentTime = new Date().getTime())) && isPolling()) {
synchronized (preferenceSemaphore) {
preferenceSemaphore.wait(lLPullTime + userReportingFrequency - currentTime);
// this means we need to re-read the gps sensitivity
if(preferenceSemaphore.get() == true) {
break;
}
}
}
synchronized (preferenceSemaphore) {
preferenceSemaphore.set(false);
}
} else {
// disable location updates
mHandler.post(new Runnable() {
public void run() {
removeLocationUpdates();
}
});
synchronized (preferenceSemaphore) {
preferenceSemaphore.wait();
}
}
} catch (InterruptedException e) {
e.printStackTrace();
pollingRunning = Boolean.FALSE;
}
}
}
});
}
/**
* Will alert the polling thread that changes have been made
*/
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (key.equalsIgnoreCase(mContext.getString(R.string.gpsSensitivityKey))) {
synchronized (preferenceSemaphore) {
// this will cause the polling-thread to reset the gps sensitivity
locationUpdatesEnabled = false;
preferenceSemaphore.set(true);
preferenceSemaphore.notifyAll();
}
} else if (key.equalsIgnoreCase(mContext.getString(R.string.userReportingFrequencyKey))) {
synchronized (preferenceSemaphore) {
preferenceSemaphore.notifyAll();
}
}
}
} |
package DashboardInterface;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.util.Date;
import javax.swing.JPanel;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.annotations.XYTextAnnotation;
import org.jfree.chart.axis.DateAxis;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.ValueMarker;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYSplineRenderer;
import org.jfree.data.time.Second;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import org.jfree.data.xy.XYDataset;
import org.jfree.ui.TextAnchor;
/**
*
* @author Alex
*/
public class SpeedGraph extends JPanel {
private static final long serialVersionUID = 1L;
private final int maxTension = 150;
private final int maxSpeed = 50;
private final int maxHeight = 120;
private int maxLaunchtime = 20000;
private JFreeChart chart;
public SpeedGraph(String title) {
ChartPanel chartPanel = (ChartPanel) createDemoPanel();
chartPanel.setPreferredSize(new java.awt.Dimension(1000, 270));
add(chartPanel);
}
/**
* Creates a chart.
*
* @param dataset a dataset.
*
* @return A chart.
*/
private JFreeChart createChart(XYDataset dataset) {
chart = ChartFactory.createXYLineChart(
"Speed v Time:", // title
"Time", // x-axis label
"Speed", // y-axis label
dataset, // data
PlotOrientation.VERTICAL,
true, // create legend?
true, // generate tooltips?
false // generate URLs?
);
chart.setBackgroundPaint(Color.white);
XYPlot plot = chart.getXYPlot();
XYSplineRenderer splinerenderer1 = new XYSplineRenderer();
XYSplineRenderer splinerenderer2 = new XYSplineRenderer();
XYSplineRenderer splinerenderer3 = new XYSplineRenderer();
XYDataset dataset1 = createDataset(0L);
plot.setDataset(0,dataset1);
plot.setRenderer(0,splinerenderer1);
DateAxis domainAxis = new DateAxis("Date");
plot.setDomainAxis(domainAxis);
plot.setRangeAxis(new NumberAxis("Height"));
XYDataset dataset2 = createDataset2();
plot.setDataset(1, dataset2);
plot.setRenderer(1, splinerenderer2);
plot.setRangeAxis(1, new NumberAxis("Speed"));
XYDataset dataset3 = createDataset3();
plot.setDataset(2, dataset3);
plot.setRenderer(2, splinerenderer3);
plot.setRangeAxis(2, new NumberAxis("Tension"));
plot.mapDatasetToRangeAxis(0, 0);//1st dataset to 1st y-axis
plot.mapDatasetToRangeAxis(1, 1); //2nd dataset to 2nd y-axis
plot.mapDatasetToRangeAxis(2, 2);
plot.getRangeAxis(0).setRange(0, maxHeight);
plot.getRangeAxis(1).setRange(0, maxSpeed);
plot.getRangeAxis(2).setRange(0, maxTension);
plot.addRangeMarker(new ValueMarker(100, Color.RED, new BasicStroke()));
XYTextAnnotation text = new XYTextAnnotation("Max Tension", 600, 105);
text.setFont(new Font("SansSerif", Font.PLAIN, 9));
plot.addAnnotation(text);
addStateTransition("Profile", 0, 50);
addStateTransition("Ramp", 1000, 60);
addStateTransition("Constant", 7000, 70);
addStateTransition("Recovery", 14000, 80);
/*plot.addDomainMarker(new ValueMarker(0, Color.BLUE, new BasicStroke((float) 2.5)));
plot.addDomainMarker(new ValueMarker(1000, Color.BLUE, new BasicStroke((float) 2.5)));
plot.addDomainMarker(new ValueMarker(7000, Color.BLUE, new BasicStroke((float) 2.5)));
plot.addDomainMarker(new ValueMarker(14000, Color.BLUE, new BasicStroke((float) 2.5)));
XYTextAnnotation text2 = new XYTextAnnotation("Profile", 0, 50);
text2.setFont(new Font("SansSerif", Font.PLAIN, 9));
plot.addAnnotation(text2);
XYTextAnnotation text3 = new XYTextAnnotation("Ramp", 1000, 50);
text3.setFont(new Font("SansSerif", Font.PLAIN, 9));
plot.addAnnotation(text3);
XYTextAnnotation text4 = new XYTextAnnotation("Constant", 7000, 50);
text4.setFont(new Font("SansSerif", Font.PLAIN, 9));
plot.addAnnotation(text4);
XYTextAnnotation text5 = new XYTextAnnotation("Recovery", 14000, 50);
text5.setFont(new Font("SansSerif", Font.PLAIN, 9));
plot.addAnnotation(text5);*/
return chart;
}
private void addStateTransition(String state, int time, int height) {
XYPlot chartPlot = chart.getXYPlot();
chartPlot.addDomainMarker(new ValueMarker(time, Color.BLUE, new BasicStroke((float) 2.5)));
XYTextAnnotation text = new XYTextAnnotation(state, time, height);
text.setTextAnchor(TextAnchor.BASELINE_LEFT);
text.setFont(new Font("SansSerif", Font.PLAIN, 9));
chartPlot.addAnnotation(text);
}
/**
* Creates a dataset, consisting of two series of monthly data.
*
* @return The dataset.
*/
private XYDataset createDataset(long startTimeMili) {
TimeSeries s1 = new TimeSeries("Height ");
s1.add(new Second(new Date(startTimeMili)), 10);
s1.add(new Second(new Date(startTimeMili + 1000)), 15);
s1.add(new Second(new Date(startTimeMili + 2000)), 35);
s1.add(new Second(new Date(startTimeMili + 3000)), 60);
s1.add(new Second(new Date(startTimeMili + 4000)), 75);
s1.add(new Second(new Date(startTimeMili + 5000)), 100);
s1.add(new Second(new Date(startTimeMili + 6000)), 105);
s1.add(new Second(new Date(startTimeMili + 7000)), 106);
s1.add(new Second(new Date(startTimeMili + 8000)), 105);
s1.add(new Second(new Date(startTimeMili + 9000)), 105);
s1.add(new Second(new Date(startTimeMili + 10000)), 105);
s1.add(new Second(new Date(startTimeMili + 11000)), 104);
s1.add(new Second(new Date(startTimeMili + maxLaunchtime)), null);
TimeSeriesCollection dataset = new TimeSeriesCollection();
dataset.addSeries(s1);
return dataset;
}
private static XYDataset createDataset2() {
long dateMili = 0L;
TimeSeries s1 = new TimeSeries("Speed ");
s1.add(new Second(new Date(dateMili)), 1.1);
s1.add(new Second(new Date(dateMili + 1000)), 1.3);
s1.add(new Second(new Date(dateMili + 2000)), 2.8);
s1.add(new Second(new Date(dateMili + 3000)), 4.0);
s1.add(new Second(new Date(dateMili + 4000)), 5.7);
s1.add(new Second(new Date(dateMili + 5000)), 8.0);
s1.add(new Second(new Date(dateMili + 6000)), 10.9);
s1.add(new Second(new Date(dateMili + 7000)), 9.6);
s1.add(new Second(new Date(dateMili + 8000)), 9.5);
s1.add(new Second(new Date(dateMili + 9000)), 9.5);
s1.add(new Second(new Date(dateMili + 10000)), 9.5);
s1.add(new Second(new Date(dateMili + 11000)), 10.4);
TimeSeriesCollection dataset = new TimeSeriesCollection();
dataset.addSeries(s1);
return dataset;
}
private static XYDataset createDataset3 () {
long dateMili = 0L;
TimeSeries s1 = new TimeSeries("Tension ");
s1.add(new Second(new Date(dateMili)), 90);
s1.add(new Second(new Date(dateMili + 1000)), 95);
s1.add(new Second(new Date(dateMili + 2000)), 103);
s1.add(new Second(new Date(dateMili + 3000)), 106);
s1.add(new Second(new Date(dateMili + 4000)), 112);
s1.add(new Second(new Date(dateMili + 5000)), 115);
s1.add(new Second(new Date(dateMili + 6000)), 126);
s1.add(new Second(new Date(dateMili + 7000)), 128);
s1.add(new Second(new Date(dateMili + 8000)), 135);
s1.add(new Second(new Date(dateMili + 9000)), 137);
s1.add(new Second(new Date(dateMili + 10000)), 139);
s1.add(new Second(new Date(dateMili + 11000)), 139);
TimeSeriesCollection dataset = new TimeSeriesCollection();
dataset.addSeries(s1);
return dataset;
}
private static XYDataset createDataset4(int offset) {
long dateMili = 1387265266000L;
TimeSeries s1 = new TimeSeries("");
s1.add(new Second(new Date(dateMili)), 110);
s1.add(new Second(new Date(dateMili + offset)), 110);
TimeSeriesCollection dataset = new TimeSeriesCollection();
dataset.addSeries(s1);
return dataset;
}
/**
* Creates a panel for the demo (used by SuperDemo.java).
*
* @return A panel.
*/
public JPanel createDemoPanel() {
chart = createChart(createDataset(1387265266000L));
ChartPanel panel = new ChartPanel(chart);
panel.setFillZoomRectangle(false);
panel.setMouseWheelEnabled(false);
panel.setAutoscrolls(false);
panel.setDomainZoomable(false);
panel.setFocusable(false);
return panel;
}
} |
package net.yadan.banana.utils;
import net.yadan.banana.utils.LRU.Callback;
import net.yadan.banana.utils.LRU.DataType;
public class LRUExample {
public static void main(String[] args) {
int maxCapacity = 5;
LRU lru = new LRU(maxCapacity, DataType.OBJECT);
// adding 10 items to an LRU with size 5 with leave the last 5 items in
for (int i = 0; i < 10; i++) {
long key = i;
lru.add(key, "Hello " + i);
}
System.out.println(lru.exists(4)); // false, 4 was evicted
System.out.println(lru.get(5)); // Hello 5
// callback for evicted items
for (int i = 11; i < 15; i++) {
long key = i;
lru.add(key, "Hello " + i, new Callback() {
@Override
public void keyEvicted(long key, Object data) {
System.out.println("Evicted " + data);
}
});
}
LRU primitiveLRU = new LRU(maxCapacity, DataType.LONG);
// adding 10 items to an LRU with size 5 with leave the last 10 items i
for (int i = 0; i < 10; i++) {
long key = i;
// no Boxing/Unboxing or memory allocation, pure primitive operation
// function signature : void addLong(long id, long data)
primitiveLRU.addLong(key, 100 + i);
}
}
} |
/*
* QseqToTBTPlugin
*/
package net.maizegenetics.gbs.pipeline;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.InputStreamReader;
import net.maizegenetics.util.MultiMemberGZIPInputStream;
import net.maizegenetics.gbs.homology.ParseBarcodeRead;
import net.maizegenetics.gbs.homology.ReadBarcodeResult;
import net.maizegenetics.gbs.maps.TagsOnPhysicalMap;
import net.maizegenetics.gbs.tagdist.TagCounts;
import net.maizegenetics.gbs.tagdist.Tags;
import net.maizegenetics.gbs.tagdist.TagsByTaxa;
import net.maizegenetics.gbs.tagdist.TagsByTaxa.FilePacking;
import net.maizegenetics.gbs.tagdist.TagsByTaxaBit;
import net.maizegenetics.gbs.tagdist.TagsByTaxaByte;
import net.maizegenetics.util.ArgsEngine;
import net.maizegenetics.util.DirectoryCrawler;
import net.maizegenetics.plugindef.AbstractPlugin;
import net.maizegenetics.plugindef.DataSet;
import java.awt.Frame;
import javax.swing.ImageIcon;
import org.apache.log4j.Logger;
/**
* This pipeline converts a series of qseq files to TagsByTaxa files (one per qseq file).
* It requires a list of existing tags (Tags object), which may come from a TagCounts file or TOPM file.
*
* @author james
*/
public class QseqToTBTPlugin extends AbstractPlugin {
private static final Logger myLogger = Logger.getLogger(QseqToTBTPlugin.class);
private ArgsEngine myArgsEngine = null;
private String[] myQseqFileS = null;
private String myKeyFile = null;
private String myEnzyme = null;
private String myOutputDir = null;
private int myMinCount = 1;
private Tags myMasterTags = null;
private boolean useTBTByte = false;
public QseqToTBTPlugin() {
super(null, false);
}
public QseqToTBTPlugin(Frame parentFrame) {
super(parentFrame, false);
}
@Override
public DataSet performFunction(DataSet input) {
matchTagsToTaxa(myQseqFileS, myKeyFile, myEnzyme, myMasterTags, myOutputDir, myMinCount, useTBTByte);
return null;
}
private void printUsage() {
myLogger.info(
"\nUsage is as follows:\n"
+ "-i Input directory containing .qseq files\n"
+ "-k Barcode key file\n"
+ "-e Enzyme used to create the GBS library, if it differs from the one listed in the key file.\n"
+ "-o Output directory\n"
+ "-c Minimum taxa count within a qseq file for a tag to be output (default 1)\n" // Nb: using TagsByTaxaBit, so max count PER TAXON = 1
+ "-y Output to tagsByTaxaByte (tag counts per taxon from 0 to 127) instead of tagsByTaxaBit (0 or 1)\n"
+ "One of either:\n"
+ " -t Tag count file, OR A\n"
+ " -m Physical map file containing alignments\n");
}
@Override
public void setParameters(String[] args) {
if (args.length == 0) {
printUsage();
throw new IllegalArgumentException("\n\nPlease use the above arguments/options.\n\n");
}
if (myArgsEngine == null) {
myArgsEngine = new ArgsEngine();
myArgsEngine.add("-i", "--input-directory", true);
myArgsEngine.add("-k", "--key-file", true);
myArgsEngine.add("-e", "--enzyme", true);
myArgsEngine.add("-o", "--output-directory", true);
myArgsEngine.add("-c", "--min-count", true);
myArgsEngine.add("-y", "--TBTbyte", false);
myArgsEngine.add("-t", "--tag-count", true);
myArgsEngine.add("-m", "--physical-map", true);
}
myArgsEngine.parse(args);
String tempDirectory = myArgsEngine.getString("-i");
if (tempDirectory != null) {
File qseqDirectory = new File(tempDirectory);
if (!qseqDirectory.isDirectory()) {
printUsage();
throw new IllegalArgumentException("setParameters: The input name you supplied is not a directory: " + tempDirectory);
}
myQseqFileS = DirectoryCrawler.listFileNames(".*_qseq\\.txt$|.*_qseq\\.txt\\.gz$", qseqDirectory.getAbsolutePath());
if (myQseqFileS.length == 0 || myQseqFileS == null) {
printUsage();
throw new IllegalArgumentException("Couldn't find any files that end with \"_qseq.txt\" or \"_qseq.txt.gz\" in the supplied directory: " + tempDirectory);
} else {
myLogger.info("QseqToTBTPlugin: setParameters: Using the following .qseq files:");
for (String filename : myQseqFileS) {
myLogger.info(filename);
}
}
}
if (myArgsEngine.getBoolean("-k")) {
myKeyFile = myArgsEngine.getString("-k");
} else {
printUsage();
throw new IllegalArgumentException("Please specify a key file (option -k).");
}
if (myArgsEngine.getBoolean("-e")) {
myEnzyme = myArgsEngine.getString("-e");
} else {
System.out.println("No enzyme specified. Using enzyme listed in key file.");
}
if (myArgsEngine.getBoolean("-o")) {
myOutputDir = myArgsEngine.getString("-o");
File outDirectory = new File(myOutputDir);
if (!outDirectory.isDirectory()) {
printUsage();
throw new IllegalArgumentException("The output name you supplied (option -o) is not a directory: " + myOutputDir);
}
outDirectory = null;
} else {
printUsage();
throw new IllegalArgumentException("Please specify an output directory (option -o).");
}
if (myArgsEngine.getBoolean("-c")) {
myMinCount = Integer.parseInt(myArgsEngine.getString("-c"));
} else {
myMinCount = 1;
}
if (myArgsEngine.getBoolean("-y")) {
useTBTByte = true;
}
// Create Tags object from tag count file with option -t, or from TOPM file with option -m
if (myArgsEngine.getBoolean("-t")) {
if (myArgsEngine.getBoolean("-m")) {
printUsage();
throw new IllegalArgumentException("Options -t and -m are mutually exclusive.");
}
myMasterTags = new TagCounts(myArgsEngine.getString("-t"), FilePacking.Bit);
} else if (myArgsEngine.getBoolean("-m")) {
if (myArgsEngine.getBoolean("-t")) {
printUsage();
throw new IllegalArgumentException("Options -t and -m are mutually exclusive.");
}
myMasterTags = new TagsOnPhysicalMap(myArgsEngine.getString("-m"), true);
} else {
printUsage();
throw new IllegalArgumentException("Please specify a tagCounts file (-t) *OR* a TagsOnPhysicalMap file (-m)");
}
}
/**
* Uses an existing Tags object to create one TagsByTaxa file for each qseq file in the input directory.
*
* Output TBT files written to the outputDir, using qseq file names with extension changed to .tbt.bin (or .tbt.txt)
*
* @param qseqFileS Array of qseq file names (Illumina-created files with raw read sequence, quality score, machine name, etc.)
* @param keyFileS A key file (list of taxa by barcode, lane & flow cell, including plate maps)
* @param enzyme The enzyme used to make the library (currently ApeKI or PstI)
* @param theMasterTags A Tags object: list of tags to be included in the final TBT
* @param outputDir String containing the path of the output directory to contain tags-by-taxa files
* @param minCount The minimum number of times a tag must show up in a qseq file before it is included in the corresponding TBT file
*/
public static void matchTagsToTaxa(String[] qseqFileS, String keyFileS, String enzyme, Tags theMasterTags, String outputDir, int minCount, boolean useTBTByte) {
for (int laneNum = 0; laneNum < qseqFileS.length; laneNum++) {
System.out.println("\nWorking on qseq file: " + qseqFileS[laneNum]);
TagsByTaxa theTBT = null;
System.gc();
File outfile;
FilePacking outFormat = useTBTByte ? FilePacking.Byte : FilePacking.Bit;
String outFileS = outputDir + qseqFileS[laneNum].substring(qseqFileS[laneNum].lastIndexOf(File.separator));
String replaceS = (outFormat == FilePacking.Text) ? ".tbt.txt" : ((outFormat == FilePacking.Byte) ? ".tbt.byte" : ".tbt.bin");
outfile = new File(outFileS.replaceAll("_qseq\\.txt$|_qseq\\.txt\\.gz$", replaceS));
//Skip input file if a corresponding output file has already been written.
if (outfile.isFile()) {
System.out.println(
"An output file " + outfile.getName() + "\n"
+ " already exists in the output directory for file " + qseqFileS[laneNum] + ". Skipping.");
continue;
}
int goodBarcodedReads = 0, allReads = 0, goodMatched = 0;
File qseqFile = new File(qseqFileS[laneNum]);
String[] np = qseqFile.getName().split("_");
//Create a new object to hold barcoded tags. The constructor can optionally process a group of fastq
//files. A minimum quality score for inclusion of a read can also be provided.
ParseBarcodeRead thePBR;
if (np.length == 3) {
thePBR = new ParseBarcodeRead(keyFileS, enzyme, np[0], np[1]);
} else if (np.length == 4) {
thePBR = new ParseBarcodeRead(keyFileS, enzyme, np[0], np[2]);
} else if (np.length == 5) {
thePBR = new ParseBarcodeRead(keyFileS, enzyme, np[1], np[3]);
} else {
System.out.println("Error in parsing file name:");
System.out.println(" The filename does not contain either 3 or 5 underscore-delimited values.");
System.out.println(" Expect: flowcell_lane_qseq.txt OR code_flowcell_s_lane_qseq.txt");
System.out.println(" Filename: " + qseqFileS[laneNum]);
return;
}
System.out.println("Total barcodes found in lane:" + thePBR.getBarCodeCount());
if (thePBR.getBarCodeCount() == 0) {
System.out.println("No barcodes found. Skipping this flowcell lane.");
continue;
}
//Fill an array with taxon names.
String[] taxaNames = new String[thePBR.getBarCodeCount()];
for (int i = 0; i < taxaNames.length; i++) {
taxaNames[i] = thePBR.getTheBarcodes(i).getTaxaName();
}
if (useTBTByte) {
theTBT = new TagsByTaxaByte(taxaNames, theMasterTags);
} else {
theTBT = new TagsByTaxaBit(taxaNames, theMasterTags);
}
// Read the qseq file and assign reads to tags and taxa
String temp = "";
goodBarcodedReads = 0;
allReads = 0;
goodMatched = 0;
try {
BufferedReader br;
//Read in qseq file as a gzipped text stream if its name ends in ".gz", otherwise read as text
if (qseqFileS[laneNum].endsWith(".gz")) {
br = new BufferedReader(new InputStreamReader(new MultiMemberGZIPInputStream(new FileInputStream(qseqFileS[laneNum]))));
} else {
br = new BufferedReader(new FileReader(qseqFileS[laneNum]), 65536);
}
String sl, qualS = "";
while ((temp = br.readLine()) != null) {
String[] jj = temp.split("\\s");
allReads++;
if (allReads % 1000000 == 0) {
System.out.println("Total Reads:" + allReads + " goodReads:" + goodBarcodedReads + " goodMatched:" + goodMatched);
}
sl = jj[8];
qualS = jj[9];
ReadBarcodeResult rr = thePBR.parseReadIntoTagAndTaxa(sl, qualS, false, 0);
if (rr != null) {
goodBarcodedReads++;
int t = theTBT.getIndexOfTaxaName(rr.getTaxonName());
int h = theTBT.getTagIndex(rr.getRead());
if (h > -1) {
theTBT.addReadsToTagTaxon(h, t, 1);
goodMatched++;
}
}
}
br.close();
} catch (Exception e) {
System.out.println("Catch testBasicPipeline c=" + goodBarcodedReads + " e=" + e);
System.out.println(temp);
e.printStackTrace();
}
System.out.println("Timing process (writing TagsByTaxa file)...");
long timePoint1 = System.currentTimeMillis();
theTBT.writeDistFile(outfile, outFormat, minCount);
System.out.println("...process (writing TagsByTaxa file) took " + (System.currentTimeMillis() - timePoint1) + " milliseconds.");
System.out.println("Total number of reads in lane=" + allReads);
System.out.println("Total number of good, barcoded reads=" + goodBarcodedReads);
int filesDone = laneNum + 1;
System.out.println("Finished reading " + filesDone + " of " + qseqFileS.length + " sequence files: " + qseqFileS[laneNum] + "\n");
}
}
@Override
public ImageIcon getIcon() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public String getButtonName() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public String getToolTipText() {
throw new UnsupportedOperationException("Not supported yet.");
}
} |
package org.coffeeshop.swing;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.MouseInfo;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.util.Collection;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.InputMap;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import org.coffeeshop.awt.StackLayout;
import org.coffeeshop.awt.StackLayout.Orientation;
import org.coffeeshop.swing.ImagePanel;
public class Splash {
private Window window;
private Object result = null;
private class Window extends JDialog {
public static final long serialVersionUID = 1;
private Action exit = new AbstractAction("Exit") {
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent arg0) {
closeWithResult(null);
}
};
public Window(Image splashImage, boolean horizontal) {
super();
setUndecorated(true);
setResizable(false);
JPanel root = new JPanel(new BorderLayout());
root.add(new ImagePanel(splashImage), BorderLayout.CENTER);
JPanel sidebar = new JPanel(new BorderLayout());
JComponent sidebarComponent = createSidebarComponent();
/*if (orientation == Orientation.VERTICAL) {
//sidebar.setPreferredSize(new Dimension(400, splashImage.getHeight(null)));
} else {
sidebar.setPreferredSize(new Dimension(splashImage.getWidth(null), 200));
}*/
JPanel buttons = new JPanel(new StackLayout(horizontal ?
Orientation.VERTICAL : Orientation.HORIZONTAL, 5, 5, horizontal));
Color background = getBackground();
if (System.getProperty("splash.background") != null) {
background = Color.decode(System.getProperty("splash.background"));
}
sidebar.setBackground(background);
if (sidebarComponent != null) {
sidebarComponent.setBackground(background);
sidebar.add(sidebarComponent, BorderLayout.CENTER);
}
buttons.setBackground(background);
Collection<Action> actions = createActions();
if (actions != null && actions.size() > 0) {
for (Action action : actions) {
buttons.add(new JButton(action));
}
buttons.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
sidebar.add(buttons, BorderLayout.SOUTH);
}
root.add(sidebar, horizontal ? BorderLayout.EAST : BorderLayout.SOUTH);
setContentPane(root);
if (!horizontal) {
setMinimumSize(new Dimension(-1, splashImage.getHeight(null)));
} else {
setMinimumSize(new Dimension(splashImage.getWidth(null), -1));
}
pack();
Dimension w = getSize();
Rectangle r = MouseInfo.getPointerInfo().getDevice().getDefaultConfiguration().getBounds();
setLocation(r.x + (r.width - w.width) / 2, r.y + (r.height - w.height) / 2);
getRootPane().getActionMap().put("exit", exit);
InputMap im = getRootPane().getInputMap(
JComponent.WHEN_IN_FOCUSED_WINDOW);
im.put(KeyStroke.getKeyStroke(
KeyEvent.VK_ESCAPE, 0), "exit");
}
}
private Image image;
private String title;
private Window createWindow() {
if (window != null)
return window;
window = new Window(image, image.getWidth(null) < image.getHeight(null));
window.setTitle(title);
Image icon = ImageStore.getImage("icon.png", "icon-16.png", "icon-32.png", "icon-46.png");
if (icon != null)
window.setIconImage(icon);
return window;
}
public Splash(String title, Image image) {
this.title = title;
this.image = image;
}
public final synchronized Object block() {
createWindow();
if (window.isVisible())
return null;
window.setVisible(true);
synchronized (window) {
try {
window.wait();
} catch (InterruptedException e) {
window.setVisible(false);
return null;
}
}
return result;
}
public final synchronized void show() {
createWindow();
if (window.isVisible())
return;
window.setVisible(true);
}
public final synchronized void hide() {
createWindow();
if (!window.isVisible())
return;
window.setVisible(false);
}
protected final void closeWithResult(Object result) {
this.result = result;
window.setVisible(false);
synchronized (window) {
window.notifyAll();
}
}
protected final void close() {
window.setVisible(false);
synchronized (window) {
window.notifyAll();
}
}
protected JComponent createSidebarComponent() {
return null;
}
protected Collection<Action> createActions() {
return null;
}
} |
package gcm2sbml.parser;
import gcm2sbml.util.GlobalConstants;
import gcm2sbml.util.Utility;
import java.awt.AWTError;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Properties;
import java.util.Set;
import java.util.prefs.Preferences;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import org.sbml.libsbml.ASTNode;
import org.sbml.libsbml.Constraint;
import org.sbml.libsbml.EventAssignment;
import org.sbml.libsbml.FunctionDefinition;
import org.sbml.libsbml.InitialAssignment;
import org.sbml.libsbml.Model;
import org.sbml.libsbml.ModifierSpeciesReference;
import org.sbml.libsbml.Rule;
import org.sbml.libsbml.SBMLDocument;
import org.sbml.libsbml.Species;
import org.sbml.libsbml.SpeciesReference;
import org.sbml.libsbml.UnitDefinition;
import org.sbml.libsbml.libsbml;
import com.mxgraph.layout.mxCircleLayout;
import com.mxgraph.layout.mxCompactTreeLayout;
import com.mxgraph.layout.mxIGraphLayout;
import com.mxgraph.view.mxEdgeStyle;
import com.mxgraph.view.mxGraph;
import com.mxgraph.view.mxLayoutManager;
import lhpn2sbml.parser.ExprTree;
import lhpn2sbml.parser.LhpnFile;
import biomodelsim.BioSim;
import biomodelsim.Log;
import buttons.Buttons;
/**
* This class describes a GCM file
*
* @author Nam Nguyen
* @organization University of Utah
* @email namphuon@cs.utah.edu
*/
public class GCMFile {
private String separator;
private String filename;
public GCMFile(String path) {
if (File.separator.equals("\\")) {
separator = "\\\\";
}
else {
separator = File.separator;
}
this.path = path;
species = new HashMap<String, Properties>();
influences = new HashMap<String, Properties>();
promoters = new HashMap<String, Properties>();
components = new HashMap<String, Properties>();
conditions = new ArrayList<String>();
globalParameters = new HashMap<String, String>();
parameters = new HashMap<String, String>();
loadDefaultParameters();
}
public String getSBMLFile() {
return sbmlFile;
}
public void setSBMLFile(String file) {
sbmlFile = file;
}
public boolean getDimAbs() {
return dimAbs;
}
public void setDimAbs(boolean dimAbs) {
this.dimAbs = dimAbs;
}
public boolean getBioAbs() {
return bioAbs;
}
public void setBioAbs(boolean bioAbs) {
this.bioAbs = bioAbs;
}
public void createLogicalModel(final String filename, final Log log, final BioSim biosim,
final String lpnName) {
try {
new File(filename + ".temp").createNewFile();
}
catch (IOException e2) {
}
final JFrame naryFrame = new JFrame("Thresholds");
WindowListener w = new WindowListener() {
public void windowClosing(WindowEvent arg0) {
naryFrame.dispose();
}
public void windowOpened(WindowEvent arg0) {
}
public void windowClosed(WindowEvent arg0) {
}
public void windowIconified(WindowEvent arg0) {
}
public void windowDeiconified(WindowEvent arg0) {
}
public void windowActivated(WindowEvent arg0) {
}
public void windowDeactivated(WindowEvent arg0) {
}
};
naryFrame.addWindowListener(w);
JTabbedPane naryTabs = new JTabbedPane();
ArrayList<JPanel> specProps = new ArrayList<JPanel>();
final ArrayList<JTextField> texts = new ArrayList<JTextField>();
final ArrayList<JList> consLevel = new ArrayList<JList>();
final ArrayList<Object[]> conLevel = new ArrayList<Object[]>();
final ArrayList<String> specs = new ArrayList<String>();
for (String spec : species.keySet()) {
specs.add(spec);
JPanel newPanel1 = new JPanel(new GridLayout(1, 2));
JPanel newPanel2 = new JPanel(new GridLayout(1, 2));
JPanel otherLabel = new JPanel();
otherLabel.add(new JLabel(spec + " Amount:"));
newPanel2.add(otherLabel);
consLevel.add(new JList());
conLevel.add(new Object[0]);
consLevel.get(consLevel.size() - 1).setListData(new Object[0]);
conLevel.set(conLevel.size() - 1, new Object[0]);
JScrollPane scroll = new JScrollPane();
scroll.setPreferredSize(new Dimension(260, 100));
scroll.setViewportView(consLevel.get(consLevel.size() - 1));
JPanel area = new JPanel();
area.add(scroll);
newPanel2.add(area);
JPanel addAndRemove = new JPanel();
JTextField adding = new JTextField(15);
texts.add(adding);
JButton Add = new JButton("Add");
JButton Remove = new JButton("Remove");
Add.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int number = Integer.parseInt(e.getActionCommand().substring(3,
e.getActionCommand().length()));
try {
int get = Integer.parseInt(texts.get(number).getText().trim());
if (get <= 0) {
JOptionPane.showMessageDialog(naryFrame,
"Amounts Must Be Positive Integers.", "Error",
JOptionPane.ERROR_MESSAGE);
}
else {
JList add = new JList();
Object[] adding = { "" + get };
add.setListData(adding);
add.setSelectedIndex(0);
Object[] sort = Buttons.add(conLevel.get(number),
consLevel.get(number), add, false, null, null, null, null,
null, null, naryFrame);
int in;
for (int out = 1; out < sort.length; out++) {
int temp = Integer.parseInt((String) sort[out]);
in = out;
while (in > 0 && Integer.parseInt((String) sort[in - 1]) >= temp) {
sort[in] = sort[in - 1];
--in;
}
sort[in] = temp + "";
}
conLevel.set(number, sort);
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(naryFrame,
"Amounts Must Be Positive Integers.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
});
Add.setActionCommand("Add" + (consLevel.size() - 1));
Remove.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int number = Integer.parseInt(e.getActionCommand().substring(6,
e.getActionCommand().length()));
conLevel.set(number, Buttons
.remove(consLevel.get(number), conLevel.get(number)));
}
});
Remove.setActionCommand("Remove" + (consLevel.size() - 1));
addAndRemove.add(adding);
addAndRemove.add(Add);
addAndRemove.add(Remove);
JPanel newnewPanel = new JPanel(new BorderLayout());
newnewPanel.add(newPanel1, "North");
newnewPanel.add(newPanel2, "Center");
newnewPanel.add(addAndRemove, "South");
specProps.add(newnewPanel);
naryTabs.addTab(spec + " Properties", specProps.get(specProps.size() - 1));
}
JButton naryRun = new JButton("Create");
JButton naryClose = new JButton("Cancel");
naryRun.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
flattenGCM(false);
convertToLHPN(specs, conLevel).save(filename);
log.addText("Saving GCM file as LPN:\n" + path + separator + lpnName + "\n");
biosim.refreshTree();
naryFrame.dispose();
new File(filename + ".temp").delete();
}
});
naryClose.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
naryFrame.dispose();
new File(filename + ".temp").delete();
}
});
JPanel naryRunPanel = new JPanel();
naryRunPanel.add(naryRun);
naryRunPanel.add(naryClose);
JPanel naryPanel = new JPanel(new BorderLayout());
naryPanel.add(naryTabs, "Center");
naryPanel.add(naryRunPanel, "South");
naryFrame.setContentPane(naryPanel);
naryFrame.pack();
Dimension screenSize;
try {
Toolkit tk = Toolkit.getDefaultToolkit();
screenSize = tk.getScreenSize();
}
catch (AWTError awe) {
screenSize = new Dimension(640, 480);
}
Dimension frameSize = naryFrame.getSize();
if (frameSize.height > screenSize.height) {
frameSize.height = screenSize.height;
}
if (frameSize.width > screenSize.width) {
frameSize.width = screenSize.width;
}
int x = screenSize.width / 2 - frameSize.width / 2;
int y = screenSize.height / 2 - frameSize.height / 2;
naryFrame.setLocation(x, y);
naryFrame.setResizable(false);
naryFrame.setVisible(true);
}
public SBMLDocument flattenGCM(boolean includeSBML) {
save(filename + ".temp");
ArrayList<String> comps = setToArrayList(components.keySet());
SBMLDocument sbml = new SBMLDocument(BioSim.SBML_LEVEL, BioSim.SBML_VERSION);
Model m = sbml.createModel();
sbml.setModel(m);
Utility.addCompartments(sbml, "default");
sbml.getModel().getCompartment("default").setSize(1);
if (!sbmlFile.equals("") && includeSBML) {
sbml = BioSim.readSBML(path + separator + sbmlFile);
}
else if (!sbmlFile.equals("") && !includeSBML) {
Utility.createErrorMessage("SBMLs Included",
"There are sbml files associated with the gcm file and its components.");
load(filename + ".temp");
return null;
}
for (String s : comps) {
GCMFile file = new GCMFile(path);
file.load(path + separator + components.get(s).getProperty("gcm"));
for (String p : globalParameters.keySet()) {
if (!file.globalParameters.containsKey(p)) {
file.setParameter(p, globalParameters.get(p));
}
}
sbml = unionSBML(sbml, unionGCM(this, file, s, includeSBML), s);
if (sbml == null && includeSBML) {
Utility.createErrorMessage("Cannot Merge SBMLs", "Unable to merge sbml files from components.");
load(filename + ".temp");
return null;
}
else if (sbml == null && !includeSBML) {
Utility.createErrorMessage("SBMLs Included",
"There are sbml files associated with the gcm file and its components.");
load(filename + ".temp");
return null;
}
}
components = new HashMap<String, Properties>();
if (sbml != null) {
long numErrors = sbml.checkConsistency();
if (numErrors > 0) {
Utility.createErrorMessage("Merged SBMLs Are Inconsistent", "The merged sbml files have inconsistencies.");
}
}
return sbml;
}
private SBMLDocument unionGCM(GCMFile topLevel, GCMFile bottomLevel, String compName, boolean includeSBML) {
ArrayList<String> mod = setToArrayList(bottomLevel.components.keySet());
SBMLDocument sbml = new SBMLDocument(BioSim.SBML_LEVEL, BioSim.SBML_VERSION);
Model m = sbml.createModel();
sbml.setModel(m);
if (!bottomLevel.sbmlFile.equals("") && includeSBML) {
sbml = BioSim.readSBML(path + separator + bottomLevel.sbmlFile);
}
else if (!bottomLevel.sbmlFile.equals("") && !includeSBML) {
return null;
}
for (String s : mod) {
GCMFile file = new GCMFile(path);
file.load(path + separator + bottomLevel.components.get(s).getProperty("gcm"));
for (String p : bottomLevel.globalParameters.keySet()) {
if (!file.globalParameters.containsKey(p)) {
file.setParameter(p, bottomLevel.globalParameters.get(p));
}
}
sbml = unionSBML(sbml, unionGCM(bottomLevel, file, s, includeSBML), s);
if (sbml == null) {
return null;
}
}
mod = setToArrayList(bottomLevel.promoters.keySet());
for (String prom : mod) {
bottomLevel.promoters.get(prom).put(GlobalConstants.ID, compName + "_" + prom);
bottomLevel.changePromoterName(prom, compName + "_" + prom);
}
mod = setToArrayList(bottomLevel.species.keySet());
for (String spec : mod) {
bottomLevel.species.get(spec).put(GlobalConstants.ID, compName + "_" + spec);
bottomLevel.changeSpeciesName(spec, compName + "_" + spec);
}
mod = setToArrayList(bottomLevel.species.keySet());
for (String spec : mod) {
for (Object port : topLevel.components.get(compName).keySet()) {
if (spec.equals(compName + "_" + port)) {
bottomLevel.species.get(spec).put(GlobalConstants.ID,
topLevel.components.get(compName).getProperty((String) port));
bottomLevel.changeSpeciesName(spec, topLevel.components.get(compName).getProperty((String) port));
}
}
}
for (String param : bottomLevel.globalParameters.keySet()) {
if (param.equals(GlobalConstants.KDECAY_STRING)) {
mod = setToArrayList(bottomLevel.species.keySet());
for (String spec : mod) {
if (!bottomLevel.species.get(spec).containsKey(GlobalConstants.KDECAY_STRING)) {
bottomLevel.species.get(spec).put(GlobalConstants.KDECAY_STRING,
bottomLevel.globalParameters.get(GlobalConstants.KDECAY_STRING));
}
}
}
else if (param.equals(GlobalConstants.KASSOCIATION_STRING)) {
mod = setToArrayList(bottomLevel.influences.keySet());
for (String infl : mod) {
if (!bottomLevel.influences.get(infl).containsKey(GlobalConstants.KASSOCIATION_STRING)) {
bottomLevel.influences.get(infl).put(GlobalConstants.KASSOCIATION_STRING,
bottomLevel.globalParameters.get(GlobalConstants.KASSOCIATION_STRING));
}
}
}
else if (param.equals(GlobalConstants.KBIO_STRING)) {
mod = setToArrayList(bottomLevel.influences.keySet());
for (String infl : mod) {
if (!bottomLevel.influences.get(infl).containsKey(GlobalConstants.KBIO_STRING)) {
bottomLevel.influences.get(infl).put(GlobalConstants.KBIO_STRING,
bottomLevel.globalParameters.get(GlobalConstants.KBIO_STRING));
}
}
}
else if (param.equals(GlobalConstants.COOPERATIVITY_STRING)) {
mod = setToArrayList(bottomLevel.influences.keySet());
for (String infl : mod) {
if (!bottomLevel.influences.get(infl).containsKey(GlobalConstants.COOPERATIVITY_STRING)) {
bottomLevel.influences.get(infl).put(GlobalConstants.COOPERATIVITY_STRING,
bottomLevel.globalParameters.get(GlobalConstants.COOPERATIVITY_STRING));
}
}
}
else if (param.equals(GlobalConstants.KREP_STRING)) {
mod = setToArrayList(bottomLevel.influences.keySet());
for (String infl : mod) {
if (!bottomLevel.influences.get(infl).containsKey(GlobalConstants.KREP_STRING)) {
bottomLevel.influences.get(infl).put(GlobalConstants.KREP_STRING,
bottomLevel.globalParameters.get(GlobalConstants.KREP_STRING));
}
}
}
else if (param.equals(GlobalConstants.KACT_STRING)) {
mod = setToArrayList(bottomLevel.influences.keySet());
for (String infl : mod) {
if (!bottomLevel.influences.get(infl).containsKey(GlobalConstants.KACT_STRING)) {
bottomLevel.influences.get(infl).put(GlobalConstants.KACT_STRING,
bottomLevel.globalParameters.get(GlobalConstants.KACT_STRING));
}
}
}
else if (param.equals(GlobalConstants.RNAP_BINDING_STRING)) {
mod = setToArrayList(bottomLevel.promoters.keySet());
for (String prom : mod) {
if (!bottomLevel.promoters.get(prom).containsKey(GlobalConstants.RNAP_BINDING_STRING)) {
bottomLevel.promoters.get(prom).put(GlobalConstants.RNAP_BINDING_STRING,
bottomLevel.globalParameters.get(GlobalConstants.RNAP_BINDING_STRING));
}
}
}
else if (param.equals(GlobalConstants.OCR_STRING)) {
mod = setToArrayList(bottomLevel.promoters.keySet());
for (String prom : mod) {
if (!bottomLevel.promoters.get(prom).containsKey(GlobalConstants.OCR_STRING)) {
bottomLevel.promoters.get(prom).put(GlobalConstants.OCR_STRING,
bottomLevel.globalParameters.get(GlobalConstants.OCR_STRING));
}
}
}
else if (param.equals(GlobalConstants.KBASAL_STRING)) {
mod = setToArrayList(bottomLevel.promoters.keySet());
for (String prom : mod) {
if (!bottomLevel.promoters.get(prom).containsKey(GlobalConstants.KBASAL_STRING)) {
bottomLevel.promoters.get(prom).put(GlobalConstants.KBASAL_STRING,
bottomLevel.globalParameters.get(GlobalConstants.KBASAL_STRING));
}
}
}
else if (param.equals(GlobalConstants.PROMOTER_COUNT_STRING)) {
mod = setToArrayList(bottomLevel.promoters.keySet());
for (String prom : mod) {
if (!bottomLevel.promoters.get(prom).containsKey(GlobalConstants.PROMOTER_COUNT_STRING)) {
bottomLevel.promoters.get(prom).put(GlobalConstants.PROMOTER_COUNT_STRING,
bottomLevel.globalParameters.get(GlobalConstants.PROMOTER_COUNT_STRING));
}
}
}
else if (param.equals(GlobalConstants.STOICHIOMETRY_STRING)) {
mod = setToArrayList(bottomLevel.promoters.keySet());
for (String prom : mod) {
if (!bottomLevel.promoters.get(prom).containsKey(GlobalConstants.STOICHIOMETRY_STRING)) {
bottomLevel.promoters.get(prom).put(GlobalConstants.STOICHIOMETRY_STRING,
bottomLevel.globalParameters.get(GlobalConstants.STOICHIOMETRY_STRING));
}
}
}
else if (param.equals(GlobalConstants.ACTIVED_STRING)) {
mod = setToArrayList(bottomLevel.promoters.keySet());
for (String prom : mod) {
if (!bottomLevel.promoters.get(prom).containsKey(GlobalConstants.ACTIVED_STRING)) {
bottomLevel.promoters.get(prom).put(GlobalConstants.ACTIVED_STRING,
bottomLevel.globalParameters.get(GlobalConstants.ACTIVED_STRING));
}
}
}
else if (param.equals(GlobalConstants.MAX_DIMER_STRING)) {
mod = setToArrayList(bottomLevel.species.keySet());
for (String spec : mod) {
if (!bottomLevel.species.get(spec).containsKey(GlobalConstants.MAX_DIMER_STRING)) {
bottomLevel.species.get(spec).put(GlobalConstants.MAX_DIMER_STRING,
bottomLevel.globalParameters.get(GlobalConstants.MAX_DIMER_STRING));
}
}
}
else if (param.equals(GlobalConstants.INITIAL_STRING)) {
mod = setToArrayList(bottomLevel.species.keySet());
for (String spec : mod) {
if (!bottomLevel.species.get(spec).containsKey(GlobalConstants.INITIAL_STRING)) {
bottomLevel.species.get(spec).put(GlobalConstants.INITIAL_STRING,
bottomLevel.globalParameters.get(GlobalConstants.INITIAL_STRING));
}
}
}
}
for (String prom : bottomLevel.promoters.keySet()) {
topLevel.addPromoter(prom, bottomLevel.promoters.get(prom));
}
for (String spec : bottomLevel.species.keySet()) {
if (!topLevel.species.keySet().contains(spec)) {
topLevel.addSpecies(spec, bottomLevel.species.get(spec));
}
}
for (String infl : bottomLevel.influences.keySet()) {
topLevel.addInfluences(infl, bottomLevel.influences.get(infl));
}
for (String cond : bottomLevel.conditions) {
topLevel.addCondition(cond);
}
return sbml;
}
public LhpnFile convertToLHPN(ArrayList<String> specs, ArrayList<Object[]> conLevel) {
HashMap<String, ArrayList<String>> infl = new HashMap<String, ArrayList<String>>();
for (String influence : influences.keySet()) {
if (influences.get(influence).get(GlobalConstants.TYPE).equals(GlobalConstants.ACTIVATION)) {
String input = getInput(influence);
String output = getOutput(influence);
if (influences.get(influence).containsKey(GlobalConstants.BIO)
&& influences.get(influence).get(GlobalConstants.BIO).equals("yes")) {
if (infl.containsKey(output)) {
infl.get(output).add("bioAct:" + input + ":" + influence);
}
else {
ArrayList<String> out = new ArrayList<String>();
out.add("bioAct:" + input + ":" + influence);
infl.put(output, out);
}
}
else {
if (infl.containsKey(output)) {
infl.get(output).add("act:" + input + ":" + influence);
}
else {
ArrayList<String> out = new ArrayList<String>();
out.add("act:" + input + ":" + influence);
infl.put(output, out);
}
}
}
else if (influences.get(influence).get(GlobalConstants.TYPE).equals(GlobalConstants.REPRESSION)) {
String input = getInput(influence);
String output = getOutput(influence);
if (influences.get(influence).containsKey(GlobalConstants.BIO)
&& influences.get(influence).get(GlobalConstants.BIO).equals("yes")) {
if (infl.containsKey(output)) {
infl.get(output).add("bioRep:" + input + ":" + influence);
}
else {
ArrayList<String> out = new ArrayList<String>();
out.add("bioRep:" + input + ":" + influence);
infl.put(output, out);
}
}
else {
if (infl.containsKey(output)) {
infl.get(output).add("rep:" + input + ":" + influence);
}
else {
ArrayList<String> out = new ArrayList<String>();
out.add("rep:" + input + ":" + influence);
infl.put(output, out);
}
}
}
}
LhpnFile LHPN = new LhpnFile();
for (int i = 0; i < specs.size(); i++) {
LHPN.addInteger(specs.get(i), "0");
}
for (int i = 0; i < specs.size(); i++) {
int placeNum = 0;
int transNum = 0;
String previousPlaceName = specs.get(i) + placeNum;
placeNum++;
LHPN.addPlace(previousPlaceName, true);
String number = "0";
for (Object threshold : conLevel.get(i)) {
LHPN.addPlace(specs.get(i) + placeNum, false);
LHPN.addTransition(specs.get(i) + "_trans" + transNum);
LHPN.addMovement(previousPlaceName, specs.get(i) + "_trans" + transNum);
LHPN.addMovement(specs.get(i) + "_trans" + transNum, specs.get(i) + placeNum);
LHPN.addIntAssign(specs.get(i) + "_trans" + transNum, specs.get(i), (String) threshold);
ArrayList<String> activators = new ArrayList<String>();
ArrayList<String> repressors = new ArrayList<String>();
ArrayList<String> bioActivators = new ArrayList<String>();
ArrayList<String> bioRepressors = new ArrayList<String>();
ArrayList<String> proms = new ArrayList<String>();
Double global_np = Double.parseDouble(parameters.get(GlobalConstants.STOICHIOMETRY_STRING));
Double global_ng = Double.parseDouble(parameters.get(GlobalConstants.PROMOTER_COUNT_STRING));
Double global_kb = Double.parseDouble(parameters.get(GlobalConstants.KBASAL_STRING));
Double global_Kb = Double.parseDouble(parameters.get(GlobalConstants.KBIO_STRING));
Double global_Ko = Double.parseDouble(parameters.get(GlobalConstants.RNAP_BINDING_STRING));
Double global_ka = Double.parseDouble(parameters.get(GlobalConstants.ACTIVED_STRING));
Double global_Ka = Double.parseDouble(parameters.get(GlobalConstants.KACT_STRING));
Double global_ko = Double.parseDouble(parameters.get(GlobalConstants.OCR_STRING));
Double global_Kr = Double.parseDouble(parameters.get(GlobalConstants.KREP_STRING));
Double global_kd = Double.parseDouble(parameters.get(GlobalConstants.KDECAY_STRING));
Double global_nc = Double.parseDouble(parameters.get(GlobalConstants.COOPERATIVITY_STRING));
Double RNAP = Double.parseDouble(parameters.get(GlobalConstants.RNAP_STRING));
Double np = global_np;
Double ng = global_ng;
Double kb = global_kb;
Double Kb = global_Kb;
Double Ko = global_Ko;
Double ka = global_ka;
Double Ka = global_Ka;
Double ko = global_ko;
Double Kr = global_Kr;
Double kd = global_kd;
Double nc = global_nc;
if (infl.containsKey(specs.get(i))) {
for (String in : infl.get(specs.get(i))) {
String[] parse = in.split(":");
String species = parse[1];
String influence = parse[2];
String promoter = influence.split(" ")[influence.split(" ").length - 1];
if (!proms.contains(promoter)) {
proms.add(promoter);
}
if (parse[0].equals("act")) {
activators.add(promoter + ":" + species + ":" + influence);
}
else if (parse[0].equals("rep")) {
repressors.add(promoter + ":" + species + ":" + influence);
}
else if (parse[0].equals("bioAct")) {
bioActivators.add(promoter + ":" + species + ":" + influence);
}
else if (parse[0].equals("bioRep")) {
bioRepressors.add(promoter + ":" + species + ":" + influence);
}
}
}
String rate = "";
for (String promoter : proms) {
ng = global_ng;
Ko = global_Ko;
ko = global_ko;
np = global_np;
kb = global_kb;
ka = global_ka;
if (promoters.containsKey(promoter)) {
Properties p = promoters.get(promoter);
if (p.containsKey(GlobalConstants.PROMOTER_COUNT_STRING)) {
ng = Double.parseDouble((String) p.get(GlobalConstants.PROMOTER_COUNT_STRING));
}
if (p.containsKey(GlobalConstants.RNAP_BINDING_STRING)) {
Ko = Double.parseDouble((String) p.get(GlobalConstants.RNAP_BINDING_STRING));
}
if (p.containsKey(GlobalConstants.OCR_STRING)) {
ko = Double.parseDouble((String) p.get(GlobalConstants.OCR_STRING));
}
if (p.containsKey(GlobalConstants.STOICHIOMETRY_STRING)) {
np = Double.parseDouble((String) p.get(GlobalConstants.STOICHIOMETRY_STRING));
}
if (p.containsKey(GlobalConstants.KBASAL_STRING)) {
kb = Double.parseDouble((String) p.get(GlobalConstants.KBASAL_STRING));
}
if (p.containsKey(GlobalConstants.ACTIVED_STRING)) {
ka = Double.parseDouble((String) p.get(GlobalConstants.ACTIVED_STRING));
}
}
String addBio = "";
String influence = "";
for (String bioAct : bioActivators) {
String split[] = bioAct.split(":");
if (split[0].equals(promoter)) {
influence = split[2];
Properties p = influences.get(influence);
Kb = global_Kb;
if (p.containsKey(GlobalConstants.KBIO_STRING)) {
Kb = Double.parseDouble((String) p.get(GlobalConstants.KBIO_STRING));
}
if (addBio.equals("")) {
addBio = Kb + "*" + split[1];
}
else {
addBio += "*" + split[1];
}
}
}
if (!addBio.equals("")) {
activators.add(promoter + ":" + addBio + ":" + influence);
}
addBio = "";
influence = "";
for (String bioRep : bioRepressors) {
String split[] = bioRep.split(":");
if (split[0].equals(promoter)) {
influence = split[2];
Properties p = influences.get(influence);
Kb = global_Kb;
if (p.containsKey(GlobalConstants.KBIO_STRING)) {
Kb = Double.parseDouble((String) p.get(GlobalConstants.KBIO_STRING));
}
if (addBio.equals("")) {
addBio = Kb + "*" + split[1];
}
else {
addBio += "*" + split[1];
}
}
}
if (!addBio.equals("")) {
repressors.add(promoter + ":" + addBio + ":" + influence);
}
String promRate = "";
ArrayList<String> promActivators = new ArrayList<String>();
ArrayList<String> promRepressors = new ArrayList<String>();
for (String act : activators) {
String split[] = act.split(":");
if (split[0].equals(promoter)) {
promActivators.add(split[1] + ":" + split[2]);
}
}
for (String rep : repressors) {
String split[] = rep.split(":");
if (split[0].equals(promoter)) {
promRepressors.add(split[1] + ":" + split[2]);
}
}
if (promActivators.size() != 0) {
promRate += "(" + np + "*" + ng + ")*((" + kb + "*" + Ko + "*" + RNAP + ")";
for (String act : promActivators) {
String split[] = act.split(":");
Properties p = influences.get(split[1]);
nc = global_nc;
Kr = global_Kr;
Ka = global_Ka;
if (p.containsKey(GlobalConstants.COOPERATIVITY_STRING)) {
nc = Double.parseDouble((String) p.get(GlobalConstants.COOPERATIVITY_STRING));
}
if (p.containsKey(GlobalConstants.KREP_STRING)) {
Kr = Double.parseDouble((String) p.get(GlobalConstants.KREP_STRING));
}
if (p.containsKey(GlobalConstants.KACT_STRING)) {
Ka = Double.parseDouble((String) p.get(GlobalConstants.KACT_STRING));
}
promRate += "+(" + ka + "*((" + Ka + "*" + RNAP + "*" + split[0] + ")^" + nc + "))";
}
promRate += ")/((1+(" + Ko + "*" + RNAP + "))";
for (String act : promActivators) {
String split[] = act.split(":");
Properties p = influences.get(split[1]);
nc = global_nc;
Kr = global_Kr;
Ka = global_Ka;
if (p.containsKey(GlobalConstants.COOPERATIVITY_STRING)) {
nc = Double.parseDouble((String) p.get(GlobalConstants.COOPERATIVITY_STRING));
}
if (p.containsKey(GlobalConstants.KREP_STRING)) {
Kr = Double.parseDouble((String) p.get(GlobalConstants.KREP_STRING));
}
if (p.containsKey(GlobalConstants.KACT_STRING)) {
Ka = Double.parseDouble((String) p.get(GlobalConstants.KACT_STRING));
}
promRate += "+((" + Ka + "*" + RNAP + "*" + split[0] + ")^" + nc + ")";
}
if (promRepressors.size() != 0) {
for (String rep : promRepressors) {
String split[] = rep.split(":");
Properties p = influences.get(split[1]);
nc = global_nc;
Kr = global_Kr;
Ka = global_Ka;
if (p.containsKey(GlobalConstants.COOPERATIVITY_STRING)) {
nc = Double.parseDouble((String) p.get(GlobalConstants.COOPERATIVITY_STRING));
}
if (p.containsKey(GlobalConstants.KREP_STRING)) {
Kr = Double.parseDouble((String) p.get(GlobalConstants.KREP_STRING));
}
if (p.containsKey(GlobalConstants.KACT_STRING)) {
Ka = Double.parseDouble((String) p.get(GlobalConstants.KACT_STRING));
}
promRate += "+((" + Kr + "*" + split[0] + ")^" + nc + ")";
}
}
promRate += ")";
}
else {
if (promRepressors.size() != 0) {
promRate += "(" + np + "*" + ko + "*" + ng + ")*((" + Ko + "*" + RNAP + "))/((1+(" + Ko
+ "*" + RNAP + "))";
for (String rep : promRepressors) {
String split[] = rep.split(":");
Properties p = influences.get(split[1]);
nc = global_nc;
Kr = global_Kr;
Ka = global_Ka;
if (p.containsKey(GlobalConstants.COOPERATIVITY_STRING)) {
nc = Double.parseDouble((String) p.get(GlobalConstants.COOPERATIVITY_STRING));
}
if (p.containsKey(GlobalConstants.KREP_STRING)) {
Kr = Double.parseDouble((String) p.get(GlobalConstants.KREP_STRING));
}
if (p.containsKey(GlobalConstants.KACT_STRING)) {
Ka = Double.parseDouble((String) p.get(GlobalConstants.KACT_STRING));
}
promRate += "+((" + Kr + "*" + split[0] + ")^" + nc + ")";
}
promRate += ")";
}
}
if (!promRate.equals("")) {
if (rate.equals("")) {
rate = "(" + promRate + ")";
}
else {
rate += "+(" + promRate + ")";
}
}
}
if (rate.equals("")) {
rate = "0.0";
}
LHPN.addTransitionRate(specs.get(i) + "_trans" + transNum, "(" + rate + ")/" + "(" + threshold + "-"
+ number + ")");
transNum++;
LHPN.addTransition(specs.get(i) + "_trans" + transNum);
LHPN.addMovement(specs.get(i) + placeNum, specs.get(i) + "_trans" + transNum);
LHPN.addMovement(specs.get(i) + "_trans" + transNum, previousPlaceName);
LHPN.addIntAssign(specs.get(i) + "_trans" + transNum, specs.get(i), number);
Properties p = this.species.get(specs.get(i));
kd = global_kd;
if (p.containsKey(GlobalConstants.KDECAY_STRING)) {
kd = Double.parseDouble((String) p.get(GlobalConstants.KDECAY_STRING));
}
LHPN.addTransitionRate(specs.get(i) + "_trans" + transNum, "(" + specs.get(i) + "*" + kd + ")/" + "("
+ threshold + "-" + number + ")");
transNum++;
previousPlaceName = specs.get(i) + placeNum;
placeNum++;
number = (String) threshold;
}
}
return LHPN;
}
/**
* Save the contents to a StringBuffer. Can later be written to a file or other stream.
* @return
*/
public StringBuffer saveToBuffer(Boolean includeGlobals){
StringBuffer buffer = new StringBuffer("digraph G {\n");
for (String s : species.keySet()) {
buffer.append(s + " [");
Properties prop = species.get(s);
for (Object propName : prop.keySet()) {
if ((propName.toString().equals(GlobalConstants.NAME))
|| (propName.toString().equals("label"))) {
buffer.append(checkCompabilitySave(propName.toString()) + "=" + "\""
+ prop.getProperty(propName.toString()).toString() + "\"" + ",");
}
else {
buffer.append(checkCompabilitySave(propName.toString()) + "=" + "\""
+ prop.getProperty(propName.toString()).toString() + "\"" + ",");
}
}
if (!prop.containsKey("shape")) {
buffer.append("shape=ellipse,");
}
if (!prop.containsKey("label")) {
buffer.append("label=\"" + s + "\"");
}
else {
buffer.deleteCharAt(buffer.lastIndexOf(","));
}
// buffer.deleteCharAt(buffer.length() - 1);
buffer.append("]\n");
}
for (String s : components.keySet()) {
buffer.append(s + " [");
Properties prop = components.get(s);
for (Object propName : prop.keySet()) {
if (propName.toString().equals("gcm")) {
buffer.append(checkCompabilitySave(propName.toString()) + "=\""
+ prop.getProperty(propName.toString()).toString() + "\"");
}
}
buffer.append("]\n");
}
for (String s : influences.keySet()) {
buffer.append(getInput(s) + " -> "// + getArrow(s) + " "
+ getOutput(s) + " [");
Properties prop = influences.get(s);
String promo = "default";
if (prop.containsKey(GlobalConstants.PROMOTER)) {
promo = prop.getProperty(GlobalConstants.PROMOTER);
}
prop.setProperty(GlobalConstants.NAME, "\"" + getInput(s) + " " + getArrow(s) + " "
+ getOutput(s) + ", Promoter " + promo + "\"");
for (Object propName : prop.keySet()) {
if (propName.toString().equals("label") &&
prop.getProperty(propName.toString()).toString().equals("")) {
buffer.append("label=\"\",");
}
else {
buffer.append(checkCompabilitySave(propName.toString()) + "="
+ prop.getProperty(propName.toString()).toString() + ",");
}
}
String type = "";
if (!prop.containsKey("arrowhead")) {
if (prop.getProperty(GlobalConstants.TYPE).equals(GlobalConstants.ACTIVATION)) {
type = "vee";
}
else if (prop.getProperty(GlobalConstants.TYPE).equals(
GlobalConstants.REPRESSION)) {
type = "tee";
}
else {
type = "dot";
}
buffer.append("arrowhead=" + type + "");
}
if (buffer.charAt(buffer.length() - 1) == ',') {
buffer.deleteCharAt(buffer.length() - 1);
}
buffer.append("]\n");
}
for (String s : components.keySet()) {
Properties prop = components.get(s);
for (Object propName : prop.keySet()) {
if (!propName.toString().equals("gcm")
&& !propName.toString().equals(GlobalConstants.ID)
&& prop.keySet().contains("type_" + propName)) {
if (prop.getProperty("type_" + propName).equals("Output")) {
buffer.append(s + " -> " + prop.getProperty(propName.toString()).toString()
+ " [port=" + propName.toString() + ", type=Output");
buffer.append(", arrowhead=normal]\n");
}
else {
buffer.append(prop.getProperty(propName.toString()).toString() + " -> " + s
+ " [port=" + propName.toString() + ", type=Input");
buffer.append(", arrowhead=normal]\n");
}
}
}
}
buffer.append("}\n");
// For saving .gcm file before sending to dotty, omit the rest of this.
if(includeGlobals){
buffer.append("Global {\n");
for (String s : defaultParameters.keySet()) {
if (globalParameters.containsKey(s)) {
String value = globalParameters.get(s);
buffer.append(s + "=" + value + "\n");
}
}
buffer.append("}\nPromoters {\n");
for (String s : promoters.keySet()) {
buffer.append(s + " [");
Properties prop = promoters.get(s);
for (Object propName : prop.keySet()) {
if (propName.toString().equals(GlobalConstants.NAME)) {
buffer.append(checkCompabilitySave(propName.toString()) + "=" + "\""
+ prop.getProperty(propName.toString()).toString() + "\"" + ",");
}
else {
buffer.append(checkCompabilitySave(propName.toString()) + "="
+ prop.getProperty(propName.toString()).toString() + ",");
}
}
if (buffer.charAt(buffer.length() - 1) == ',') {
buffer.deleteCharAt(buffer.length() - 1);
}
buffer.append("]\n");
}
buffer.append("}\nConditions {\n");
for (String s : conditions) {
buffer.append(s + "\n");
}
/*
* buffer.append("}\nComponents {\n"); for (String s :
* components.keySet()) { buffer.append(s + " ["); Properties prop =
* components.get(s); for (Object propName : prop.keySet()) { if
* (propName.toString().equals(GlobalConstants.ID)) { } else {
* buffer.append(checkCompabilitySave(propName.toString()) + "=" +
* prop.getProperty(propName.toString()).toString() + ","); } } if
* (buffer.charAt(buffer.length() - 1) == ',') {
* buffer.deleteCharAt(buffer.length() - 1); } buffer.append("]\n");
* }
*/
buffer.append("}\n");
buffer.append(GlobalConstants.SBMLFILE + "=\"" + sbmlFile + "\"\n");
if (bioAbs) {
buffer.append(GlobalConstants.BIOABS + "=true\n");
}
if (dimAbs) {
buffer.append(GlobalConstants.DIMABS + "=true\n");
}
}
return buffer;
}
/**
* Save the current object to file.
* @param filename
*/
public void save(String filename) {
try {
PrintStream p = new PrintStream(new FileOutputStream(filename));
StringBuffer buffer = saveToBuffer(true);
p.print(buffer);
p.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public void load(String filename) {
this.filename = filename;
species = new HashMap<String, Properties>();
influences = new HashMap<String, Properties>();
promoters = new HashMap<String, Properties>();
components = new HashMap<String, Properties>();
conditions = new ArrayList<String>();
globalParameters = new HashMap<String, String>();
parameters = new HashMap<String, String>();
StringBuffer data = new StringBuffer();
loadDefaultParameters();
try {
BufferedReader in = new BufferedReader(new FileReader(filename));
String str;
while ((str = in.readLine()) != null) {
data.append(str + "\n");
}
in.close();
}
catch (IOException e) {
e.printStackTrace();
throw new IllegalStateException("Error opening file");
}
try {
parseStates(data);
parseInfluences(data);
parseGlobal(data);
parsePromoters(data);
parseSBMLFile(data);
parseBioAbs(data);
parseDimAbs(data);
parseConditions(data);
}
catch (Exception e) {
throw new IllegalArgumentException("Unable to parse GCM");
// JOptionPane.showMessageDialog(null,
// "Unable to parse model, creating a blank model.", "Error",
// JOptionPane.ERROR_MESSAGE);
// species = new HashMap<String, Properties>();
// influences = new HashMap<String, Properties>();
// promoters = new HashMap<String, Properties>();
// globalParameters = new HashMap<String, String>();
}
}
public void changePromoterName(String oldName, String newName) {
String[] sArray = new String[influences.keySet().size()];
sArray = influences.keySet().toArray(sArray);
for (int i = 0; i < sArray.length; i++) {
String s = sArray[i];
String input = getInput(s);
String arrow = getArrow(s);
String output = getOutput(s);
String newInfluenceName = "";
if (influences.get(s).containsKey(GlobalConstants.PROMOTER)
&& influences.get(s).get(GlobalConstants.PROMOTER).equals(oldName)) {
newInfluenceName = input + " " + arrow + " " + output + ", Promoter " + newName;
influences.put(newInfluenceName, influences.get(s));
influences.remove(s);
// If you don't remove the promoter, it will end up in the properties list twice, one with the old value and one with the new.
influences.get(newInfluenceName).remove(GlobalConstants.PROMOTER);
influences.get(newInfluenceName).setProperty(GlobalConstants.PROMOTER, newName);
influences.get(newInfluenceName).setProperty(GlobalConstants.NAME, newInfluenceName);
}
}
promoters.put(newName, promoters.get(oldName));
promoters.remove(oldName);
}
public void changeSpeciesName(String oldName, String newName) {
String[] sArray = new String[influences.keySet().size()];
sArray = influences.keySet().toArray(sArray);
for (int i = 0; i < sArray.length; i++) {
String s = sArray[i];
String input = getInput(s);
String arrow = getArrow(s);
String output = getOutput(s);
boolean replaceInput = input.equals(oldName);
boolean replaceOutput = output.equals(oldName);
String newInfluenceName = "";
if (replaceInput || replaceOutput) {
if (replaceInput) {
newInfluenceName = newInfluenceName + newName;
}
else {
newInfluenceName = newInfluenceName + input;
}
if (replaceOutput) {
newInfluenceName = newInfluenceName + " " + arrow + " " + newName;
}
else {
newInfluenceName = newInfluenceName + " " + arrow + " " + output;
}
String promoterName = "default";
if (influences.get(s).containsKey(GlobalConstants.PROMOTER)) {
promoterName = influences.get(s).get(GlobalConstants.PROMOTER).toString();
}
newInfluenceName = newInfluenceName + ", Promoter " + promoterName;
influences.put(newInfluenceName, influences.get(s));
influences.remove(s);
}
}
ArrayList<String> newConditions = new ArrayList<String>();
for (String condition : conditions) {
int index = condition.indexOf(oldName, 0);
if (index != -1) {
while (index <= condition.length() && index != -1) {
if (index != 0 && !Character.isDigit(condition.charAt(index - 1))
&& !Character.isLetter(condition.charAt(index - 1))
&& condition.charAt(index - 1) != '_'
&& index + oldName.length() != condition.length()
&& !Character.isDigit(condition.charAt(index + oldName.length()))
&& !Character.isLetter(condition.charAt(index + oldName.length()))
&& condition.charAt(index + oldName.length()) != '_') {
condition = condition.substring(0, index) + condition.substring(index, condition.length()).replace(oldName, newName);
}
index ++;
index = condition.indexOf(oldName, index);
}
}
newConditions.add(condition);
}
conditions = newConditions;
species.put(newName, species.get(oldName));
species.remove(oldName);
}
public void changeComponentName(String oldName, String newName) {
String[] sArray = new String[influences.keySet().size()];
sArray = influences.keySet().toArray(sArray);
for (int i = 0; i < sArray.length; i++) {
String s = sArray[i];
String input = getInput(s);
String arrow = getArrow(s);
String output = getOutput(s);
boolean replaceInput = input.equals(oldName);
boolean replaceOutput = output.equals(oldName);
String newInfluenceName = "";
if (replaceInput || replaceOutput) {
if (replaceInput) {
newInfluenceName = newInfluenceName + newName;
}
else {
newInfluenceName = newInfluenceName + input;
}
if (replaceOutput) {
newInfluenceName = newInfluenceName + " " + arrow + " " + newName;
}
else {
newInfluenceName = newInfluenceName + " " + arrow + " " + output;
}
String promoterName = "default";
if (influences.get(s).containsKey(GlobalConstants.PROMOTER)) {
promoterName = influences.get(s).get(GlobalConstants.PROMOTER).toString();
}
newInfluenceName = newInfluenceName + ", Promoter " + promoterName;
influences.put(newInfluenceName, influences.get(s));
influences.remove(s);
}
}
components.put(newName, components.get(oldName));
components.remove(oldName);
}
public void addSpecies(String name, Properties property) {
species.put(name, property);
}
public void addPromoter(String name, Properties properties) {
promoters.put(name.replace("\"", ""), properties);
}
public void addComponent(String name, Properties properties) {
components.put(name, properties);
}
public String addCondition(String condition) {
boolean retval = true;
String finalCond = "";
ArrayList<String> split = new ArrayList<String>();
String splitting = condition;
while (splitting.contains("||")) {
split.add(splitting.substring(0, splitting.indexOf("||")));
splitting = splitting.substring(splitting.indexOf("||") + 2);
}
split.add(splitting);
for (String cond : split) {
finalCond += "(";
if (cond.split("->").length > 2) {
return null;
}
String[] split2 = cond.split("->");
int countLeft1 = 0;
int countRight1 = 0;
int countLeft2 = 0;
int countRight2 = 0;
int index = 0;
while (index <= split2[0].length()) {
index = split2[0].indexOf('(', index);
if (index == -1) {
break;
}
countLeft1 ++;
index ++;
}
index = 0;
while (index <= split2[0].length()) {
index = split2[0].indexOf(')', index);
if (index == -1) {
break;
}
countRight1 ++;
index ++;
}
if (split2.length > 1) {
index = 0;
while (index <= split2[0].length()) {
index = split2[1].indexOf('(', index);
if (index == -1) {
break;
}
countLeft2 ++;
index ++;
}
index = 0;
while (index <= split2[0].length()) {
index = split2[1].indexOf(')', index);
if (index == -1) {
break;
}
countRight2 ++;
index ++;
}
}
if ((countLeft1 - countRight1) == (countRight2 - countLeft2)) {
for (int i = 0; i < countLeft1 - countRight1; i ++) {
split2[0] += ")";
split2[1] = "(" + split2[1];
}
}
ArrayList<String> specs = new ArrayList<String>();
ArrayList<Object[]> conLevel = new ArrayList<Object[]>();
for (String spec : species.keySet()) {
specs.add(spec);
ArrayList<String> level = new ArrayList<String>();
level.add("0");
conLevel.add(level.toArray());
}
ExprTree expr = new ExprTree(convertToLHPN(specs, conLevel));
expr.token = expr.intexpr_gettok(split2[0]);
if (!split2[0].equals("")) {
retval = (expr.intexpr_L(split2[0]) && retval);
}
else {
expr = null;
retval = false;
}
if (split2.length > 1) {
if (retval) {
finalCond += "(" + expr.toString() + ")->";
}
expr = new ExprTree(convertToLHPN(specs, conLevel));
expr.token = expr.intexpr_gettok(split2[0]);
if (!split2[0].equals("")) {
retval = (expr.intexpr_L(split2[0]) && retval);
}
else {
expr = null;
retval = false;
}
if (retval) {
finalCond += "(" + expr.toString() + ")";
}
}
else if (retval) {
finalCond += expr.toString();
}
finalCond += ")||";
}
finalCond = finalCond.substring(0, finalCond.length() - 2);
if (retval) {
conditions.add(finalCond);
}
if (retval) {
return finalCond;
}
else {
return null;
}
}
public void removeCondition(String condition) {
conditions.remove(condition);
}
public ArrayList<String> getConditions() {
return conditions;
}
public void addInfluences(String name, Properties property) {
influences.put(name, property);
// Now check to see if a promoter exists in the property
if (property.containsKey("promoter")) {
promoters.put(property.getProperty("promoter").replaceAll("\"", ""), new Properties());
}
}
public void removeSpecies(String name) {
if (name != null && species.containsKey(name)) {
species.remove(name);
}
}
public HashMap<String, Properties> getSpecies() {
return species;
}
public ArrayList<String> getInputSpecies() {
ArrayList<String> inputs = new ArrayList<String>();
for (String spec : species.keySet()) {
if (species.get(spec).getProperty(GlobalConstants.TYPE).equals(GlobalConstants.INPUT)) {
inputs.add(spec);
}
}
return inputs;
}
public ArrayList<String> getOutputSpecies() {
ArrayList<String> outputs = new ArrayList<String>();
for (String spec : species.keySet()) {
if (species.get(spec).getProperty(GlobalConstants.TYPE).equals(GlobalConstants.OUTPUT)) {
outputs.add(spec);
}
}
return outputs;
}
public HashMap<String, Properties> getComponents() {
return components;
}
public String getComponentPortMap(String s) {
String portmap = "(";
Properties c = components.get(s);
ArrayList<String> ports = new ArrayList<String>();
for (Object key : c.keySet()) {
if (!key.equals("gcm") && c.containsKey("type_" + key)) {
ports.add((String) key);
}
}
int i, j;
String index;
for (i = 1; i < ports.size(); i++) {
index = ports.get(i);
j = i;
while ((j > 0) && ports.get(j - 1).compareToIgnoreCase(index) > 0) {
ports.set(j, ports.get(j - 1));
j = j - 1;
}
ports.set(j, index);
}
if (ports.size() > 0) {
portmap += ports.get(0) + "->" + c.getProperty(ports.get(0));
}
for (int k = 1; k < ports.size(); k++) {
portmap += ", " + ports.get(k) + "->" + c.getProperty(ports.get(k));
}
portmap += ")";
return portmap;
}
public HashMap<String, Properties> getInfluences() {
return influences;
}
/**
* Checks to see if removing influence is okay
*
* @param name
* influence to remove
* @return true, it is always okay to remove influence
*/
public boolean removeInfluenceCheck(String name) {
return true;
}
/**
* Checks to see if removing specie is okay
*
* @param name
* specie to remove
* @return true if specie is in no influences
*/
public boolean removeSpeciesCheck(String name) {
for (String s : influences.keySet()) {
if (s.contains(name)) {
return false;
}
}
return true;
}
public boolean removeComponentCheck(String name) {
for (String s : influences.keySet()) {
if ((" " + s + " ").contains(" " + name + " ")) {
return false;
}
}
return true;
}
/**
* Checks to see if removing promoter is okay
*
* @param name
* promoter to remove
* @return true if promoter is in no influences
*/
public boolean removePromoterCheck(String name) {
for (Properties p : influences.values()) {
if (p.containsKey(GlobalConstants.PROMOTER)
&& p.getProperty(GlobalConstants.PROMOTER).equals(name)) {
return false;
}
}
return true;
}
public void removePromoter(String name) {
if (name != null && promoters.containsKey(name)) {
promoters.remove(name);
}
}
public void removeComponent(String name) {
if (name != null && components.containsKey(name)) {
components.remove(name);
}
}
public void removeInfluence(String name) {
if (name != null && influences.containsKey(name)) {
influences.remove(name);
}
}
public void changeInfluencePromoter(String oldInfluence, String oldPromoter, String newPromoter){
if(oldPromoter == null)
oldPromoter = "default";
String pattern = oldPromoter + "$";
String newInfluence = oldInfluence.replaceFirst(pattern, newPromoter);
Properties prop = influences.get(oldInfluence);
prop.remove(GlobalConstants.PROMOTER);
prop.setProperty(GlobalConstants.PROMOTER, newPromoter);
if(prop.get(GlobalConstants.NAME) == oldInfluence){
prop.remove(GlobalConstants.NAME);
prop.put(GlobalConstants.NAME, newPromoter);
}
removeInfluence(oldInfluence);
influences.put(newInfluence, prop);
}
public static String getInput(String name) {
Pattern pattern = Pattern.compile(PARSE);
Matcher matcher = pattern.matcher(name);
matcher.find();
return matcher.group(2);
}
public String getArrow(String name) {
Pattern pattern = Pattern.compile(PARSE);
Matcher matcher = pattern.matcher(name);
matcher.find();
return matcher.group(3) + matcher.group(4);
}
public static String getOutput(String name) {
Pattern pattern = Pattern.compile(PARSE);
Matcher matcher = pattern.matcher(name);
matcher.find();
return matcher.group(5);
}
public String getPromoter(String name) {
Pattern pattern = Pattern.compile(PARSE);
Matcher matcher = pattern.matcher(name);
matcher.find();
return matcher.group(6);
}
public String[] getSpeciesAsArray() {
String[] s = new String[species.size()];
s = species.keySet().toArray(s);
Arrays.sort(s);
return s;
}
public String[] getPromotersAsArray() {
String[] s = new String[promoters.size()];
s = promoters.keySet().toArray(s);
Arrays.sort(s);
return s;
}
public HashMap<String, Properties> getPromoters() {
return promoters;
}
public HashMap<String, String> getGlobalParameters() {
return globalParameters;
}
public HashMap<String, String> getDefaultParameters() {
return defaultParameters;
}
public HashMap<String, String> getParameters() {
return parameters;
}
public String getParameter(String parameter) {
if (globalParameters.containsKey(parameter)) {
return globalParameters.get(parameter);
}
else {
return defaultParameters.get(parameter);
}
}
public void setParameter(String parameter, String value) {
globalParameters.put(parameter, value);
parameters.put(parameter, value);
}
public void removeParameter(String parameter) {
globalParameters.remove(parameter);
}
private void parseStates(StringBuffer data) {
Pattern network = Pattern.compile(NETWORK);
Matcher matcher = network.matcher(data.toString());
Pattern pattern = Pattern.compile(STATE);
Pattern propPattern = Pattern.compile(PROPERTY);
matcher.find();
matcher = pattern.matcher(matcher.group(1));
while (matcher.find()) {
String name = matcher.group(2);
Matcher propMatcher = propPattern.matcher(matcher.group(3));
Properties properties = new Properties();
while (propMatcher.find()) {
if (propMatcher.group(3) != null) {
properties.put(propMatcher.group(1), propMatcher.group(3));
}
else {
properties.put(propMatcher.group(1), propMatcher.group(4));
}
}
// for backwards compatibility
if (properties.containsKey("const")) {
properties.setProperty(GlobalConstants.TYPE, GlobalConstants.INPUT);
}
else if (!properties.containsKey(GlobalConstants.TYPE)) {
properties.setProperty(GlobalConstants.TYPE, GlobalConstants.OUTPUT);
}
if (properties.getProperty(GlobalConstants.TYPE).equals("constant")) {
properties.setProperty(GlobalConstants.TYPE, GlobalConstants.INPUT);
}
if (properties.getProperty(GlobalConstants.TYPE).equals(GlobalConstants.CONSTANT)) {
properties.setProperty(GlobalConstants.TYPE, GlobalConstants.INPUT);
}
if (properties.getProperty(GlobalConstants.TYPE).equals(GlobalConstants.NORMAL)) {
properties.setProperty(GlobalConstants.TYPE, GlobalConstants.OUTPUT);
}
// for backwards compatibility
if (properties.containsKey("label")) {
properties.put(GlobalConstants.ID, properties.getProperty("label")
.replace("\"", ""));
}
if (properties.containsKey("gcm")) {
if (properties.containsKey(GlobalConstants.TYPE)) {
properties.remove(GlobalConstants.TYPE);
}
properties.put("gcm", properties.getProperty("gcm").replace("\"", ""));
components.put(name, properties);
}
else {
species.put(name, properties);
}
}
}
private void parseSBMLFile(StringBuffer data) {
Pattern pattern = Pattern.compile(SBMLFILE);
Matcher matcher = pattern.matcher(data.toString());
if (matcher.find()) {
sbmlFile = matcher.group(1);
}
}
private void parseDimAbs(StringBuffer data) {
Pattern pattern = Pattern.compile(DIMABS);
Matcher matcher = pattern.matcher(data.toString());
if (matcher.find()) {
if (matcher.group(1).equals("true")) {
dimAbs = true;
}
}
}
private void parseBioAbs(StringBuffer data) {
Pattern pattern = Pattern.compile(BIOABS);
Matcher matcher = pattern.matcher(data.toString());
if (matcher.find()) {
if (matcher.group(1).equals("true")) {
bioAbs = true;
}
}
}
private void parseGlobal(StringBuffer data) {
Pattern pattern = Pattern.compile(GLOBAL);
Pattern propPattern = Pattern.compile(PROPERTY);
Matcher matcher = pattern.matcher(data.toString());
if (matcher.find()) {
String s = matcher.group(1);
matcher = propPattern.matcher(s);
while (matcher.find()) {
if (matcher.group(3) != null) {
globalParameters.put(matcher.group(1), matcher.group(3));
parameters.put(matcher.group(1), matcher.group(3));
}
else {
globalParameters.put(matcher.group(1), matcher.group(4));
parameters.put(matcher.group(1), matcher.group(4));
}
}
}
}
private void parseConditions(StringBuffer data) {
Pattern pattern = Pattern.compile(CONDITION);
Matcher matcher = pattern.matcher(data.toString());
if (matcher.find()) {
String s = matcher.group(1).trim();
for (String cond : s.split("\n")) {
addCondition(cond.trim());
}
}
}
private void parsePromoters(StringBuffer data) {
Pattern network = Pattern.compile(PROMOTERS_LIST);
Matcher matcher = network.matcher(data.toString());
Pattern pattern = Pattern.compile(STATE);
Pattern propPattern = Pattern.compile(PROPERTY);
if (!matcher.find()) {
return;
}
matcher = pattern.matcher(matcher.group(1));
while (matcher.find()) {
String name = matcher.group(2);
Matcher propMatcher = propPattern.matcher(matcher.group(3));
Properties properties = new Properties();
while (propMatcher.find()) {
if (propMatcher.group(3) != null) {
properties.put(propMatcher.group(1), propMatcher.group(3));
}
else {
properties.put(propMatcher.group(1), propMatcher.group(4));
}
}
promoters.put(name, properties);
}
}
/*
* private void parseComponents(StringBuffer data) { Pattern network =
* Pattern.compile(COMPONENTS_LIST); Matcher matcher =
* network.matcher(data.toString()); Pattern pattern =
* Pattern.compile(STATE); Pattern propPattern = Pattern.compile(PROPERTY);
* if (!matcher.find()) { return; } matcher =
* pattern.matcher(matcher.group(1)); while (matcher.find()) { String name =
* matcher.group(2); Matcher propMatcher =
* propPattern.matcher(matcher.group(3)); Properties properties = new
* Properties(); while (propMatcher.find()) { if
* (propMatcher.group(3)!=null) { properties.put(propMatcher.group(1),
* propMatcher.group(3)); } else { properties.put(propMatcher.group(1),
* propMatcher.group(4)); } } components.put(name, properties); } }
*/
private void parseInfluences(StringBuffer data) {
Pattern pattern = Pattern.compile(REACTION);
Pattern propPattern = Pattern.compile(PROPERTY);
Matcher matcher = pattern.matcher(data.toString());
while (matcher.find()) {
Matcher propMatcher = propPattern.matcher(matcher.group(6));
Properties properties = new Properties();
while (propMatcher.find()) {
if (propMatcher.group(3) != null) {
properties
.put(checkCompabilityLoad(propMatcher.group(1)), propMatcher.group(3));
if (propMatcher.group(1).equalsIgnoreCase(GlobalConstants.PROMOTER)
&& !promoters.containsKey(propMatcher.group(3))) {
promoters.put(propMatcher.group(3).replaceAll("\"", ""), new Properties());
properties.setProperty(GlobalConstants.PROMOTER, propMatcher.group(3)
.replace("\"", "")); // for backwards
// compatibility
}
}
else {
properties
.put(checkCompabilityLoad(propMatcher.group(1)), propMatcher.group(4));
if (propMatcher.group(1).equalsIgnoreCase(GlobalConstants.PROMOTER)
&& !promoters.containsKey(propMatcher.group(4))) {
promoters.put(propMatcher.group(4).replaceAll("\"", ""), new Properties());
properties.setProperty(GlobalConstants.PROMOTER, propMatcher.group(4)
.replace("\"", "")); // for backwards
// compatibility
}
}
}
if (properties.containsKey("port")) {
if (components.containsKey(matcher.group(2))) {
components.get(matcher.group(2)).put(properties.get("port"), matcher.group(5));
if (properties.containsKey("type")) {
components.get(matcher.group(2)).put("type_" + properties.get("port"), properties.get("type"));
}
else {
GCMFile file = new GCMFile(path);
file.load(path + separator + components.get(matcher.group(2)).getProperty("gcm"));
if (file.getSpecies().get(properties.get("port")).get(GlobalConstants.TYPE).equals(GlobalConstants.INPUT)) {
components.get(matcher.group(2)).put("type_" + properties.get("port"), "Input");
}
else if (file.getSpecies().get(properties.get("port")).get(GlobalConstants.TYPE).equals(GlobalConstants.OUTPUT)) {
components.get(matcher.group(2)).put("type_" + properties.get("port"), "Output");
}
}
}
else {
components.get(matcher.group(5)).put(properties.get("port"), matcher.group(2));
if (properties.containsKey("type")) {
components.get(matcher.group(5)).put("type_" + properties.get("port"), properties.get("type"));
}
else {
GCMFile file = new GCMFile(path);
file.load(path + separator + components.get(matcher.group(5)).getProperty("gcm"));
if (file.getSpecies().get(properties.get("port")).get(GlobalConstants.TYPE).equals(GlobalConstants.INPUT)) {
components.get(matcher.group(5)).put("type_" + properties.get("port"), "Input");
}
else if (file.getSpecies().get(properties.get("port")).get(GlobalConstants.TYPE).equals(GlobalConstants.OUTPUT)) {
components.get(matcher.group(5)).put("type_" + properties.get("port"), "Output");
}
}
}
}
else {
String name = "";
if (properties.containsKey("arrowhead")) {
if (properties.getProperty("arrowhead").indexOf("vee") != -1) {
properties.setProperty(GlobalConstants.TYPE, GlobalConstants.ACTIVATION);
if (properties.containsKey(GlobalConstants.BIO)
&& properties.get(GlobalConstants.BIO).equals("yes")) {
name = matcher.group(2) + " +> " + matcher.group(5);
}
else {
name = matcher.group(2) + " -> " + matcher.group(5);
}
}
else if (properties.getProperty("arrowhead").indexOf("tee") != -1) {
properties.setProperty(GlobalConstants.TYPE, GlobalConstants.REPRESSION);
if (properties.containsKey(GlobalConstants.BIO)
&& properties.get(GlobalConstants.BIO).equals("yes")) {
name = matcher.group(2) + " +| " + matcher.group(5);
}
else {
name = matcher.group(2) + " -| " + matcher.group(5);
}
}
else {
properties.setProperty(GlobalConstants.TYPE, GlobalConstants.NOINFLUENCE);
if (properties.containsKey(GlobalConstants.BIO)
&& properties.get(GlobalConstants.BIO).equals("yes")) {
name = matcher.group(2) + " x> " + matcher.group(5);
}
else {
name = matcher.group(2) + " x> " + matcher.group(5);
}
}
}
if (properties.getProperty(GlobalConstants.PROMOTER) != null) {
name = name + ", Promoter " + properties.getProperty(GlobalConstants.PROMOTER);
}
else {
name = name + ", Promoter " + "default";
}
if (!properties.containsKey("label")) {
String label = properties.getProperty(GlobalConstants.PROMOTER);
if (label == null) {
label = "";
}
if (properties.containsKey(GlobalConstants.BIO)
&& properties.get(GlobalConstants.BIO).equals("yes")) {
label = label + "+";
}
properties.put("label", "\"" + label + "\"");
}
properties.put(GlobalConstants.NAME, name);
influences.put(name, properties);
}
}
}
public void loadDefaultParameters() {
Preferences biosimrc = Preferences.userRoot();
defaultParameters = new HashMap<String, String>();
defaultParameters.put(GlobalConstants.KDECAY_STRING, biosimrc.get(
"biosim.gcm.KDECAY_VALUE", ""));
defaultParameters.put(GlobalConstants.KASSOCIATION_STRING, biosimrc.get(
"biosim.gcm.KASSOCIATION_VALUE", ""));
defaultParameters.put(GlobalConstants.KBIO_STRING, biosimrc
.get("biosim.gcm.KBIO_VALUE", ""));
defaultParameters.put(GlobalConstants.COOPERATIVITY_STRING, biosimrc.get(
"biosim.gcm.COOPERATIVITY_VALUE", ""));
defaultParameters.put(GlobalConstants.KREP_STRING, biosimrc
.get("biosim.gcm.KREP_VALUE", ""));
defaultParameters.put(GlobalConstants.KACT_STRING, biosimrc
.get("biosim.gcm.KACT_VALUE", ""));
defaultParameters.put(GlobalConstants.RNAP_BINDING_STRING, biosimrc.get(
"biosim.gcm.RNAP_BINDING_VALUE", ""));
defaultParameters.put(GlobalConstants.RNAP_STRING, biosimrc
.get("biosim.gcm.RNAP_VALUE", ""));
defaultParameters.put(GlobalConstants.OCR_STRING, biosimrc.get("biosim.gcm.OCR_VALUE", ""));
defaultParameters.put(GlobalConstants.KBASAL_STRING, biosimrc.get(
"biosim.gcm.KBASAL_VALUE", ""));
defaultParameters.put(GlobalConstants.PROMOTER_COUNT_STRING, biosimrc.get(
"biosim.gcm.PROMOTER_COUNT_VALUE", ""));
defaultParameters.put(GlobalConstants.STOICHIOMETRY_STRING, biosimrc.get(
"biosim.gcm.STOICHIOMETRY_VALUE", ""));
defaultParameters.put(GlobalConstants.ACTIVED_STRING, biosimrc.get(
"biosim.gcm.ACTIVED_VALUE", ""));
defaultParameters.put(GlobalConstants.MAX_DIMER_STRING, biosimrc.get(
"biosim.gcm.MAX_DIMER_VALUE", ""));
defaultParameters.put(GlobalConstants.INITIAL_STRING, biosimrc.get(
"biosim.gcm.INITIAL_VALUE", ""));
for (String s : defaultParameters.keySet()) {
parameters.put(s, defaultParameters.get(s));
}
}
public void setParameters(HashMap<String, String> parameters) {
for (String s : parameters.keySet()) {
defaultParameters.put(s, parameters.get(s));
this.parameters.put(s, parameters.get(s));
}
}
private String checkCompabilitySave(String key) {
if (key.equals(GlobalConstants.MAX_DIMER_STRING)) {
return "maxDimer";
}
return key;
}
private String checkCompabilityLoad(String key) {
if (key.equals("maxDimer")) {
return GlobalConstants.MAX_DIMER_STRING;
}
return key;
}
private ArrayList<String> setToArrayList(Set<String> set) {
ArrayList<String> array = new ArrayList<String>();
for (String s : set) {
array.add(s);
}
return array;
}
/**
* Returns a hash containing the inner model.
*/
public HashMap<String, HashMap<String, Properties>> getInternalModel(){
HashMap<String, HashMap<String, Properties>> im = new HashMap<String, HashMap<String, Properties>>();
im.put("species", species);
im.put("promoters", promoters);
im.put("influences", influences);
im.put("components", components);
return im;
}
private SBMLDocument unionSBML(SBMLDocument mainDoc, SBMLDocument doc, String compName) {
Model m = doc.getModel();
for (int i = 0; i < m.getNumCompartmentTypes(); i++) {
org.sbml.libsbml.CompartmentType c = m.getCompartmentType(i);
String newName = compName + "_" + c.getId();
updateVarId(false, c.getId(), newName, doc);
c.setId(newName);
boolean add = true;
for (int j = 0; j < mainDoc.getModel().getNumCompartmentTypes(); j++) {
if (mainDoc.getModel().getCompartmentType(j).getId().equals(c.getId())) {
add = false;
org.sbml.libsbml.CompartmentType comp = mainDoc.getModel().getCompartmentType(j);
if (!c.getName().equals(comp.getName())) {
return null;
}
}
}
if (add) {
mainDoc.getModel().addCompartmentType(c);
}
}
for (int i = 0; i < m.getNumCompartments(); i++) {
org.sbml.libsbml.Compartment c = m.getCompartment(i);
String newName = compName + "_" + c.getId();
updateVarId(false, c.getId(), newName, doc);
c.setId(newName);
boolean add = true;
for (int j = 0; j < mainDoc.getModel().getNumCompartments(); j++) {
if (mainDoc.getModel().getCompartment(j).getId().equals(c.getId())) {
add = false;
org.sbml.libsbml.Compartment comp = mainDoc.getModel().getCompartment(j);
if (!c.getName().equals(comp.getName())) {
return null;
}
if (!c.getCompartmentType().equals(comp.getCompartmentType())) {
return null;
}
if (c.getConstant() != comp.getConstant()) {
return null;
}
if (!c.getOutside().equals(comp.getOutside())) {
return null;
}
if (c.getVolume() != comp.getVolume()) {
return null;
}
if (c.getSpatialDimensions() != comp.getSpatialDimensions()) {
return null;
}
if (c.getSize() != comp.getSize()) {
return null;
}
if (!c.getUnits().equals(comp.getUnits())) {
return null;
}
}
}
if (add) {
mainDoc.getModel().addCompartment(c);
}
}
for (int i = 0; i < m.getNumSpeciesTypes(); i++) {
org.sbml.libsbml.SpeciesType s = m.getSpeciesType(i);
String newName = compName + "_" + s.getId();
updateVarId(false, s.getId(), newName, doc);
s.setId(newName);
boolean add = true;
for (int j = 0; j < mainDoc.getModel().getNumSpeciesTypes(); j++) {
if (mainDoc.getModel().getSpeciesType(j).getId().equals(s.getId())) {
add = false;
org.sbml.libsbml.SpeciesType spec = mainDoc.getModel().getSpeciesType(j);
if (!s.getName().equals(spec.getName())) {
return null;
}
}
}
if (add) {
mainDoc.getModel().addSpeciesType(s);
}
}
for (int i = 0; i < m.getNumSpecies(); i++) {
Species spec = m.getSpecies(i);
String newName = compName + "_" + spec.getId();
for (Object port : getComponents().get(compName).keySet()) {
if (spec.getId().equals((String) port)) {
newName = "_" + compName + "_" + getComponents().get(compName).getProperty((String) port);
}
}
updateVarId(true, spec.getId(), newName, doc);
spec.setId(newName);
}
for (int i = 0; i < m.getNumSpecies(); i++) {
Species spec = m.getSpecies(i);
boolean add = true;
if (spec.getId().startsWith("_" + compName + "_")) {
updateVarId(true, spec.getId(), spec.getId().substring(2 + compName.length()), doc);
spec.setId(spec.getId().substring(2 + compName.length()));
}
else {
for (int j = 0; j < mainDoc.getModel().getNumSpecies(); j++) {
if (mainDoc.getModel().getSpecies(j).getId().equals(spec.getId())) {
Species s = mainDoc.getModel().getSpecies(j);
if (!s.getName().equals(spec.getName())) {
return null;
}
if (!s.getCompartment().equals(spec.getCompartment())) {
return null;
}
if (s.getConstant() != spec.getConstant()) {
return null;
}
if (s.getBoundaryCondition() != spec.getBoundaryCondition()) {
return null;
}
if (s.getHasOnlySubstanceUnits() != spec.getHasOnlySubstanceUnits()) {
return null;
}
if (s.getCharge() != spec.getCharge()) {
return null;
}
if (!s.getSpatialSizeUnits().equals(spec.getSpatialSizeUnits())) {
return null;
}
if (s.getInitialAmount() != spec.getInitialAmount()) {
return null;
}
if (s.getInitialConcentration() != spec.getInitialConcentration()) {
return null;
}
if (!s.getSpeciesType().equals(spec.getSpeciesType())) {
return null;
}
if (!s.getSubstanceUnits().equals(spec.getSubstanceUnits())) {
return null;
}
if (!s.getUnits().equals(spec.getUnits())) {
return null;
}
add = false;
}
}
}
if (add) {
mainDoc.getModel().addSpecies(spec);
}
}
for (int i = 0; i < m.getNumParameters(); i++) {
org.sbml.libsbml.Parameter p = m.getParameter(i);
String newName = compName + "_" + p.getId();
updateVarId(false, p.getId(), newName, doc);
p.setId(newName);
boolean add = true;
for (int j = 0; j < mainDoc.getModel().getNumParameters(); j++) {
if (mainDoc.getModel().getParameter(j).getId().equals(p.getId())) {
add = false;
org.sbml.libsbml.Parameter param = mainDoc.getModel().getParameter(j);
if (!p.getName().equals(param.getName())) {
return null;
}
if (!p.getUnits().equals(param.getUnits())) {
return null;
}
if (p.getConstant() != param.getConstant()) {
return null;
}
if (p.getValue() != param.getValue()) {
return null;
}
}
}
if (add) {
mainDoc.getModel().addParameter(p);
}
}
for (int i = 0; i < m.getNumReactions(); i++) {
org.sbml.libsbml.Reaction r = m.getReaction(i);
String newName = compName + "_" + r.getId();
updateVarId(false, r.getId(), newName, doc);
r.setId(newName);
boolean add = true;
for (int j = 0; j < mainDoc.getModel().getNumReactions(); j++) {
if (mainDoc.getModel().getReaction(j).getId().equals(r.getId())) {
add = false;
org.sbml.libsbml.Reaction reac = mainDoc.getModel().getReaction(j);
if (!r.getName().equals(reac.getName())) {
return null;
}
if (r.getFast() != reac.getFast()) {
return null;
}
if (r.getReversible() != reac.getReversible()) {
return null;
}
if (!r.getKineticLaw().equals(reac.getKineticLaw())) {
return null;
}
for (int k = 0; k < reac.getNumModifiers(); k++) {
ModifierSpeciesReference mod = reac.getModifier(k);
boolean found = false;
for (int l = 0; l < r.getNumModifiers(); l++) {
ModifierSpeciesReference mod2 = r.getModifier(l);
if (mod.getId().equals(mod2.getId())) {
found = true;
if (!mod.getSpecies().equals(mod2.getSpecies())) {
return null;
}
}
}
if (!found) {
return null;
}
}
for (int k = 0; k < r.getNumModifiers(); k++) {
ModifierSpeciesReference mod = r.getModifier(k);
boolean found = false;
for (int l = 0; l < reac.getNumModifiers(); l++) {
ModifierSpeciesReference mod2 = reac.getModifier(l);
if (mod.getId().equals(mod2.getId())) {
found = true;
if (!mod.getSpecies().equals(mod2.getSpecies())) {
return null;
}
}
}
if (!found) {
return null;
}
}
for (int k = 0; k < reac.getNumProducts(); k++) {
SpeciesReference p = reac.getProduct(k);
boolean found = false;
for (int l = 0; l < r.getNumProducts(); l++) {
SpeciesReference prod = r.getProduct(l);
if (p.getId().equals(prod.getId())) {
found = true;
if (!p.getSpecies().equals(prod.getSpecies())) {
return null;
}
if (!p.getStoichiometryMath().equals(prod.getStoichiometryMath())) {
return null;
}
if (p.getStoichiometry() != prod.getStoichiometry()) {
return null;
}
if (p.getDenominator() != prod.getDenominator()) {
return null;
}
}
}
if (!found) {
return null;
}
}
for (int k = 0; k < r.getNumProducts(); k++) {
SpeciesReference p = r.getProduct(k);
boolean found = false;
for (int l = 0; l < reac.getNumProducts(); l++) {
SpeciesReference prod = reac.getProduct(l);
if (p.getId().equals(prod.getId())) {
found = true;
if (!p.getSpecies().equals(prod.getSpecies())) {
return null;
}
if (!p.getStoichiometryMath().equals(prod.getStoichiometryMath())) {
return null;
}
if (p.getStoichiometry() != prod.getStoichiometry()) {
return null;
}
if (p.getDenominator() != prod.getDenominator()) {
return null;
}
}
}
if (!found) {
return null;
}
}
for (int k = 0; k < reac.getNumReactants(); k++) {
SpeciesReference react = reac.getReactant(k);
boolean found = false;
for (int l = 0; l < r.getNumReactants(); l++) {
SpeciesReference react2 = r.getReactant(l);
if (react.getId().equals(react2.getId())) {
found = true;
if (!react.getSpecies().equals(react2.getSpecies())) {
return null;
}
if (!react.getStoichiometryMath().equals(react2.getStoichiometryMath())) {
return null;
}
if (react.getStoichiometry() != react2.getStoichiometry()) {
return null;
}
if (react.getDenominator() != react2.getDenominator()) {
return null;
}
}
}
if (!found) {
return null;
}
}
for (int k = 0; k < r.getNumReactants(); k++) {
SpeciesReference react = r.getReactant(k);
boolean found = false;
for (int l = 0; l < reac.getNumReactants(); l++) {
SpeciesReference react2 = reac.getReactant(l);
if (react.getId().equals(react2.getId())) {
found = true;
if (!react.getSpecies().equals(react2.getSpecies())) {
return null;
}
if (!react.getStoichiometryMath().equals(react2.getStoichiometryMath())) {
return null;
}
if (react.getStoichiometry() != react2.getStoichiometry()) {
return null;
}
if (react.getDenominator() != react2.getDenominator()) {
return null;
}
}
}
if (!found) {
return null;
}
}
}
}
if (add) {
mainDoc.getModel().addReaction(r);
}
}
for (int i = 0; i < m.getNumInitialAssignments(); i++) {
InitialAssignment init = (InitialAssignment) m.getListOfInitialAssignments().get(i);
mainDoc.getModel().addInitialAssignment(init);
}
for (int i = 0; i < m.getNumRules(); i++) {
org.sbml.libsbml.Rule r = m.getRule(i);
mainDoc.getModel().addRule(r);
}
for (int i = 0; i < m.getNumConstraints(); i++) {
Constraint constraint = (Constraint) m.getListOfConstraints().get(i);
mainDoc.getModel().addConstraint(constraint);
}
for (int i = 0; i < m.getNumEvents(); i++) {
org.sbml.libsbml.Event event = (org.sbml.libsbml.Event) m.getListOfEvents().get(i);
String newName = compName + "_" + event.getId();
updateVarId(false, event.getId(), newName, doc);
event.setId(newName);
boolean add = true;
for (int j = 0; j < mainDoc.getModel().getNumEvents(); j++) {
if (mainDoc.getModel().getEvent(j).getId().equals(event.getId())) {
add = false;
org.sbml.libsbml.Event e = mainDoc.getModel().getEvent(j);
if (!e.getName().equals(event.getName())) {
return null;
}
if (e.getUseValuesFromTriggerTime() != event.getUseValuesFromTriggerTime()) {
return null;
}
if (!e.getDelay().equals(event.getDelay())) {
return null;
}
if (!e.getTimeUnits().equals(event.getTimeUnits())) {
return null;
}
if (!e.getTrigger().equals(event.getTrigger())) {
return null;
}
for (int k = 0; k < e.getNumEventAssignments(); k++) {
EventAssignment a = e.getEventAssignment(k);
boolean found = false;
for (int l = 0; l < event.getNumEventAssignments(); l++) {
EventAssignment assign = event.getEventAssignment(l);
if (a.getVariable().equals(assign.getVariable())) {
found = true;
if (!a.getMath().equals(assign.getMath())) {
return null;
}
}
}
if (!found) {
return null;
}
}
for (int k = 0; k < event.getNumEventAssignments(); k++) {
EventAssignment a = event.getEventAssignment(k);
boolean found = false;
for (int l = 0; l < e.getNumEventAssignments(); l++) {
EventAssignment assign = e.getEventAssignment(l);
if (a.getVariable().equals(assign.getVariable())) {
found = true;
if (!a.getMath().equals(assign.getMath())) {
return null;
}
}
}
if (!found) {
return null;
}
}
}
}
if (add) {
mainDoc.getModel().addEvent(event);
}
}
for (int i = 0; i < m.getNumUnitDefinitions(); i++) {
UnitDefinition u = m.getUnitDefinition(i);
boolean add = true;
for (int j = 0; j < mainDoc.getModel().getNumUnitDefinitions(); j++) {
if (mainDoc.getModel().getUnitDefinition(j).getId().equals(u.getId())) {
add = false;
}
}
if (add) {
mainDoc.getModel().addUnitDefinition(u);
}
}
for (int i = 0; i < m.getNumFunctionDefinitions(); i++) {
FunctionDefinition f = m.getFunctionDefinition(i);
boolean add = true;
for (int j = 0; j < mainDoc.getModel().getNumFunctionDefinitions(); j++) {
if (mainDoc.getModel().getFunctionDefinition(j).getId().equals(f.getId())) {
add = false;
}
}
if (add) {
mainDoc.getModel().addFunctionDefinition(f);
}
}
return mainDoc;
}
private String myFormulaToString(ASTNode mathFormula) {
String formula = libsbml.formulaToString(mathFormula);
formula = formula.replaceAll("arccot", "acot");
formula = formula.replaceAll("arccoth", "acoth");
formula = formula.replaceAll("arccsc", "acsc");
formula = formula.replaceAll("arccsch", "acsch");
formula = formula.replaceAll("arcsec", "asec");
formula = formula.replaceAll("arcsech", "asech");
formula = formula.replaceAll("arccosh", "acosh");
formula = formula.replaceAll("arcsinh", "asinh");
formula = formula.replaceAll("arctanh", "atanh");
String newformula = formula.replaceFirst("00e", "0e");
while (!(newformula.equals(formula))) {
formula = newformula;
newformula = formula.replaceFirst("0e\\+", "e+");
newformula = newformula.replaceFirst("0e-", "e-");
}
formula = formula.replaceFirst("\\.e\\+", ".0e+");
formula = formula.replaceFirst("\\.e-", ".0e-");
return formula;
}
private ASTNode myParseFormula(String formula) {
ASTNode mathFormula = libsbml.parseFormula(formula);
if (mathFormula == null)
return null;
setTimeAndTrigVar(mathFormula);
return mathFormula;
}
private String updateFormulaVar(String s, String origVar, String newVar) {
s = " " + s + " ";
s = s.replace(" " + origVar + " ", " " + newVar + " ");
s = s.replace(" " + origVar + "(", " " + newVar + "(");
s = s.replace("(" + origVar + ")", "(" + newVar + ")");
s = s.replace("(" + origVar + " ", "(" + newVar + " ");
s = s.replace("(" + origVar + ",", "(" + newVar + ",");
s = s.replace(" " + origVar + ")", " " + newVar + ")");
s = s.replace(" " + origVar + "^", " " + newVar + "^");
return s.trim();
}
private ASTNode updateMathVar(ASTNode math, String origVar, String newVar) {
String s = updateFormulaVar(myFormulaToString(math), origVar, newVar);
return myParseFormula(s);
}
private void updateVarId(boolean isSpecies, String origId, String newId, SBMLDocument document) {
if (origId.equals(newId))
return;
Model model = document.getModel();
for (int i = 0; i < model.getNumSpecies(); i++) {
org.sbml.libsbml.Species species = (org.sbml.libsbml.Species) model.getListOfSpecies().get(i);
if (species.getCompartment().equals(origId)) {
species.setCompartment(newId);
}
if (species.getSpeciesType().equals(origId)) {
species.setSpeciesType(newId);
}
}
for (int i = 0; i < model.getNumCompartments(); i++) {
org.sbml.libsbml.Compartment compartment = (org.sbml.libsbml.Compartment) model.getListOfCompartments().get(i);
if (compartment.getCompartmentType().equals(origId)) {
compartment.setCompartmentType(newId);
}
}
for (int i = 0; i < model.getNumReactions(); i++) {
org.sbml.libsbml.Reaction reaction = (org.sbml.libsbml.Reaction) model.getListOfReactions().get(i);
for (int j = 0; j < reaction.getNumProducts(); j++) {
if (reaction.getProduct(j).isSetSpecies()) {
SpeciesReference specRef = reaction.getProduct(j);
if (isSpecies && origId.equals(specRef.getSpecies())) {
specRef.setSpecies(newId);
}
if (specRef.isSetStoichiometryMath()) {
specRef.getStoichiometryMath().setMath(updateMathVar(specRef
.getStoichiometryMath().getMath(), origId, newId));
}
}
}
if (isSpecies) {
for (int j = 0; j < reaction.getNumModifiers(); j++) {
if (reaction.getModifier(j).isSetSpecies()) {
ModifierSpeciesReference specRef = reaction.getModifier(j);
if (origId.equals(specRef.getSpecies())) {
specRef.setSpecies(newId);
}
}
}
}
for (int j = 0; j < reaction.getNumReactants(); j++) {
if (reaction.getReactant(j).isSetSpecies()) {
SpeciesReference specRef = reaction.getReactant(j);
if (isSpecies && origId.equals(specRef.getSpecies())) {
specRef.setSpecies(newId);
}
if (specRef.isSetStoichiometryMath()) {
specRef.getStoichiometryMath().setMath(updateMathVar(specRef
.getStoichiometryMath().getMath(), origId, newId));
}
}
}
reaction.getKineticLaw().setMath(
updateMathVar(reaction.getKineticLaw().getMath(), origId, newId));
}
if (model.getNumInitialAssignments() > 0) {
for (int i = 0; i < model.getNumInitialAssignments(); i++) {
InitialAssignment init = (InitialAssignment) model.getListOfInitialAssignments().get(i);
if (origId.equals(init.getSymbol())) {
init.setSymbol(newId);
}
init.setMath(updateMathVar(init.getMath(), origId, newId));
}
}
if (model.getNumRules() > 0) {
for (int i = 0; i < model.getNumRules(); i++) {
Rule rule = (Rule) model.getListOfRules().get(i);
if (rule.isSetVariable() && origId.equals(rule.getVariable())) {
rule.setVariable(newId);
}
rule.setMath(updateMathVar(rule.getMath(), origId, newId));
}
}
if (model.getNumConstraints() > 0) {
for (int i = 0; i < model.getNumConstraints(); i++) {
Constraint constraint = (Constraint) model.getListOfConstraints().get(i);
constraint.setMath(updateMathVar(constraint.getMath(), origId, newId));
}
}
if (model.getNumEvents() > 0) {
for (int i = 0; i < model.getNumEvents(); i++) {
org.sbml.libsbml.Event event = (org.sbml.libsbml.Event) model.getListOfEvents().get(i);
if (event.isSetTrigger()) {
event.getTrigger().setMath(updateMathVar(event.getTrigger().getMath(), origId, newId));
}
if (event.isSetDelay()) {
event.getDelay().setMath(updateMathVar(event.getDelay().getMath(), origId, newId));
}
for (int j = 0; j < event.getNumEventAssignments(); j++) {
EventAssignment ea = (EventAssignment) event.getListOfEventAssignments().get(j);
if (ea.getVariable().equals(origId)) {
ea.setVariable(newId);
}
if (ea.isSetMath()) {
ea.setMath(updateMathVar(ea.getMath(), origId, newId));
}
}
}
}
}
private void setTimeAndTrigVar(ASTNode node) {
if (node.getType() == libsbml.AST_NAME) {
if (node.getName().equals("t")) {
node.setType(libsbml.AST_NAME_TIME);
}
else if (node.getName().equals("time")) {
node.setType(libsbml.AST_NAME_TIME);
}
}
if (node.getType() == libsbml.AST_FUNCTION) {
if (node.getName().equals("acot")) {
node.setType(libsbml.AST_FUNCTION_ARCCOT);
}
else if (node.getName().equals("acoth")) {
node.setType(libsbml.AST_FUNCTION_ARCCOTH);
}
else if (node.getName().equals("acsc")) {
node.setType(libsbml.AST_FUNCTION_ARCCSC);
}
else if (node.getName().equals("acsch")) {
node.setType(libsbml.AST_FUNCTION_ARCCSCH);
}
else if (node.getName().equals("asec")) {
node.setType(libsbml.AST_FUNCTION_ARCSEC);
}
else if (node.getName().equals("asech")) {
node.setType(libsbml.AST_FUNCTION_ARCSECH);
}
else if (node.getName().equals("acosh")) {
node.setType(libsbml.AST_FUNCTION_ARCCOSH);
}
else if (node.getName().equals("asinh")) {
node.setType(libsbml.AST_FUNCTION_ARCSINH);
}
else if (node.getName().equals("atanh")) {
node.setType(libsbml.AST_FUNCTION_ARCTANH);
}
}
for (int c = 0; c < node.getNumChildren(); c++)
setTimeAndTrigVar(node.getChild(c));
}
private static final String NETWORK = "digraph\\sG\\s\\{([^}]*)\\s\\}";
private static final String STATE = "(^|\\n) *([^- \\n]*) *\\[(.*)\\]";
private static final String REACTION = "(^|\\n) *([^ \\n]*) (\\-|\\+|x)(\\>|\\|) *([^ \n]*) *\\[([^\\]]*)]";
// private static final String PARSE = "(^|\\n) *([^ \\n,]*) *\\-\\> *([^
private static final String PARSE = "(^|\\n) *([^ \\n,]*) (\\-|\\+|x)(\\>|\\|) *([^ \n,]*), Promoter ([a-zA-Z\\d_]+)";
private static final String PROPERTY = "([a-zA-Z\\ \\-]+)=(\"([^\"]*)\"|([^\\s,]+))";
private static final String GLOBAL = "Global\\s\\{([^}]*)\\s\\}";
private static final String CONDITION = "Conditions\\s\\{([^}]*)\\s\\}";
private static final String SBMLFILE = GlobalConstants.SBMLFILE + "=\"([^\"]*)\"";
private static final String DIMABS = GlobalConstants.DIMABS + "=(true|false)";
private static final String BIOABS = GlobalConstants.BIOABS + "=(true|false)";
private static final String PROMOTERS_LIST = "Promoters\\s\\{([^}]*)\\s\\}";
// private static final String COMPONENTS_LIST =
// "Components\\s\\{([^}]*)\\s\\}";
private String sbmlFile = "";
private boolean dimAbs = false;
private boolean bioAbs = false;
private HashMap<String, Properties> species;
private HashMap<String, Properties> influences;
private HashMap<String, Properties> promoters;
private HashMap<String, Properties> components;
private ArrayList<String> conditions;
private HashMap<String, String> parameters;
private HashMap<String, String> defaultParameters;
private HashMap<String, String> globalParameters;
private String path;
} |
package com.example.client;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.Element;
public class Main implements EntryPoint{
@Override
public void onModuleLoad(){
Element textDiv = Document.get().getElementById("text");
textDiv.setInnerHTML("Hello GWT World!");
}
} |
package com.malhartech.stram;
import com.malhartech.api.BackupAgent;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Stack;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.malhartech.api.Context.OperatorContext;
import com.malhartech.api.Context.PortContext;
import com.malhartech.api.Operator;
import com.malhartech.api.Operator.InputPort;
import com.malhartech.api.Operator.Unifier;
import com.malhartech.api.PartitionableOperator;
import com.malhartech.api.PartitionableOperator.Partition;
import com.malhartech.api.PartitionableOperator.PartitionKeys;
import com.malhartech.engine.DefaultUnifier;
import com.malhartech.stram.OperatorPartitions.PartitionImpl;
import com.malhartech.stram.plan.logical.LogicalPlan;
import com.malhartech.stram.plan.logical.Operators;
import com.malhartech.stram.plan.logical.LogicalPlan.InputPortMeta;
import com.malhartech.stram.plan.logical.LogicalPlan.OperatorMeta;
import com.malhartech.stram.plan.logical.LogicalPlan.StreamMeta;
import com.malhartech.stram.plan.logical.Operators.PortMappingDescriptor;
/**
* Translates the logical DAG into physical model. Is the initial query planner
* and performs dynamic changes.
* <p>
* Attributes in the logical DAG affect how the physical plan is derived.
* Examples include partitioning schemes, resource allocation, recovery
* semantics etc.<br>
*
* The current implementation does not dynamically change or optimize allocation
* of containers. The maximum number of containers and container size can be
* specified per application, but all containers are requested at the same size
* and execution will block until all containers were allocated by the resource
* manager. Future enhancements will allow to define resource constraints at the
* operator level and elasticity in resource allocation.<br>
*/
public class PhysicalPlan {
private final static Logger LOG = LoggerFactory.getLogger(PhysicalPlan.class);
/**
* Common abstraction for physical DAG nodes.<p>
* <br>
*
*/
public abstract static class PTComponent {
PTContainer container;
abstract int getId();
/**
*
* @return String
*/
abstract public String getLogicalId();
public PTContainer getContainer() {
return container;
}
}
/**
*
* Representation of an input in the physical layout. A source in the DAG<p>
* <br>
*/
public static class PTInput {
final LogicalPlan.StreamMeta logicalStream;
final PTComponent target;
final PartitionKeys partitions;
final PTOutput source;
final String portName;
/**
*
* @param portName
* @param logicalStream
* @param target
* @param partitions
* @param source
*/
protected PTInput(String portName, StreamMeta logicalStream, PTComponent target, PartitionKeys partitions, PTOutput source) {
this.logicalStream = logicalStream;
this.target = target;
this.partitions = partitions;
this.source = source;
this.portName = portName;
this.source.sinks.add(this);
}
/**
*
* @return String
*/
@Override
public String toString() {
return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE).
append("target", this.target).
append("port", this.portName).
append("stream", this.logicalStream.getId()).
toString();
}
}
/**
*
* Representation of an output in the physical layout. A sink in the DAG<p>
* <br>
*/
public static class PTOutput {
final LogicalPlan.StreamMeta logicalStream;
final PTComponent source;
final String portName;
final PhysicalPlan plan;
final List<PTInput> sinks;
/**
* Constructor
* @param plan
* @param portName
* @param logicalStream
* @param source
*/
protected PTOutput(PhysicalPlan plan, String portName, StreamMeta logicalStream, PTComponent source) {
this.plan = plan;
this.logicalStream = logicalStream;
this.source = source;
this.portName = portName;
this.sinks = new ArrayList<PTInput>();
}
/**
* Determine whether downstream operators are deployed inline.
* (all instances of the downstream operator are in the same container)
* @return boolean
*/
protected boolean isDownStreamInline() {
for (PTInput sink : this.sinks) {
if (this.source.container != sink.target.container) {
return false;
}
}
return true;
}
/**
*
* @return String
*/
@Override
public String toString() {
return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE).
append("source", this.source).
append("port", this.portName).
append("stream", this.logicalStream.getId()).
toString();
}
}
public static interface StatsHandler {
// TODO: handle stats generically
public void onThroughputUpdate(PTOperator operatorInstance, long tps);
public void onCpuPercentageUpdate(PTOperator operatorInstance, double percentage);
}
/**
* Handler for partition load check.
* Used when throughput monitoring is configured.
*/
public static class PartitionLoadWatch implements StatsHandler {
protected long evalIntervalMillis = 30*1000;
private final long tpsMin;
private final long tpsMax;
private long lastEvalMillis;
private long lastTps = 0;
private final PMapping m;
private PartitionLoadWatch(PMapping mapping, long min, long max) {
this.m = mapping;
this.tpsMin = min;
this.tpsMax = max;
}
protected PartitionLoadWatch(PMapping mapping) {
this(mapping, 0, 0);
}
protected int getLoadIndicator(PTOperator operator, long tps) {
if ((tps < tpsMin && lastTps != 0) || tps > tpsMax) {
lastTps = tps;
return (tps < tpsMin) ? -1 : 1;
}
lastTps = tps;
return 0;
}
@Override
public void onThroughputUpdate(final PTOperator operatorInstance, long tps) {
//LOG.debug("onThroughputUpdate {} {}", operatorInstance, tps);
operatorInstance.loadIndicator = getLoadIndicator(operatorInstance, tps);
if (operatorInstance.loadIndicator != 0) {
if (lastEvalMillis < (System.currentTimeMillis() - evalIntervalMillis)) {
lastEvalMillis = System.currentTimeMillis();
synchronized (m) {
// concurrent heartbeat processing
if (m.shouldRedoPartitions) {
LOG.debug("Skipping partition update for {} tps: {}", operatorInstance, tps);
return;
}
m.shouldRedoPartitions = true;
LOG.debug("Scheduling partitioning update for {} {}", m.logicalOperator, operatorInstance.loadIndicator);
// hand over to monitor thread
Runnable r = new Runnable() {
@Override
public void run() {
operatorInstance.getPlan().redoPartitions(m);
synchronized (m) {
m.shouldRedoPartitions = false;
}
}
};
operatorInstance.getPlan().ctx.dispatch(r);
}
}
}
}
@Override
public void onCpuPercentageUpdate(final PTOperator operatorInstance, double percentage) {
// not implemented yet
}
}
/**
* Determine operators that should be deployed into the execution environment.
* Operators can be deployed once all containers are running and any pending
* undeploy operations are complete.
* @param c
* @return
*/
public Set<PTOperator> getOperatorsForDeploy(PTContainer c) {
for (PTContainer otherContainer : this.containers) {
if (otherContainer != c && (otherContainer.state != PTContainer.State.ACTIVE || !otherContainer.pendingUndeploy.isEmpty())) {
LOG.debug("{}({}) unsatisfied dependency: {}({}) undeploy: {}", new Object[] {c.containerId, c.state, otherContainer.containerId, otherContainer.state, otherContainer.pendingUndeploy.size()});
return Collections.emptySet();
}
}
return c.pendingDeploy;
}
/**
*
* Representation of an operator in the physical layout<p>
* <br>
*
*/
public static class PTOperator extends PTComponent {
public enum State {
NEW,
PENDING_DEPLOY,
ACTIVE,
PENDING_UNDEPLOY,
INACTIVE,
REMOVED
}
PTOperator(PhysicalPlan plan, int id, String name) {
this.plan = plan;
this.name = name;
this.id = id;
}
private State state = State.NEW;
private final PhysicalPlan plan;
private LogicalPlan.OperatorMeta logicalNode;
private final int id;
private final String name;
Partition<?> partition;
Operator merge;
List<PTInput> inputs;
List<PTOutput> outputs;
final LinkedList<Long> checkpointWindows = new LinkedList<Long>();
long recoveryCheckpoint = 0;
int failureCount = 0;
int loadIndicator = 0;
List<? extends StatsHandler> statsMonitors;
private enum LocalityType {
CONTAINER_LOCAL,
NODE_LOCAL,
RACK_LOCAL
}
private final Map<LocalityType, Set<PTOperator>> groupings = Maps.newHashMapWithExpectedSize(3);
List<StreamingContainerUmbilicalProtocol.StramToNodeRequest> deployRequests = Collections.emptyList();
final HashMap<InputPortMeta, PTOperator> upstreamMerge = new HashMap<InputPortMeta, PTOperator>();
/**
*
* @return Operator
*/
public OperatorMeta getOperatorMeta() {
return this.logicalNode;
}
public State getState() {
return state;
}
public void setState(State state) {
this.state = state;
}
/**
* Return the most recent checkpoint for this operator,
* representing the last backup reported.
* @return long
*/
public long getRecentCheckpoint() {
if (checkpointWindows != null && !checkpointWindows.isEmpty()) {
return checkpointWindows.getLast();
}
return 0;
}
/**
* Return the checkpoint that can be used for recovery. This may not be the
* most recent checkpoint, depending on downstream state.
*
* @return long
*/
public long getRecoveryCheckpoint() {
return recoveryCheckpoint;
}
/**
*
* @return String
*/
@Override
public String getLogicalId() {
return logicalNode.getId();
}
@Override
public int getId() {
return id;
}
public String getName() {
return name;
}
public PhysicalPlan getPlan() {
return plan;
}
public Partition<?> getPartition() {
return partition;
}
private Set<PTOperator> getGrouping(LocalityType type) {
Set<PTOperator> s = this.groupings.get(type);
if (s == null) {
s = Sets.newHashSet();
this.groupings.put(type, s);
}
return s;
}
public Set<PTOperator> getNodeLocalOperators() {
return getGrouping(LocalityType.NODE_LOCAL);
}
/**
*
* @return String
*/
@Override
public String toString() {
return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE).
append("id", id).
append("name", name).
toString();
}
}
/**
*
* Representation of a container for physical objects of DAG to be placed in
* <p>
* <br>
* References the actual container assigned by the resource manager which
* hosts the streaming operators in the execution layer.<br>
* The container reference may change throughout the lifecycle of the
* application due to failure/recovery or scheduler decisions in general. <br>
*
*/
public static class PTContainer {
public enum State {
NEW,
ALLOCATED,
ACTIVE,
TIMEDOUT,
KILLED
}
private State state = State.NEW;
private int requiredMemoryMB;
private int allocatedMemoryMB;
private int resourceRequestPriority;
List<PTOperator> operators = new ArrayList<PTOperator>();
Set<PTOperator> pendingUndeploy = Collections.newSetFromMap(new ConcurrentHashMap<PTOperator, Boolean>());
Set<PTOperator> pendingDeploy = Collections.newSetFromMap(new ConcurrentHashMap<PTOperator, Boolean>());
String containerId; // assigned yarn container id
String host;
InetSocketAddress bufferServerAddress;
int restartAttempts;
final PhysicalPlan plan;
private final int seq;
PTContainer(PhysicalPlan plan) {
this.plan = plan;
this.seq = plan.containerSeq.incrementAndGet();
}
public State getState() {
return this.state;
}
public void setState(State state) {
this.state = state;
}
public int getRequiredMemoryMB() {
return requiredMemoryMB;
}
public void setRequiredMemoryMB(int requiredMemoryMB) {
this.requiredMemoryMB = requiredMemoryMB;
}
public int getAllocatedMemoryMB() {
return allocatedMemoryMB;
}
public void setAllocatedMemoryMB(int allocatedMemoryMB) {
this.allocatedMemoryMB = allocatedMemoryMB;
}
public int getResourceRequestPriority() {
return resourceRequestPriority;
}
public void setResourceRequestPriority(int resourceRequestPriority) {
this.resourceRequestPriority = resourceRequestPriority;
}
/**
*
* @return String
*/
@Override
public String toString() {
return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE).
append("id", ""+seq + "(" + this.containerId + ")").
append("state", this.getState()).
append("operators", this.operators).
toString();
}
}
private final AtomicInteger idSequence = new AtomicInteger();
private final AtomicInteger containerSeq = new AtomicInteger();
private final LinkedHashMap<OperatorMeta, PMapping> logicalToPTOperator = new LinkedHashMap<OperatorMeta, PMapping>();
private final List<PTContainer> containers = new CopyOnWriteArrayList<PTContainer>();
private final LogicalPlan dag;
private final PlanContext ctx;
private int maxContainers = 1;
private final LocalityPrefs localityPrefs = new LocalityPrefs();
private final LocalityPrefs inlinePrefs = new LocalityPrefs();
private PTContainer getContainer(int index) {
if (index >= containers.size()) {
if (index >= maxContainers) {
index = maxContainers - 1;
}
for (int i=containers.size(); i<index+1; i++) {
containers.add(i, new PTContainer(this));
}
}
return containers.get(index);
}
/**
* Interface to execution context that can be mocked for plan testing.
*/
public interface PlanContext {
/**
* Dynamic partitioning requires access to operator state for split or merge.
* @return
*/
public BackupAgent getBackupAgent();
/**
* Request deployment change as sequence of undeploy, container start and deploy groups with dependency.
* Called on initial plan and on dynamic changes during execution.
*/
public void deploy(Set<PTContainer> releaseContainers, Collection<PTOperator> undeploy, Set<PTContainer> startContainers, Collection<PTOperator> deploy);
/**
* Trigger event to perform plan modification.
* @param r
*/
public void dispatch(Runnable r);
}
/**
* The logical operator with physical plan info tagged on.
*/
public static class PMapping {
private PMapping(OperatorMeta om) {
this.logicalOperator = om;
}
final private OperatorMeta logicalOperator;
private List<PTOperator> partitions = new LinkedList<PTOperator>();
private Map<LogicalPlan.OutputPortMeta, PTOperator> mergeOperators = new HashMap<LogicalPlan.OutputPortMeta, PTOperator>();
volatile private boolean shouldRedoPartitions = false;
private List<StatsHandler> statsHandlers;
/**
* Operators that form a parallel partition
*/
private Set<OperatorMeta> parallelPartitions = Sets.newHashSet();
private void addPartition(PTOperator p) {
partitions.add(p);
p.statsMonitors = this.statsHandlers;
}
private Collection<PTOperator> getAllOperators() {
if (partitions.size() == 1) {
return Collections.singletonList(partitions.get(0));
}
Collection<PTOperator> c = new ArrayList<PTOperator>(partitions.size() + 1);
c.addAll(partitions);
for (PTOperator out : mergeOperators.values()) {
c.add(out);
}
return c;
}
private boolean isPartitionable() {
int partitionCnt = logicalOperator.getAttributes().attrValue(OperatorContext.INITIAL_PARTITION_COUNT, 0);
return (partitionCnt > 0);
}
@Override
public String toString() {
return logicalOperator.toString();
}
}
private class LocalityPref {
String host;
Set<PMapping> operators = Sets.newHashSet();
}
private class LocalityPrefs {
private final Map<PMapping, LocalityPref> prefs = Maps.newHashMap();
private final AtomicInteger groupSeq = new AtomicInteger();
void add(PMapping m, String group) {
if (group != null) {
LocalityPref pref = null;
for (LocalityPref lp : prefs.values()) {
if (group.equals(lp.host)) {
lp.operators.add(m);
pref = lp;
break;
}
}
if (pref == null) {
pref = new LocalityPref();
pref.host = group;
pref.operators.add(m);
this.prefs.put(m, pref);
}
}
}
void setLocal(PMapping m1, PMapping m2) {
LocalityPref lp1 = prefs.get(m1);
LocalityPref lp2 = prefs.get(m2);
if (lp1 == null && lp2 == null) {
lp1 = lp2 = new LocalityPref();
lp1.host = "host" + groupSeq.incrementAndGet();
lp1.operators.add(m1);
lp1.operators.add(m2);
} else if (lp1 != null && lp2 != null) {
// check if we can combine
if (StringUtils.equals(lp1.host, lp2.host)) {
lp1.operators.addAll(lp2.operators);
lp2.operators.addAll(lp1.operators);
} else {
LOG.warn("Node locality conflict {} {}", m1, m2);
}
} else {
if (lp1 == null) {
lp2.operators.add(m1);
lp1 = lp2;
} else {
lp1.operators.add(m2);
lp2 = lp1;
}
}
prefs.put(m1, lp1);
prefs.put(m2, lp2);
}
}
/**
*
* @param dag
* @param ctx
*/
public PhysicalPlan(LogicalPlan dag, PlanContext ctx) {
this.dag = dag;
this.ctx = ctx;
this.maxContainers = Math.max(dag.getMaxContainerCount(),1);
LOG.debug("Initializing for {} containers.", this.maxContainers);
Stack<OperatorMeta> pendingNodes = new Stack<OperatorMeta>();
for (OperatorMeta n : dag.getAllOperators()) {
pendingNodes.push(n);
}
while (!pendingNodes.isEmpty()) {
OperatorMeta n = pendingNodes.pop();
if (this.logicalToPTOperator.containsKey(n)) {
// already processed as upstream dependency
continue;
}
boolean upstreamDeployed = true;
for (StreamMeta s : n.getInputStreams().values()) {
if (s.getSource() != null && !this.logicalToPTOperator.containsKey(s.getSource().getOperatorWrapper())) {
pendingNodes.push(n);
pendingNodes.push(s.getSource().getOperatorWrapper());
upstreamDeployed = false;
break;
}
}
if (upstreamDeployed) {
addLogicalOperator(n);
}
}
// assign operators to containers
int groupCount = 0;
Set<PTOperator> deployOperators = Sets.newHashSet();
for (Map.Entry<OperatorMeta, PMapping> e : logicalToPTOperator.entrySet()) {
for (PTOperator oper : e.getValue().getAllOperators()) {
if (oper.container == null) {
PTContainer container = getContainer((groupCount++) % maxContainers);
Set<PTOperator> inlineSet = oper.getGrouping(PTOperator.LocalityType.CONTAINER_LOCAL);
if (!inlineSet.isEmpty()) {
// process inline operators
for (PTOperator inlineOper : inlineSet) {
setContainer(inlineOper, container);
}
} else {
setContainer(oper, container);
}
deployOperators.addAll(container.operators);
}
}
}
// request initial deployment
ctx.deploy(Collections.<PTContainer>emptySet(), Collections.<PTOperator>emptySet(), Sets.newHashSet(containers), deployOperators);
}
private void setContainer(PTOperator pOperator, PTContainer container) {
LOG.debug("Setting container {} for {}", container, pOperator);
assert (pOperator.container == null) : "Container already assigned for " + pOperator;
pOperator.container = container;
container.operators.add(pOperator);
if (!pOperator.upstreamMerge.isEmpty()) {
for (Map.Entry<InputPortMeta, PTOperator> mEntry : pOperator.upstreamMerge.entrySet()) {
mEntry.getValue().container = container;
container.operators.add(mEntry.getValue());
}
}
}
private void initPartitioning(PMapping m) {
/*
* partitioning is enabled through initial count attribute.
* if the attribute is not present or set to zero, partitioning is off
*/
int partitionCnt = m.logicalOperator.getAttributes().attrValue(OperatorContext.INITIAL_PARTITION_COUNT, 0);
if (partitionCnt == 0) {
throw new AssertionError("operator not partitionable " + m.logicalOperator);
}
Operator operator = m.logicalOperator.getOperator();
Collection<Partition<?>> partitions = new ArrayList<Partition<?>>(1);
if (operator instanceof PartitionableOperator) {
// operator to provide initial partitioning
partitions.add(new PartitionImpl(operator));
partitions = ((PartitionableOperator)operator).definePartitions(partitions, partitionCnt - 1);
}
else {
partitions = new OperatorPartitions.DefaultPartitioner().defineInitialPartitions(m.logicalOperator, partitionCnt);
}
if (partitions == null || partitions.isEmpty()) {
throw new IllegalArgumentException("PartitionableOperator must return at least one partition: " + m.logicalOperator);
}
int minTps = m.logicalOperator.getAttributes().attrValue(OperatorContext.PARTITION_TPS_MIN, 0);
int maxTps = m.logicalOperator.getAttributes().attrValue(OperatorContext.PARTITION_TPS_MAX, 0);
if (maxTps > minTps) {
// monitor load
if (m.statsHandlers == null) {
m.statsHandlers = new ArrayList<StatsHandler>(1);
}
m.statsHandlers.add(new PartitionLoadWatch(m, minTps, maxTps));
}
String handlers = m.logicalOperator.getAttributes().attrValue(OperatorContext.PARTITION_STATS_HANDLER, null);
if (handlers != null) {
if (m.statsHandlers == null) {
m.statsHandlers = new ArrayList<StatsHandler>(1);
}
Class<? extends StatsHandler> shClass = StramUtils.classForName(handlers, StatsHandler.class);
final StatsHandler sh;
if (PartitionLoadWatch.class.isAssignableFrom(shClass)) {
try {
sh = shClass.getConstructor(m.getClass()).newInstance(m);
}
catch (Exception e) {
throw new RuntimeException("Failed to create custom partition load handler.", e);
}
}
else {
sh = StramUtils.newInstance(shClass);
}
m.statsHandlers.add(sh);
}
// create operator instance per partition
for (Partition<?> p: partitions) {
addPTOperator(m, p);
}
}
private void redoPartitions(PMapping currentMapping) {
// collect current partitions with committed operator state
// those will be needed by the partitioner for split/merge
List<PTOperator> operators = currentMapping.partitions;
List<PartitionImpl> currentPartitions = new ArrayList<PartitionImpl>(operators.size());
Map<Partition<?>, PTOperator> currentPartitionMap = new HashMap<Partition<?>, PTOperator>(operators.size());
final Collection<Partition<?>> newPartitions;
long minCheckpoint = -1;
for (PTOperator pOperator : operators) {
Partition<?> p = pOperator.partition;
if (p == null) {
throw new AssertionError("Null partition: " + pOperator);
}
// load operator state
// the partitioning logic will have the opportunity to merge/split state
// since partitions checkpoint at different windows, processing for new or modified
// partitions will start from earliest checkpoint found (at least once semantics)
Operator partitionedOperator = p.getOperator();
if (pOperator.recoveryCheckpoint != 0) {
try {
LOG.debug("Loading state for {}", pOperator);
partitionedOperator = (Operator)ctx.getBackupAgent().restore(pOperator.id, pOperator.recoveryCheckpoint);
} catch (IOException e) {
LOG.warn("Failed to read partition state for " + pOperator, e);
return; // TODO: emit to event log
}
}
if (minCheckpoint < 0) {
minCheckpoint = pOperator.recoveryCheckpoint;
} else {
minCheckpoint = Math.min(minCheckpoint, pOperator.recoveryCheckpoint);
}
// assume it does not matter which operator instance's port objects are referenced in mapping
PartitionImpl partition = new PartitionImpl(partitionedOperator, p.getPartitionKeys(), pOperator.loadIndicator);
currentPartitions.add(partition);
currentPartitionMap.put(partition, pOperator);
}
for (Map.Entry<Partition<?>, PTOperator> e : currentPartitionMap.entrySet()) {
LOG.debug("partition load: {} {} {}", new Object[] {e.getValue(), e.getKey().getPartitionKeys(), e.getKey().getLoad()});
}
if (currentMapping.logicalOperator.getOperator() instanceof PartitionableOperator) {
// would like to know here how much more capacity we have here so that definePartitions can act accordingly.
final int incrementalCapacity = 0;
newPartitions = ((PartitionableOperator)currentMapping.logicalOperator.getOperator()).definePartitions(currentPartitions, incrementalCapacity);
} else {
newPartitions = new OperatorPartitions.DefaultPartitioner().repartition(currentPartitions);
}
List<Partition<?>> addedPartitions = new ArrayList<Partition<?>>();
// determine modifications of partition set, identify affected operator instance(s)
for (Partition<?> newPartition : newPartitions) {
PTOperator op = currentPartitionMap.remove(newPartition);
if (op == null) {
addedPartitions.add(newPartition);
} else {
// check whether mapping was changed
for (PartitionImpl pi : currentPartitions) {
if (pi == newPartition && pi.isModified()) {
// existing partition changed (operator or partition keys)
// remove/add to update subscribers and state
currentPartitionMap.put(newPartition, op);
addedPartitions.add(newPartition);
}
}
}
}
Set<PTOperator> undeployOperators = new HashSet<PTOperator>();
Set<PTOperator> deployOperators = new HashSet<PTOperator>();
// remaining entries represent deprecated partitions
undeployOperators.addAll(currentPartitionMap.values());
// resolve dependencies that require redeploy
undeployOperators = this.getDependents(undeployOperators);
// plan updates start here, after all changes were identified
// remove obsolete operators first, any freed resources
// can subsequently be used for new/modified partitions
PMapping newMapping = new PMapping(currentMapping.logicalOperator);
newMapping.partitions.addAll(currentMapping.partitions);
newMapping.mergeOperators.putAll(currentMapping.mergeOperators);
newMapping.statsHandlers = currentMapping.statsHandlers;
// remove deprecated partitions from plan
for (PTOperator p : currentPartitionMap.values()) {
newMapping.partitions.remove(p);
removePartition(p, currentMapping.parallelPartitions);
}
// keep mapping reference as that is where stats monitors point to
currentMapping.mergeOperators = newMapping.mergeOperators;
currentMapping.partitions = newMapping.partitions;
// add new operators after cleanup complete
Set<PTContainer> newContainers = Sets.newHashSet();
Set<PTOperator> newOperators = Sets.newHashSet();
for (Partition<?> newPartition : addedPartitions) {
// new partition, add operator instance
PTOperator p = addPTOperator(currentMapping, newPartition);
newOperators.add(p);
deployOperators.add(p);
initCheckpoint(p, newPartition.getOperator(), minCheckpoint);
for (PTOperator unifier : p.upstreamMerge.values()) {
deployOperators.add(unifier);
initCheckpoint(unifier, unifier.merge, minCheckpoint);
}
// handle parallel partition
Stack<OperatorMeta> pending = new Stack<LogicalPlan.OperatorMeta>();
pending.addAll(currentMapping.parallelPartitions);
pendingLoop:
while (!pending.isEmpty()) {
OperatorMeta pp = pending.pop();
for (StreamMeta s : pp.getInputStreams().values()) {
if (currentMapping.parallelPartitions.contains(s.getSource().getOperatorWrapper()) && pending.contains(s.getSource().getOperatorWrapper())) {
pending.push(pp);
pending.remove(s.getSource().getOperatorWrapper());
pending.push(s.getSource().getOperatorWrapper());
continue pendingLoop;
}
}
LOG.debug("Adding to parallel partition {}", pp);
PTOperator ppOper = addPTOperator(this.logicalToPTOperator.get(pp), null);
// even though we don't track state for parallel partitions
// set recovery windowId to play with upstream checkpoints
initCheckpoint(ppOper, pp.getOperator(), minCheckpoint);
newOperators.add(ppOper);
}
}
assignContainers(newOperators, newContainers);
Set<PTContainer> releaseContainers = Sets.newHashSet();
// release containers that are no longer used
for (PTContainer c : this.containers) {
if (c.operators.isEmpty()) {
LOG.debug("Container {} to be released", c);
releaseContainers.add(c);
containers.remove(c);
}
}
deployOperators = this.getDependents(deployOperators);
containers.addAll(newContainers);
ctx.deploy(releaseContainers, undeployOperators, newContainers, deployOperators);
}
public void assignContainers(Set<PTOperator> newOperators, Set<PTContainer> newContainers) {
// assign containers to new operators
for (PTOperator oper : newOperators) {
PTContainer newContainer = null;
// check for existing inline set
for (PTOperator inlineOper : oper.getGrouping(PTOperator.LocalityType.CONTAINER_LOCAL)) {
if (inlineOper.container != null) {
newContainer = inlineOper.container;
break;
}
}
if (newContainer != null) {
setContainer(oper, newContainer);
continue;
}
// find container
PTContainer c = null;
if (c == null) {
c = findContainer(oper);
if (c == null) {
// get new container
LOG.debug("New container for partition: " + oper);
c = new PTContainer(this);
newContainers.add(c);
}
}
setContainer(oper, c);
}
}
private void initCheckpoint(PTOperator partition, Operator operator, long windowId) {
partition.checkpointWindows.add(windowId);
partition.recoveryCheckpoint = windowId;
try {
ctx.getBackupAgent().backup(partition.id, windowId, operator);
} catch (IOException e) {
// inconsistent state, no recovery option, requires shutdown
throw new IllegalStateException("Failed to write operator state after partition change " + partition, e);
}
}
/**
* Remove the given partition with any associated parallel partitions and
* per-partition unifiers.
*
* @param oper
* @return
*/
private void removePartition(PTOperator oper, Set<LogicalPlan.OperatorMeta> parallelPartitions) {
// remove any parallel partition
for (PTOutput out : oper.outputs) {
for (PTInput in : Lists.newArrayList(out.sinks)) {
for (LogicalPlan.InputPortMeta im : in.logicalStream.getSinks()) {
PMapping m = this.logicalToPTOperator.get(im.getOperatorWrapper());
if (m.parallelPartitions == parallelPartitions) {
// associated operator parallel partitioned
removePartition((PTOperator)in.target, parallelPartitions);
m.partitions.remove(in.target);
}
}
}
}
// remove the operator
removePTOperator(oper);
oper.container.operators.remove(oper); // TODO: thread safety
// per partition merge operators
if (!oper.upstreamMerge.isEmpty()) {
for (Map.Entry<InputPortMeta, PTOperator> mEntry : oper.upstreamMerge.entrySet()) {
removePTOperator(mEntry.getValue());
mEntry.getValue().container.operators.remove(mEntry.getValue());
}
}
}
private PTContainer findContainer(PTOperator oper) {
// TODO: find container based on utilization
for (PTContainer c : this.containers) {
if (c.operators.isEmpty() && c.getState() == PTContainer.State.ACTIVE) {
LOG.debug("Reusing existing container {} for {}", c, oper);
return c;
}
}
return null;
}
private Map<LogicalPlan.InputPortMeta, PartitionKeys> getPartitionKeys(PTOperator oper) {
if (oper.partition == null) {
return Collections.emptyMap();
}
HashMap<LogicalPlan.InputPortMeta, PartitionKeys> partitionKeys = Maps.newHashMapWithExpectedSize(oper.partition.getPartitionKeys().size());
Map<InputPort<?>, PartitionKeys> partKeys = oper.partition.getPartitionKeys();
for (Map.Entry<InputPort<?>, PartitionKeys> portEntry : partKeys.entrySet()) {
LogicalPlan.InputPortMeta pportMeta = oper.logicalNode.getMeta(portEntry.getKey());
if (pportMeta == null) {
throw new IllegalArgumentException("Invalid port reference " + portEntry);
}
partitionKeys.put(pportMeta, portEntry.getValue());
}
return partitionKeys;
}
private PTOperator addPTOperator(PMapping nodeDecl, Partition<?> partition) {
PTOperator pOperator = createInstance(nodeDecl, partition);
nodeDecl.addPartition(pOperator);
Map<LogicalPlan.InputPortMeta, PartitionKeys> partitionKeys = getPartitionKeys(pOperator);
for (Map.Entry<LogicalPlan.InputPortMeta, StreamMeta> inputEntry : nodeDecl.logicalOperator.getInputStreams().entrySet()) {
// find upstream node(s), (can be multiple partitions)
StreamMeta streamDecl = inputEntry.getValue();
if (streamDecl.getSource() != null) {
PMapping upstream = logicalToPTOperator.get(streamDecl.getSource().getOperatorWrapper());
Collection<PTOperator> upstreamNodes = upstream.partitions;
if (inputEntry.getKey().getAttributes().attrValue(PortContext.PARTITION_PARALLEL, false)) {
if (upstream.partitions.size() < nodeDecl.partitions.size()) {
throw new AssertionError("Number of partitions don't match in parallel mapping");
}
// pick upstream partition for new instance to attach to
upstreamNodes = Collections.singletonList(upstream.partitions.get(nodeDecl.partitions.size()-1));
}
else if (upstream.partitions.size() > 1) {
PTOperator mergeNode = upstream.mergeOperators.get(streamDecl.getSource());
if (mergeNode == null) {
// create the merge operator
Unifier<?> unifier = streamDecl.getSource().getUnifier();
if (unifier == null) {
LOG.debug("Using default unifier for {}", streamDecl.getSource());
unifier = new DefaultUnifier();
}
PortMappingDescriptor mergeDesc = new PortMappingDescriptor();
Operators.describe(unifier, mergeDesc);
if (mergeDesc.outputPorts.size() != 1) {
throw new IllegalArgumentException("Merge operator should have single output port, found: " + mergeDesc.outputPorts);
}
mergeNode = new PTOperator(this, idSequence.incrementAndGet(), upstream.logicalOperator.getId() + "#merge#" + streamDecl.getSource().getPortName());
mergeNode.logicalNode = upstream.logicalOperator;
mergeNode.inputs = new ArrayList<PTInput>();
mergeNode.outputs = new ArrayList<PTOutput>();
mergeNode.merge = unifier;
mergeNode.outputs.add(new PTOutput(this, mergeDesc.outputPorts.keySet().iterator().next(), streamDecl, mergeNode));
PartitionKeys pks = partitionKeys.get(inputEntry.getKey());
// add existing partitions as inputs
for (PTOperator upstreamInstance : upstream.partitions) {
for (PTOutput upstreamOut : upstreamInstance.outputs) {
if (upstreamOut.logicalStream == streamDecl) {
// merge operator input
PTInput input = new PTInput("<merge#" + streamDecl.getSource().getPortName() + ">", streamDecl, mergeNode, pks, upstreamOut);
mergeNode.inputs.add(input);
}
}
}
if (pks == null) {
upstream.mergeOperators.put(streamDecl.getSource(), mergeNode);
} else {
// NxM partitioning: create unifier per upstream partition
LOG.debug("Partitioned unifier for {} {} {}", new Object[] {pOperator, inputEntry.getKey().getPortName(), pks});
pOperator.upstreamMerge.put(inputEntry.getKey(), mergeNode);
}
}
upstreamNodes = Collections.singletonList(mergeNode);
}
for (PTOperator upNode : upstreamNodes) {
// link to upstream output(s) for this stream
for (PTOutput upstreamOut : upNode.outputs) {
if (upstreamOut.logicalStream == streamDecl) {
PartitionKeys pks = partitionKeys.get(inputEntry.getKey());
if (pOperator.upstreamMerge.containsKey(inputEntry.getKey())) {
pks = null; // partitions applied to unifier input
}
PTInput input = new PTInput(inputEntry.getKey().getPortName(), streamDecl, pOperator, pks, upstreamOut);
pOperator.inputs.add(input);
}
}
}
}
}
// update locality
setLocalityGrouping(nodeDecl, pOperator, inlinePrefs, PTOperator.LocalityType.CONTAINER_LOCAL);
setLocalityGrouping(nodeDecl, pOperator, localityPrefs, PTOperator.LocalityType.NODE_LOCAL);
return pOperator;
}
private PTOperator createInstance(PMapping mapping, Partition<?> partition) {
PTOperator pOperator = new PTOperator(this, idSequence.incrementAndGet(), mapping.logicalOperator.getId());
pOperator.logicalNode = mapping.logicalOperator;
pOperator.inputs = new ArrayList<PTInput>();
pOperator.outputs = new ArrayList<PTOutput>();
pOperator.partition = partition;
// output port objects - these could be deferred until inputs are connected
for (Map.Entry<LogicalPlan.OutputPortMeta, StreamMeta> outputEntry : mapping.logicalOperator.getOutputStreams().entrySet()) {
PTOutput out = new PTOutput(this, outputEntry.getKey().getPortName(), outputEntry.getValue(), pOperator);
pOperator.outputs.add(out);
PTOperator merge = mapping.mergeOperators.get(outputEntry.getKey());
if (merge != null) {
// dynamically added partitions need to feed into existing unifier
PTInput input = new PTInput("<merge#" + out.portName + ">", out.logicalStream, merge, null, out);
merge.inputs.add(input);
} else {
// non partitioned operator
List<InputPortMeta> inputs = outputEntry.getValue().getSinks();
for (InputPortMeta inputMeta : inputs) {
PMapping m = this.logicalToPTOperator.get(inputMeta.getOperatorWrapper());
if (m != null) {
// connect existing operators
for (PTOperator downstreamOper : m.partitions) {
Map<LogicalPlan.InputPortMeta, PartitionKeys> partitionKeys = getPartitionKeys(downstreamOper);
PartitionKeys pks = partitionKeys.get(inputMeta);
PTInput input = new PTInput(inputMeta.getPortName(), outputEntry.getValue(), downstreamOper, pks, out);
downstreamOper.inputs.add(input);
}
}
}
}
}
return pOperator;
}
private void setLocalityGrouping(PMapping pnodes, PTOperator newOperator, LocalityPrefs localityPrefs, PTOperator.LocalityType ltype) {
Set<PTOperator> s = newOperator.getGrouping(ltype);
s.add(newOperator);
LocalityPref loc = localityPrefs.prefs.get(pnodes);
if (loc != null) {
for (PMapping localPM : loc.operators) {
if (pnodes.parallelPartitions == localPM.parallelPartitions) {
if (localPM.partitions.size() >= pnodes.partitions.size()) {
// apply locality setting per partition
s.addAll(localPM.partitions.get(pnodes.partitions.size()-1).getGrouping(ltype));
}
} else {
for (PTOperator otherNode : localPM.partitions) {
s.addAll(otherNode.getGrouping(ltype));
}
}
}
for (PTOperator localOper : s) {
localOper.groupings.put(ltype, s);
}
}
}
private void removePTOperator(PTOperator node) {
LOG.debug("Removing operator " + node);
OperatorMeta nodeDecl = node.logicalNode;
PMapping mapping = logicalToPTOperator.get(node.logicalNode);
for (Map.Entry<LogicalPlan.OutputPortMeta, StreamMeta> outputEntry : nodeDecl.getOutputStreams().entrySet()) {
PTOperator merge = mapping.mergeOperators.get(outputEntry.getKey());
if (merge != null) {
List<PTInput> newInputs = new ArrayList<PTInput>(merge.inputs.size());
for (PTInput sinkIn : merge.inputs) {
if (sinkIn.source.source != node) {
newInputs.add(sinkIn);
}
}
merge.inputs = newInputs;
} else {
StreamMeta streamDecl = outputEntry.getValue();
for (LogicalPlan.InputPortMeta inp : streamDecl.getSinks()) {
List<PTOperator> sinkNodes = logicalToPTOperator.get(inp.getOperatorWrapper()).partitions;
for (PTOperator sinkNode : sinkNodes) {
// unlink from downstream operators
List<PTInput> newInputs = new ArrayList<PTInput>(sinkNode.inputs.size());
for (PTInput sinkIn : sinkNode.inputs) {
if (sinkIn.source.source != node) {
newInputs.add(sinkIn);
} else {
sinkIn.source.sinks.remove(sinkIn);
}
}
sinkNode.inputs = newInputs;
}
}
}
}
// remove from upstream operators
for (PTInput in : node.inputs) {
in.source.sinks.remove(in);
}
// remove checkpoint states
try {
for (long checkpointWindowId : node.checkpointWindows) {
ctx.getBackupAgent().delete(node.id, checkpointWindowId);
}
} catch (IOException e) {
LOG.warn("Failed to remove state for " + node, e);
}
}
public LogicalPlan getDAG() {
return this.dag;
}
protected List<PTContainer> getContainers() {
return this.containers;
}
public List<PTOperator> getOperators(OperatorMeta logicalOperator) {
return this.logicalToPTOperator.get(logicalOperator).partitions;
}
// used for testing only
protected Map<LogicalPlan.OutputPortMeta, PTOperator> getMergeOperators(OperatorMeta logicalOperator) {
return this.logicalToPTOperator.get(logicalOperator).mergeOperators;
}
protected List<OperatorMeta> getRootOperators() {
return dag.getRootOperators();
}
protected List<PTOperator> getAllOperators() {
List<PTOperator> list = new ArrayList<PTOperator>();
for (Map.Entry<OperatorMeta, PMapping> entry : logicalToPTOperator.entrySet()) {
list.addAll(entry.getValue().partitions);
}
return list;
}
private void getDeps(PTOperator operator, Set<PTOperator> visited) {
visited.add(operator);
for (PTInput in : operator.inputs) {
if (in.source.isDownStreamInline()) {
PTOperator sourceOperator = (PTOperator)in.source.source;
if (!visited.contains(sourceOperator)) {
getDeps(sourceOperator, visited);
}
}
}
// downstream traversal
for (PTOutput out: operator.outputs) {
for (PhysicalPlan.PTInput sink : out.sinks) {
PTOperator sinkOperator = (PTOperator)sink.target;
if (!visited.contains(sinkOperator)) {
getDeps(sinkOperator, visited);
}
}
}
}
/**
* Get all operator instances that depend on the specified operator instance(s).
* Dependencies are all downstream and upstream inline operators.
* @param operators
* @return
*/
public Set<PTOperator> getDependents(Collection<PTOperator> operators)
{
Set<PTOperator> visited = new LinkedHashSet<PTOperator>();
if (operators != null) {
for (PTOperator operator: operators) {
getDeps(operator, visited);
}
}
return visited;
}
/**
* Add logical operator to the plan. Assumes that upstream operators have been added before.
* @param om
*/
public void addLogicalOperator(OperatorMeta om) {
// ready to look at this node
PMapping pnodes = new PMapping(om);
localityPrefs.add(pnodes, pnodes.logicalOperator.getAttributes().attrValue(OperatorContext.LOCALITY_HOST, null));
PMapping upstreamPartitioned = null;
for (Map.Entry<LogicalPlan.InputPortMeta, StreamMeta> e : om.getInputStreams().entrySet()) {
PMapping m = logicalToPTOperator.get(e.getValue().getSource().getOperatorWrapper());
if (e.getKey().getAttributes().attrValue(PortContext.PARTITION_PARALLEL, false).equals(true)) {
// operator partitioned with upstream
if (upstreamPartitioned != null) {
// need to have common root
if (!upstreamPartitioned.parallelPartitions.contains(m.logicalOperator)) {
String msg = String.format("operator cannot extend multiple partitions (%s and %s)", upstreamPartitioned.logicalOperator, m.logicalOperator);
throw new AssertionError(msg);
}
}
m.parallelPartitions.add(pnodes.logicalOperator);
pnodes.parallelPartitions = m.parallelPartitions;
upstreamPartitioned = m;
}
if (e.getValue().isInline()) {
inlinePrefs.setLocal(m, pnodes);
} else if (e.getValue().isNodeLocal()) {
localityPrefs.setLocal(m, pnodes);
}
}
// create operator instances
if (pnodes.isPartitionable()) {
initPartitioning(pnodes);
} else {
if (upstreamPartitioned != null) {
// parallel partition
for (int i=0; i<upstreamPartitioned.partitions.size(); i++) {
addPTOperator(pnodes, null);
}
} else {
// single instance, no partitions
addPTOperator(pnodes, null);
}
}
this.logicalToPTOperator.put(om, pnodes);
}
} |
package erogenousbeef.core.multiblock;
import java.util.LinkedList;
import java.util.List;
import net.minecraft.block.material.Material;
import net.minecraft.client.Minecraft;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World;
import erogenousbeef.core.common.CoordTriplet;
/**
* This class contains the base logic for "multiblock controllers". You can think of them
* as meta-TileEntities. They govern the logic for an associated group of TileEntities.
*
* Subordinate TileEntities implement the IMultiblockPart class and, generally, should not have an update() loop.
*/
public abstract class MultiblockControllerBase {
// Multiblock stuff - do not mess with
protected World worldObj;
// Disassembled -> Assembled; Assembled -> Disassembled OR Paused; Paused -> Assembled
protected enum AssemblyState { Disassembled, Assembled, Paused };
protected AssemblyState assemblyState;
protected LinkedList<CoordTriplet> connectedBlocks;
/** This is a deterministically-picked coordinate that identifies this
* multiblock uniquely in its dimension.
* Currently, this is the coord with the lowest X, Y and Z coordinates, in that order of evaluation.
* i.e. If something has a lower X but higher Y/Z coordinates, it will still be the reference.
* If something has the same X but a lower Y coordinate, it will be the reference. Etc.
*/
protected CoordTriplet referenceCoord;
/**
* Minimum bounding box coordinate. Blocks do not necessarily exist at this coord if your machine
* is not a cube/rectangular prism.
*/
private CoordTriplet minimumCoord;
/**
* Maximum bounding box coordinate. Blocks do not necessarily exist at this coord if your machine
* is not a cube/rectangular prism.
*/
private CoordTriplet maximumCoord;
/**
* Set to true when adding/removing blocks to the controller.
* If true, the controller will check to see if the machine
* should be assembled/disassembled on the next tick.
*/
private boolean blocksHaveChangedThisFrame;
/**
* Set to true when all blocks unloading this frame are unloading due to
* chunk unloading.
*/
private boolean chunksHaveUnloaded;
protected MultiblockControllerBase(World world) {
// Multiblock stuff
worldObj = world;
connectedBlocks = new LinkedList<CoordTriplet>();
referenceCoord = null;
assemblyState = AssemblyState.Disassembled;
minimumCoord = new CoordTriplet(0,0,0);
maximumCoord = new CoordTriplet(0,0,0);
blocksHaveChangedThisFrame = false;
chunksHaveUnloaded = false;
}
/**
* Call when the save delegate block finishes loading its chunk.
* Immediately call attachBlock after this, or risk your multiblock
* being destroyed!
* @param savedData The NBT tag containing this controller's data.
*/
public void restore(NBTTagCompound savedData) {
this.readFromNBT(savedData);
MultiblockRegistry.register(this);
}
/**
* Check if a block is being tracked by this machine.
* @param blockCoord Coordinate to check.
* @return True if the tile entity at blockCoord is being tracked by this machine, false otherwise.
*/
public boolean hasBlock(CoordTriplet blockCoord) {
return connectedBlocks.contains(blockCoord);
}
/**
* Call this to attach a block to this machine. Generally, you want to call this when
* the block is added to the world.
* @param part The part representing the block to attach to this machine.
*/
public void attachBlock(IMultiblockPart part) {
IMultiblockPart candidate;
CoordTriplet coord = part.getWorldLocation();
boolean firstBlock = this.connectedBlocks.isEmpty();
// No need to re-add a block
if(connectedBlocks.contains(coord)) {
return;
}
connectedBlocks.add(coord);
part.onAttached(this);
this.onBlockAdded(part);
this.worldObj.markBlockForUpdate(coord.x, coord.y, coord.z);
if(firstBlock) {
MultiblockRegistry.register(this);
}
if(this.referenceCoord == null) {
referenceCoord = coord;
part.becomeMultiblockSaveDelegate();
}
else if(coord.compareTo(referenceCoord) < 0) {
TileEntity te = this.worldObj.getBlockTileEntity(referenceCoord.x, referenceCoord.y, referenceCoord.z);
((IMultiblockPart)te).forfeitMultiblockSaveDelegate();
referenceCoord = coord;
part.becomeMultiblockSaveDelegate();
}
blocksHaveChangedThisFrame = true;
}
/**
* Called when a new part is added to the machine. Good time to register things into lists.
* @param newPart The part being added.
*/
protected abstract void onBlockAdded(IMultiblockPart newPart);
/**
* Called when a part is removed from the machine. Good time to clean up lists.
* @param oldPart The part being removed.
*/
protected abstract void onBlockRemoved(IMultiblockPart oldPart);
/**
* Called when a machine is assembled from a disassembled state.
*/
protected abstract void onMachineAssembled();
/**
* Called when a machine is restored to the assembled state from a paused state.
*/
protected abstract void onMachineRestored();
/**
* Called when a machine is paused from an assembled state
* This generally only happens due to chunk-loads and other "system" events.
*/
protected abstract void onMachinePaused();
/**
* Called when a machine is disassembled from an assembled state.
* This happens due to user or in-game actions (e.g. explosions)
*/
protected abstract void onMachineDisassembled();
/**
* Call to detach a block from this machine. Generally, this should be called
* when the tile entity is being released, e.g. on block destruction.
* @param part The part to detach from this machine.
* @param chunkUnloading Is this entity detaching due to the chunk unloading? If true, the multiblock will be paused instead of broken.
*/
public void detachBlock(IMultiblockPart part, boolean chunkUnloading) {
_detachBlock(part, chunkUnloading);
// If we've lost blocks while disassembled, split up our machine. Can result in up to 6 new TEs.
if(!chunkUnloading && this.assemblyState == AssemblyState.Disassembled) {
this.revisitBlocks();
}
}
/**
* Internal helper that can be safely called for internal use
* Does not trigger fission.
* @param part The part to detach from this machine.
* @param chunkUnloading Is this entity detaching due to the chunk unloading? If true, the multiblock will be paused instead of broken.
*/
private void _detachBlock(IMultiblockPart part, boolean chunkUnloading) {
CoordTriplet coord = part.getWorldLocation();
if(chunkUnloading) {
if(this.assemblyState == AssemblyState.Assembled) {
this.assemblyState = AssemblyState.Paused;
this.onMachinePaused();
}
}
if(connectedBlocks.contains(coord)) {
part.onDetached(this);
}
while(connectedBlocks.contains(coord))
{
connectedBlocks.remove(coord);
this.onBlockRemoved(part);
if(referenceCoord != null && referenceCoord.equals(coord)) {
part.forfeitMultiblockSaveDelegate();
referenceCoord = null;
}
}
if(connectedBlocks.isEmpty()) {
// Destroy/unregister
MultiblockRegistry.unregister(this);
return;
}
if(!blocksHaveChangedThisFrame && chunkUnloading) {
// If the first change this frame is a chunk unload, set to true.
this.chunksHaveUnloaded = true;
}
else if(this.chunksHaveUnloaded) {
// If we get multiple unloads in a frame, any one of them being false flips this false too.
this.chunksHaveUnloaded = chunkUnloading;
}
blocksHaveChangedThisFrame = true;
this.recalculateMinMaxCoords();
// Find new save delegate if we need to.
if(referenceCoord == null) {
// ConnectedBlocks can be empty due to chunk unloading. This is OK. We'll die next frame.
if(!this.connectedBlocks.isEmpty()) {
for(CoordTriplet connectedCoord : connectedBlocks) {
TileEntity te = this.worldObj.getBlockTileEntity(connectedCoord.x, connectedCoord.y, connectedCoord.z);
if(te == null) { continue; } // Chunk unload has removed this block. It'll get hit soon. Ignore it.
if(referenceCoord == null) {
referenceCoord = connectedCoord;
}
else if(connectedCoord.compareTo(referenceCoord) < 0) {
referenceCoord = connectedCoord;
}
}
}
if(referenceCoord != null) {
TileEntity te = this.worldObj.getBlockTileEntity(referenceCoord.x, referenceCoord.y, referenceCoord.z);
((IMultiblockPart)te).becomeMultiblockSaveDelegate();
}
}
}
/**
* Helper method so we don't check for a whole machine until we have enough blocks
* to actually assemble it. This isn't as simple as xmax*ymax*zmax for non-cubic machines
* or for machines with hollow/complex interiors.
* @return The minimum number of blocks connected to the machine for it to be assembled.
*/
protected abstract int getMinimumNumberOfBlocksForAssembledMachine();
/**
* @return True if the machine is "whole" and should be assembled. False otherwise.
*/
protected boolean isMachineWhole() {
if(connectedBlocks.size() >= getMinimumNumberOfBlocksForAssembledMachine()) {
// Now we run a simple check on each block within that volume.
// Any block deviating = NO DEAL SIR
TileEntity te;
IMultiblockPart part;
boolean dealbreaker = false;
for(int x = minimumCoord.x; !dealbreaker && x <= maximumCoord.x; x++) {
for(int y = minimumCoord.y; !dealbreaker && y <= maximumCoord.y; y++) {
for(int z = minimumCoord.z; !dealbreaker && z <= maximumCoord.z; z++) {
// Okay, figure out what sort of block this should be.
te = this.worldObj.getBlockTileEntity(x, y, z);
if(te != null && te instanceof IMultiblockPart) {
part = (IMultiblockPart)te;
}
else {
part = null;
}
// Validate block type against both part-level and material-level validators.
int extremes = 0;
if(x == minimumCoord.x) { extremes++; }
if(y == minimumCoord.y) { extremes++; }
if(z == minimumCoord.z) { extremes++; }
if(x == maximumCoord.x) { extremes++; }
if(y == maximumCoord.y) { extremes++; }
if(z == maximumCoord.z) { extremes++; }
if(extremes >= 2) {
if(part != null && !part.isGoodForFrame()) {
dealbreaker = true;
}
else if(part == null && !isBlockGoodForFrame(this.worldObj, x, y, z)) {
dealbreaker = true;
}
}
else if(extremes == 1) {
if(y == maximumCoord.y) {
if(part != null && !part.isGoodForTop()) {
dealbreaker = true;
}
else if(part == null & !isBlockGoodForTop(this.worldObj, x, y, z)) {
dealbreaker = true;
}
}
else if(y == minimumCoord.y) {
if(part != null && !part.isGoodForBottom()) {
dealbreaker = true;
}
else if(part == null & !isBlockGoodForBottom(this.worldObj, x, y, z)) {
dealbreaker = true;
}
}
else {
// Side
if(part != null && !part.isGoodForSides()) {
dealbreaker = true;
}
else if(part == null & !isBlockGoodForSides(this.worldObj, x, y, z)) {
dealbreaker = true;
}
}
}
else {
if(part != null && !part.isGoodForInterior()) {
dealbreaker = true;
}
else if(part == null & !isBlockGoodForInterior(this.worldObj, x, y, z)) {
dealbreaker = true;
}
}
}
}
}
return !dealbreaker;
}
return false;
}
/**
* Check if the machine is whole or not.
* If the machine was not whole, but now is, assemble the machine.
* If the machine was whole, but no longer is, disassemble the machine.
*/
protected void checkIfMachineIsWhole() {
AssemblyState oldState = this.assemblyState;
boolean isWhole = isMachineWhole();
if(isWhole) {
// This will alter assembly state
this.assemblyState = AssemblyState.Assembled;
assembleMachine(oldState);
}
else if(oldState == AssemblyState.Assembled) {
// This will alter assembly state
this.assemblyState = AssemblyState.Disassembled;
disassembleMachine();
}
// Else Paused, do nothing
}
/**
* Called when a machine becomes "whole" and should begin
* functioning as a game-logically finished machine.
* Calls onMachineAssembled on all attached parts.
*/
private void assembleMachine(AssemblyState oldState) {
TileEntity te;
for(CoordTriplet coord : connectedBlocks) {
te = this.worldObj.getBlockTileEntity(coord.x, coord.y, coord.z);
if(te instanceof IMultiblockPart) {
((IMultiblockPart)te).onMachineAssembled();
}
}
if(oldState == assemblyState.Paused) {
onMachineRestored();
}
else {
onMachineAssembled();
}
}
/**
* Called when the machine needs to be disassembled.
* It is not longer "whole" and should not be functional, usually
* as a result of a block being removed.
* Calls onMachineBroken on all attached parts.
*/
private void disassembleMachine() {
TileEntity te;
for(CoordTriplet coord : connectedBlocks) {
te = this.worldObj.getBlockTileEntity(coord.x, coord.y, coord.z);
if(te instanceof IMultiblockPart) {
((IMultiblockPart)te).onMachineBroken();
}
}
onMachineDisassembled();
}
/**
* Called when the machine is paused, generally due to chunk unloads or merges.
* This should perform any machine-halt cleanup logic, but not change any user
* settings.
* Calls onMachineBroken on all attached parts.
*/
private void pauseMachine() {
TileEntity te;
for(CoordTriplet coord : connectedBlocks) {
te = this.worldObj.getBlockTileEntity(coord.x, coord.y, coord.z);
if(te instanceof IMultiblockPart) {
((IMultiblockPart)te).onMachineBroken();
}
}
onMachinePaused();
}
/**
* Called before other machines are merged into this one.
*/
public void beginMerging() { }
/**
* Merge another controller into this controller.
* Acquire all of the other controller's blocks and attach them
* to this machine.
*
* NOTE: endMerging MUST be called after 1 or more merge calls!
*
* @param other The controller to merge into this one.
* {@link erogenousbeef.core.multiblock.MultiblockControllerBase#endMerging()}
*/
public void merge(MultiblockControllerBase other) {
if(this.referenceCoord.compareTo(other.referenceCoord) >= 0) {
throw new IllegalArgumentException("The controller with the lowest minimum-coord value must consume the one with the higher coords");
}
TileEntity te;
List<CoordTriplet> blocksToAcquire = (LinkedList<CoordTriplet>)other.connectedBlocks.clone();
// releases all blocks and references gently so they can be incorporated into another multiblock
other.onMergedIntoOtherController(this);
IMultiblockPart acquiredPart;
for(CoordTriplet coord : blocksToAcquire) {
// By definition, none of these can be the minimum block.
this.connectedBlocks.add(coord);
te = this.worldObj.getBlockTileEntity(coord.x, coord.y, coord.z);
acquiredPart = (IMultiblockPart)te;
acquiredPart.onMergedIntoOtherMultiblock(this);
this.onBlockAdded(acquiredPart);
}
}
/**
* Called when this machine is consumed by another controller.
* Essentially, forcibly tear down this object.
* @param otherController The controller consuming this controller.
*/
private void onMergedIntoOtherController(MultiblockControllerBase otherController) {
this.pauseMachine();
if(referenceCoord != null) {
TileEntity te = this.worldObj.getBlockTileEntity(referenceCoord.x, referenceCoord.y, referenceCoord.z);
((IMultiblockPart)te).forfeitMultiblockSaveDelegate();
this.referenceCoord = null;
}
this.connectedBlocks.clear();
MultiblockRegistry.unregister(this);
this.onMachineMerge(otherController);
}
/**
* Callback. Called after this machine is consumed by another controller.
* This means all blocks have been stripped out of this object and
* handed over to the other controller.
* @param otherMachine The machine consuming this controller.
*/
protected abstract void onMachineMerge(MultiblockControllerBase otherMachine);
/**
* Called after all multiblock machine merges have been completed for
* this machine.
*/
public void endMerging() {
this.recalculateMinMaxCoords();
}
/**
* The update loop! Implement the game logic you would like to execute
* on every world tick here. Note that this only executes on the server,
* so you will need to send updates to the client manually.
*/
public final void updateMultiblockEntity() {
if(this.connectedBlocks.isEmpty()) {
MultiblockRegistry.unregister(this);
return;
}
if(this.blocksHaveChangedThisFrame) {
// Assemble/break machine if we have to
checkIfMachineIsWhole();
this.blocksHaveChangedThisFrame = false;
}
if(this.assemblyState == AssemblyState.Assembled) {
update();
}
}
/**
* The update loop! Use this similarly to a TileEntity's update loop.
* You do not need to call your superclass' update() if you're directly
* derived from MultiblockControllerBase. This is a callback.
* Note that this will only be called when the machine is assembled.
*/
protected abstract void update();
/**
* Visits all blocks via a breadth-first walk of neighbors from the
* reference coordinate. If any blocks remain unvisited after this
* method is called, they are orphans and are split off the main
* machine.
*/
private void revisitBlocks() {
TileEntity te;
// Ensure that our current reference coord is valid. If not, invalidate it.
if(referenceCoord != null && this.worldObj.getBlockTileEntity(referenceCoord.x, referenceCoord.y, referenceCoord.z) == null) {
referenceCoord = null;
}
// Reset visitations and find the minimum coordinate
for(CoordTriplet c: connectedBlocks) {
te = this.worldObj.getBlockTileEntity(c.x, c.y, c.z);
if(te == null) { continue; } // This happens during chunk unload. Consider it valid, move on.
((IMultiblockPart)te).setUnvisited();
if(referenceCoord == null) {
referenceCoord = c;
}
else if(c.compareTo(referenceCoord) < 0) {
referenceCoord = c;
}
}
if(referenceCoord == null) {
// There are no valid parts remaining. This is due to a chunk unload. Halt.
return;
}
// Now visit all connected parts, breadth-first, starting from reference coord.
LinkedList<IMultiblockPart> partsToCheck = new LinkedList<IMultiblockPart>();
IMultiblockPart[] nearbyParts = null;
IMultiblockPart part = (IMultiblockPart)this.worldObj.getBlockTileEntity(referenceCoord.x, referenceCoord.y, referenceCoord.z);
partsToCheck.add(part);
while(!partsToCheck.isEmpty()) {
part = partsToCheck.removeFirst();
part.setVisited();
nearbyParts = part.getNeighboringParts();
for(IMultiblockPart nearbyPart : nearbyParts) {
// Ignore different machines
if(nearbyPart.getMultiblockController() != this) {
continue;
}
if(!nearbyPart.isVisited()) {
nearbyPart.setVisited();
partsToCheck.add(nearbyPart);
}
}
}
// First, remove any blocks that are still disconnected.
List<IMultiblockPart> orphans = new LinkedList<IMultiblockPart>();
for(CoordTriplet c : connectedBlocks) {
part = (IMultiblockPart)this.worldObj.getBlockTileEntity(c.x, c.y, c.z);
if(!part.isVisited()) {
orphans.add(part);
}
}
// Remove all orphaned parts. i.e. Actually orphan them.
for(IMultiblockPart orphan : orphans) {
this._detachBlock(orphan, false);
}
// Now go through and start up as many new machines as possible.
for(IMultiblockPart orphan : orphans) {
if(!orphan.isConnected()) {
// Creating a new multiblock should capture all other orphans connected to this orphan.
orphan.onOrphaned();
}
}
}
// Validation helpers
/**
* The "frame" consists of the outer edges of the machine, plus the corners.
*
* @param world World object for the world in which this controller is located.
* @param x X coordinate of the block being tested
* @param y Y coordinate of the block being tested
* @param z Z coordinate of the block being tested
* @return True if this block can be used as part of the frame.
*/
protected boolean isBlockGoodForFrame(World world, int x, int y, int z) {
return false;
}
/**
* The top consists of the top face, minus the edges.
* @param world World object for the world in which this controller is located.
* @param x X coordinate of the block being tested
* @param y Y coordinate of the block being tested
* @param z Z coordinate of the block being tested
* @return True if this block can be used as part of the top face.
*/
protected boolean isBlockGoodForTop(World world, int x, int y, int z) {
return false;
}
/**
* The bottom consists of the bottom face, minus the edges.
* @param world World object for the world in which this controller is located.
* @param x X coordinate of the block being tested
* @param y Y coordinate of the block being tested
* @param z Z coordinate of the block being tested
* @return True if this block can be used as part of the bottom face.
*/
protected boolean isBlockGoodForBottom(World world, int x, int y, int z) {
return false;
}
/**
* The sides consists of the N/E/S/W-facing faces, minus the edges.
* @param world World object for the world in which this controller is located.
* @param x X coordinate of the block being tested
* @param y Y coordinate of the block being tested
* @param z Z coordinate of the block being tested
* @return True if this block can be used as part of the sides.
*/
protected boolean isBlockGoodForSides(World world, int x, int y, int z) {
return false;
}
/**
* The interior is any block that does not touch blocks outside the machine.
* @param world World object for the world in which this controller is located.
* @param x X coordinate of the block being tested
* @param y Y coordinate of the block being tested
* @param z Z coordinate of the block being tested
* @return True if this block can be used as part of the sides.
*/
protected boolean isBlockGoodForInterior(World world, int x, int y, int z) {
return false;
}
/**
* @return The reference coordinate, the block with the lowest x, y, z coordinates, evaluated in that order.
*/
public CoordTriplet getReferenceCoord() { return referenceCoord; }
/**
* @return The number of blocks connected to this controller.
*/
public int getNumConnectedBlocks() { return connectedBlocks.size(); }
public abstract void writeToNBT(NBTTagCompound data);
public abstract void readFromNBT(NBTTagCompound data);
private void recalculateMinMaxCoords() {
minimumCoord.x = minimumCoord.y = minimumCoord.z = Integer.MAX_VALUE;
maximumCoord.x = maximumCoord.y = maximumCoord.z = Integer.MIN_VALUE;
for(CoordTriplet coord : connectedBlocks) {
if(coord.x < minimumCoord.x) { minimumCoord.x = coord.x; }
if(coord.x > maximumCoord.x) { maximumCoord.x = coord.x; }
if(coord.y < minimumCoord.y) { minimumCoord.y = coord.y; }
if(coord.y > maximumCoord.y) { maximumCoord.y = coord.y; }
if(coord.z < minimumCoord.z) { minimumCoord.z = coord.z; }
if(coord.z > maximumCoord.z) { maximumCoord.z = coord.z; }
}
}
/**
* @return The minimum bounding-box coordinate containing this machine's blocks.
*/
public CoordTriplet getMinimumCoord() { return minimumCoord.copy(); }
/**
* @return The maximum bounding-box coordinate containing this machine's blocks.
*/
public CoordTriplet getMaximumCoord() { return maximumCoord.copy(); }
/**
* Called when the save delegate's tile entity is being asked for its description packet
* @param tag A fresh compound tag to write your multiblock data into
*/
public abstract void formatDescriptionPacket(NBTTagCompound data);
/**
* Called when the save delegate's tile entity receiving a description packet
* @param tag A compound tag containing multiblock data to import
*/
public abstract void decodeDescriptionPacket(NBTTagCompound data);
} |
package sorts;
public class Sorts {
public static void bubbleSort(int[] a, int n) {
if (n <= 1) return;
for (int i = 0; i < n; ++i) {
boolean flag = false;
for (int j = 0; j < n - i - 1; ++j) {
if (a[j] > a[j+1]) {
int tmp = a[j];
a[j] = a[j+1];
a[j+1] = tmp;
flag = true;
}
}
if (!flag) break;
}
}
public static void insertionSort(int[] a, int n) {
if (n <= 1) return;
for (int i = 1; i < n; ++i) {
int value = a[i];
int j = i - 1;
for (; j >= 0; --j) {
if (a[j] > value) {
a[j+1] = a[j];
} else {
break;
}
}
a[j+1] = value;
}
}
public static void selectionSort(int[] a, int n) {
if (n <= 1) return;
for (int i = 0; i < n - 1; ++i) {
int minIndex = i;
for (int j = i + 1; j < n; ++j) {
if (a[j] < a[minIndex]) {
minIndex = j;
}
}
int tmp = a[i];
a[i] = a[minIndex];
a[minIndex] = tmp;
}
}
} |
package com.fatecpg.data;
import br.com.fatecpg.helpers.ConnectionFactory;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Date;
public class Partida {
private Integer _id;
private Integer _pontuacao;
private Date _data;
private Integer _usuarioId;
//
public Partida(Integer _id, Integer _pontuacao, Date _data, Integer _usuarioId) {
this._id = _id;
this._pontuacao = _pontuacao;
this._data = _data;
this._usuarioId = _usuarioId;
}
public Partida(Integer _pontuacao, Date _data, Integer _usuarioId) {
this._pontuacao = _pontuacao;
this._data = _data;
this._usuarioId = _usuarioId;
}
//
public Integer getId() {
return _id;
}
public Integer getPontuacao() {
return _pontuacao;
}
public void setPontuacao(Integer _pontuacao) {
this._pontuacao = _pontuacao;
}
public Date getData() {
return _data;
}
public void setData(Date _data) {
this._data = _data;
}
public Integer getUsuarioId() {
return _usuarioId;
}
public void setUsuarioId(Integer _usuarioId) {
this._usuarioId = _usuarioId;
}
//
// Insere o registro no banco de dados de acordo com os atributos do objeto
public boolean store() throws SQLException {
try (Connection connection = ConnectionFactory.getConnection()) {
try {
Statement statement = connection.createStatement();
String SQL = String.format(
"INSERT INTO PARTIDA(PONTUACAO, DT_PARTIDA, USUARIO_ID) VALUES('%d', %t, %d)",
this._pontuacao, this._data, this._usuarioId);
statement.execute(SQL, Statement.RETURN_GENERATED_KEYS);
ResultSet rs = statement.getGeneratedKeys();
if (rs.next()) {
this._id = rs.getInt(1);
}
rs.close();
if (this._id != null) {
return true;
}
} catch (SQLException ex) {
throw ex;
}
connection.close();
}
return false;
}
// Busca uma partida pelo ID
public static Partida find(Integer id) throws SQLException {
try (Connection connection = ConnectionFactory.getConnection()) {
PreparedStatement pstatement = connection.prepareStatement(String.format("SELECT * FROM PARTIDA WHERE ID = ?"));
pstatement.setInt(1, id);
try (ResultSet result = pstatement.executeQuery()) {
if (result.next()) {
return new Partida(
result.getInt("ID"),
result.getInt("PONTUACAO"),
result.getDate("DT_PARTIDA"),
result.getInt("USUARIO_ID")
);
}
} catch (Exception ex) {
System.out.println("Erro ao consultar a Partida: " + ex.getMessage());
}
connection.close();
} catch (Exception ex) {
System.out.println("Erro ao obter conexão com o banco de dados: " + ex.getMessage());
}
return null;
}
// Retorna todas as partidas
public static ArrayList<Partida> all() throws SQLException {
ArrayList<Partida> alternativas = new ArrayList<>();
try (Connection connection = ConnectionFactory.getConnection()) {
Statement statement = connection.createStatement();
ResultSet result = statement.executeQuery("SELECT * FROM PARTIDA");
while (result.next()) {
alternativas.add(new Partida(
result.getInt("ID"),
result.getInt("PONTUACAO"),
result.getDate("DT_PARTIDA"),
result.getInt("USUARIO_ID")
));
}
} catch (Exception ex) {
System.out.println("Erro ao obter conexão com o banco de dados: " + ex.getMessage());
}
return alternativas;
}
public static ArrayList<Partida> all(int usuarioId) throws SQLException {
ArrayList<Partida> alternativas = new ArrayList<>();
try (Connection connection = ConnectionFactory.getConnection()) {
Statement statement = connection.createStatement();
ResultSet result = statement.executeQuery("SELECT * FROM PARTIDA WHERE USUARIO_ID = " + usuarioId);
while (result.next()) {
alternativas.add(new Partida(
result.getInt("ID"),
result.getInt("PONTUACAO"),
result.getDate("DT_PARTIDA"),
result.getInt("USUARIO_ID")
));
}
} catch (Exception ex) {
System.out.println("Erro ao obter conexão com o banco de dados: " + ex.getMessage());
}
return alternativas;
}
public boolean update() throws SQLException {
try {
int linhasAlteradas = 0;
try (Connection connection = ConnectionFactory.getConnection()) {
String SQL = String.format(
"UPDATE PARTIDA SET PONTUACAO = '%d', DT_PARTIDA = %t, USUARIO_ID = %d WHERE ID = %d",
this._pontuacao,
this._data,
this._usuarioId,
this._id
);
try (Statement statement = connection.createStatement()) {
linhasAlteradas = statement.executeUpdate(SQL);
} catch (Exception ex) {
System.out.println("Erro ao atualizar Partida: " + ex.getMessage());
}
}
return linhasAlteradas > 0;
} catch (SQLException ex) {
System.out.println("Erro ao obter conexão com o banco de dados: " + ex.getMessage());
}
return false;
}
// Remove registro do banco de dados
public boolean delete() throws SQLException {
try (Connection connection = ConnectionFactory.getConnection()) {
try (PreparedStatement pstatement = connection.prepareStatement("DELETE FROM PARTIDA WHERE ID = ?")) {
pstatement.setInt(1, this._id);
pstatement.execute();
} catch (Exception ex) {
System.out.println("Erro ao excluir a Partida: " + ex.getMessage());
}
connection.close();
if (Partida.find(this._id) == null) {
return true;
}
} catch (Exception ex) {
System.out.println("Erro ao obter conexão com o banco de dados: " + ex.getMessage());
}
return false;
}
//
public boolean registrarAlternativaEscolhida(int alternativaId) {
try (Connection connection = ConnectionFactory.getConnection()) {
try (PreparedStatement pstatement = connection.prepareStatement("INSERT INTO ALTERNATIVA_PARTIDA(ALTERNATIVA_ID, PARTIDA_ID) VALUES(?, ?)")) {
pstatement.setInt(1, alternativaId);
pstatement.setInt(2, this._id);
pstatement.execute();
pstatement.close();
connection.close();
return true;
} catch (Exception ex) {
System.out.println("Erro ao registrar a resposta: " + ex.getMessage());
}
connection.close();
} catch (Exception ex) {
System.out.println("Erro ao obter conexão com o banco de dados: " + ex.getMessage());
}
return false;
}
public ArrayList<Alternativa> getAlternativasEscolhidas() {
ArrayList<Alternativa> alternativas = null;
try (Connection connection = ConnectionFactory.getConnection()) {
try (PreparedStatement pstatement = connection.prepareStatement("SELECT ALTERNATIVA_ID FROM ALTERNATIVA_PARTIDA WHERE PARTIDA_ID = ?")) {
pstatement.setInt(1, this._id);
pstatement.execute();
ResultSet result = pstatement.getResultSet();
alternativas = new ArrayList<>();
if(result.next()) {
alternativas.add(new Alternativa(
result.getString("TEXTO"),
result.getBoolean("CORRETA"),
result.getInt("QUESTAO_ID")
));
}
pstatement.close();
connection.close();
} catch (Exception ex) {
System.out.println("Erro ao consultar as respostas: " + ex.getMessage());
}
} catch (Exception ex) {
System.out.println("Erro ao obter conexão com o banco de dados: " + ex.getMessage());
}
return alternativas;
}
} |
package net.katsuster.ememu.ui;
import java.lang.reflect.*;
import java.io.*;
import java.awt.event.*;
import javax.swing.*;
/**
*
*
* @author katsuhiro
*/
public class VirtualTerminal extends JPanel {
//Keyboard -> KeyListener -> inPout -> inPin -> (other class)
private PipedInputStream inPin;
private PipedOutputStream inPout;
//(other class) -> outPout -> outPin -> (virtual terminal)
private PipedInputStream outPin;
private PipedOutputStream outPout;
private JTextArea outText;
public VirtualTerminal() throws IOException {
inPin = new PipedInputStream();
inPout = new PipedOutputStream(inPin);
outPin = new PipedInputStream();
outPout = new PipedOutputStream(outPin);
JScrollPane outScr = new JScrollPane(outText);
outText = new JTextArea();
outScr.add(outText);
add(outScr);
}
/**
* inPout
*/
private class KeyInListener implements KeyListener {
public KeyInListener() {
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyPressed(KeyEvent e) {
int c = e.getKeyCode();
try {
inPout.write(c);
} catch (IOException ex) {
//ignored
}
}
@Override
public void keyReleased(KeyEvent e) {
}
}
/**
* outPout
*/
private class TextDrainer implements Runnable {
public TextDrainer() {
//do nothing
}
@Override
public void run() {
try {
StringBuffer b = new StringBuffer();
output:
while (true) {
b.setLength(0);
do {
int ch = outPin.read();
if (ch == -1) {
//EOF
break output;
}
b.append((char) ch);
} while (outPin.available() != 0);
try {
SwingUtilities.invokeAndWait(new StringAppender(b.toString()));
} catch (InterruptedException e) {
e.printStackTrace(System.err);
} catch (InvocationTargetException e) {
e.printStackTrace(System.err);
}
}
} catch (IOException e) {
e.printStackTrace(System.err);
}
}
private class StringAppender implements Runnable {
private String s;
public StringAppender(String str) {
s = str;
}
@Override
public void run() {
outText.append(s);
}
}
}
} |
package com.google.refine;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.tools.tar.TarOutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.refine.history.HistoryEntryManager;
import com.google.refine.model.Project;
import com.google.refine.preference.PreferenceStore;
import com.google.refine.preference.TopList;
/**
* ProjectManager is responsible for loading and saving the workspace and projects.
*
*
*/
public abstract class ProjectManager {
// last n expressions used across all projects
static protected final int s_expressionHistoryMax = 100;
protected Map<Long, ProjectMetadata> _projectsMetadata;
protected PreferenceStore _preferenceStore;
final static Logger logger = LoggerFactory.getLogger("project_manager");
/**
* What caches the joins between projects.
*/
transient protected InterProjectModel _interProjectModel = new InterProjectModel();
/**
* Flag for heavy operations like creating or importing projects. Workspace saves are skipped while it's set.
*/
transient protected int _busy = 0;
/**
* While each project's metadata is loaded completely at start-up, each project's raw data
* is loaded only when the project is accessed by the user. This is because project
* metadata is tiny compared to raw project data. This hash map from project ID to project
* is more like a last accessed-last out cache.
*/
transient protected Map<Long, Project> _projects;
static public ProjectManager singleton;
protected ProjectManager(){
_projectsMetadata = new HashMap<Long, ProjectMetadata>();
_preferenceStore = new PreferenceStore();
_projects = new HashMap<Long, Project>();
preparePreferenceStore(_preferenceStore);
}
public void dispose() {
save(true); // complete save
for (Project project : _projects.values()) {
if (project != null) {
project.dispose();
}
}
_projects.clear();
_projectsMetadata.clear();
}
/**
* Registers the project in the memory of the current session
* @param project
* @param projectMetadata
*/
public void registerProject(Project project, ProjectMetadata projectMetadata) {
synchronized (this) {
_projects.put(project.id, project);
_projectsMetadata.put(project.id, projectMetadata);
}
}
/**
* Load project metadata from data storage
* @param projectID
* @return
*/
public abstract boolean loadProjectMetadata(long projectID);
/**
* Loads a project from the data store into memory
* @param id
* @return
*/
protected abstract Project loadProject(long id);
/**
* Import project from a Google Refine archive
* @param projectID
* @param inputStream
* @param gziped
* @throws IOException
*/
public abstract void importProject(long projectID, InputStream inputStream, boolean gziped) throws IOException;
/**
* Export project to a Google Refine archive
* @param projectId
* @param tos
* @throws IOException
*/
public abstract void exportProject(long projectId, TarOutputStream tos) throws IOException;
/**
* Saves a project and its metadata to the data store
* @param id
*/
public void ensureProjectSaved(long id) {
synchronized(this){
ProjectMetadata metadata = this.getProjectMetadata(id);
if (metadata != null) {
try {
saveMetadata(metadata, id);
} catch (Exception e) {
e.printStackTrace();
}
}//FIXME what should be the behaviour if metadata is null? i.e. not found
Project project = getProject(id);
if (project != null && metadata != null && metadata.getModified().after(project.getLastSave())) {
try {
saveProject(project);
} catch (Exception e) {
e.printStackTrace();
}
}//FIXME what should be the behaviour if project is null? i.e. not found or loaded.
//FIXME what should happen if the metadata is found, but not the project? or vice versa?
}
}
/**
* Save project metadata to the data store
* @param metadata
* @param projectId
* @throws Exception
*/
protected abstract void saveMetadata(ProjectMetadata metadata, long projectId) throws Exception;
/**
* Save project to the data store
* @param project
*/
protected abstract void saveProject(Project project);
/**
* Save workspace and all projects to data store
* @param allModified
*/
public void save(boolean allModified) {
if (allModified || _busy == 0) {
saveProjects(allModified);
saveWorkspace();
}
}
/**
* Saves the workspace to the data store
*/
protected abstract void saveWorkspace();
/**
* A utility class to prioritize projects for saving, depending on how long ago
* they have been changed but have not been saved.
*/
static protected class SaveRecord {
final Project project;
final long overdue;
SaveRecord(Project project, long overdue) {
this.project = project;
this.overdue = overdue;
}
}
static protected final int s_projectFlushDelay = 1000 * 60 * 60; // 1 hour
static protected final int s_quickSaveTimeout = 1000 * 30; // 30 secs
/**
* Saves all projects to the data store
* @param allModified
*/
protected void saveProjects(boolean allModified) {
List<SaveRecord> records = new ArrayList<SaveRecord>();
Date startTimeOfSave = new Date();
synchronized (this) {
for (long id : _projectsMetadata.keySet()) {
ProjectMetadata metadata = getProjectMetadata(id);
Project project = _projects.get(id); // don't call getProject() as that will load the project.
if (project != null) {
boolean hasUnsavedChanges =
metadata.getModified().getTime() >= project.getLastSave().getTime();
// We use >= instead of just > to avoid the case where a newly created project
// has the same modified and last save times, resulting in the project not getting
// saved at all.
if (hasUnsavedChanges) {
long msecsOverdue = startTimeOfSave.getTime() - project.getLastSave().getTime();
records.add(new SaveRecord(project, msecsOverdue));
} else if (!project.getProcessManager().hasPending()
&& startTimeOfSave.getTime() - project.getLastSave().getTime() > s_projectFlushDelay) {
/*
* It's been a while since the project was last saved and it hasn't been
* modified. We can safely remove it from the cache to save some memory.
*/
_projects.remove(id).dispose();
}
}
}
}
if (records.size() > 0) {
Collections.sort(records, new Comparator<SaveRecord>() {
@Override
public int compare(SaveRecord o1, SaveRecord o2) {
if (o1.overdue < o2.overdue) {
return 1;
} else if (o1.overdue > o2.overdue) {
return -1;
} else {
return 0;
}
}
});
logger.info(allModified ?
"Saving all modified projects ..." :
"Saving some modified projects ..."
);
for (int i = 0;
i < records.size() &&
(allModified || (new Date().getTime() - startTimeOfSave.getTime() < s_quickSaveTimeout));
i++) {
try {
saveProject(records.get(i).project);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
/**
* Gets the InterProjectModel from memory
*/
public InterProjectModel getInterProjectModel() {
return _interProjectModel;
}
/**
* Gets the project metadata from memory
* Requires that the metadata has already been loaded from the data store
* @param id
* @return
*/
public ProjectMetadata getProjectMetadata(long id) {
return _projectsMetadata.get(id);
}
/**
* Gets the project metadata from memory
* Requires that the metadata has already been loaded from the data store
* @param name
* @return
*/
public ProjectMetadata getProjectMetadata(String name) {
for (ProjectMetadata pm : _projectsMetadata.values()) {
if (pm.getName().equals(name)) {
return pm;
}
}
return null;
}
/**
* Tries to find the project id when given a project name
* Requires that all project metadata exists has been loaded to memory from the data store
* @param name
* The name of the project
* @return
* The id of the project, or -1 if it cannot be found
*/
public long getProjectID(String name) {
for (Entry<Long, ProjectMetadata> entry : _projectsMetadata.entrySet()) {
if (entry.getValue().getName().equals(name)) {
return entry.getKey();
}
}
return -1;
}
/**
* Gets all the project Metadata currently held in memory
* @return
*/
public Map<Long, ProjectMetadata> getAllProjectMetadata() {
return _projectsMetadata;
}
/**
* Gets the required project from the data store
* If project does not already exist in memory, it is loaded from the data store
* @param id
* the id of the project
* @return
* the project with the matching id, or null if it can't be found
*/
public Project getProject(long id) {
synchronized (this) {
if (_projects.containsKey(id)) {
return _projects.get(id);
} else {
Project project = loadProject(id);
if (project != null) {
_projects.put(id, project);
}
return project;
}
}
}
/**
* Gets the preference store
* @return
*/
public PreferenceStore getPreferenceStore() {
return _preferenceStore;
}
/**
* Gets all expressions from the preference store
* @return
*/
public List<String> getExpressions() {
return ((TopList) _preferenceStore.get("scripting.expressions")).getList();
}
/**
* The history entry manager deals with changes
* @return manager for handling history
*/
public abstract HistoryEntryManager getHistoryEntryManager();
/**
* Remove the project from the data store
* @param project
*/
public void deleteProject(Project project) {
deleteProject(project.id);
}
/**
* Remove project from data store
* @param projectID
*/
public abstract void deleteProject(long projectID);
/**
* Removes project from memory
* @param projectID
*/
protected void removeProject(long projectID){
if (_projects.containsKey(projectID)) {
_projects.remove(projectID).dispose();
}
if (_projectsMetadata.containsKey(projectID)) {
_projectsMetadata.remove(projectID);
}
}
/**
* Sets the flag for long running operations. This will prevent
* workspace saves from happening while it's set.
* @param busy
*/
public void setBusy(boolean busy) {
synchronized (this) {
if (busy) {
_busy++;
} else {
_busy
}
}
}
/**
* Add the latest expression to the preference store
* @param s
*/
public void addLatestExpression(String s) {
synchronized (this) {
((TopList) _preferenceStore.get("scripting.expressions")).add(s);
}
}
/**
*
* @param ps
*/
static protected void preparePreferenceStore(PreferenceStore ps) {
ps.put("scripting.expressions", new TopList(s_expressionHistoryMax));
ps.put("scripting.starred-expressions", new TopList(Integer.MAX_VALUE));
}
} |
package org.voovan.tools;
import java.lang.ref.WeakReference;
import java.util.LinkedList;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.function.Supplier;
public class ThreadLocalPool<T> {
private final ConcurrentLinkedQueue<T> GLOBAL_POOL = new ConcurrentLinkedQueue<T>();
private final ThreadLocal<LinkedList<WeakReference<T>>> THREAD_LOCAL_BYTE_BUFFER_POOL = new ThreadLocal<LinkedList<WeakReference<T>>>();
private int globalMaxSize = 1000;
private int threadLocalMaxSize = 10;
public ThreadLocalPool(int globalMaxSize, int threadLocalMaxSize) {
this.threadLocalMaxSize = threadLocalMaxSize;
this.globalMaxSize = globalMaxSize;
}
public int getThreadLocalMaxSize() {
return threadLocalMaxSize;
}
public void setThreadLocalMaxSize(int threadLocalMaxSize) {
this.threadLocalMaxSize = threadLocalMaxSize;
}
public int getGlobalMaxSize() {
return globalMaxSize;
}
public void setGlobalMaxSize(int globalMaxSize) {
this.globalMaxSize = globalMaxSize;
}
public LinkedList<WeakReference<T>> getThreadLoaclPool(){
LinkedList<WeakReference<T>> threadLocalPool = THREAD_LOCAL_BYTE_BUFFER_POOL.get();
if(threadLocalPool == null){
threadLocalPool = new LinkedList<WeakReference<T>>();
THREAD_LOCAL_BYTE_BUFFER_POOL.set(threadLocalPool);
}
return threadLocalPool;
}
public T getObject(Supplier<T> supplier){
LinkedList<WeakReference<T>> threadLocalPool = getThreadLoaclPool();
WeakReference<T> localWeakRef = threadLocalPool.poll();
T t = null;
if(localWeakRef!=null) {
t = localWeakRef.get();
localWeakRef.clear();
}
if(t==null){
t = GLOBAL_POOL.poll();
}
if(t==null) {
t = (T) supplier.get();
}
return t;
}
public void release(T t, Supplier destory){
LinkedList<WeakReference<T>> threadLocalPool = getThreadLoaclPool();
if(threadLocalPool.size() < threadLocalMaxSize) {
threadLocalPool.offer(new WeakReference<T>(t));
}
else if(GLOBAL_POOL.size() < globalMaxSize){
GLOBAL_POOL.offer(t);
} else {
destory.get();
}
}
} |
package org.endeavourhealth.queuereader.routines;
import com.google.common.base.Strings;
import jdk.nashorn.internal.objects.NativeJSON;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.apache.commons.io.FileUtils;
import org.endeavourhealth.common.fhir.CodeableConceptHelper;
import org.endeavourhealth.common.fhir.IdentifierHelper;
import org.endeavourhealth.common.utility.FileHelper;
import org.endeavourhealth.common.utility.ThreadPool;
import org.endeavourhealth.common.utility.ThreadPoolError;
import org.endeavourhealth.core.database.dal.DalProvider;
import org.endeavourhealth.core.database.dal.admin.LibraryRepositoryHelper;
import org.endeavourhealth.core.database.dal.admin.ServiceDalI;
import org.endeavourhealth.core.database.dal.admin.models.Service;
import org.endeavourhealth.core.database.dal.audit.ExchangeDalI;
import org.endeavourhealth.core.database.dal.audit.models.Exchange;
import org.endeavourhealth.core.database.dal.audit.models.ExchangeTransformAudit;
import org.endeavourhealth.core.database.dal.eds.PatientLinkDalI;
import org.endeavourhealth.core.database.dal.eds.PatientSearchDalI;
import org.endeavourhealth.core.database.dal.eds.models.PatientLinkPair;
import org.endeavourhealth.core.database.dal.ehr.ResourceDalI;
import org.endeavourhealth.core.database.dal.ehr.models.ResourceWrapper;
import org.endeavourhealth.core.database.dal.subscriberTransform.PseudoIdDalI;
import org.endeavourhealth.core.database.dal.subscriberTransform.SubscriberCohortDalI;
import org.endeavourhealth.core.database.dal.subscriberTransform.SubscriberPersonMappingDalI;
import org.endeavourhealth.core.database.dal.subscriberTransform.SubscriberResourceMappingDalI;
import org.endeavourhealth.core.database.dal.subscriberTransform.models.SubscriberCohortRecord;
import org.endeavourhealth.core.database.dal.subscriberTransform.models.SubscriberId;
import org.endeavourhealth.core.database.rdbms.enterprise.EnterpriseConnector;
import org.endeavourhealth.core.fhirStorage.FhirSerializationHelper;
import org.endeavourhealth.core.messaging.pipeline.PipelineException;
import org.endeavourhealth.core.queueing.QueueHelper;
import org.endeavourhealth.core.subscribers.SubscriberHelper;
import org.endeavourhealth.core.xml.QueryDocument.*;
import org.endeavourhealth.im.client.IMClient;
import org.endeavourhealth.im.models.mapping.MapColumnRequest;
import org.endeavourhealth.im.models.mapping.MapColumnValueRequest;
import org.endeavourhealth.im.models.mapping.MapResponse;
import org.endeavourhealth.subscriber.filer.EnterpriseFiler;
import org.endeavourhealth.subscriber.filer.SubscriberFiler;
import org.endeavourhealth.transform.common.resourceBuilders.*;
import org.endeavourhealth.transform.enterprise.EnterpriseTransformHelper;
import org.endeavourhealth.transform.enterprise.FhirToEnterpriseCsvTransformer;
import org.endeavourhealth.transform.enterprise.transforms.EpisodeOfCareEnterpriseTransformer;
import org.endeavourhealth.transform.enterprise.transforms.PatientEnterpriseTransformer;
import org.endeavourhealth.transform.hl7v2fhir.transforms.OrganizationTransformer;
import org.endeavourhealth.transform.subscriber.*;
import org.endeavourhealth.transform.subscriber.targetTables.OrganizationContact_v2;
import org.endeavourhealth.transform.subscriber.targetTables.OutputContainer;
import org.endeavourhealth.transform.subscriber.targetTables.SubscriberTableId;
import org.endeavourhealth.transform.subscriber.transforms.EpisodeOfCareTransformer;
import org.endeavourhealth.transform.subscriber.transforms.OrganisationTransformer;
import org.endeavourhealth.transform.subscriber.transforms.OrganisationTransformer_v2;
import org.endeavourhealth.transform.subscriber.transforms.PatientTransformer;
import org.hl7.fhir.instance.model.Patient;
import org.hl7.fhir.instance.model.ResourceType;
import org.hl7.fhir.utilities.CSVReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.lang.System;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import org.endeavourhealth.core.database.rdbms.enterprise.EnterpriseConnector;
import org.endeavourhealth.core.database.rdbms.ConnectionManager;
import java.sql.*;
import javax.persistence.EntityManager;
import org.hibernate.internal.SessionImpl;
import org.hl7.fhir.instance.model.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.concurrent.Callable;
public abstract class CQC extends AbstractRoutine {
private static final Logger LOG = LoggerFactory.getLogger(SpecialRoutines.class);
// test stub that's run on laptops
public static void CQC() {
//ResourceDalI resourceDal = DalProvider.factoryResourceDal();
//ResourceWrapper wrapper = resourceDal.getCurrentVersion(serviceId, ResourceType.Organization.toString(), orgId);
//ResourceWrapper var13;
try {
//LoadODSFile("D:\\TEMP\\ODSFILES\\ecarehomesite.csv");
//findODSCode("D:\\TEMP\\ODSFILES\\","BH23 5RT");
/*
List<EnterpriseConnector.ConnectionWrapper> connectionWrappers = EnterpriseConnector.openSubscriberConnections("subscriber_test");
EnterpriseConnector.ConnectionWrapper connectionWrapper = connectionWrappers.get(0);
Connection subscriberConnection = connectionWrapper.getConnection();
String sql ="insert into ods_v2(code) values('test');";
PreparedStatement preparedStmt = null;
preparedStmt = subscriberConnection.prepareStatement(sql);
//preparedStmt.setString(1,cqc_id);
//preparedStmt.setString(2,resource_guid);
boolean z = preparedStmt.execute();
System.out.println(z);
preparedStmt.close();
subscriberConnection.close();
*/
//LoadODSData("D:\\TEMP\\ODSFILES\\");
//OrganizationBuilder();
//SplitBuilderFile("C:\\Users\\PaulSimon\\Desktop\\builder.txt","d:\\temp\\builder\\");
//UUID serviceId = UUID.fromString("9d23eb25-b710-4c8b-a0ef-793b3df68c29");
UUID serviceId = UUID.fromString("2bb86ffb-c36f-4f8d-a419-60f6bcb7c0dc"); // where does this get logged (it does'nt)
/* so that we can query patient_address_match, or whatever else
List<EnterpriseConnector.ConnectionWrapper> connectionWrappers = EnterpriseConnector.openSubscriberConnections("subscriber_test");
EnterpriseConnector.ConnectionWrapper connectionWrapper = connectionWrappers.get(0);
Connection subscriberConnection = connectionWrapper.getConnection();
String sql = "select * from organization";
PreparedStatement ps = subscriberConnection.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
//EntityManager edsEntityManager = ConnectionManager.getEdsEntityManager();
//SessionImpl session = (SessionImpl) edsEntityManager.getDelegate();
//Connection edsConnection = session.connection();
//Statement s = edsConnection.createStatement();
//ResultSet rs = s.executeQuery(sql);
while (rs.next()) {
System.out.println(">> " + rs.getString("name"));
}
subscriberConnection.close();
*/
// from the bottom:
// abp_classification
// abp_address
// property
// address
// location_additional
// organization_additional
// organization
//String pathToCsv = "C:\\Users\\PaulSimon\\Desktop\\org-json.txt";
//String pathToCsv = "C:\\Users\\PaulSimon\\Desktop\\org-json - Copy.txt";
//String pathToCsv = "C:\\Users\\PaulSimon\\Desktop\\org-json-contained.txt";
//String pathToCsv = "C:\\Users\\PaulSimon\\Desktop\\builder0.txt";
//String pathToCsv = "d:\\temp\\builder\\builder0.txt";
String pathToCsv = "C:\\Users\\PaulSimon\\Desktop\\builder_single.txt";
BufferedReader csvReader = new BufferedReader(new FileReader(pathToCsv));
String row = ""; String resource_guid = ""; String json = "";
while ((row = csvReader.readLine()) != null) {
String[] ss = row.split("\t", -1);
resource_guid = ss[0];
json = ss[1];
System.out.println(resource_guid + " * " + json);
ResourceWrapper w = new ResourceWrapper();
// if the organization contains a Location, then that needs to be added first
// unless the system does not check for the existence of the location?
//UUID serviceId = UUID.fromString("9d23eb25-b710-4c8b-a0ef-793b3df68c29");
w.setServiceId(serviceId);
// this is the one that worked
//w.setSystemId(UUID.fromString("55c08fa5-ef1e-4e94-aadc-e3d6adc80774"));
w.setSystemId(UUID.fromString("f3ded58f-dec5-4a21-bd43-9ec307cd1b60")); // random uuids work ok as well?
w.setResourceType("Organization");
UUID zuid = UUID.randomUUID();
//w.setResourceId(zuid);
//w.setResourceId(UUID.fromString("7bbdc091-1b20-47b1-ae82-3aae42b8fd58"));
w.setResourceId(UUID.fromString(resource_guid));
w.setResourceData(json);
w.setCreatedAt(new java.util.Date(System.currentTimeMillis()));
List<ResourceWrapper> resourceWrappers = new ArrayList<>();
resourceWrappers.add(w);
String subscriberConfigName = "subscriber_test";
SubscriberConfig subscriberConfig = SubscriberConfig.readFromConfig(subscriberConfigName);
SubscriberTransformHelper helper = new SubscriberTransformHelper(serviceId, null, null, null, subscriberConfig, resourceWrappers, false);
//Long enterpriseOrgId = FhirToSubscriberCsvTransformer.findEnterpriseOrgId(serviceId, helper, Collections.emptyList());
//helper.setSubscriberOrganisationId(enterpriseOrgId);
//OrganisationTransformer t = new OrganisationTransformer();
OrganisationTransformer_v2 t = new OrganisationTransformer_v2();
t.transformResources(resourceWrappers, helper);
OutputContainer output = helper.getOutputContainer();
byte[] bytes = output.writeToZip();
String base64 = Base64.getEncoder().encodeToString(bytes);
UUID batchId = UUID.randomUUID();
UUID queuedMessageId = UUID.randomUUID();
SubscriberFiler.file(batchId, queuedMessageId, base64, subscriberConfigName);
}
csvReader.close();
} catch (Throwable t) {
LOG.error("", t);
}
}
public static void CQCOrganizationBuilder(String configName, String filename, String builderFilename) throws Exception
{
// subscriber_test, D:\\TEMP\\COVID-Jiras\\08_July_2020_CQC_directory_NEL8.csv, C:\\Users\\PaulSimon\\Desktop\\builder.txt
OrganizationBuilder(configName, filename, builderFilename);
}
public static void ThreadCQC(String configName, String serviceUUID, String builderFilename, String systemId) throws Exception
{
try {
UUID serviceId = UUID.fromString(serviceUUID);
ThreadCQCFile(builderFilename,serviceId,configName, systemId);
//UUID serviceId = UUID.fromString("2bb86ffb-c36f-4f8d-a419-60f6bcb7c0dc"); // where does this get logged (it does'nt)
//ThreadCQCFile("C:\\Users\\PaulSimon\\Desktop\\builder.txt",serviceId,"subscriber_test");
//ThreadCQCFile("C:\\Users\\PaulSimon\\Desktop\\builder_single.txt",serviceId,"subscriber_test");
} catch (Throwable t) {
LOG.error("", t);
}
}
static class CQCCallable implements Callable {
private String row;
private UUID serviceUUID;
private String subscriberConfigName;
private String systemId;
public CQCCallable(String row, UUID serviceUUID, String subscriberConfigName, String systemId) {
this.row = row;
this.serviceUUID = serviceUUID;
this.subscriberConfigName = subscriberConfigName;
this.systemId = systemId;
}
@Override
public Object call() throws Exception {
try {
String[] ss = row.split("\t", -1);
String resource_guid = ss[0]; String json = ss[1];
ResourceWrapper w = new ResourceWrapper();
w.setServiceId(serviceUUID);
// random uuid => w.setSystemId(UUID.fromString("f3ded58f-dec5-4a21-bd43-9ec307cd1b60"));
w.setSystemId(UUID.fromString(systemId));
w.setResourceType("Organization");
w.setResourceId(UUID.fromString(resource_guid));
w.setResourceData(json);
w.setCreatedAt(new java.util.Date(System.currentTimeMillis()));
List<ResourceWrapper> resourceWrappers = new ArrayList<>();
resourceWrappers.add(w);
SubscriberConfig subscriberConfig = SubscriberConfig.readFromConfig(subscriberConfigName);
SubscriberTransformHelper helper = new SubscriberTransformHelper(serviceUUID, null, null, null, subscriberConfig, resourceWrappers, false);
OrganisationTransformer_v2 t = new OrganisationTransformer_v2();
t.transformResources(resourceWrappers, helper);
OutputContainer output = helper.getOutputContainer();
byte[] bytes = output.writeToZip();
String base64 = Base64.getEncoder().encodeToString(bytes);
UUID batchId = UUID.randomUUID();
UUID queuedMessageId = UUID.randomUUID();
SubscriberFiler.file(batchId, queuedMessageId, base64, subscriberConfigName);
} catch (Throwable t) {
LOG.error("", t);
}
return null;
}
}
public static void ThreadCQCFile(String builderFile, UUID serviceUUID, String subscriberConfigName, String systemId) throws Exception
{
BufferedReader csvReader = new BufferedReader(new FileReader(builderFile));
String row = ""; String resource_guid = ""; String json = "";
Integer threads = 3;
Integer QBeforeBlock = 4;
ThreadPool threadPool = new ThreadPool(threads, QBeforeBlock);
while ((row = csvReader.readLine()) != null) {
List<ThreadPoolError> errors = threadPool.submit(new CQCCallable(row, serviceUUID, subscriberConfigName, systemId));
handleErrors(errors);
}
List<ThreadPoolError> errors = threadPool.waitAndStop();
handleErrors(errors);
}
private static void handleErrors(List<ThreadPoolError> errors) throws Exception {
if (errors == null || errors.isEmpty()) {
return;
}
//if we've had multiple errors, just throw the first one, since they'll most-likely be the same
ThreadPoolError first = errors.get(0);
Throwable cause = first.getException();
//the cause may be an Exception or Error so we need to explicitly
//cast to the right type to throw it without changing the method signature
if (cause instanceof Exception) {
throw (Exception)cause;
} else if (cause instanceof Error) {
throw (Error)cause;
}
}
/*
public static void SplitBuilderFile(String pathtoTxt, String outputFolder) throws Exception
{
Integer count = 0;
BufferedReader csvReader = new BufferedReader(new FileReader(pathtoTxt));
FileWriter csvWriter = new FileWriter(outputFolder+"builder"+count.toString()+".txt");
String row = "";
while ((row = csvReader.readLine()) != null) {
csvWriter.write(row+"\n");
count++;
if (count%100 == 0) {
System.out.println("create a new file"+count);
csvWriter.close();
String file = outputFolder+"builder"+count.toString()+".txt";
csvWriter = new FileWriter(outputFolder+"builder"+count.toString()+".txt");
}
}
csvReader.close();
csvWriter.close();
}
*/
public static void LoadODSFile2(String filedir, String filename) throws Exception
{
String configName = "subscriber_test";
List<EnterpriseConnector.ConnectionWrapper> connectionWrappers = EnterpriseConnector.openSubscriberConnections(configName);
EnterpriseConnector.ConnectionWrapper connectionWrapper = connectionWrappers.get(0);
Connection subscriberConnection = connectionWrapper.getConnection();
Reader reader = Files.newBufferedReader(Paths.get(filedir));
CSVParser csvParser = new CSVParser(reader, CSVFormat.DEFAULT);
String ret = "";
String d = "','";
for (CSVRecord csvRecord : csvParser) {
String postcode = csvRecord.get(9);
String ods_code = csvRecord.get(0);
String name = csvRecord.get(1);
String addline1 = csvRecord.get(4);
String addline2 = csvRecord.get(5);
String addline3 = csvRecord.get(6);
String addline4 = csvRecord.get(7);
String addline5 = csvRecord.get(8);
String parent_organization = csvRecord.get(14);
String parent_current = csvRecord.get(23);
String opendate = csvRecord.get(10);
String closedate = csvRecord.get(11);
String adrec = addline1+","+addline2+","+addline3+","+addline4+","+addline5+","+postcode;
String uprn = getUPRN(adrec, "odsload`"+ods_code+"`"+filename);
if (uprn.isEmpty()) {
// try including the name in the address string
adrec = name+","+addline1+","+addline2+","+addline3+","+addline4+","+addline5+","+postcode;
uprn = getUPRN(adrec, "odsload`"+ods_code+"`"+filename);
}
String sql = "INSERT INTO ods_v2 (ods_code,name,postcode,filename,address_line_1,address_line_2,address_line_3,address_line_4,address_line_5,uprn,parent_organization,parent_current,opendate,closedate) ";
sql = sql + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?);";
System.out.println(sql);
PreparedStatement preparedStmt = null;
preparedStmt = subscriberConnection.prepareStatement(sql);
preparedStmt.setDate(13,null);
if (!opendate.isEmpty()) {
opendate = opendate.substring(0,4)+"-"+opendate.substring(4,6)+"-"+opendate.substring(6,8);
preparedStmt.setDate(13,java.sql.Date.valueOf(opendate));
}
preparedStmt.setDate(14,null);
if (!closedate.isEmpty()) {
closedate = closedate.substring(0,4)+"-"+closedate.substring(4,6)+"-"+closedate.substring(6,8);
preparedStmt.setDate(14,java.sql.Date.valueOf(closedate));
}
preparedStmt.setString(1,ods_code);
preparedStmt.setString(2,name);
preparedStmt.setString(3,postcode.replaceAll(" ","").toLowerCase());
preparedStmt.setString(4,filename);
preparedStmt.setString(5,addline1);
preparedStmt.setString(6,addline2);
preparedStmt.setString(7,addline3);
preparedStmt.setString(8,addline4);
preparedStmt.setString(9,addline5);
preparedStmt.setString(10,uprn);
preparedStmt.setString(11,parent_organization);
preparedStmt.setString(12,parent_current);
preparedStmt.executeUpdate();
subscriberConnection.commit();
preparedStmt.close();
}
subscriberConnection.close();
}
public static String LoadODSFile(String filename, String postcode) throws Exception
{
Reader reader = Files.newBufferedReader(Paths.get(filename));
CSVParser csvParser = new CSVParser(reader, CSVFormat.DEFAULT);
String ret = "";
for (CSVRecord csvRecord : csvParser) {
String csv_postcode = csvRecord.get(9);
if (csv_postcode.equals(postcode)) {
String code = csvRecord.get(0);
String addline1 = csvRecord.get(4);
String addline2 = csvRecord.get(5);
String addline3 = csvRecord.get(6);
String addline4 = csvRecord.get(7);
String addline5 = csvRecord.get(8);
ret = ret+code+"~"+addline1+"~"+addline2+"~"+addline3+"~"+addline4+"~"+addline5+"~"+csv_postcode;
break;
}
}
return ret;
}
public static void LoadODSData(String DirectoryPath) throws Exception
{
File dir = new File(DirectoryPath);
File[] directoryListing = dir.listFiles();
for (File child : directoryListing) {
String filename = child.toString();
String[] ss = filename.split("\\.");
String ext = ss[ss.length-1];
if (!ext.contains("csv")) {continue;}
String file = ss[ss.length-2];
String[] f = file.split("\\\\");
System.out.println(f[3]);
LoadODSFile2(filename, f[3]);
}
}
public static String FindODSCodeUsingUprn(String postcode, String sFilename, String uprn, String name, String configName) throws Exception
{
// String configName = "subscriber_test";
//List<EnterpriseConnector.ConnectionWrapper> connectionWrappers = EnterpriseConnector.openSubscriberConnections(configName);
//EnterpriseConnector.ConnectionWrapper connectionWrapper = connectionWrappers.get(0);
// switch to subscriber_transform database
Connection connection = ConnectionManager.getSubscriberTransformConnection(configName);
//Connection subscriberConnection = connectionWrapper.getConnection();
postcode = postcode.replaceAll(" ","").toLowerCase();
//String sql = "select * from ods_v2 where uprn = '"+uprn+"' and filename='"+sFilename+"'";
// get the first word in name and do a sql like
name = name.replaceAll("'","\\\\'");
String[] ss = name.split(" ",-1);
String first_word = ss[0];
//first_word = first_word.replaceAll("'","\\\\'");
// count the number of records in result set for uprn?
// or, just check organization name is the same?
// String sql = "select * from ods_v2 where uprn = '"+uprn+"' and lower(name) like '%"+first_word.toLowerCase()+"%'";
String sql = "select * from ods_v2 where uprn = '"+uprn+"' and lower(name) ='"+name.toLowerCase()+"'";
//PreparedStatement ps = subscriberConnection.prepareStatement(sql);
PreparedStatement ps = connection.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
String ret = "";
if (rs.next()) {
String id = rs.getString("id");
String ods_code = rs.getString("ods_code");
String filename = rs.getString("filename");
String address_line_1 = rs.getString("address_line_1");
String address_line_2 = rs.getString("address_line_2");
String address_line_3 = rs.getString("address_line_3");
String address_line_4 = rs.getString("address_line_4");
String address_line_5 = rs.getString("address_line_5");
String parent_organization = rs.getString("parent_organization");
String parent_current = rs.getString("parent_current");
String opendate = rs.getString("opendate");
String closedate = rs.getString("closedate");
if (parent_organization==null) parent_organization="";
if (parent_current==null) parent_current="";
if (opendate==null) opendate="";
if (closedate==null) closedate="";
ret = id+"~"+ods_code+"~"+address_line_1+"~"+address_line_2+"~"+address_line_3+"~"+address_line_4+"~"+address_line_5+"~"+filename+"~";
ret = ret+"~"+parent_organization+"~"+parent_current+"~"+opendate+"~"+closedate;
}
ps.close();
//subscriberConnection.close();
connection.close();
return ret;
}
public static boolean indexInBound(String[] data, int index){
return data != null && index >= 0 && index < data.length;
}
private static String getUPRN(String adrec, String id) throws Exception
{
String csv = UPRN.getAdrec(adrec, id);
if (Strings.isNullOrEmpty(csv)) {System.out.println("Unable to get address from UPRN API");}
String uprn = "";
if (!csv.isEmpty()) {
String ss[] = csv.split("\\~",-1);
uprn = ss[20];
}
return uprn;
}
// subscriber_test, D:\\TEMP\\COVID-Jiras\\08_July_2020_CQC_directory_NEL8.csv, C:\\Users\\PaulSimon\\Desktop\\builder.txt
public static void OrganizationBuilder(String configName, String filename, String builderFilename) throws Exception
{
Connection connection = ConnectionManager.getSubscriberTransformConnection(configName);
BufferedReader reader = new BufferedReader(
new InputStreamReader(new FileInputStream(filename), "UTF-8"));
CSVParser csvParser = new CSVParser(reader, CSVFormat.DEFAULT);
Integer ft = 1; String RESOURCE_GUID = "";
FileWriter csvWriter = new FileWriter(builderFilename);
String csv = "";
for (CSVRecord csvRecord : csvParser) {
if (ft.equals(1)) {ft=0; continue;} // skip headers
String cqc_id = csvRecord.get(0);
String name = csvRecord.get(1);
String also = csvRecord.get(2);
String cqc_address = csvRecord.get(3);
String postcode = csvRecord.get(4);
String phone = csvRecord.get(5);
String service_web_site = csvRecord.get(6);
String service_type = csvRecord.get(7);
String date_of_last_check = csvRecord.get(8);
String specialism = csvRecord.get(9);
String provider_name = csvRecord.get(10);
String local_authority = csvRecord.get(11);
String region = csvRecord.get(12);
String location_url = csvRecord.get(13);
String cqc_location = csvRecord.get(14);
String cqc_provider_id = csvRecord.get(15);
String on_ratings = csvRecord.get(16);
String uprn = getUPRN(name+","+cqc_address+","+postcode, "cqc`"+cqc_id);
String ods_address = FindODSCodeUsingUprn(postcode, "ecarehomesite", uprn, name, configName);
String ods_code = ""; String addline1=""; String addline2=""; String addline3=""; String addline4=""; String addline5="";
String parent_organization = ""; String parent_current = ""; String opendate = ""; String closedate = "";
if (!ods_address.isEmpty()) {
String[] ss = ods_address.split("\\~",-1);
ods_code = ss[1]; addline1 = ss[2]; addline2 = ss[3]; addline3 = ss[4]; addline4 = ss[5]; addline5 = ss[6];
parent_organization = ss[9]; parent_current = ss[10];
opendate = ss[11]; closedate = ss[12];
}
// get the address lines form the cqc file (but no way of working out district/county)
System.out.println(cqc_address);
if (ods_code.isEmpty()) {
String[] ss = cqc_address.split("\\,",-1);
if (indexInBound(ss, 0)) addline1 = ss[0].trim();
if (indexInBound(ss, 1)) addline2 = ss[1].trim();
if (indexInBound(ss, 2)) addline3 = ss[2].trim();
}
// >>> VLTVL~107 NEAVE CRESCENT~HAROLD HILL~~ROMFORD~ESSEX~RM3 8HW
OrganizationBuilder organizationBuilder = new OrganizationBuilder();
if (!ods_code.isEmpty()) {
System.out.println(ods_code);
organizationBuilder.setOdsCode(ods_code);
}
organizationBuilder.setName(name);
AddressBuilder addressBuilder = new AddressBuilder(organizationBuilder);
addressBuilder.addLine(addline1);
addressBuilder.addLine(addline2);
addressBuilder.addLine(addline3);
if (!ods_code.isEmpty()) {
addressBuilder.setCity(addline4);
addressBuilder.setDistrict(addline5);
}
addressBuilder.setPostcode(postcode);
createContactPoint(ContactPoint.ContactPointSystem.PHONE, phone, organizationBuilder);
if (!cqc_id.isEmpty()) createContainedCoded(organizationBuilder,"ID",cqc_id);
if (!name.isEmpty()) createContainedCoded(organizationBuilder,"name",name);
if (!also.isEmpty()) createContainedCoded(organizationBuilder,"also_known_as",also);
if (!service_web_site.isEmpty()) createContainedCoded(organizationBuilder,"services_web_site",service_web_site);
if (!date_of_last_check.isEmpty()) createContainedCoded(organizationBuilder, "date_of_last_check", date_of_last_check);
if (!provider_name.isEmpty()) createContainedCoded(organizationBuilder, "provider_name", provider_name);
if (!local_authority.isEmpty()) createContainedCoded(organizationBuilder,"local_authority",local_authority);
if (!region.isEmpty()) createContainedCoded(organizationBuilder,"region",region);
if (!location_url.isEmpty()) createContainedCoded(organizationBuilder,"location_url",location_url);
if (!cqc_location.isEmpty()) createContainedCoded(organizationBuilder,"cqc_location",cqc_location);
if (!cqc_provider_id.isEmpty()) createContainedCoded(organizationBuilder,"cqc_provider_id",cqc_provider_id);
if (!on_ratings.isEmpty()) createContainedCoded(organizationBuilder,"on_ratings",on_ratings);
if (!service_type.isEmpty()) createContainedCoded(organizationBuilder,"service_type",service_type);
if (!specialism.isEmpty()) {
String[] ss = specialism.split("\\|");
for (int i = 0; i < ss.length; i++) {
String spec = ss[i];
createContainedCoded(organizationBuilder,"specialisms/services",spec);
}
//createContainedCoded(organizationBuilder,"specialisms/services",specialism);
}
// ods stuff
if (!parent_organization.isEmpty()) createContainedCoded(organizationBuilder,"parent_organization",parent_organization);
if (!parent_current.isEmpty()) createContainedCoded(organizationBuilder,"parent_current",parent_current);
if (!opendate.isEmpty()) createContainedCoded(organizationBuilder,"open_date",opendate);
if (!closedate.isEmpty()) createContainedCoded(organizationBuilder,"close_date",closedate);
//RESOURCE_GUID = scratch(cqc_id, configName);
RESOURCE_GUID = scratch(cqc_location, configName);
organizationBuilder.setId(RESOURCE_GUID);
String json = OrganisationTransformer_v2.Test(organizationBuilder);
System.out.println(json);
csvWriter.write(RESOURCE_GUID + "\t"+ json + "\n");
}
csvWriter.flush();
csvWriter.close();
}
private static void createContainedCoded(HasContainedParametersI organizationBuilder, String property, String value) throws Exception
{
ContainedParametersBuilder containedParametersBuilder = new ContainedParametersBuilder(organizationBuilder);
MapColumnRequest propertyRequest = new MapColumnRequest(
"CM_Org_CQC", "CM_Sys_CQC", "CQC", "CQC",
property
);
MapResponse propertyResponse = IMHelper.getIMMappedPropertyResponse(propertyRequest);
MapColumnValueRequest valueRequest = new MapColumnValueRequest(
"CM_Org_CQC", "CM_Sys_CQC", "CQC", "CQC",
property, value
);
MapResponse valueResponse = IMHelper.getIMMappedPropertyValueResponse(valueRequest);
CodeableConcept ccValue = new CodeableConcept();
ccValue.addCoding().setCode(valueResponse.getConcept().getCode())
.setSystem(valueResponse.getConcept().getScheme())
.setDisplay(value+"~"+property); // include the property_name
containedParametersBuilder.addParameter(propertyResponse.getConcept().getCode(), ccValue);
}
private static void createContactPoint(ContactPoint.ContactPointSystem system, String contactCell, HasContactPointI parentBuilder) throws Exception {
ContactPointBuilder contactPointBuilder = new ContactPointBuilder(parentBuilder);
contactPointBuilder.setSystem(system);
contactPointBuilder.setUse(ContactPoint.ContactPointUse.WORK);
contactPointBuilder.setValue(contactCell);
}
/*
private static Long GetNextMap3Id(Connection connection) throws Exception
{
String sql = "SELECT MAX(subscriber_id) FROM subscriber_id_map_3";
PreparedStatement ps = connection.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
Long max = 0L;
if (rs.next()) {
max = rs.getLong(1);
max++;
System.out.println(max);
}
ps.close();
return max+100;
}
*/
private static String ResourceExist(String cqc_id, Connection connection) throws Exception
{
String sql = "select guid from cqc_id_map where cqc_id='"+cqc_id+"'";
PreparedStatement preparedStmt = null;
preparedStmt = connection.prepareStatement(sql);
ResultSet rs = preparedStmt.executeQuery();
String scratch_guid="";
if (rs.next()) {scratch_guid = rs.getString(1);}
preparedStmt.close();
return scratch_guid;
}
private static String scratch(String cqc_id, String configName) throws Exception
{
//PseudoIdDalI pseudoIdDal = DalProvider.factoryPseudoIdDal("subscriber_test");
//pseudoIdDal.PSTest();
//OrganisationTransformer_v2.TestInsert();
Connection connection = ConnectionManager.getSubscriberTransformConnection(configName);
String sql = "";
String scratch_guid = ResourceExist(cqc_id, connection);
if (scratch_guid.isEmpty()) {scratch_guid = UUID.randomUUID().toString();}
System.out.println(scratch_guid);
// check that the guid is in subscriber_id_map_3
sql = "SELECT * FROM subscriber_id_map_3 where subscriber_table=33 and source_id='Organization/"+scratch_guid+"'";
PreparedStatement preparedStmt = connection.prepareStatement(sql);
ResultSet rs = preparedStmt.executeQuery();
if (rs.next()) {
System.out.println(rs.getString(1));
preparedStmt.close();
connection.close();
return scratch_guid;
}
preparedStmt.close();
// subscriber_Id_map subscriber_id is auto incremental, so don't need this code!
//Long id = GetNextMap3Id(connection);
//System.out.println(id);
sql = "INSERT INTO subscriber_id_map_3 (subscriber_table,source_id) values (?,?)";
preparedStmt = null;
preparedStmt = connection.prepareStatement(sql);
preparedStmt.setString(1,"33");
//preparedStmt.setString(2,id.toString());
preparedStmt.setString(2,"Organization/"+scratch_guid);
preparedStmt.executeUpdate();
connection.commit();
preparedStmt.close();
// insert into scratch_v2 and subscriber_id_map_3
sql = "insert into cqc_id_map(cqc_id, guid) values(?,?);";
preparedStmt = null;
preparedStmt = connection.prepareStatement(sql);
preparedStmt.setString(1,cqc_id);
preparedStmt.setString(2,scratch_guid);
preparedStmt.executeUpdate();
connection.commit();
preparedStmt.close();
connection.close();
return scratch_guid;
}
} |
package org.bouncycastle.crypto.tls;
import org.bouncycastle.asn1.x509.RSAPublicKeyStructure;
import org.bouncycastle.crypto.InvalidCipherTextException;
import org.bouncycastle.crypto.encodings.PKCS1Encoding;
import org.bouncycastle.crypto.engines.RSABlindedEngine;
import org.bouncycastle.crypto.params.ParametersWithRandom;
import org.bouncycastle.crypto.params.RSAKeyParameters;
import org.bouncycastle.crypto.prng.ThreadedSeedGenerator;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigInteger;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
/**
* An implementation of all high level protocols in TLS 1.0.
*/
public class TlsProtocolHandler
{
private static final short RL_CHANGE_CIPHER_SPEC = 20;
private static final short RL_ALERT = 21;
private static final short RL_HANDSHAKE = 22;
private static final short RL_APPLICATION_DATA = 23;
/*
hello_request(0), client_hello(1), server_hello(2),
certificate(11), server_key_exchange (12),
certificate_request(13), server_hello_done(14),
certificate_verify(15), client_key_exchange(16),
finished(20), (255)
*/
private static final short HP_HELLO_REQUEST = 0;
private static final short HP_CLIENT_HELLO = 1;
private static final short HP_SERVER_HELLO = 2;
private static final short HP_CERTIFICATE = 11;
private static final short HP_SERVER_KEY_EXCHANGE = 12;
private static final short HP_CERTIFICATE_REQUEST = 13;
private static final short HP_SERVER_HELLO_DONE = 14;
private static final short HP_CERTIFICATE_VERIFY = 15;
private static final short HP_CLIENT_KEY_EXCHANGE = 16;
private static final short HP_FINISHED = 20;
/*
* Our Connection states
*/
private static final short CS_CLIENT_HELLO_SEND = 1;
private static final short CS_SERVER_HELLO_RECEIVED = 2;
private static final short CS_SERVER_CERTIFICATE_RECEIVED = 3;
private static final short CS_SERVER_KEY_EXCHANGE_RECEIVED = 4;
private static final short CS_SERVER_HELLO_DONE_RECEIVED = 5;
private static final short CS_CLIENT_KEY_EXCHANGE_SEND = 6;
private static final short CS_CLIENT_CHANGE_CIPHER_SPEC_SEND = 7;
private static final short CS_CLIENT_FINISHED_SEND = 8;
private static final short CS_SERVER_CHANGE_CIPHER_SPEC_RECEIVED = 9;
private static final short CS_DONE = 10;
protected static final short AP_close_notify = 0;
protected static final short AP_unexpected_message = 10;
protected static final short AP_bad_record_mac = 20;
protected static final short AP_decryption_failed = 21;
protected static final short AP_record_overflow = 22;
protected static final short AP_decompression_failure = 30;
protected static final short AP_handshake_failure = 40;
protected static final short AP_bad_certificate = 42;
protected static final short AP_unsupported_certificate = 43;
protected static final short AP_certificate_revoked = 44;
protected static final short AP_certificate_expired = 45;
protected static final short AP_certificate_unknown = 46;
protected static final short AP_illegal_parameter = 47;
protected static final short AP_unknown_ca = 48;
protected static final short AP_access_denied = 49;
protected static final short AP_decode_error = 50;
protected static final short AP_decrypt_error = 51;
protected static final short AP_export_restriction = 60;
protected static final short AP_protocol_version = 70;
protected static final short AP_insufficient_security = 71;
protected static final short AP_internal_error = 80;
protected static final short AP_user_canceled = 90;
protected static final short AP_no_renegotiation = 100;
protected static final short AL_warning = 1;
protected static final short AL_fatal = 2;
private static final byte[] emptybuf = new byte[0];
private static final String TLS_ERROR_MESSAGE = "Internal TLS error, this could be an attack";
/*
* Queues for data from some protocolls.
*/
private ByteQueue applicationDataQueue = new ByteQueue();
private ByteQueue changeCipherSpecQueue = new ByteQueue();
private ByteQueue alertQueue = new ByteQueue();
private ByteQueue handshakeQueue = new ByteQueue();
/*
* The Record Stream we use
*/
private RecordStream rs;
private SecureRandom random;
/*
* The public rsa-key of the server.
*/
private RSAKeyParameters serverRsaKey = null;
private TlsInputStream tlsInputStream = null;
private TlsOuputStream tlsOutputStream = null;
private boolean closed = false;
private boolean failedWithError = false;
private boolean appDataReady = false;
private byte[] clientRandom;
private byte[] serverRandom;
private byte[] ms;
private TlsCipherSuite choosenCipherSuite = null;
private BigInteger Yc;
private byte[] pms;
private CertificateVerifyer verifyer = null;
public TlsProtocolHandler(InputStream is, OutputStream os)
{
/*
* We use our threaded seed generator to generate a good random
* seed. If the user has a better random seed, he should use
* the constructor with a SecureRandom.
*/
ThreadedSeedGenerator tsg = new ThreadedSeedGenerator();
try
{
this.random = SecureRandom.getInstance("SHA1PRNG");
}
catch (NoSuchAlgorithmException e)
{
throw new RuntimeException(e);
}
/*
* Hopefully, 20 bytes in fast mode are good enough.
*/
this.random.setSeed(tsg.generateSeed(20, true));
this.rs = new RecordStream(this, is, os);
}
public TlsProtocolHandler(InputStream is, OutputStream os, SecureRandom sr)
{
this.random = sr;
this.rs = new RecordStream(this, is, os);
}
private short connection_state;
protected void processData(short protocol, byte[] buf, int offset, int len)
throws IOException
{
/*
* Have a look at the protocol type, and add it to the correct queue.
*/
switch (protocol)
{
case RL_CHANGE_CIPHER_SPEC:
changeCipherSpecQueue.addData(buf, offset, len);
processChangeCipherSpec();
break;
case RL_ALERT:
alertQueue.addData(buf, offset, len);
processAlert();
break;
case RL_HANDSHAKE:
handshakeQueue.addData(buf, offset, len);
processHandshake();
break;
case RL_APPLICATION_DATA:
if (!appDataReady)
{
this.failWithError(AL_fatal, AP_unexpected_message);
}
applicationDataQueue.addData(buf, offset, len);
processApplicationData();
break;
default:
/*
* Uh, we don't know this protocol.
*
* RFC2246 defines on page 13, that we should ignore this.
*/
}
}
private void processHandshake() throws IOException
{
boolean read;
do
{
read = false;
/*
* We need the first 4 bytes, they contain type and length of
* the message.
*/
if (handshakeQueue.size() >= 4)
{
byte[] beginning = new byte[4];
handshakeQueue.read(beginning, 0, 4, 0);
ByteArrayInputStream bis = new ByteArrayInputStream(beginning);
short type = TlsUtils.readUint8(bis);
int len = TlsUtils.readUint24(bis);
/*
* Check if we have enough bytes in the buffer to read
* the full message.
*/
if (handshakeQueue.size() >= (len + 4))
{
/*
* Read the message.
*/
byte[] buf = new byte[len];
handshakeQueue.read(buf, 0, len, 4);
handshakeQueue.removeData(len + 4);
/*
* If it is not a finished message, update our hashes
* we prepare for the finish message.
*/
if (type != HP_FINISHED)
{
rs.hash1.update(beginning, 0, 4);
rs.hash2.update(beginning, 0, 4);
rs.hash1.update(buf, 0, len);
rs.hash2.update(buf, 0, len);
}
/*
* Now, parse the message.
*/
ByteArrayInputStream is = new ByteArrayInputStream(buf);
/*
* Check the type.
*/
switch (type)
{
case HP_CERTIFICATE:
switch (connection_state)
{
case CS_SERVER_HELLO_RECEIVED:
/*
* Parse the certificates.
*/
Certificate cert = Certificate.parse(is);
assertEmpty(is);
/*
* Verify them.
*/
if (!this.verifyer.isValid(cert.getCerts()))
{
this.failWithError(AL_fatal, AP_user_canceled);
}
/*
* We only support RSA certificates. Lets hope
* this is one.
*/
RSAPublicKeyStructure rsaKey = null;
try
{
rsaKey = RSAPublicKeyStructure.getInstance(cert.certs[0].getTBSCertificate().getSubjectPublicKeyInfo().getPublicKey());
}
catch (Exception e)
{
/*
* Sorry, we have to fail ;-(
*/
this.failWithError(AL_fatal, AP_unsupported_certificate);
}
/*
* Parse the servers public RSA key.
*/
this.serverRsaKey = new RSAKeyParameters(
false,
rsaKey.getModulus(),
rsaKey.getPublicExponent());
connection_state = CS_SERVER_CERTIFICATE_RECEIVED;
read = true;
break;
default:
this.failWithError(AL_fatal, AP_unexpected_message);
}
break;
case HP_FINISHED:
switch (connection_state)
{
case CS_SERVER_CHANGE_CIPHER_SPEC_RECEIVED:
/*
* Read the checksum from the finished message,
* it has always 12 bytes.
*/
byte[] receivedChecksum = new byte[12];
TlsUtils.readFully(receivedChecksum, is);
assertEmpty(is);
/*
* Calculate our owne checksum.
*/
byte[] checksum = new byte[12];
byte[] md5andsha1 = new byte[16 + 20];
rs.hash2.doFinal(md5andsha1, 0);
TlsUtils.PRF(this.ms, "server finished".getBytes(), md5andsha1, checksum);
/*
* Compare both checksums.
*/
for (int i = 0; i < receivedChecksum.length; i++)
{
if (receivedChecksum[i] != checksum[i])
{
/*
* Wrong checksum in the finished message.
*/
this.failWithError(AL_fatal, AP_handshake_failure);
}
}
connection_state = CS_DONE;
/*
* We are now ready to receive application data.
*/
this.appDataReady = true;
read = true;
break;
default:
this.failWithError(AL_fatal, AP_unexpected_message);
}
break;
case HP_SERVER_HELLO:
switch (connection_state)
{
case CS_CLIENT_HELLO_SEND:
/*
* Read the server hello message
*/
TlsUtils.checkVersion(is, this);
/*
* Read the server random
*/
this.serverRandom = new byte[32];
TlsUtils.readFully(this.serverRandom, is);
/*
* Currenty, we don't support session ids
*/
short sessionIdLength = TlsUtils.readUint8(is);
byte[] sessionId = new byte[sessionIdLength];
TlsUtils.readFully(sessionId, is);
/*
* Find out which ciphersuite the server has
* choosen. If we don't support this ciphersuite,
* the TlsCipherSuiteManager will throw an
* exception.
*/
this.choosenCipherSuite = TlsCipherSuiteManager.getCipherSuite(TlsUtils.readUint16(is), this);
/*
* We support only the null compression which
* means no compression.
*/
short compressionMethod = TlsUtils.readUint8(is);
if (compressionMethod != 0)
{
this.failWithError(TlsProtocolHandler.AL_fatal, TlsProtocolHandler.AP_illegal_parameter);
}
assertEmpty(is);
connection_state = CS_SERVER_HELLO_RECEIVED;
read = true;
break;
default:
this.failWithError(AL_fatal, AP_unexpected_message);
}
break;
case HP_SERVER_HELLO_DONE:
switch (connection_state)
{
case CS_SERVER_CERTIFICATE_RECEIVED:
/*
* There was no server key exchange message, check
* that we are doing RSA key exchange.
*/
if (this.choosenCipherSuite.getKeyExchangeAlgorithm() != TlsCipherSuite.KE_RSA)
{
this.failWithError(AL_fatal, AP_unexpected_message);
}
/*
* NB: Fall through to next case label to continue RSA key exchange
*/
case CS_SERVER_KEY_EXCHANGE_RECEIVED:
assertEmpty(is);
connection_state = CS_SERVER_HELLO_DONE_RECEIVED;
/*
* Send the client key exchange message, depending
* on the key exchange we are using in our
* ciphersuite.
*/
short ke = this.choosenCipherSuite.getKeyExchangeAlgorithm();
switch (ke)
{
case TlsCipherSuite.KE_RSA:
/*
* We are doing RSA key exchange. We will
* choose a pre master secret and send it
* rsa encrypted to the server.
*
* Prepare pre master secret.
*/
pms = new byte[48];
pms[0] = 3;
pms[1] = 1;
for (int i = 2; i < 48; i++)
{
pms[i] = (byte)random.nextInt(256);
}
/*
* Encode the pms and send it to the server.
*
* Prepare an PKCS1Encoding with good random
* padding.
*/
RSABlindedEngine rsa = new RSABlindedEngine();
PKCS1Encoding encoding = new PKCS1Encoding(rsa);
encoding.init(true, new ParametersWithRandom(this.serverRsaKey, this.random));
byte[] encrypted = null;
try
{
encrypted = encoding.processBlock(pms, 0, pms.length);
}
catch (InvalidCipherTextException e)
{
/*
* This should never happen, only during decryption.
*/
this.failWithError(AL_fatal, AP_internal_error);
}
/*
* Send the encrypted pms.
*/
ByteArrayOutputStream bos = new ByteArrayOutputStream();
TlsUtils.writeUint8(HP_CLIENT_KEY_EXCHANGE, bos);
TlsUtils.writeUint24(encrypted.length + 2, bos);
TlsUtils.writeUint16(encrypted.length, bos);
bos.write(encrypted);
byte[] message = bos.toByteArray();
rs.writeMessage((short)RL_HANDSHAKE, message, 0, message.length);
break;
case TlsCipherSuite.KE_DHE_RSA:
/*
* Send the Client Key Exchange message for
* DHE key exchange.
*/
byte[] YcByte = this.Yc.toByteArray();
ByteArrayOutputStream DHbos = new ByteArrayOutputStream();
TlsUtils.writeUint8(HP_CLIENT_KEY_EXCHANGE, DHbos);
TlsUtils.writeUint24(YcByte.length + 2, DHbos);
TlsUtils.writeUint16(YcByte.length, DHbos);
DHbos.write(YcByte);
byte[] DHmessage = DHbos.toByteArray();
rs.writeMessage((short)RL_HANDSHAKE, DHmessage, 0, DHmessage.length);
break;
default:
/*
* Proble during handshake, we don't know
* how to thandle this key exchange method.
*/
this.failWithError(AL_fatal, AP_unexpected_message);
}
connection_state = CS_CLIENT_KEY_EXCHANGE_SEND;
/*
* Now, we send change cipher state
*/
byte[] cmessage = new byte[1];
cmessage[0] = 1;
rs.writeMessage((short)RL_CHANGE_CIPHER_SPEC, cmessage, 0, cmessage.length);
connection_state = CS_CLIENT_CHANGE_CIPHER_SPEC_SEND;
/*
* Calculate the ms
*/
this.ms = new byte[48];
byte[] random = new byte[clientRandom.length + serverRandom.length];
System.arraycopy(clientRandom, 0, random, 0, clientRandom.length);
System.arraycopy(serverRandom, 0, random, clientRandom.length, serverRandom.length);
TlsUtils.PRF(pms, "master secret".getBytes(), random, this.ms);
/*
* Initialize our cipher suite
*/
rs.writeSuite = this.choosenCipherSuite;
rs.writeSuite.init(this.ms, clientRandom, serverRandom);
/*
* Send our finished message.
*/
byte[] checksum = new byte[12];
byte[] md5andsha1 = new byte[16 + 20];
rs.hash1.doFinal(md5andsha1, 0);
TlsUtils.PRF(this.ms, "client finished".getBytes(), md5andsha1, checksum);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
TlsUtils.writeUint8(HP_FINISHED, bos);
TlsUtils.writeUint24(12, bos);
bos.write(checksum);
byte[] message = bos.toByteArray();
rs.writeMessage((short)RL_HANDSHAKE, message, 0, message.length);
this.connection_state = CS_CLIENT_FINISHED_SEND;
read = true;
break;
default:
this.failWithError(AL_fatal, AP_handshake_failure);
}
break;
case HP_SERVER_KEY_EXCHANGE:
switch (connection_state)
{
case CS_SERVER_CERTIFICATE_RECEIVED:
/*
* Check that we are doing DHE key exchange
*/
if (this.choosenCipherSuite.getKeyExchangeAlgorithm() != TlsCipherSuite.KE_DHE_RSA)
{
this.failWithError(AL_fatal, AP_unexpected_message);
}
/*
* Parse the Structure
*/
int pLength = TlsUtils.readUint16(is);
byte[] pByte = new byte[pLength];
TlsUtils.readFully(pByte, is);
int gLength = TlsUtils.readUint16(is);
byte[] gByte = new byte[gLength];
TlsUtils.readFully(gByte, is);
int YsLength = TlsUtils.readUint16(is);
byte[] YsByte = new byte[YsLength];
TlsUtils.readFully(YsByte, is);
int sigLength = TlsUtils.readUint16(is);
byte[] sigByte = new byte[sigLength];
TlsUtils.readFully(sigByte, is);
this.assertEmpty(is);
/*
* Verify the Signature.
*
* First, calculate the hash.
*/
CombinedHash sigDigest = new CombinedHash();
ByteArrayOutputStream signedData = new ByteArrayOutputStream();
TlsUtils.writeUint16(pLength, signedData);
signedData.write(pByte);
TlsUtils.writeUint16(gLength, signedData);
signedData.write(gByte);
TlsUtils.writeUint16(YsLength, signedData);
signedData.write(YsByte);
byte[] signed = signedData.toByteArray();
sigDigest.update(this.clientRandom, 0, this.clientRandom.length);
sigDigest.update(this.serverRandom, 0, this.serverRandom.length);
sigDigest.update(signed, 0, signed.length);
byte[] hash = new byte[sigDigest.getDigestSize()];
sigDigest.doFinal(hash, 0);
/*
* Now, do the RSA operation
*/
RSABlindedEngine rsa = new RSABlindedEngine();
PKCS1Encoding encoding = new PKCS1Encoding(rsa);
encoding.init(false, this.serverRsaKey);
/*
* The data which was signed
*/
byte[] sigHash = null;
try
{
sigHash = encoding.processBlock(sigByte, 0, sigByte.length);
}
catch (InvalidCipherTextException e)
{
this.failWithError(AL_fatal, AP_bad_certificate);
}
/*
* Check if the data which was signed is equal to
* the hash we calculated.
*/
if (sigHash.length != hash.length)
{
this.failWithError(AL_fatal, AP_bad_certificate);
}
for (int i = 0; i < sigHash.length; i++)
{
if (sigHash[i] != hash[i])
{
this.failWithError(AL_fatal, AP_bad_certificate);
}
}
/*
* OK, Signature was correct.
*
* Do the DH calculation.
*/
BigInteger p = new BigInteger(1, pByte);
BigInteger g = new BigInteger(1, gByte);
BigInteger Ys = new BigInteger(1, YsByte);
BigInteger x = new BigInteger(p.bitLength() - 1, this.random);
Yc = g.modPow(x, p);
this.pms = (Ys.modPow(x, p)).toByteArray();
/*
* Remove leading zero byte, if present.
*/
if (this.pms[0] == 0)
{
byte[] tmp = new byte[this.pms.length - 1];
System.arraycopy(this.pms, 1, tmp, 0, tmp.length);
this.pms = tmp;
}
this.connection_state = CS_SERVER_KEY_EXCHANGE_RECEIVED;
read = true;
break;
default:
this.failWithError(AL_fatal, AP_unexpected_message);
}
break;
case HP_HELLO_REQUEST:
case HP_CLIENT_KEY_EXCHANGE:
case HP_CERTIFICATE_REQUEST:
case HP_CERTIFICATE_VERIFY:
case HP_CLIENT_HELLO:
default:
// We do not support this!
this.failWithError(AL_fatal, AP_unexpected_message);
break;
}
}
}
}
while (read);
}
private void processApplicationData()
{
/*
* There is nothing we need to do here.
*
* This function could be used for callbacks when application
* data arrives in the future.
*/
}
private void processAlert() throws IOException
{
while (alertQueue.size() >= 2)
{
/*
* An alert is always 2 bytes. Read the alert.
*/
byte[] tmp = new byte[2];
alertQueue.read(tmp, 0, 2, 0);
alertQueue.removeData(2);
short level = tmp[0];
short description = tmp[1];
if (level == AL_fatal)
{
/*
* This is a fatal error.
*/
this.failedWithError = true;
this.closed = true;
/*
* Now try to close the stream, ignore errors.
*/
try
{
rs.close();
}
catch (Exception e)
{
}
throw new IOException(TLS_ERROR_MESSAGE);
}
else
{
/*
* This is just a warning.
*/
if (description == AP_close_notify)
{
/*
* Close notify
*/
this.failWithError(AL_warning, AP_close_notify);
}
/*
* If it is just a warning, we continue.
*/
}
}
}
/**
* This method is called, when a change cipher spec message is received.
*
* @throws IOException If the message has an invalid content or the
* handshake is not in the correct state.
*/
private void processChangeCipherSpec() throws IOException
{
while (changeCipherSpecQueue.size() > 0)
{
/*
* A change cipher spec message is only one byte with the value 1.
*/
byte[] b = new byte[1];
changeCipherSpecQueue.read(b, 0, 1, 0);
changeCipherSpecQueue.removeData(1);
if (b[0] != 1)
{
/*
* This should never happen.
*/
this.failWithError(AL_fatal, AP_unexpected_message);
}
else
{
/*
* Check if we are in the correct connection state.
*/
if (this.connection_state == CS_CLIENT_FINISHED_SEND)
{
rs.readSuite = rs.writeSuite;
this.connection_state = CS_SERVER_CHANGE_CIPHER_SPEC_RECEIVED;
}
else
{
/*
* We are not in the correct connection state.
*/
this.failWithError(AL_fatal, AP_handshake_failure);
}
}
}
}
/**
* Connects to the remote system.
*
* @param verifyer Will be used when a certificate is received to verify
* that this certificate is accepted by the client.
* @throws IOException If handshake was not successfull.
*/
public void connect(CertificateVerifyer verifyer) throws IOException
{
this.verifyer = verifyer;
/*
* Send Client hello
*
* First, generate some random data.
*/
this.clientRandom = new byte[32];
int t = (int)(System.currentTimeMillis() / 1000);
this.clientRandom[0] = (byte)(t >> 24);
this.clientRandom[1] = (byte)(t >> 16);
this.clientRandom[2] = (byte)(t >> 8);
this.clientRandom[3] = (byte)t;
for (int i = 4; i < clientRandom.length; i++)
{
this.clientRandom[i] = (byte)random.nextInt(256);
}
ByteArrayOutputStream os = new ByteArrayOutputStream();
TlsUtils.writeVersion(os);
os.write(this.clientRandom);
/*
* Length of Session id
*/
TlsUtils.writeUint8((short)0, os);
/*
* Cipher suites
*/
TlsCipherSuiteManager.writeCipherSuites(os);
/*
* Compression methods, just the null method.
*/
byte[] compressionMethods = new byte[]{0x00};
TlsUtils.writeUint8((short)compressionMethods.length, os);
os.write(compressionMethods);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
TlsUtils.writeUint8(HP_CLIENT_HELLO, bos);
TlsUtils.writeUint24(os.size(), bos);
bos.write(os.toByteArray());
byte[] message = bos.toByteArray();
rs.writeMessage(RL_HANDSHAKE, message, 0, message.length);
connection_state = CS_CLIENT_HELLO_SEND;
/*
* We will now read data, until we have completed the handshake.
*/
while (connection_state != CS_DONE)
{
rs.readData();
}
this.tlsInputStream = new TlsInputStream(this);
this.tlsOutputStream = new TlsOuputStream(this);
}
/**
* Read data from the network. The method will return immed, if there is
* still some data left in the buffer, or block untill some application
* data has been read from the network.
*
* @param buf The buffer where the data will be copied to.
* @param offset The position where the data will be placed in the buffer.
* @param len The maximum number of bytes to read.
* @return The number of bytes read.
* @throws IOException If something goes wrong during reading data.
*/
protected int readApplicationData(byte[] buf, int offset, int len) throws IOException
{
while (applicationDataQueue.size() == 0)
{
/*
* We need to read some data.
*/
if (this.failedWithError)
{
/*
* Something went terribly wrong, we should throw an IOException
*/
throw new IOException(TLS_ERROR_MESSAGE);
}
if (this.closed)
{
/*
* Connection has been closed, there is no more data to read.
*/
return -1;
}
try
{
rs.readData();
}
catch (IOException e)
{
if (!this.closed)
{
this.failWithError(AL_fatal, AP_internal_error);
}
throw e;
}
catch (RuntimeException e)
{
if (!this.closed)
{
this.failWithError(AL_fatal, AP_internal_error);
}
throw e;
}
}
len = Math.min(len, applicationDataQueue.size());
applicationDataQueue.read(buf, offset, len, 0);
applicationDataQueue.removeData(len);
return len;
}
/**
* Send some application data to the remote system.
* <p/>
* The method will handle fragmentation internally.
*
* @param buf The buffer with the data.
* @param offset The position in the buffer where the data is placed.
* @param len The length of the data.
* @throws IOException If something goes wrong during sending.
*/
protected void writeData(byte[] buf, int offset, int len) throws IOException
{
if (this.failedWithError)
{
throw new IOException(TLS_ERROR_MESSAGE);
}
if (this.closed)
{
throw new IOException("Sorry, connection has been closed, you cannot write more data");
}
/*
* Protect against known IV attack!
*
* DO NOT REMOVE THIS LINE, EXCEPT YOU KNOW EXACTLY WHAT
* YOU ARE DOING HERE.
*/
rs.writeMessage(RL_APPLICATION_DATA, emptybuf, 0, 0);
do
{
/*
* We are only allowed to write fragments up to 2^14 bytes.
*/
int toWrite = Math.min(len, 1 << 14);
try
{
rs.writeMessage(RL_APPLICATION_DATA, buf, offset, toWrite);
}
catch (IOException e)
{
if (!closed)
{
this.failWithError(AL_fatal, AP_internal_error);
}
throw e;
}
catch (RuntimeException e)
{
if (!closed)
{
this.failWithError(AL_fatal, AP_internal_error);
}
throw e;
}
offset += toWrite;
len -= toWrite;
}
while (len > 0);
}
/**
* @return An OutputStream which can be used to send data.
*/
public TlsOuputStream getTlsOuputStream()
{
return this.tlsOutputStream;
}
/**
* @return An InputStream which can be used to read data.
*/
public TlsInputStream getTlsInputStream()
{
return this.tlsInputStream;
}
/**
* Terminate this connection whith an alert.
* <p/>
* Can be used for normal closure too.
*
* @param alertLevel The level of the alert, an be AL_fatal or AL_warning.
* @param alertDescription The exact alert message.
* @throws IOException If alert was fatal.
*/
protected void failWithError(short alertLevel, short alertDescription) throws IOException
{
/*
* Check if the connection is still open.
*/
if (!closed)
{
/*
* Prepare the message
*/
byte[] error = new byte[2];
error[0] = (byte)alertLevel;
error[1] = (byte)alertDescription;
this.closed = true;
if (alertLevel == AL_fatal)
{
/*
* This is a fatal message.
*/
this.failedWithError = true;
}
rs.writeMessage(RL_ALERT, error, 0, 2);
rs.close();
if (alertLevel == AL_fatal)
{
throw new IOException(TLS_ERROR_MESSAGE);
}
}
else
{
throw new IOException(TLS_ERROR_MESSAGE);
}
}
/**
* Closes this connection.
*
* @throws IOException If something goes wrong during closing.
*/
public void close() throws IOException
{
if (!closed)
{
this.failWithError((short)1, (short)0);
}
}
/**
* Make sure the InputStream is now empty. Fail otherwise.
*
* @param is The InputStream to check.
* @throws IOException If is is not empty.
*/
protected void assertEmpty(ByteArrayInputStream is) throws IOException
{
if (is.available() > 0)
{
this.failWithError(AL_fatal, AP_decode_error);
}
}
protected void flush() throws IOException
{
rs.flush();
}
} |
package gov.nih.nci.cananolab.service.common.impl;
import gov.nih.nci.cananolab.domain.common.ExperimentConfig;
import gov.nih.nci.cananolab.domain.common.Instrument;
import gov.nih.nci.cananolab.domain.common.Technique;
import gov.nih.nci.cananolab.exception.CaNanoLabException;
import gov.nih.nci.cananolab.exception.ExperimentConfigException;
import gov.nih.nci.cananolab.service.common.ExperimentConfigService;
import gov.nih.nci.cananolab.service.common.LookupService;
import gov.nih.nci.cananolab.system.applicationservice.CustomizedApplicationService;
import gov.nih.nci.cananolab.util.CaNanoLabComparators;
import gov.nih.nci.cananolab.util.DateUtil;
import gov.nih.nci.system.client.ApplicationServiceProvider;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.SortedSet;
import org.apache.log4j.Logger;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Property;
import org.hibernate.criterion.Restrictions;
public class ExperimentConfigServiceLocalImpl implements
ExperimentConfigService {
private static Logger logger = Logger
.getLogger(ExperimentConfigServiceLocalImpl.class);
public void saveExperimentConfig(ExperimentConfig config)
throws ExperimentConfigException {
try {
CustomizedApplicationService appService = (CustomizedApplicationService) ApplicationServiceProvider
.getApplicationService();
// get existing createdDate and createdBy
if (config.getId() != null) {
ExperimentConfig dbConfig = findExperimentConfigById(config
.getId().toString());
if (dbConfig != null) {
config.setCreatedBy(dbConfig.getCreatedBy());
config.setCreatedDate(dbConfig.getCreatedDate());
}
}
Technique technique = config.getTechnique();
// check if technique already exists;
Technique dbTechnique = findTechniqueByType(technique.getType());
if (dbTechnique != null) {
technique.setId(dbTechnique.getId());
technique.setCreatedBy(dbTechnique.getCreatedBy());
technique.setCreatedDate(dbTechnique.getCreatedDate());
} else {
technique.setCreatedBy(config.getCreatedBy());
technique.setCreatedDate(new Date());
}
// check if instrument already exists;
if (config.getInstrumentCollection() != null) {
Collection<Instrument> instruments = new HashSet<Instrument>(
config.getInstrumentCollection());
config.getInstrumentCollection().clear();
int i = 0;
for (Instrument instrument : instruments) {
Instrument dbInstrument = findInstrumentBy(instrument
.getType(), instrument.getManufacturer(),
instrument.getModelName());
if (dbInstrument != null) {
instrument.setId(dbInstrument.getId());
instrument.setCreatedBy(dbInstrument.getCreatedBy());
instrument
.setCreatedDate(dbInstrument.getCreatedDate());
} else {
instrument.setCreatedBy(config.getCreatedBy());
instrument.setCreatedDate(DateUtil
.addSecondsToCurrentDate(i));
}
config.getInstrumentCollection().add(instrument);
}
}
appService.saveOrUpdate(config);
} catch (Exception e) {
String err = "Error in saving the technique and associated instruments.";
logger.error(err, e);
throw new ExperimentConfigException(err, e);
}
}
public void deleteExperimentConfig(ExperimentConfig config)
throws ExperimentConfigException {
try {
CustomizedApplicationService appService = (CustomizedApplicationService) ApplicationServiceProvider
.getApplicationService();
// get existing createdDate and createdBy
if (config.getId() != null) {
ExperimentConfig dbConfig = findExperimentConfigById(config
.getId().toString());
if (dbConfig != null) {
config.setCreatedBy(dbConfig.getCreatedBy());
config.setCreatedDate(dbConfig.getCreatedDate());
}
}
Technique technique = config.getTechnique();
// check if technique already exists;
Technique dbTechnique = findTechniqueByType(technique.getType());
if (dbTechnique != null) {
technique.setId(dbTechnique.getId());
technique.setCreatedBy(dbTechnique.getCreatedBy());
technique.setCreatedDate(dbTechnique.getCreatedDate());
} else {
technique.setCreatedBy(config.getCreatedBy());
technique.setCreatedDate(new Date());
// need to save the transient object before deleting the
// experiment config
appService.saveOrUpdate(technique);
}
// check if instrument already exists;
if (config.getInstrumentCollection() != null) {
Collection<Instrument> instruments = new HashSet<Instrument>(
config.getInstrumentCollection());
config.getInstrumentCollection().clear();
int i = 0;
for (Instrument instrument : instruments) {
Instrument dbInstrument = findInstrumentBy(instrument
.getType(), instrument.getManufacturer(),
instrument.getModelName());
if (dbInstrument != null) {
instrument.setId(dbInstrument.getId());
instrument.setCreatedBy(dbInstrument.getCreatedBy());
instrument
.setCreatedDate(dbInstrument.getCreatedDate());
} else {
instrument.setCreatedBy(config.getCreatedBy());
instrument.setCreatedDate(DateUtil
.addSecondsToCurrentDate(i));
// need to save the transient object before deleting the
// experiment config
appService.saveOrUpdate(instrument);
}
config.getInstrumentCollection().add(instrument);
}
}
appService.delete(config);
} catch (Exception e) {
String err = "Error in deleting the technique and associated instruments";
logger.error(err, e);
throw new ExperimentConfigException(err, e);
}
}
public List<Technique> findAllTechniques() throws ExperimentConfigException {
List<Technique> techniques = new ArrayList<Technique>();
try {
CustomizedApplicationService appService = (CustomizedApplicationService) ApplicationServiceProvider
.getApplicationService();
DetachedCriteria crit = DetachedCriteria.forClass(Technique.class);
List results = appService.query(crit);
for (Object obj : results) {
Technique technique = (Technique) obj;
techniques.add(technique);
}
Collections.sort(techniques,
new CaNanoLabComparators.TechniqueComparator());
} catch (Exception e) {
String err = "Problem to retrieve all techniques.";
logger.error(err, e);
throw new ExperimentConfigException(err);
}
return techniques;
}
public List<String> getAllManufacturers() throws ExperimentConfigException {
List<String> manufacturers = new ArrayList<String>();
try {
CustomizedApplicationService appService = (CustomizedApplicationService) ApplicationServiceProvider
.getApplicationService();
DetachedCriteria crit = DetachedCriteria.forClass(Instrument.class)
.setProjection(
Projections.distinct(Property
.forName("manufacturer")));
;
List results = appService.query(crit);
for (Object obj : results) {
String manufacturer = (String) obj;
if (manufacturer != null && manufacturer.trim().length() > 0) {
manufacturers.add(manufacturer);
}
}
Collections.sort(manufacturers);
} catch (Exception e) {
String err = "Problem to retrieve all manufacturers.";
logger.error(err, e);
throw new ExperimentConfigException(err);
}
return manufacturers;
}
public ExperimentConfig findExperimentConfigById(String id)
throws ExperimentConfigException {
ExperimentConfig config = null;
try {
CustomizedApplicationService appService = (CustomizedApplicationService) ApplicationServiceProvider
.getApplicationService();
DetachedCriteria crit = DetachedCriteria.forClass(
ExperimentConfig.class).add(
Property.forName("id").eq(new Long(id)));
List results = appService.query(crit);
for (Object obj : results) {
config = (ExperimentConfig) obj;
}
} catch (Exception e) {
String err = "Problem to retrieve all manufacturers.";
logger.error(err, e);
throw new ExperimentConfigException(err);
}
return config;
}
public ExperimentConfig getANewExperimentConfig()
throws ExperimentConfigException {
//add by Qina tempory
ExperimentConfig config = new ExperimentConfig();
config.setTechnique(new Technique());
config.setInstrumentCollection(new ArrayList<Instrument>());
return config;
}
public Technique findTechniqueByType(String type)
throws ExperimentConfigException {
Technique technique = null;
try {
CustomizedApplicationService appService = (CustomizedApplicationService) ApplicationServiceProvider
.getApplicationService();
DetachedCriteria crit = DetachedCriteria.forClass(Technique.class)
.add(Property.forName("type").eq(new String(type)));
List results = appService.query(crit);
for (Object obj : results) {
technique = (Technique) obj;
}
} catch (Exception e) {
String err = "Problem to retrieve technique by type.";
logger.error(err, e);
throw new ExperimentConfigException(err);
}
return technique;
}
public Instrument findInstrumentBy(String type, String manufacturer,
String modelName) throws ExperimentConfigException {
Instrument instrument = null;
try {
CustomizedApplicationService appService = (CustomizedApplicationService) ApplicationServiceProvider
.getApplicationService();
DetachedCriteria crit = DetachedCriteria.forClass(Instrument.class);
if (type != null || type.length() > 0) {
crit.add(Restrictions.eq("type", type));
}
if (manufacturer != null || manufacturer.length() > 0) {
crit.add(Restrictions.eq("manufacturer", manufacturer));
}
if (modelName != null || modelName.length() > 0) {
crit.add(Restrictions.eq("modelName", modelName));
}
List results = appService.query(crit);
for (Object obj : results) {
instrument = (Instrument) obj;
}
} catch (Exception e) {
String err = "Problem to retrieve instrument by type, manufacturer, and model name.";
logger.error(err, e);
throw new ExperimentConfigException(err);
}
return instrument;
}
public String[] findInstrumentTypesByTechniqueType(String techniqueType)
throws ExperimentConfigException, CaNanoLabException {
SortedSet<String> types = null;
types = LookupService.getDefaultAndOtherLookupTypes(techniqueType,
"instrument", "otherInstrument");
if (types != null && types.size() > 0) {
String[] typeArray = new String[types.size()];
types.toArray(typeArray);
return typeArray;
} else {
return null;
}
}
public String[] findInstrumentTypesByConfigId(String configId)
throws ExperimentConfigException, CaNanoLabException {
String techniqueType = null;
SortedSet<String> types = null;
ExperimentConfig config = findExperimentConfigById(configId);
if (config != null && config.getTechnique() != null
&& config.getTechnique().getType() != null) {
techniqueType = config.getTechnique().getType();
types = LookupService.getDefaultAndOtherLookupTypes(techniqueType,
"instrument", "otherInstrument");
}
if (types != null && types.size() > 0) {
String[] typeArray = new String[types.size()];
types.toArray(typeArray);
return typeArray;
} else {
return null;
}
}
} |
package net.hawkengine.services;
import net.hawkengine.db.IDbRepository;
import net.hawkengine.db.redis.RedisRepository;
import net.hawkengine.model.JobDefinition;
import net.hawkengine.model.MaterialDefinition;
import net.hawkengine.model.PipelineDefinition;
import net.hawkengine.model.ServiceResult;
import net.hawkengine.model.StageDefinition;
import net.hawkengine.model.TaskDefinition;
import net.hawkengine.services.interfaces.IPipelineDefinitionService;
import java.util.List;
public class PipelineDefinitionService extends CrudService<PipelineDefinition> implements IPipelineDefinitionService {
public PipelineDefinitionService() {
super.setRepository(new RedisRepository(PipelineDefinition.class));
super.setObjectType("PipelineDefinition");
}
public PipelineDefinitionService(IDbRepository repository) {
super.setRepository(repository);
super.setObjectType("PipelineDefinition");
}
@Override
public ServiceResult getById(String pipelineDefinitionId) {
return super.getById(pipelineDefinitionId);
}
@Override
public ServiceResult getAll() {
return super.getAll();
}
@Override
public ServiceResult add(PipelineDefinition pipelineDefinition) {
List<MaterialDefinition> materialDefinitions = pipelineDefinition.getMaterials();
for(MaterialDefinition materialDefinition : materialDefinitions){
materialDefinition.setPipelineDefinitionId(pipelineDefinition.getId());
}
List<StageDefinition> stageDefinitions = pipelineDefinition.getStageDefinitions();
for (StageDefinition stageDefinition : stageDefinitions) {
stageDefinition.setPipelineDefinitionId(pipelineDefinition.getId());
List<JobDefinition> jobDefinitions = stageDefinition.getJobDefinitions();
for (JobDefinition jobDefinition : jobDefinitions) {
jobDefinition.setPipelineDefinitionId(pipelineDefinition.getId());
jobDefinition.setStageDefinitionId(stageDefinition.getId());
List<TaskDefinition> taskDefinitions = jobDefinition.getTaskDefinitions();
for (TaskDefinition taskDefinition : taskDefinitions) {
taskDefinition.setPipelineDefinitionId(pipelineDefinition.getId());
taskDefinition.setStageDefinitionId(stageDefinition.getId());
taskDefinition.setJobDefinitionId(jobDefinition.getId());
}
}
}
return super.add(pipelineDefinition);
}
@Override
public ServiceResult update(PipelineDefinition pipelineDefinition) {
return super.update(pipelineDefinition);
}
@Override
public ServiceResult delete(String pipelineDefinitionId) {
return super.delete(pipelineDefinitionId);
}
} |
package org.exist.xquery.functions.util;
import java.net.URLDecoder;
import org.exist.dom.QName;
import org.exist.xquery.BasicFunction;
import org.exist.xquery.Cardinality;
import org.exist.xquery.FunctionSignature;
import org.exist.xquery.XPathException;
import org.exist.xquery.XQueryContext;
import org.exist.xquery.value.Sequence;
import org.exist.xquery.value.SequenceType;
import org.exist.xquery.value.StringValue;
import org.exist.xquery.value.Type;
/**
* @author Adam Retter (adam.retter@devon.gov.uk)
*/
public class FunUnEscapeURI extends BasicFunction {
public final static FunctionSignature signature =
new FunctionSignature(
new QName("unescape-uri", UtilModule.NAMESPACE_URI, UtilModule.PREFIX),
"Returns an un-escaped URL escaped string identified by $a with the encoding scheme indicated by the string $b (e.g. \"UTF-8\"). Decodes encoded sensitive characters from a URL, for example \"%2F\" becomes \"/\", i.e. does the oposite to escape-uri()",
new SequenceType[]
{
new SequenceType(Type.STRING, Cardinality.EXACTLY_ONE),
new SequenceType(Type.STRING, Cardinality.EXACTLY_ONE)
},
new SequenceType(Type.STRING, Cardinality.EXACTLY_ONE));
/**
* @param context
* @param signature
*/
public FunUnEscapeURI(XQueryContext context)
{
super(context, signature);
}
/* (non-Javadoc)
* @see org.exist.xquery.BasicFunction#eval(org.exist.xquery.value.Sequence[], org.exist.xquery.value.Sequence)
*/
public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException
{
try
{
return new StringValue(URLDecoder.decode(args[0].getStringValue(), args[1].getStringValue()));
}
catch(java.io.UnsupportedEncodingException e)
{
throw new XPathException("Unsupported Encoding Scheme: " + e.getMessage(), e);
}
}
} |
package org.jamocha.dn.compiler;
import static java.util.stream.Collectors.toCollection;
import static java.util.stream.Collectors.toMap;
import static java.util.stream.Collectors.toSet;
import static org.jamocha.util.ToArray.toArray;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.tuple.Pair;
import org.jamocha.dn.ConstructCache.Defrule;
import org.jamocha.dn.ConstructCache.Defrule.TranslatedPath;
import org.jamocha.dn.memory.SlotType;
import org.jamocha.dn.memory.Template;
import org.jamocha.filter.FWACollector;
import org.jamocha.filter.Path;
import org.jamocha.filter.PathCollector;
import org.jamocha.filter.PathFilter;
import org.jamocha.filter.PathFilter.PathFilterElement;
import org.jamocha.filter.PathFilterList;
import org.jamocha.filter.PathFilterList.PathFilterSharedListWrapper;
import org.jamocha.filter.SymbolCollector;
import org.jamocha.filter.SymbolInSymbolLeafsCollector;
import org.jamocha.function.FunctionDictionary;
import org.jamocha.function.FunctionNormaliser;
import org.jamocha.function.Predicate;
import org.jamocha.function.fwa.DefaultFunctionWithArgumentsVisitor;
import org.jamocha.function.fwa.FunctionWithArguments;
import org.jamocha.function.fwa.PathLeaf;
import org.jamocha.function.fwa.PredicateWithArguments;
import org.jamocha.function.fwa.PredicateWithArgumentsComposite;
import org.jamocha.function.fwa.SymbolLeaf;
import org.jamocha.function.fwatransformer.FWADeepCopy;
import org.jamocha.function.impls.predicates.Equals;
import org.jamocha.function.impls.predicates.Not;
import org.jamocha.languages.common.ConditionalElement;
import org.jamocha.languages.common.ConditionalElement.AndFunctionConditionalElement;
import org.jamocha.languages.common.ConditionalElement.ExistentialConditionalElement;
import org.jamocha.languages.common.ConditionalElement.NegatedExistentialConditionalElement;
import org.jamocha.languages.common.ConditionalElement.NotFunctionConditionalElement;
import org.jamocha.languages.common.ConditionalElement.OrFunctionConditionalElement;
import org.jamocha.languages.common.ConditionalElement.SharedConditionalElementWrapper;
import org.jamocha.languages.common.ConditionalElement.TestConditionalElement;
import org.jamocha.languages.common.DefaultConditionalElementsVisitor;
import org.jamocha.languages.common.RuleCondition.EquivalenceClass;
import org.jamocha.languages.common.ScopeStack.VariableSymbol;
import org.jamocha.languages.common.SingleFactVariable;
import org.jamocha.languages.common.SingleFactVariable.SingleSlotVariable;
import org.jamocha.languages.common.errors.VariableNotDeclaredError;
/**
* Collect all PathFilters inside all children of an OrFunctionConditionalElement, returning a List
* of Lists. Each inner List contains the PathFilters of one child.
*
* @author Fabian Ohler <fabian.ohler1@rwth-aachen.de>
* @author Christoph Terwelp <christoph.terwelp@rwth-aachen.de>
*/
@RequiredArgsConstructor
public class PathFilterConsolidator implements DefaultConditionalElementsVisitor {
private final Template initialFactTemplate;
private final Defrule rule;
private final Map<Path, Set<Path>> pathToJoinedWith = new HashMap<>();
@Getter
private List<Defrule.TranslatedPath> translateds = null;
public List<Defrule.TranslatedPath> consolidate() {
assert rule.getCondition().getConditionalElements().size() == 1;
return rule.getCondition().getConditionalElements().get(0).accept(this).translateds;
}
@Override
public void defaultAction(final ConditionalElement ce) {
// If there is no OrFunctionConditionalElement just proceed with the CE as it were
// the only child of an OrFunctionConditionalElement.
final Map<VariableSymbol, EquivalenceClass> symbolToEC =
new SymbolCollector(rule.getCondition()).getSymbols().stream()
.collect(toMap(Function.identity(), VariableSymbol::getEqual));
translateds =
Collections.singletonList(NoORsPFC.consolidate(initialFactTemplate, rule, pathToJoinedWith, ce,
symbolToEC));
}
@Override
public void visit(final OrFunctionConditionalElement ce) {
final Map<VariableSymbol, EquivalenceClass> symbolToEC =
new SymbolCollector(rule.getCondition()).getSymbols().stream()
.collect(toMap(Function.identity(), VariableSymbol::getEqual));
// For each child of the OrCE ...
this.translateds =
ce.getChildren().stream().map(child ->
// ... collect all PathFilters in the child
NoORsPFC.consolidate(initialFactTemplate, rule, pathToJoinedWith, child, symbolToEC))
.collect(Collectors.toCollection(ArrayList::new));
}
/**
* @author Fabian Ohler <fabian.ohler1@rwth-aachen.de>
* @author Christoph Terwelp <christoph.terwelp@rwth-aachen.de>
*/
@RequiredArgsConstructor(access = AccessLevel.PRIVATE)
static class NoORsPFC implements DefaultConditionalElementsVisitor {
private final Template initialFactTemplate;
private final Path initialFactPath;
private final Map<SingleFactVariable, Path> paths;
private final Map<Path, Set<Path>> pathToJoinedWith;
private final Map<EquivalenceClass, PathLeaf> equivalenceClassToPathLeaf;
private final boolean negated;
@Getter
private List<PathFilterList> pathFilters = new ArrayList<>();
public static TranslatedPath consolidate(final Template initialFactTemplate, final Defrule rule,
final Map<Path, Set<Path>> pathToJoinedWith, final ConditionalElement ce,
final Map<VariableSymbol, EquivalenceClass> symbolToECbackup) {
// copy the equivalence classes
final Map<EquivalenceClass, EquivalenceClass> oldToNew =
symbolToECbackup.values().stream().collect(toMap(Function.identity(), EquivalenceClass::new));
// update the negation references between the sets
oldToNew.values().stream().forEach(n -> n.replace(oldToNew));
// use the new equivalence classes in the symbols
symbolToECbackup.forEach((vs, ec) -> vs.setEqual(oldToNew.get(ec)));
final Set<VariableSymbol> symbols = symbolToECbackup.keySet();
final HashSet<FunctionWithArguments<SymbolLeaf>> occurringFWAs =
FWACollector.newHashSet().collect(ce).getFwas();
final HashSet<SingleFactVariable> occurringFactVariables =
new HashSet<>(DeepFactVariableCollector.collect(ce));
/* inspect the equivalence class hierarchy for sections not contained in this rule part */
// for every symbol in the CE
for (final VariableSymbol vs : symbols) {
// and thus for every equivalence class
final EquivalenceClass ec = vs.getEqual();
// check whether the fact variable is bound via a TPCE
final Optional<SingleFactVariable> fv = ec.getFactVariable();
if (fv.isPresent() && !occurringFactVariables.contains(fv.get())) {
// the fact variable for the EC is not contained in the CE, remove it
ec.removeFactVariable();
}
// for every slot variable, check whether the corresponding fact variable is
// contained in the CE
for (final Iterator<SingleSlotVariable> iterator = ec.getEqualSlotVariables().iterator(); iterator
.hasNext();) {
final SingleSlotVariable sv = iterator.next();
if (!occurringFactVariables.contains(sv.getFactVariable())) {
// not contained, remove the SV and its reference to this EC
iterator.remove();
sv.getEqual().remove(ec);
}
}
// for every FWA, check whether the FWA occurs in the CE
ec.getEqualFWAs().removeIf(fwa -> !occurringFWAs.contains(fwa));
}
/* merge (bind)s and overlapping SlotVariables */
for (final VariableSymbol vs : symbols) {
final EquivalenceClass ec = vs.getEqual();
for (final SingleSlotVariable sv : ec.getEqualSlotVariables()) {
if (sv.getEqual().size() <= 1)
continue;
final Iterator<EquivalenceClass> ecIter = sv.getEqual().iterator();
final EquivalenceClass first = ecIter.next();
while (ecIter.hasNext()) {
final EquivalenceClass other = ecIter.next();
first.add(other);
symbols.forEach(sym -> {
if (other == sym.getEqual())
sym.setEqual(first);
});
}
}
}
/* check that all variables are bound */
final Set<VariableSymbol> symbolsInLeafs = new SymbolInSymbolLeafsCollector(ce).getSymbols();
for (final VariableSymbol vs : symbols) {
final EquivalenceClass ec = vs.getEqual();
if (!ec.getFactVariable().isPresent() && ec.getEqualSlotVariables().isEmpty()) {
if (!ec.getUnequalEquivalenceClasses().isEmpty() || symbolsInLeafs.contains(vs))
// vs is not bound
throw new VariableNotDeclaredError(vs);
}
}
/* merge equals test conditional elements arguments */
ce.accept(new CEEquivalenceClassBuilder(symbols, false));
final TranslatedPath result =
consolidateOnCopiedEquivalenceClasses(initialFactTemplate, rule, pathToJoinedWith, ce, symbols
.stream().map(VariableSymbol::getEqual).collect(toSet()));
// reset the symbol - equivalence class mapping
symbolToECbackup.forEach((vs, ec) -> vs.setEqual(ec));
return result;
}
static class CEEquivalenceClassBuilder implements DefaultConditionalElementsVisitor {
final Set<VariableSymbol> occurringSymbols;
final Map<FunctionWithArguments<SymbolLeaf>, EquivalenceClass> equivalenceClasses;
final FWAEquivalenceClassBuilder fwaBuilder = new FWAEquivalenceClassBuilder();
boolean negated = false;
public CEEquivalenceClassBuilder(final Set<VariableSymbol> occurringSymbols, final boolean negated) {
super();
this.negated = negated;
this.occurringSymbols = occurringSymbols;
this.equivalenceClasses =
occurringSymbols.stream().collect(toMap(SymbolLeaf::new, VariableSymbol::getEqual));
}
@RequiredArgsConstructor
class FWAEquivalenceClassBuilder implements DefaultFunctionWithArgumentsVisitor<SymbolLeaf> {
private EquivalenceClass getEC(final FunctionWithArguments<SymbolLeaf> fwa) {
return equivalenceClasses.computeIfAbsent(fwa, f -> new EquivalenceClass(f));
}
@Override
public void visit(final PredicateWithArgumentsComposite<SymbolLeaf> fwa) {
if (fwa.getFunction().inClips().equals(Equals.inClips)) {
final FunctionWithArguments<SymbolLeaf>[] args =
FunctionNormaliser.normalise(FWADeepCopy.copy(fwa)).getArgs();
if (negated) {
final EquivalenceClass left = getEC(args[0]);
for (int i = 1; i < args.length; ++i) {
final EquivalenceClass right = getEC(args[i]);
left.addNegatedEdge(right);
}
} else {
final EquivalenceClass left = getEC(args[0]);
for (int i = 1; i < args.length; i++) {
final FunctionWithArguments<SymbolLeaf> arg = args[i];
final EquivalenceClass right = getEC(arg);
left.add(right);
equivalenceClasses.put(arg, left);
occurringSymbols.forEach(sym -> {
if (right == sym.getEqual())
sym.setEqual(left);
});
}
}
}
}
@Override
public void defaultAction(final FunctionWithArguments<SymbolLeaf> function) {
}
}
@Override
public void defaultAction(final ConditionalElement ce) {
ce.getChildren().forEach(c -> c.accept(this));
}
@Override
public void visit(final TestConditionalElement ce) {
ce.getPredicateWithArguments().accept(fwaBuilder);
}
@Override
public void visit(final NotFunctionConditionalElement ce) {
negated = !negated;
defaultAction(ce);
negated = !negated;
}
}
@SuppressWarnings("unchecked")
private static TranslatedPath consolidateOnCopiedEquivalenceClasses(final Template initialFactTemplate,
final Defrule rule, final Map<Path, Set<Path>> pathToJoinedWith, final ConditionalElement ce,
final Set<EquivalenceClass> equivalenceClasses) {
final Pair<Path, Map<SingleFactVariable, Path>> initialFactAndPathMap =
ShallowFactVariableCollector.generatePaths(initialFactTemplate, ce);
final Map<SingleFactVariable, Path> pathMap = initialFactAndPathMap.getRight();
final Set<Path> allPaths = new HashSet<>(pathMap.values());
final Map<EquivalenceClass, PathLeaf> equivalenceClassToPathLeaf = new HashMap<>();
for (final EquivalenceClass equiv : equivalenceClasses) {
equivalenceClassToPathLeaf.put(equiv, equiv.getPathLeaf(pathMap));
}
final NoORsPFC instance =
new NoORsPFC(initialFactTemplate, initialFactAndPathMap.getLeft(), pathMap, pathToJoinedWith,
equivalenceClassToPathLeaf, false).collect(ce);
final List<PathFilterList> pathFilters = instance.getPathFilters();
// add the tests for the equivalence classes
{
final Set<EquivalenceClass> neqAlreadyDone = new HashSet<>();
// TODO improve the test generation by doing something smart
for (final EquivalenceClass equiv : equivalenceClasses) {
if (!neqAlreadyDone.add(equiv))
continue;
final FunctionWithArguments<PathLeaf> element = equivalenceClassToPathLeaf.get(equiv);
if (null == element)
continue;
if (equiv.getEqualSlotVariables().isEmpty()) {
assert equiv.getFactVariable().isPresent();
} else {
final Set<FunctionWithArguments<PathLeaf>> equalPathLeafs =
equiv.getEqualSlotVariables().stream()
.map(sv -> equivalenceClassToPathLeaf.get(sv.getFactVariable().getEqual()))
.collect(toSet());
equiv.getFactVariable().map(fv -> fv.getPathLeaf(pathMap)).ifPresent(equalPathLeafs::add);
if (equalPathLeafs.size() > 1) {
final PathFilter eqTest =
new PathFilter(new PathFilterElement(new PredicateWithArgumentsComposite<PathLeaf>(
FunctionDictionary.lookupPredicate(Equals.inClips,
SlotType.nCopies(equiv.getType(), equalPathLeafs.size())), toArray(
equalPathLeafs, FunctionWithArguments[]::new))));
joinPaths(pathToJoinedWith, eqTest);
pathFilters.add(eqTest);
}
}
if (!equiv.getEqualFWAs().isEmpty()) {
final FunctionWithArguments<PathLeaf>[] equalFWAsArray =
new FunctionWithArguments[equiv.getEqualFWAs().size() + 1];
equalFWAsArray[0] = element;
int i = 1;
for (final FunctionWithArguments<SymbolLeaf> fwa : equiv.getEqualFWAs()) {
equalFWAsArray[i++] = SymbolToPathTranslator.translate(fwa, equivalenceClassToPathLeaf);
}
final PathFilter eqTest =
new PathFilter(new PathFilterElement(new PredicateWithArgumentsComposite<PathLeaf>(
FunctionDictionary.lookupPredicate(Equals.inClips,
SlotType.nCopies(equiv.getType(), equalFWAsArray.length + 1)),
equalFWAsArray)));
joinPaths(pathToJoinedWith, eqTest);
pathFilters.add(eqTest);
}
if (!equiv.getUnequalEquivalenceClasses().isEmpty()) {
final Predicate not = FunctionDictionary.lookupPredicate(Not.inClips, SlotType.BOOLEAN);
for (final EquivalenceClass nequiv : equiv.getUnequalEquivalenceClasses()) {
if (!neqAlreadyDone.contains(nequiv)) {
final PathLeaf pathLeaf = equivalenceClassToPathLeaf.get(nequiv);
final PathFilter neqTest =
new PathFilter(new PathFilterElement(
new PredicateWithArgumentsComposite<PathLeaf>(not,
new PredicateWithArgumentsComposite<PathLeaf>(
FunctionDictionary.lookupPredicate(Equals.inClips,
element.getReturnType(),
pathLeaf.getReturnType()), element, pathLeaf))));
joinPaths(pathToJoinedWith, neqTest);
pathFilters.add(neqTest);
}
}
}
}
}
final Set<Path> collectedPaths =
(pathFilters.isEmpty() ? Collections.<Path> emptySet() : PathCollector.newHashSet()
.collectOnlyInFilterElements(pathFilters.get(pathFilters.size() - 1)).getPaths().stream()
.flatMap((p) -> pathToJoinedWith.get(p).stream()).collect(toSet()));
final TranslatedPath translated =
rule.newTranslated(new PathFilterSharedListWrapper().newSharedElement(pathFilters),
equivalenceClassToPathLeaf);
if (collectedPaths.containsAll(allPaths)) {
return translated;
}
allPaths.addAll(collectedPaths);
final PathFilter dummy =
new PathFilter(new PathFilter.DummyPathFilterElement(toArray(allPaths, Path[]::new)));
joinPaths(pathToJoinedWith, dummy);
pathFilters.add(dummy);
return translated;
}
private <T extends ConditionalElement> NoORsPFC collect(final T ce) {
return ce.accept(this);
}
static List<PathFilterList> processExistentialCondition(final Template initialFactTemplate,
final Path initialFactPath, final ConditionalElement ce, final Map<SingleFactVariable, Path> fact2Path,
final Map<Path, Set<Path>> pathToJoinedWith,
final Map<EquivalenceClass, PathLeaf> equivalenceClassToPathLeaf, final boolean isPositive) {
// Collect the existential FactVariables and corresponding paths from the existentialCE
final Pair<Path, Map<SingleFactVariable, Path>> initialFactAndPathMap =
ShallowFactVariableCollector.generatePaths(initialFactTemplate, ce);
final Map<SingleFactVariable, Path> existentialFact2Path = initialFactAndPathMap.getRight();
// combine existential FactVariables and Paths with non existential ones for PathFilter
// generation
final Map<SingleFactVariable, Path> combinedFact2Path = new HashMap<SingleFactVariable, Path>(fact2Path);
combinedFact2Path.putAll(existentialFact2Path);
for (final EquivalenceClass equiv : equivalenceClassToPathLeaf.keySet()) {
equivalenceClassToPathLeaf.computeIfAbsent(equiv, e -> e.getPathLeaf(combinedFact2Path));
}
// Only existential Paths without Variables
final Set<Path> existentialPaths = new HashSet<>(existentialFact2Path.values());
// Generate PathFilters from CE (recurse)
final List<PathFilterList> filters =
new NoORsPFC(initialFactTemplate, initialFactAndPathMap.getLeft(), combinedFact2Path,
pathToJoinedWith, equivalenceClassToPathLeaf, false).collect(ce).getPathFilters();
// Collect all used Paths for every PathFilter
final Map<PathFilterList, HashSet<Path>> filter2Paths =
filters.stream().collect(
Collectors.toMap(Function.identity(),
filter -> PathCollector.newHashSet().collectAll(filter).getPaths()));
// Split PathFilters into those only using existential Paths and those also using non
// existential Paths
final Map<Boolean, LinkedList<PathFilterList>> tmp =
filters.stream().collect(
Collectors.partitioningBy(filter -> existentialPaths.containsAll(filter2Paths.get(filter)),
toCollection(LinkedList::new)));
final LinkedList<PathFilterList> pureExistentialFilters = tmp.get(Boolean.TRUE);
final LinkedList<PathFilterList> nonPureExistentialFilters = tmp.get(Boolean.FALSE);
// Add all pureExistentialFilters to result List because they don't have to be combined
// or ordered
final List<PathFilterList> resultFilters = new ArrayList<>(pureExistentialFilters);
if (nonPureExistentialFilters.isEmpty()) {
// if there are only existential filters, append one combining them with an initial
// fact path
assert null != initialFactPath;
final ArrayList<Path> paths = new ArrayList<>();
paths.addAll(existentialPaths);
paths.add(initialFactPath);
final PathFilter existentialClosure =
new PathFilter(isPositive, existentialPaths, new PathFilter.DummyPathFilterElement(toArray(
paths, Path[]::new)));
joinPaths(pathToJoinedWith, existentialClosure);
return Arrays.asList(new PathFilterList.PathFilterExistentialList(resultFilters, existentialClosure));
}
// Construct HashMap from Paths to Filters
final Map<Path, Set<PathFilterList>> path2Filters = new HashMap<>();
filter2Paths.forEach((pathFilter, paths) -> paths.forEach(path -> path2Filters.computeIfAbsent(path,
x -> new HashSet<>()).add(pathFilter)));
// Find connected components of the existential Paths
final Map<Path, Set<Path>> joinedExistentialPaths = new HashMap<>();
final Set<Path> processedExistentialPaths = new HashSet<>();
// While there are unjoined Filters continue
while (!pureExistentialFilters.isEmpty()) {
// Take one arbitrary filter
final LinkedList<PathFilterList> collectedFilters =
new LinkedList<>(Collections.singletonList(pureExistentialFilters.poll()));
Set<PathFilterList> newCollectedFilters = new HashSet<>(collectedFilters);
final Set<Path> collectedPaths = new HashSet<>();
// While we found new PathFilters in the last round
while (!newCollectedFilters.isEmpty()) {
// search for all Paths used by the new Filters
final Set<Path> newCollectedPaths =
newCollectedFilters.stream().flatMap(f -> filter2Paths.get(f).stream())
.collect(Collectors.toSet());
// removed already known paths
newCollectedPaths.removeAll(collectedPaths);
// add the new ones to the collect set
collectedPaths.addAll(newCollectedPaths);
// search for all filters containing the new found paths
newCollectedFilters =
newCollectedPaths.stream().flatMap(path -> path2Filters.get(path).stream())
.collect(toSet());
// remove already known filters
newCollectedFilters.removeAll(collectedFilters);
// add them all to the collect set
collectedFilters.addAll(newCollectedFilters);
// remove them from the set of unassigned filters
pureExistentialFilters.removeAll(newCollectedFilters);
}
// save the connected components
for (final Path path : collectedPaths) {
joinedExistentialPaths.put(path, collectedPaths);
}
// mark the paths as processed
processedExistentialPaths.addAll(collectedPaths);
}
// Combine nonPureExistentialFilters if necessary and add them to result List
while (!nonPureExistentialFilters.isEmpty()) {
final List<PathFilterList> collectedFilters =
new ArrayList<>(Collections.singletonList(nonPureExistentialFilters.poll()));
Set<PathFilterList> newCollectedFilters = new HashSet<>(collectedFilters);
final Set<Path> collectedExistentialPaths = new HashSet<>();
while (!newCollectedFilters.isEmpty()) {
// search for all existential Paths used by the new Filters
final Set<Path> newCollectedExistentialPaths =
newCollectedFilters.stream()
.flatMap((final PathFilterList f) -> filter2Paths.get(f).stream()).collect(toSet());
newCollectedExistentialPaths.retainAll(existentialPaths);
// removed already known paths
newCollectedExistentialPaths.removeAll(collectedExistentialPaths);
// add all existential paths already joined with the new paths
{
final Set<Path> toDeplete = new HashSet<>(newCollectedExistentialPaths);
while (!toDeplete.isEmpty()) {
final Path path = toDeplete.iterator().next();
final Set<Path> joined = joinedExistentialPaths.get(path);
toDeplete.removeAll(joined);
newCollectedExistentialPaths.addAll(joined);
}
}
// add the new ones to the collect set
collectedExistentialPaths.addAll(newCollectedExistentialPaths);
// search for all filters containing the new found paths
newCollectedFilters =
newCollectedExistentialPaths.stream().flatMap(path -> path2Filters.get(path).stream())
.collect(toSet());
newCollectedFilters.retainAll(nonPureExistentialFilters);
// remove already known filters
newCollectedFilters.removeAll(collectedFilters);
// add them all to the collect set
collectedFilters.addAll(newCollectedFilters);
// remove them from the set of unassigned filters
nonPureExistentialFilters.removeAll(newCollectedFilters);
}
final List<PathFilterElement> filterElements = new ArrayList<>();
for (final PathFilterList filterList : collectedFilters) {
for (final PathFilter filter : filterList) {
filterElements.addAll(Arrays.asList(filter.getFilterElements()));
}
}
final PathFilter combiningFilter =
new PathFilter(isPositive, collectedExistentialPaths, toArray(filterElements,
PathFilterElement[]::new));
joinPaths(pathToJoinedWith, combiningFilter);
resultFilters.add(combiningFilter);
processedExistentialPaths.addAll(collectedExistentialPaths);
}
{
// if not all paths within this existential CE have been used in some test, add a
// dummy filter element to have them joined, too
final Set<Path> unprocessedExistentialPaths = new HashSet<>(existentialPaths);
unprocessedExistentialPaths.removeAll(processedExistentialPaths);
if (!unprocessedExistentialPaths.isEmpty()) {
final PathFilter dummy =
new PathFilter(isPositive, unprocessedExistentialPaths,
new PathFilter.DummyPathFilterElement(toArray(unprocessedExistentialPaths,
Path[]::new)));
joinPaths(pathToJoinedWith, dummy);
resultFilters.add(dummy);
}
}
return resultFilters;
}
@Override
public void defaultAction(final ConditionalElement ce) {
// Just ignore. InitialFactCEs and TemplateCEs already did their job during
// FactVariable collection
}
@Override
public void visit(final AndFunctionConditionalElement ce) {
pathFilters =
ce.getChildren()
.stream()
// Process all children CEs
.map(child -> child.accept(
new NoORsPFC(initialFactTemplate, initialFactPath, paths, pathToJoinedWith,
equivalenceClassToPathLeaf, negated)).getPathFilters())
// merge Lists
.flatMap(List::stream).collect(Collectors.toCollection(ArrayList::new));
}
@Override
public void visit(final OrFunctionConditionalElement ce) {
throw new Error("There should not be any OrFunctionCEs at this level.");
}
@Override
public void visit(final ExistentialConditionalElement ce) {
assert ce.getChildren().size() == 1;
this.pathFilters =
processExistentialCondition(initialFactTemplate, initialFactPath, ce.getChildren().get(0), paths,
pathToJoinedWith, equivalenceClassToPathLeaf, true);
}
@Override
public void visit(final NegatedExistentialConditionalElement ce) {
assert ce.getChildren().size() == 1;
this.pathFilters =
processExistentialCondition(initialFactTemplate, initialFactPath, ce.getChildren().get(0), paths,
pathToJoinedWith, equivalenceClassToPathLeaf, false);
}
@Override
public void visit(final NotFunctionConditionalElement ce) {
assert ce.getChildren().size() == 1;
// Call a PathFilterCollector for the child of the NotFunctionCE with toggled negated
// flag.
this.pathFilters =
ce.getChildren()
.get(0)
.accept(new NoORsPFC(initialFactTemplate, initialFactPath, paths, pathToJoinedWith,
equivalenceClassToPathLeaf, !negated)).getPathFilters();
}
@Override
public void visit(final SharedConditionalElementWrapper ce) {
// use the wrapper for the inner shared instances
this.pathFilters =
Collections.singletonList(ce.getWrapper().newSharedElement(
ce.getCe()
.accept(new NoORsPFC(initialFactTemplate, initialFactPath, paths, pathToJoinedWith,
equivalenceClassToPathLeaf, negated)).getPathFilters()));
}
@Override
public void visit(final TestConditionalElement ce) {
final PredicateWithArguments<SymbolLeaf> pwa = ce.getPredicateWithArguments();
// ignore equals-test, they are covered via the equivalence classes
if (pwa instanceof PredicateWithArgumentsComposite
&& ((PredicateWithArgumentsComposite<SymbolLeaf>) pwa).getFunction().inClips()
.equals(Equals.inClips))
return;
final PredicateWithArguments<PathLeaf> predicate =
SymbolToPathTranslator.translate(FWADeepCopy.copy(pwa), equivalenceClassToPathLeaf);
final PathFilter pathFilter =
new PathFilter(new PathFilterElement((negated) ? new PredicateWithArgumentsComposite<>(
FunctionDictionary.lookupPredicate(Not.inClips, SlotType.BOOLEAN), predicate) : predicate));
joinPaths(pathToJoinedWith, pathFilter);
this.pathFilters = Collections.singletonList(pathFilter);
}
private static void joinPaths(final Map<Path, Set<Path>> pathToJoinedWith, final PathFilter pathFilter) {
final Set<Path> joinedPaths =
PathCollector
.newHashSet()
.collectAll(pathFilter)
.getPaths()
.stream()
.flatMap(
p -> pathToJoinedWith.computeIfAbsent(p, k -> new HashSet<Path>(Arrays.asList(k)))
.stream()).collect(toSet());
joinedPaths.forEach(p -> pathToJoinedWith.put(p, joinedPaths));
}
}
} |
// This file is part of the Whiley-to-Java Compiler (wyjc).
// The Whiley-to-Java Compiler is free software; you can redistribute
// it and/or modify it under the terms of the GNU General Public
// The Whiley-to-Java Compiler is distributed in the hope that it
// You should have received a copy of the GNU General Public
package wyjc.testing.tests;
import org.junit.*;
import wyjc.testing.TestHarness;
public class DefiniteStaticValidTests extends TestHarness {
public DefiniteStaticValidTests() {
super("tests/valid/definite","tests/valid/definite","sysout");
}
@Test public void BoolAssign_Valid_1_StaticTest() { verificationRunTest("BoolAssign_Valid_1"); }
@Test public void BoolAssign_Valid_2_StaticTest() { verificationRunTest("BoolAssign_Valid_2"); }
@Test public void BoolAssign_Valid_3_StaticTest() { verificationRunTest("BoolAssign_Valid_3"); }
@Test public void BoolAssign_Valid_4_StaticTest() { verificationRunTest("BoolAssign_Valid_4"); }
@Test public void BoolFun_Valid_1_StaticTest() { verificationRunTest("BoolFun_Valid_1"); }
@Test public void BoolIfElse_Valid_1_StaticTest() { verificationRunTest("BoolIfElse_Valid_1"); }
@Test public void BoolList_Valid_1_StaticTest() { verificationRunTest("BoolList_Valid_1"); }
@Test public void BoolRequires_Valid_1_StaticTest() { verificationRunTest("BoolRequires_Valid_1"); }
@Test public void BoolReturn_Valid_1_StaticTest() { verificationRunTest("BoolReturn_Valid_1"); }
@Test public void BoolRecord_Valid_1_StaticTest() { verificationRunTest("BoolRecord_Valid_1"); }
@Test public void BoolRecord_Valid_2_StaticTest() { verificationRunTest("BoolRecord_Valid_2"); }
@Test public void ConstrainedInt_Valid_1_StaticTest() { verificationRunTest("ConstrainedInt_Valid_1"); }
@Test public void ConstrainedInt_Valid_10_StaticTest() { verificationRunTest("ConstrainedInt_Valid_10"); }
@Test public void ConstrainedInt_Valid_11_StaticTest() { verificationRunTest("ConstrainedInt_Valid_11"); }
@Test public void ConstrainedInt_Valid_2_StaticTest() { verificationRunTest("ConstrainedInt_Valid_2"); }
@Test public void ConstrainedInt_Valid_3_StaticTest() { verificationRunTest("ConstrainedInt_Valid_3"); }
@Test public void ConstrainedInt_Valid_4_StaticTest() { verificationRunTest("ConstrainedInt_Valid_4"); }
@Test public void ConstrainedInt_Valid_5_StaticTest() { verificationRunTest("ConstrainedInt_Valid_5"); }
@Test public void ConstrainedInt_Valid_6_StaticTest() { verificationRunTest("ConstrainedInt_Valid_6"); }
@Test public void ConstrainedInt_Valid_7_StaticTest() { verificationRunTest("ConstrainedInt_Valid_7"); }
@Test public void ConstrainedInt_Valid_8_StaticTest() { verificationRunTest("ConstrainedInt_Valid_8"); }
@Test public void ConstrainedInt_Valid_9_StaticTest() { verificationRunTest("ConstrainedInt_Valid_9"); }
@Test public void ConstrainedList_Valid_1_StaticTest() { verificationRunTest("ConstrainedList_Valid_1"); }
@Test public void ConstrainedList_Valid_2_StaticTest() { verificationRunTest("ConstrainedList_Valid_2"); }
@Test public void ConstrainedList_Valid_3_StaticTest() { verificationRunTest("ConstrainedList_Valid_3"); }
@Test public void ConstrainedList_Valid_4_StaticTest() { verificationRunTest("ConstrainedList_Valid_4"); }
@Test public void ConstrainedSet_Valid_1_StaticTest() { verificationRunTest("ConstrainedSet_Valid_1"); }
@Test public void ConstrainedSet_Valid_2_StaticTest() { verificationRunTest("ConstrainedSet_Valid_2"); }
@Test public void ConstrainedSet_Valid_3_StaticTest() { verificationRunTest("ConstrainedSet_Valid_3"); }
@Test public void ConstrainedSet_Valid_4_StaticTest() { verificationRunTest("ConstrainedSet_Valid_4"); }
@Test public void ConstrainedRecord_Valid_1_StaticTest() { verificationRunTest("ConstrainedRecord_Valid_1"); }
@Test public void ConstrainedRecord_Valid_2_StaticTest() { verificationRunTest("ConstrainedRecord_Valid_2"); }
@Test public void ConstrainedRecord_Valid_3_StaticTest() { verificationRunTest("ConstrainedRecord_Valid_3"); }
@Test public void ConstrainedRecord_Valid_4_StaticTest() { verificationRunTest("ConstrainedRecord_Valid_4"); }
@Test public void ConstrainedRecord_Valid_5_StaticTest() { verificationRunTest("ConstrainedRecord_Valid_5"); }
@Test public void Define_Valid_1_StaticTest() { verificationRunTest("Define_Valid_1"); }
@Test public void Define_Valid_2_StaticTest() { verificationRunTest("Define_Valid_2"); }
@Test public void Define_Valid_3_StaticTest() { verificationRunTest("Define_Valid_3"); }
@Test public void Define_Valid_4_StaticTest() { verificationRunTest("Define_Valid_4"); }
@Test public void Ensures_Valid_1_StaticTest() { verificationRunTest("Ensures_Valid_1"); }
@Test public void Ensures_Valid_2_StaticTest() { verificationRunTest("Ensures_Valid_2"); }
@Test public void Ensures_Valid_3_StaticTest() { verificationRunTest("Ensures_Valid_3"); }
@Test public void Ensures_Valid_4_StaticTest() { verificationRunTest("Ensures_Valid_4"); }
@Test public void Ensures_Valid_5_StaticTest() { verificationRunTest("Ensures_Valid_5"); }
@Test public void For_Valid_1_StaticTest() { verificationRunTest("For_Valid_1"); }
@Test public void For_Valid_2_StaticTest() { verificationRunTest("For_Valid_2"); }
@Test public void For_Valid_3_StaticTest() { verificationRunTest("For_Valid_3"); }
@Test public void Function_Valid_1_StaticTest() { verificationRunTest("Function_Valid_1"); }
@Test public void Function_Valid_10_StaticTest() { verificationRunTest("Function_Valid_10"); }
@Test public void Function_Valid_11_StaticTest() { verificationRunTest("Function_Valid_11"); }
@Test public void Function_Valid_2_StaticTest() { verificationRunTest("Function_Valid_2"); }
@Test public void Function_Valid_3_StaticTest() { verificationRunTest("Function_Valid_3"); }
@Test public void Function_Valid_4_StaticTest() { verificationRunTest("Function_Valid_4"); }
@Test public void Function_Valid_5_StaticTest() { verificationRunTest("Function_Valid_5"); }
@Test public void Function_Valid_6_StaticTest() { verificationRunTest("Function_Valid_6"); }
@Test public void Function_Valid_7_StaticTest() { verificationRunTest("Function_Valid_7"); }
@Test public void Function_Valid_8_StaticTest() { verificationRunTest("Function_Valid_8"); }
@Test public void Function_Valid_9_StaticTest() { verificationRunTest("Function_Valid_9"); }
@Test public void IfElse_Valid_1_StaticTest() { verificationRunTest("IfElse_Valid_1"); }
@Test public void IfElse_Valid_2_StaticTest() { verificationRunTest("IfElse_Valid_2"); }
@Test public void IfElse_Valid_3_StaticTest() { verificationRunTest("IfElse_Valid_3"); }
@Test public void IntConst_Valid_1_StaticTest() { verificationRunTest("IntConst_Valid_1"); }
@Test public void IntDefine_Valid_1_StaticTest() { verificationRunTest("IntDefine_Valid_1"); }
@Test public void IntDiv_Valid_1_StaticTest() { verificationRunTest("IntDiv_Valid_1"); }
@Test public void IntMul_Valid_1_RunTest() { verificationRunTest("IntMul_Valid_1"); }
@Test public void IntEquals_Valid_1_StaticTest() { verificationRunTest("IntEquals_Valid_1"); }
@Test public void IntOp_Valid_1_StaticTest() { verificationRunTest("IntOp_Valid_1"); }
@Ignore("Known Bug") @Test public void IntersectionType_Valid_1_StaticTest() { verificationRunTest("IntersectionType_Valid_1"); }
@Ignore("Known Bug") @Test public void IntersectionType_Valid_2_StaticTest() { verificationRunTest("IntersectionType_Valid_2"); }
@Test public void ListAccess_Valid_1_StaticTest() { verificationRunTest("ListAccess_Valid_1"); }
@Test public void ListAccess_Valid_2_StaticTest() { verificationRunTest("ListAccess_Valid_2"); }
@Test public void ListAccess_Valid_3_StaticTest() { verificationRunTest("ListAccess_Valid_3"); }
@Test public void ListAssign_Valid_1_StaticTest() { verificationRunTest("ListAssign_Valid_1"); }
@Test public void ListAssign_Valid_2_StaticTest() { verificationRunTest("ListAssign_Valid_2"); }
@Test public void ListAssign_Valid_3_StaticTest() { verificationRunTest("ListAssign_Valid_3"); }
@Test public void ListAssign_Valid_4_StaticTest() { verificationRunTest("ListAssign_Valid_4"); }
@Test public void ListAssign_Valid_5_StaticTest() { verificationRunTest("ListAssign_Valid_5"); }
@Test public void ListAssign_Valid_6_StaticTest() { verificationRunTest("ListAssign_Valid_6"); }
@Test public void ListAppend_Valid_1_StaticTest() { verificationRunTest("ListAppend_Valid_1"); }
@Test public void ListAppend_Valid_2_StaticTest() { verificationRunTest("ListAppend_Valid_2"); }
@Test public void ListAppend_Valid_3_StaticTest() { verificationRunTest("ListAppend_Valid_3"); }
@Test public void ListAppend_Valid_4_StaticTest() { verificationRunTest("ListAppend_Valid_4"); }
@Test public void ListAppend_Valid_5_StaticTest() { verificationRunTest("ListAppend_Valid_5"); }
@Test public void ListAppend_Valid_6_StaticTest() { verificationRunTest("ListAppend_Valid_6"); }
@Test public void ListConversion_Valid_1_StaticTest() { verificationRunTest("ListConversion_Valid_1"); }
@Test public void ListElemOf_Valid_1_StaticTest() { verificationRunTest("ListElemOf_Valid_1"); }
@Test public void ListEmpty_Valid_1_StaticTest() { verificationRunTest("ListEmpty_Valid_1"); }
@Test public void ListEquals_Valid_1_StaticTest() { verificationRunTest("ListEquals_Valid_1"); }
@Test public void ListGenerator_Valid_1_StaticTest() { verificationRunTest("ListGenerator_Valid_1"); }
@Test public void ListGenerator_Valid_2_StaticTest() { verificationRunTest("ListGenerator_Valid_2"); }
@Test public void ListGenerator_Valid_3_StaticTest() { verificationRunTest("ListGenerator_Valid_3"); }
@Test public void ListLength_Valid_1_StaticTest() { verificationRunTest("ListLength_Valid_1"); }
@Test public void ListLength_Valid_2_StaticTest() { verificationRunTest("ListLength_Valid_2"); }
@Test public void ListSublist_Valid_1_StaticTest() { verificationRunTest("ListSublist_Valid_1"); }
@Test public void ListSublist_Valid_2_StaticTest() { verificationRunTest("ListSublist_Valid_2"); }
@Test public void MethodCall_Valid_3_StaticTest() { verificationRunTest("MethodCall_Valid_3"); }
@Test public void MethodCall_Valid_4_StaticTest() { verificationRunTest("MethodCall_Valid_4"); }
@Test public void MethodCall_Valid_5_StaticTest() { verificationRunTest("MethodCall_Valid_5"); }
@Test public void MethodCall_Valid_6_StaticTest() { verificationRunTest("MethodCall_Valid_6"); }
@Test public void Print_Valid_1_StaticTest() { verificationRunTest("Print_Valid_1"); }
@Test public void ProcessAccess_Valid_1_StaticTest() { verificationRunTest("ProcessAccess_Valid_1"); }
@Test public void ProcessAccess_Valid_2_StaticTest() { verificationRunTest("ProcessAccess_Valid_2"); }
@Test public void Process_Valid_1_StaticTest() { verificationRunTest("Process_Valid_1"); }
@Test public void Process_Valid_2_StaticTest() { verificationRunTest("Process_Valid_2"); }
@Test public void Quantifiers_Valid_1_StaticTest() { verificationRunTest("Quantifiers_Valid_1"); }
@Test public void RealConst_Valid_1_StaticTest() { verificationRunTest("RealConst_Valid_1"); }
@Test public void RealDiv_Valid_1_StaticTest() { verificationRunTest("RealDiv_Valid_1"); }
@Test public void RealDiv_Valid_2_StaticTest() { verificationRunTest("RealDiv_Valid_2"); }
@Test public void RealDiv_Valid_3_StaticTest() { verificationRunTest("RealDiv_Valid_3"); }
@Test public void RealNeg_Valid_1_StaticTest() { verificationRunTest("RealNeg_Valid_1"); }
@Test public void RealSub_Valid_1_StaticTest() { verificationRunTest("RealSub_Valid_1"); }
@Test public void RecursiveType_Valid_1_StaticTest() { verificationRunTest("RecursiveType_Valid_1"); }
@Test public void RecursiveType_Valid_2_StaticTest() { verificationRunTest("RecursiveType_Valid_2"); }
@Test public void RecursiveType_Valid_3_StaticTest() { verificationRunTest("RecursiveType_Valid_3"); }
@Test public void RecursiveType_Valid_4_StaticTest() { verificationRunTest("RecursiveType_Valid_4"); }
@Test public void RecursiveType_Valid_5_StaticTest() { verificationRunTest("RecursiveType_Valid_5"); }
@Test public void RecursiveType_Valid_6_StaticTest() { verificationRunTest("RecursiveType_Valid_6"); }
@Test public void RecursiveType_Valid_7_StaticTest() { verificationRunTest("RecursiveType_Valid_7"); }
@Test public void RecursiveType_Valid_8_StaticTest() { verificationRunTest("RecursiveType_Valid_8"); }
@Test public void RecursiveType_Valid_9_StaticTest() { verificationRunTest("RecursiveType_Valid_9"); }
@Test public void Requires_Valid_1_StaticTest() { verificationRunTest("Requires_Valid_1"); }
@Test public void Resolution_Valid_1_StaticTest() { verificationRunTest("Resolution_Valid_1"); }
@Test public void SetAssign_Valid_1_StaticTest() { verificationRunTest("SetAssign_Valid_1"); }
@Test public void SetComprehension_Valid_1_StaticTest() { verificationRunTest("SetComprehension_Valid_1"); }
@Test public void SetComprehension_Valid_2_StaticTest() { verificationRunTest("SetComprehension_Valid_2"); }
@Test public void SetComprehension_Valid_3_StaticTest() { verificationRunTest("SetComprehension_Valid_3"); }
@Test public void SetComprehension_Valid_4_StaticTest() { verificationRunTest("SetComprehension_Valid_4"); }
@Test public void SetComprehension_Valid_5_StaticTest() { verificationRunTest("SetComprehension_Valid_5"); }
@Test public void SetComprehension_Valid_6_StaticTest() { verificationRunTest("SetComprehension_Valid_6"); }
@Test public void SetComprehension_Valid_7_StaticTest() { verificationRunTest("SetComprehension_Valid_7"); }
@Test public void SetConversion_Valid_1_StaticTest() { verificationRunTest("SetConversion_Valid_1"); }
@Test public void SetDefine_Valid_1_StaticTest() { verificationRunTest("SetDefine_Valid_1"); }
@Test public void SetElemOf_Valid_1_StaticTest() { verificationRunTest("SetElemOf_Valid_1"); }
@Test public void SetEmpty_Valid_1_StaticTest() { verificationRunTest("SetEmpty_Valid_1"); }
@Test public void SetGenerator_Valid_1_StaticTest() { verificationRunTest("SetGenerator_Valid_1"); }
@Test public void SetIntersect_Valid_1_StaticTest() { verificationRunTest("SetIntersect_Valid_1"); }
@Test public void SetIntersect_Valid_2_StaticTest() { verificationRunTest("SetIntersect_Valid_2"); }
@Test public void SetIntersection_Valid_1_StaticTest() { verificationRunTest("SetIntersection_Valid_1"); }
@Test public void SetIntersection_Valid_2_StaticTest() { verificationRunTest("SetIntersection_Valid_2"); }
@Test public void SetIntersection_Valid_3_StaticTest() { verificationRunTest("SetIntersection_Valid_3"); }
@Test public void SetLength_Valid_1_StaticTest() { verificationRunTest("SetLength_Valid_1"); }
@Test public void SetSubset_Valid_1_StaticTest() { verificationRunTest("SetSubset_Valid_1"); }
@Test public void SetSubset_Valid_2_StaticTest() { verificationRunTest("SetSubset_Valid_2"); }
@Test public void SetSubset_Valid_3_StaticTest() { verificationRunTest("SetSubset_Valid_3"); }
@Test public void SetSubset_Valid_4_StaticTest() { verificationRunTest("SetSubset_Valid_4"); }
@Test public void SetSubset_Valid_5_StaticTest() { verificationRunTest("SetSubset_Valid_5"); }
@Test public void SetSubset_Valid_6_StaticTest() { verificationRunTest("SetSubset_Valid_6"); }
@Test public void SetSubset_Valid_7_StaticTest() { verificationRunTest("SetSubset_Valid_7"); }
@Test public void SetUnion_Valid_1_StaticTest() { verificationRunTest("SetUnion_Valid_1"); }
@Test public void SetUnion_Valid_2_StaticTest() { verificationRunTest("SetUnion_Valid_2"); }
@Test public void SetUnion_Valid_3_StaticTest() { verificationRunTest("SetUnion_Valid_3"); }
@Test public void SetUnion_Valid_4_StaticTest() { verificationRunTest("SetUnion_Valid_4"); }
@Test public void SetUnion_Valid_5_StaticTest() { verificationRunTest("SetUnion_Valid_5"); }
@Test public void SetUnion_Valid_6_StaticTest() { verificationRunTest("SetUnion_Valid_6"); }
@Test public void Subtype_Valid_3_StaticTest() { verificationRunTest("Subtype_Valid_3"); }
@Test public void Subtype_Valid_4_StaticTest() { verificationRunTest("Subtype_Valid_4"); }
@Test public void Subtype_Valid_5_StaticTest() { verificationRunTest("Subtype_Valid_5"); }
@Test public void Subtype_Valid_6_StaticTest() { verificationRunTest("Subtype_Valid_6"); }
@Test public void Subtype_Valid_7_StaticTest() { verificationRunTest("Subtype_Valid_7"); }
@Test public void Subtype_Valid_8_StaticTest() { verificationRunTest("Subtype_Valid_8"); }
@Test public void Subtype_Valid_9_StaticTest() { verificationRunTest("Subtype_Valid_9"); }
@Test public void RecordAccess_Valid_1_StaticTest() { verificationRunTest("RecordAccess_Valid_1"); }
@Test public void RecordAssign_Valid_1_StaticTest() { verificationRunTest("RecordAssign_Valid_1"); }
@Test public void RecordAssign_Valid_2_StaticTest() { verificationRunTest("RecordAssign_Valid_2"); }
@Test public void RecordAssign_Valid_3_StaticTest() { verificationRunTest("RecordAssign_Valid_3"); }
@Test public void RecordAssign_Valid_4_StaticTest() { verificationRunTest("RecordAssign_Valid_4"); }
@Test public void RecordAssign_Valid_5_StaticTest() { verificationRunTest("RecordAssign_Valid_5"); }
@Test public void RecordConversion_Valid_1_StaticTest() { verificationRunTest("RecordConversion_Valid_1"); }
@Test public void RecordDefine_Valid_1_StaticTest() { verificationRunTest("RecordDefine_Valid_1"); }
@Test public void TupleType_Valid_1_StaticTest() { verificationRunTest("TupleType_Valid_1"); }
@Test public void TupleType_Valid_2_StaticTest() { verificationRunTest("TupleType_Valid_2"); }
@Test public void TupleType_Valid_3_StaticTest() { verificationRunTest("TupleType_Valid_3"); }
@Test public void TypeEquals_Valid_1_StaticTest() { verificationRunTest("TypeEquals_Valid_1"); }
@Test public void TypeEquals_Valid_2_StaticTest() { verificationRunTest("TypeEquals_Valid_2"); }
@Test public void TypeEquals_Valid_3_StaticTest() { verificationRunTest("TypeEquals_Valid_3"); }
@Test public void TypeEquals_Valid_4_StaticTest() { verificationRunTest("TypeEquals_Valid_4"); }
@Test public void TypeEquals_Valid_5_StaticTest() { verificationRunTest("TypeEquals_Valid_5"); }
@Test public void TypeEquals_Valid_6_StaticTest() { verificationRunTest("TypeEquals_Valid_6"); }
@Test public void TypeEquals_Valid_7_StaticTest() { verificationRunTest("TypeEquals_Valid_7"); }
@Test public void TypeEquals_Valid_8_StaticTest() { verificationRunTest("TypeEquals_Valid_8"); }
@Test public void TypeEquals_Valid_9_StaticTest() { verificationRunTest("TypeEquals_Valid_9"); }
@Test public void TypeEquals_Valid_10_StaticTest() { verificationRunTest("TypeEquals_Valid_10"); }
@Test public void TypeEquals_Valid_11_StaticTest() { verificationRunTest("TypeEquals_Valid_11"); }
@Test public void TypeEquals_Valid_12_StaticTest() { verificationRunTest("TypeEquals_Valid_12"); }
@Test public void TypeEquals_Valid_13_StaticTest() { verificationRunTest("TypeEquals_Valid_13"); }
@Test public void TypeEquals_Valid_14_StaticTest() { verificationRunTest("TypeEquals_Valid_14"); }
@Test public void TypeEquals_Valid_15_StaticTest() { verificationRunTest("TypeEquals_Valid_15"); }
@Test public void TypeEquals_Valid_16_StaticTest() { verificationRunTest("TypeEquals_Valid_16"); }
@Test public void UnionType_Valid_1_StaticTest() { verificationRunTest("UnionType_Valid_1"); }
@Test public void UnionType_Valid_10_StaticTest() { verificationRunTest("UnionType_Valid_10"); }
@Test public void UnionType_Valid_11_StaticTest() { verificationRunTest("UnionType_Valid_11"); }
@Test public void UnionType_Valid_12_StaticTest() { verificationRunTest("UnionType_Valid_12"); }
@Test public void UnionType_Valid_13_StaticTest() { verificationRunTest("UnionType_Valid_13"); }
@Test public void UnionType_Valid_14_StaticTest() { verificationRunTest("UnionType_Valid_14"); }
@Test public void UnionType_Valid_15_StaticTest() { verificationRunTest("UnionType_Valid_15"); }
@Test public void UnionType_Valid_16_StaticTest() { verificationRunTest("UnionType_Valid_16"); }
@Test public void UnionType_Valid_2_StaticTest() { verificationRunTest("UnionType_Valid_2"); }
@Ignore("Known Bug") @Test public void UnionType_Valid_3_StaticTest() { verificationRunTest("UnionType_Valid_3"); }
@Test public void UnionType_Valid_4_StaticTest() { verificationRunTest("UnionType_Valid_4"); }
@Test public void UnionType_Valid_5_StaticTest() { verificationRunTest("UnionType_Valid_5"); }
@Test public void UnionType_Valid_6_StaticTest() { verificationRunTest("UnionType_Valid_6"); }
@Test public void UnionType_Valid_7_StaticTest() { verificationRunTest("UnionType_Valid_7"); }
@Test public void UnionType_Valid_8_StaticTest() { verificationRunTest("UnionType_Valid_8"); }
@Test public void UnionType_Valid_9_StaticTest() { verificationRunTest("UnionType_Valid_9"); }
@Test public void VarDecl_Valid_1_StaticTest() { verificationRunTest("VarDecl_Valid_1"); }
@Test public void VarDecl_Valid_2_StaticTest() { verificationRunTest("VarDecl_Valid_2"); }
@Test public void While_Valid_1_StaticTest() { verificationRunTest("While_Valid_1"); }
@Test public void While_Valid_2_StaticTest() { verificationRunTest("While_Valid_2"); }
@Test public void While_Valid_3_StaticTest() { verificationRunTest("While_Valid_3"); }
@Test public void While_Valid_4_StaticTest() { verificationRunTest("While_Valid_4"); }
@Test public void While_Valid_5_StaticTest() { verificationRunTest("While_Valid_5"); }
@Test public void While_Valid_6_StaticTest() { verificationRunTest("While_Valid_6"); }
} |
package org.kepler.webview.server.handler;
import java.net.HttpURLConnection;
import org.kepler.webview.server.MetadataUtilities;
import org.kepler.webview.server.WebViewServer;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.RoutingContext;
/** Handler for logins.
*
* @author Daniel Crawl
* @version $Id: LoginHandler.java 1375 2017-08-24 05:42:39Z crawl $
*/
public class LoginHandler extends BaseHandler {
public LoginHandler(WebViewServer server) {
super(server);
}
@Override
public void handle(RoutingContext context) {
final long timestamp = System.currentTimeMillis();
/*
System.out.println("logged in " +
context.user().principal().getString("username") + " " +
context.session().id());
*/
MetadataUtilities.getMetadata().setHandler(res -> {
if(res.failed()) {
context.response()
.putHeader("Content-Type", "text/plain")
.setStatusCode(HttpURLConnection.HTTP_INTERNAL_ERROR)
.setStatusMessage("Could not access metadata: " + res.cause())
.end();
} else {
// construct the response json
JsonObject principal = context.user().principal();
JsonObject returnJson = new JsonObject().mergeIn(principal);
boolean isAdmin = false;
if(returnJson.containsKey("admin")) {
for(Object v: returnJson.getJsonArray("admin")) {
if("*".equals(v) ) {
isAdmin = true;
}
};
}
// add metadata
JsonArray metadataJson = res.result();
if(isAdmin) {
returnJson.put("metadata", metadataJson.copy());
} else {
JsonArray returnMetadataJson = new JsonArray();
for(int i = 0; i < metadataJson.size(); i++) {
JsonObject m = metadataJson.getJsonObject(i);
// do not include type = paramset metadata entries,
// since these are not governed by groups.
if(m.containsKey("type") && "paramset".equals(m.getString("type")) ) {
continue;
}
boolean inGroup = false;
if(!m.containsKey("groups")) {
inGroup = true;
} else {
JsonArray groupsList = m.getJsonArray("groups");
for(int j = 0; j < groupsList.size(); j++) {
for(Object g: returnJson.getJsonArray("groups")) {
if(g.equals(groupsList.getString(j))) {
inGroup = true;
break;
}
}
}
}
if(inGroup) {
returnMetadataJson.add(m.copy());
}
};
returnJson.put("metadata", returnMetadataJson);
}
// remove specific fields before returning to client.
for(int i = 0; i < returnJson.getJsonArray("metadata").size(); i++) {
JsonObject obj = returnJson.getJsonArray("metadata").getJsonObject(i);
for(String key: _fieldsToRemove) {
if(obj.containsKey(key)) {
obj.remove(key);
}
}
}
//System.out.println(returnJson.encodePrettily());
context.response().putHeader("Content-Type", "application/json")
.end(returnJson.encode());
_server.log(context.request(), context.user(), HttpURLConnection.HTTP_OK, timestamp);
}
});
}
/** Names of fields to remove from metadata json before returning to the client. */
private static String[] _fieldsToRemove = {"groups", "private"};
} |
package com.coviu.examples;
import com.coviu.core.ApiClient;
import com.coviu.core.ApiException;
import com.coviu.sessions.api.SessionApi;
import com.coviu.sessions.model.*;
import static org.joda.time.DateTime.now;
public class Main {
public static void main(String[] args) {
try {
String apiKey = getSystemPropertyOrFail("coviu.api-key");
String apiKeySecret = getSystemPropertyOrFail("coviu.api-secret");
// Create an api client.
ApiClient client = new ApiClient();
client.setCredentials(apiKey, apiKeySecret, null);
// We we obtain, and update a new authorization (access_token, refresh_token, expires_in)
// we usually want to save it for later use.
client.setAuthorizationObserver(new ApiClient.AuthorizationObserver(){
public void observe(String s) {
saveUpdatedAuthorization(s);
}
});
// Construct a new session api instance using the freshly constructed api client.
SessionApi api = new SessionApi(client);
// Lets book a new session.
SessionCreationRequest scr = new SessionCreationRequest()
// Starts this time tomorrow
.startTime(now().plusDays(1))
// Finishes an hour later
.endTime(now().plusDays(1).plusHours(1))
// adding a single host participant at the moment.
.addParticipantsItem(exampleHostParticipant());
Session session = api.createSession(scr);
System.out.println(session);
// Lets add a second participant to the session
Participant guest = api.addSessionParticipant(session.getSessionId(), exampleGuestParticipant());
System.out.println(guest);
// Lets move it to start half an hour later.
SessionUpdateRequest sur = new SessionUpdateRequest()
.startTime(session.getStartTime().plusMinutes(30));
api.updateSession(session.getSessionId(), sur);
// Ok, lets cancel the session.
api.deleteSession(session.getSessionId());
} catch (ApiException e) {
e.printStackTrace();
}
}
public static String getSystemPropertyOrFail(String key) {
String result = System.getProperty(key);
if (result == null) {
System.err.println("The property \""+key+"\" must be supplied.");
System.exit(1);
}
return result;
}
public static ParticipantCreationRequest exampleGuestParticipant() {
return new ParticipantCreationRequest()
.displayName("Joe")
.role("guest");
}
public static ParticipantCreationRequest exampleHostParticipant() {
return new ParticipantCreationRequest()
.displayName("Jill")
.role("host");
}
public static void saveUpdatedAuthorization(String authorization) {
System.out.println("Authorization received...................");
System.out.println(authorization);
}
} |
package meizhuo.org.lightmeeting.acty;
import java.util.ArrayList;
import java.util.List;
import meizhuo.org.lightmeeting.R;
import meizhuo.org.lightmeeting.adapter.RelationListAdapter;
import meizhuo.org.lightmeeting.adapter.RelationListAdapter.OnItemClickListener;
import meizhuo.org.lightmeeting.api.RelationAPI;
import meizhuo.org.lightmeeting.api.RestClient;
import meizhuo.org.lightmeeting.app.BaseActivity;
import meizhuo.org.lightmeeting.imple.JsonHandler;
import meizhuo.org.lightmeeting.model.Relation;
import meizhuo.org.lightmeeting.utils.L;
import meizhuo.org.lightmeeting.widget.LoadingDialog;
import org.apache.http.Header;
import org.json.JSONObject;
import android.app.ActionBar;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ListView;
import butterknife.InjectView;
import butterknife.OnItemClick;
import com.loopj.android.http.AsyncHttpClient;
public class RelationList extends BaseActivity implements OnRefreshListener,OnScrollListener {
@InjectView(R.id.relation_list) ListView lv_relation;
@InjectView(R.id.swipeRefreshLayout) SwipeRefreshLayout swipeRefreshLayout;
RelationListAdapter adapter;
List<Relation>data;
ActionBar mActionBar;
String page = "1", limit = "";
boolean hasMore = true, isloading = false;
LoadingDialog dialog;
List<Integer>pics;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState, R.layout.acty_relation_list);
dialog = new LoadingDialog(this);
initData();
initLayout();
}
@OnItemClick(R.id.relation_list) public void ToBusinessCard(int position){
Intent it = new Intent(this, MdMemberBusinessCard.class);
it.putExtra("memberid", data.get(position).getId());
it.putExtra("nickname", data.get(position).getNickname());
startActivity(it);
}
@Override
protected void initData() {
pics = new ArrayList<Integer>();
pics.add(R.drawable.aa_pic_head1);
pics.add(R.drawable.aa_pic_head2);
pics.add(R.drawable.aa_pic_head3);
pics.add(R.drawable.aa_pic_head4);
pics.add(R.drawable.aa_pic_head5);
pics.add(R.drawable.aa_pic_head6);
data = new ArrayList<Relation>();
adapter = new RelationListAdapter(this, data,pics);
adapter.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(int position) {
}
});
adapter.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(final int position) {
AlertDialog.Builder deleteBuilder = new AlertDialog.Builder(RelationList.this);
deleteBuilder.setTitle("?");
deleteBuilder.setPositiveButton("", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
RelationAPI.deleteRelation(data.get(position).getRelationid(), new JsonHandler(){
@Override
public void onStart() {
if(RelationList.this.dialog==null){
RelationList.this.dialog = new LoadingDialog(RelationList.this);
}
RelationList.this.dialog.setText("");
RelationList.this.dialog.show();
}
@Override
public void onOK(int statusCode, Header[] headers,
JSONObject obj) throws Exception {
if(RelationList.this.dialog.isShowing()){
RelationList.this.dialog.dismiss();
RelationList.this.dialog=null;
}
data.remove(position);
adapter.notifyDataSetChanged();
toast("!");
return ;
}
@Override
public void onError(int error_code,
Header[] headers, JSONObject obj)
throws Exception {
if(RelationList.this.dialog.isShowing()){
RelationList.this.dialog.dismiss();
RelationList.this.dialog=null;
}
String msg = obj.getString("msg");
toast(msg);
return ;
}
@Override
public void onFailure(int statusCode,
Header[] headers, byte[] data,
Throwable arg3) {
if(RelationList.this.dialog.isShowing()){
RelationList.this.dialog.dismiss();
RelationList.this.dialog=null;
}
toast("");
return ;
}
});
}
});
deleteBuilder.setNegativeButton("", null);
AlertDialog deleteDialog = deleteBuilder.create();
deleteDialog.show();
}
});
mActionBar = getActionBar();
mActionBar.setTitle("");
mActionBar.setDisplayHomeAsUpEnabled(true);
}
@Override
protected void initLayout() {
swipeRefreshLayout.setOnRefreshListener(this);
swipeRefreshLayout.setColorScheme(android.R.color.holo_blue_bright,
android.R.color.holo_blue_light,
android.R.color.holo_blue_bright,
android.R.color.holo_blue_light);
lv_relation.setAdapter(adapter);
lv_relation.setOnScrollListener(this);
onRefresh();
}
@Override
public void onRefresh() {
page = "1";
RelationAPI.getRelationList(page,limit,new JsonHandler(){
@Override
public void onStart() {
swipeRefreshLayout.setRefreshing(true);
}
@Override
public void onOK(int statusCode, Header[] headers, JSONObject obj)
throws Exception {
List<Relation> relationList = Relation.create_by_jsonarray(obj
.toString());
L.i("" + relationList);
data.clear();
data.addAll(relationList);
adapter.notifyDataSetChanged();
page = "1";
if (relationList.size() == 0) {
toast("");
}
if (relationList.size() < 10) {
hasMore = false;
} else {
hasMore = true;
}
}
@Override
public void onFailure(int statusCode, Header[] headers,
byte[] data, Throwable arg3) {
swipeRefreshLayout.setRefreshing(false);
toast("!");
return ;
}
@Override
public void onFinish() {
swipeRefreshLayout.setRefreshing(false);
isloading = false;
}
});
}
private void onLoadMore(){
int i = Integer.parseInt(page);
i += 1;
page = String.valueOf(i);
RelationAPI.getRelationList(page, limit, new JsonHandler() {
@Override public void onStart() {
swipeRefreshLayout.setRefreshing(true);
}
@Override public void onOK(int statusCode, Header[] headers,
JSONObject obj) throws Exception {
List<Relation> relationList = Relation.create_by_jsonarray(obj
.toString());
data.addAll(relationList);
adapter.notifyDataSetChanged();
if (obj.isNull("response") || relationList.size() < 10) {
hasMore = false;
toast("!");
}
}
@Override public void onFailure(int statusCode, Header[] headers,
byte[] data, Throwable arg3) {
swipeRefreshLayout.setRefreshing(false);
toast(",!");
return;
}
@Override public void onFinish() {
swipeRefreshLayout.setRefreshing(false);
isloading = false;
}
});
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
if (swipeRefreshLayout.isRefreshing() || isloading)
return;
if (firstVisibleItem + visibleItemCount >= totalItemCount
&& totalItemCount != 0 && hasMore) {
isloading = true;
onLoadMore();
}
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.acty_relation, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
break;
case R.id.add_relation:
Intent openCameraIntent = new Intent(this,
CaptureActivity.class);
startActivityForResult(openCameraIntent, 330);
default:
break;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == 330 && resultCode == 51){
String qrurl = data.getStringExtra("resultcode");
L.i("resultcode" + qrurl);
AsyncHttpClient client;
client = RestClient.getClient();
client.post(qrurl, new JsonHandler(){
@Override
public void onStart() {
if (dialog == null) {
dialog = new LoadingDialog(RelationList.this);
}
dialog.setText("...");
dialog.show();
}
@Override
public void onOK(int statusCode, Header[] headers,
JSONObject obj) throws Exception {
if (dialog.isShowing()) {
dialog.dismiss();
dialog = null;
}
String response = obj.getString("response");
toast("");
onRefresh();
}
@Override public void onError(int error_code, Header[] headers,
JSONObject obj) throws Exception {
L.i( "" + obj.toString());
if (dialog.isShowing()) {
dialog.dismiss();
dialog = null;
}
String msg = obj.getString("msg");
toast(msg);
return ;
}
@Override public void onFailure(int statusCode,
Header[] headers, byte[] data, Throwable arg3) {
if (dialog.isShowing()) {
dialog.dismiss();
dialog = null;
}
toast(",!");
return;
}
});
}
}
} |
package org.nschmidt.ldparteditor.data;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import org.lwjgl.util.vector.Matrix4f;
import org.nschmidt.ldparteditor.composites.Composite3D;
import org.nschmidt.ldparteditor.data.tools.IdenticalVertexRemover;
import org.nschmidt.ldparteditor.enums.ManipulatorScope;
import org.nschmidt.ldparteditor.enums.RotationSnap;
import org.nschmidt.ldparteditor.enums.Threshold;
import org.nschmidt.ldparteditor.enums.TransformationMode;
import org.nschmidt.ldparteditor.enums.View;
import org.nschmidt.ldparteditor.helpers.Manipulator;
import org.nschmidt.ldparteditor.helpers.math.HashBiMap;
import org.nschmidt.ldparteditor.helpers.math.MathHelper;
import org.nschmidt.ldparteditor.helpers.math.ThreadsafeTreeMap;
import org.nschmidt.ldparteditor.helpers.math.Vector3d;
import org.nschmidt.ldparteditor.text.DatParser;
public class VM20Manipulator extends VM19ColourChanger {
protected VM20Manipulator(DatFile linkedDatFile) {
super(linkedDatFile);
}
/**
* Transforms the selection (vertices or data)
* @param allData
* @param allVertices
* @param transformation
* @param newVertex
* @param moveAdjacentData
*/
private void transform(Set<GData> allData, Set<Vertex> allVertices, Matrix transformation, Vector3d newVertex, boolean updateSelection, boolean moveAdjacentData) {
HashSet<GData> allData2 = new HashSet<GData>(allData);
TreeSet<Vertex> verticesToTransform = new TreeSet<Vertex>();
TreeSet<Vertex> transformedLPEvertices = new TreeSet<Vertex>();
verticesToTransform.addAll(allVertices);
for (GData gd : allData) {
Set<VertexInfo> vis = lineLinkedToVertices.get(gd);
if (vis != null) {
for (VertexInfo vi : vis) {
allVertices.add(vi.vertex);
}
}
}
TreeMap<Vertex, Vertex> oldToNewVertex = new TreeMap<Vertex, Vertex>();
// Calculate the new vertex position
if (newVertex == null) {
for (Vertex v : allVertices) {
BigDecimal[] temp = transformation.transform(v.X, v.Y, v.Z);
oldToNewVertex.put(v, new Vertex(temp[0], temp[1], temp[2]));
}
} else {
for (Vertex v : allVertices) {
oldToNewVertex.put(v, new Vertex(
newVertex.X == null ? v.X : newVertex.X,
newVertex.Y == null ? v.Y : newVertex.Y,
newVertex.Z == null ? v.Z : newVertex.Z
));
}
}
// Evaluate the adjacency
HashMap<GData, Integer> verticesCountPerGData = new HashMap<GData, Integer>();
for (Vertex v : allVertices) {
Set<VertexManifestation> manis = vertexLinkedToPositionInFile.get(v);
if (manis == null) continue;
for (VertexManifestation m : manis) {
GData gd = m.getGdata();
if (lineLinkedToVertices.containsKey(gd)) {
final int type = gd.type();
switch (type) {
case 0:
case 2:
case 3:
case 4:
case 5:
break;
default:
continue;
}
if (verticesCountPerGData.containsKey(gd)) {
verticesCountPerGData.put(gd, verticesCountPerGData.get(gd) + 1);
} else {
verticesCountPerGData.put(gd, 1);
}
allData2.add(gd);
}
}
}
// Transform the data
if (updateSelection) {
selectedData.clear();
selectedLines.clear();
selectedTriangles.clear();
selectedQuads.clear();
selectedCondlines.clear();
}
HashSet<GData> allNewData = new HashSet<GData>();
for (GData gd : allData2) {
GData newData = null;
final int type = gd.type();
switch (type) {
case 0:
{
Vertex[] verts = declaredVertices.get(gd);
if (verts != null) {
if (transformedLPEvertices.contains(verts[0])) {
continue;
} else {
if (!moveAdjacentData) transformedLPEvertices.add(verts[0]);
Vertex v1 = oldToNewVertex.get(verts[0]);
if (v1 == null) v1 = verts[0];
newData = addVertex(v1);
if (updateSelection) {
selectedVertices.remove(verts[0]);
selectedVertices.add(v1);
}
}
}
}
break;
case 2:
{
int avc = 0;
Vertex[] verts = lines.get(gd);
if (verts != null) {
Vertex v1 = oldToNewVertex.get(verts[0]);
Vertex v2 = oldToNewVertex.get(verts[1]);
if (v1 == null) v1 = verts[0]; else avc++;
if (v2 == null) v2 = verts[1]; else avc++;
if (!moveAdjacentData && (avc != 2 || !allData.contains(gd))) continue;
if (updateSelection) {
if (selectedVertices.contains(verts[0])) {
selectedVertices.remove(verts[0]);
selectedVertices.add(v1);
}
if (selectedVertices.contains(verts[1])) {
selectedVertices.remove(verts[1]);
selectedVertices.add(v2);
}
}
GData2 g2 = (GData2) gd;
newData = new GData2(g2.colourNumber, g2.r, g2.g, g2.b, g2.a, v1, v2, g2.parent, linkedDatFile, g2.isLine);
}
}
break;
case 3:
{
int avc = 0;
Vertex[] verts = triangles.get(gd);
if (verts != null) {
Vertex v1 = oldToNewVertex.get(verts[0]);
Vertex v2 = oldToNewVertex.get(verts[1]);
Vertex v3 = oldToNewVertex.get(verts[2]);
if (v1 == null) v1 = verts[0]; else avc++;
if (v2 == null) v2 = verts[1]; else avc++;
if (v3 == null) v3 = verts[2]; else avc++;
if (!moveAdjacentData && (avc != 3 || !allData.contains(gd))) continue;
if (updateSelection) {
if (selectedVertices.contains(verts[0])) {
selectedVertices.remove(verts[0]);
selectedVertices.add(v1);
}
if (selectedVertices.contains(verts[1])) {
selectedVertices.remove(verts[1]);
selectedVertices.add(v2);
}
if (selectedVertices.contains(verts[2])) {
selectedVertices.remove(verts[2]);
selectedVertices.add(v3);
}
}
GData3 g3 = (GData3) gd;
newData = new GData3(g3.colourNumber, g3.r, g3.g, g3.b, g3.a, v1, v2, v3, g3.parent, linkedDatFile, g3.isTriangle);
}
}
break;
case 4:
{
int avc = 0;
Vertex[] verts = quads.get(gd);
if (verts != null) {
Vertex v1 = oldToNewVertex.get(verts[0]);
Vertex v2 = oldToNewVertex.get(verts[1]);
Vertex v3 = oldToNewVertex.get(verts[2]);
Vertex v4 = oldToNewVertex.get(verts[3]);
if (v1 == null) v1 = verts[0]; else avc++;
if (v2 == null) v2 = verts[1]; else avc++;
if (v3 == null) v3 = verts[2]; else avc++;
if (v4 == null) v4 = verts[3]; else avc++;
if (!moveAdjacentData && (avc != 4 || !allData.contains(gd))) continue;
if (updateSelection) {
if (selectedVertices.contains(verts[0])) {
selectedVertices.remove(verts[0]);
selectedVertices.add(v1);
}
if (selectedVertices.contains(verts[1])) {
selectedVertices.remove(verts[1]);
selectedVertices.add(v2);
}
if (selectedVertices.contains(verts[2])) {
selectedVertices.remove(verts[2]);
selectedVertices.add(v3);
}
if (selectedVertices.contains(verts[3])) {
selectedVertices.remove(verts[3]);
selectedVertices.add(v4);
}
}
GData4 g4 = (GData4) gd;
newData = new GData4(g4.colourNumber, g4.r, g4.g, g4.b, g4.a, v1, v2, v3, v4, g4.parent, linkedDatFile);
}
}
break;
case 5:
{
int avc = 0;
Vertex[] verts = condlines.get(gd);
if (verts != null) {
Vertex v1 = oldToNewVertex.get(verts[0]);
Vertex v2 = oldToNewVertex.get(verts[1]);
Vertex v3 = oldToNewVertex.get(verts[2]);
Vertex v4 = oldToNewVertex.get(verts[3]);
if (v1 == null) v1 = verts[0]; else avc++;
if (v2 == null) v2 = verts[1]; else avc++;
if (v3 == null) v3 = verts[2]; else avc++;
if (v4 == null) v4 = verts[3]; else avc++;
if (!moveAdjacentData && (avc != 4 || !allData.contains(gd))) continue;
if (updateSelection) {
if (selectedVertices.contains(verts[0])) {
selectedVertices.remove(verts[0]);
selectedVertices.add(v1);
}
if (selectedVertices.contains(verts[1])) {
selectedVertices.remove(verts[1]);
selectedVertices.add(v2);
}
if (selectedVertices.contains(verts[2])) {
selectedVertices.remove(verts[2]);
selectedVertices.add(v3);
}
if (selectedVertices.contains(verts[3])) {
selectedVertices.remove(verts[3]);
selectedVertices.add(v4);
}
}
GData5 g5 = (GData5) gd;
newData = new GData5(g5.colourNumber, g5.r, g5.g, g5.b, g5.a, v1, v2, v3, v4, g5.parent, linkedDatFile);
}
}
break;
default:
continue;
}
if (newData != null) {
linker(gd, newData);
allNewData.add(newData);
setModified_NoSync();
if (updateSelection) {
switch (newData.type()) {
case 2:
if (verticesCountPerGData.get(gd) != 2) continue;
selectedLines.add((GData2) newData);
break;
case 3:
if (verticesCountPerGData.get(gd) != 3) continue;
selectedTriangles.add((GData3) newData);
break;
case 4:
if (verticesCountPerGData.get(gd) != 4) continue;
selectedQuads.add((GData4) newData);
break;
case 5:
if (verticesCountPerGData.get(gd) != 4) continue;
selectedCondlines.add((GData5) newData);
break;
default:
continue;
}
selectedData.add(newData);
}
}
}
if (updateSelection && moveAdjacentData) {
for (Vertex v : oldToNewVertex.keySet()) {
Vertex nv = oldToNewVertex.get(v);
if (nv != null) {
if (vertexLinkedToPositionInFile.containsKey(nv)) {
selectedVertices.add(nv);
}
}
}
}
}
/**
*
* @param transformation
* the transformation matrix
* @param moveAdjacentData
* {@code true} if all data should be transformed which is
* adjacent to the current selection
*/
public final void transformSelection(Matrix transformation, Vector3d newVertex, boolean moveAdjacentData) {
if (linkedDatFile.isReadOnly())
return;
final Set<Vertex> singleVertices = Collections.newSetFromMap(new ThreadsafeTreeMap<Vertex, Boolean>());
final HashSet<GData0> effSelectedVertices = new HashSet<GData0>();
final HashSet<GData2> effSelectedLines = new HashSet<GData2>();
final HashSet<GData3> effSelectedTriangles = new HashSet<GData3>();
final HashSet<GData4> effSelectedQuads = new HashSet<GData4>();
final HashSet<GData5> effSelectedCondlines = new HashSet<GData5>();
selectedData.clear();
//-1. Update CSG Tree
if (GDataCSG.hasSelectionCSG(linkedDatFile)) {
Matrix4f lowAccTransformation = transformation.getMatrix4f();
Matrix4f.transpose(lowAccTransformation, lowAccTransformation);
ArrayList<GData> newSelection = new ArrayList<>();
for (GDataCSG gd : GDataCSG.getSelection(linkedDatFile)) {
if (gd != null) newSelection.add(transformCSG(lowAccTransformation, gd));
}
GDataCSG.getSelection(linkedDatFile).clear();
for (GData gd : newSelection) {
GDataCSG.getSelection(linkedDatFile).add((GDataCSG) gd);
}
setModified_NoSync();
}
// 0. Deselect selected subfile data (for whole selected subfiles)
for (GData1 subf : selectedSubfiles) {
Set<VertexInfo> vis = lineLinkedToVertices.get(subf);
if (vis == null) continue;
for (VertexInfo vertexInfo : vis) {
if (!moveAdjacentData)
selectedVertices.remove(vertexInfo.getVertex());
GData g = vertexInfo.getLinkedData();
if (lineLinkedToVertices.containsKey(g)) continue;
switch (g.type()) {
case 2:
selectedLines.remove(g);
break;
case 3:
selectedTriangles.remove(g);
break;
case 4:
selectedQuads.remove(g);
break;
case 5:
selectedCondlines.remove(g);
break;
default:
break;
}
}
}
// 1. Vertex Based Selection
{
final Set<Vertex> objectVertices = Collections.newSetFromMap(new ThreadsafeTreeMap<Vertex, Boolean>());
if (moveAdjacentData) {
HashMap<GData, Integer> occurMap = new HashMap<GData, Integer>();
for (Vertex vertex : selectedVertices) {
Set<VertexManifestation> occurences = vertexLinkedToPositionInFile.get(vertex);
if (occurences == null)
continue;
boolean isPureSubfileVertex = true;
for (VertexManifestation vm : occurences) {
GData g = vm.getGdata();
int val = 1;
if (occurMap.containsKey(g)) {
val = occurMap.get(g);
val++;
}
occurMap.put(g, val);
switch (g.type()) {
case 0:
GData0 meta = (GData0) g;
boolean idCheck = !lineLinkedToVertices.containsKey(meta);
isPureSubfileVertex = isPureSubfileVertex && idCheck;
if (val == 1) {
if (!idCheck) {
effSelectedVertices.add(meta);
newSelectedData.add(meta);
}
}
break;
case 2:
GData2 line = (GData2) g;
idCheck = !line.parent.equals(View.DUMMY_REFERENCE);
isPureSubfileVertex = isPureSubfileVertex && idCheck;
if (val == 2) {
if (!idCheck) {
effSelectedLines.add(line);
newSelectedData.add(line);
}
}
break;
case 3:
GData3 triangle = (GData3) g;
idCheck = !triangle.parent.equals(View.DUMMY_REFERENCE);
isPureSubfileVertex = isPureSubfileVertex && idCheck;
if (val == 3) {
if (!idCheck) {
effSelectedTriangles.add(triangle);
newSelectedData.add(triangle);
}
}
break;
case 4:
GData4 quad = (GData4) g;
idCheck = !quad.parent.equals(View.DUMMY_REFERENCE);
isPureSubfileVertex = isPureSubfileVertex && idCheck;
if (val == 4) {
if (!idCheck) {
effSelectedQuads.add(quad);
newSelectedData.add(quad);
}
}
break;
case 5:
GData5 condline = (GData5) g;
idCheck = !condline.parent.equals(View.DUMMY_REFERENCE);
isPureSubfileVertex = isPureSubfileVertex && idCheck;
if (val == 4) {
if (!idCheck) {
effSelectedCondlines.add(condline);
newSelectedData.add(condline);
}
}
break;
}
}
if (isPureSubfileVertex)
objectVertices.add(vertex);
}
}
// 2. Object Based Selection
for (GData2 line : selectedLines) {
if (line.parent.equals(View.DUMMY_REFERENCE))
effSelectedLines.add(line);
Vertex[] verts = lines.get(line);
if (verts == null)
continue;
for (Vertex vertex : verts) {
objectVertices.add(vertex);
}
}
for (GData3 triangle : selectedTriangles) {
if (triangle.parent.equals(View.DUMMY_REFERENCE))
effSelectedTriangles.add(triangle);
Vertex[] verts = triangles.get(triangle);
if (verts == null)
continue;
for (Vertex vertex : verts) {
objectVertices.add(vertex);
}
}
for (GData4 quad : selectedQuads) {
if (quad.parent.equals(View.DUMMY_REFERENCE))
effSelectedQuads.add(quad);
Vertex[] verts = quads.get(quad);
if (verts == null)
continue;
for (Vertex vertex : verts) {
objectVertices.add(vertex);
}
}
for (GData5 condline : selectedCondlines) {
if (condline.parent.equals(View.DUMMY_REFERENCE))
effSelectedCondlines.add(condline);
Vertex[] verts = condlines.get(condline);
if (verts == null)
continue;
for (Vertex vertex : verts) {
objectVertices.add(vertex);
}
}
Set<GData0> vs = new HashSet<GData0>(effSelectedVertices);
for (GData0 effvert : vs) {
Vertex v = effvert.getVertex();
if (v != null && objectVertices.contains(v)) {
effSelectedVertices.remove(effvert);
}
}
singleVertices.addAll(selectedVertices);
singleVertices.removeAll(objectVertices);
// Reduce the amount of superflous selected data
selectedVertices.clear();
selectedVertices.addAll(singleVertices);
selectedLines.clear();
selectedLines.addAll(effSelectedLines);
selectedTriangles.clear();
selectedTriangles.addAll(effSelectedTriangles);
selectedQuads.clear();
selectedQuads.addAll(effSelectedQuads);
selectedCondlines.clear();
selectedCondlines.addAll(effSelectedCondlines);
// 3. Transformation of the selected data (no whole subfiles!!)
// + selectedData update!
HashSet<GData> allData = new HashSet<GData>();
allData.addAll(selectedLines);
allData.addAll(selectedTriangles);
allData.addAll(selectedQuads);
allData.addAll(selectedCondlines);
HashSet<Vertex> allVertices = new HashSet<Vertex>();
allVertices.addAll(selectedVertices);
transform(allData, allVertices, transformation, newVertex, true, moveAdjacentData);
// 4. Subfile Based Transformation & Selection
if (!selectedSubfiles.isEmpty()) {
HashBiMap<Integer, GData> drawPerLine = linkedDatFile.getDrawPerLine_NOCLONE();
HashSet<GData1> newSubfiles = new HashSet<GData1>();
for (GData1 subf : selectedSubfiles) {
if (!drawPerLine.containsValue(subf)) {
continue;
}
String transformedString = subf.getTransformedString(transformation, linkedDatFile, true);
GData transformedSubfile = DatParser
.parseLine(transformedString, drawPerLine.getKey(subf).intValue(), 0, subf.r, subf.g, subf.b, subf.a, View.DUMMY_REFERENCE, View.ID, View.ACCURATE_ID, linkedDatFile,
false, new HashSet<String>(), false).get(0).getGraphicalData();
if (subf.equals(linkedDatFile.getDrawChainTail()))
linkedDatFile.setDrawChainTail(transformedSubfile);
GData oldNext = subf.getNext();
GData oldBefore = subf.getBefore();
oldBefore.setNext(transformedSubfile);
transformedSubfile.setNext(oldNext);
Integer oldNumber = drawPerLine.getKey(subf);
if (oldNumber != null)
drawPerLine.put(oldNumber, transformedSubfile);
remove(subf);
newSubfiles.add((GData1) transformedSubfile);
}
selectedSubfiles.clear();
selectedSubfiles.addAll(newSubfiles);
for (GData1 subf : selectedSubfiles) {
Set<VertexInfo> vis = lineLinkedToVertices.get(subf);
if (vis == null) continue;
for (VertexInfo vertexInfo : vis) {
selectedVertices.add(vertexInfo.getVertex());
GData g = vertexInfo.getLinkedData();
switch (g.type()) {
case 2:
selectedLines.add((GData2) g);
break;
case 3:
selectedTriangles.add((GData3) g);
break;
case 4:
selectedQuads.add((GData4) g);
break;
case 5:
selectedCondlines.add((GData5) g);
break;
default:
break;
}
}
}
setModified_NoSync();
}
if (isModified()) {
selectedData.addAll(selectedLines);
selectedData.addAll(selectedTriangles);
selectedData.addAll(selectedQuads);
selectedData.addAll(selectedCondlines);
selectedData.addAll(selectedSubfiles);
restoreHideShowState();
syncWithTextEditors(true);
updateUnsavedStatus();
}
newSelectedData.clear();
selectedVertices.retainAll(vertexLinkedToPositionInFile.keySet());
}
}
private GDataCSG transformCSG(Matrix4f lowAccTransformation, GDataCSG gData) {
GDataCSG gdC = gData;
GDataCSG newGData = new GDataCSG(linkedDatFile, lowAccTransformation, gdC);
linker(gData, newGData);
return newGData;
}
public final void setXyzOrTranslateOrTransform(Vertex target, Vertex pivot, TransformationMode tm, boolean x, boolean y, boolean z, boolean moveAdjacentData, boolean syncWithTextEditors, ManipulatorScope scope) {
if (linkedDatFile.isReadOnly())
return;
backupHideShowState();
boolean swapWinding = false;
Matrix transformation = null;
Vertex offset = null;
if (tm == TransformationMode.TRANSLATE) offset = new Vertex(target.X, target.Y, target.Z);
if (pivot == null) pivot = new Vertex(0f, 0f, 0f);
switch (tm) {
case ROTATE:
RotationSnap flag;
if (x) {
try {
target.X.intValueExact();
switch (Math.abs(target.X.intValue())) {
case 90:
flag = RotationSnap.DEG90;
break;
case 180:
flag = RotationSnap.DEG180;
break;
case 270:
flag = RotationSnap.DEG270;
break;
case 360:
flag = RotationSnap.DEG360;
break;
default:
flag = RotationSnap.COMPLEX;
break;
}
} catch (ArithmeticException ae) {
flag = RotationSnap.COMPLEX;
}
transformation = View.ACCURATE_ID.rotate(target.X.divide(new BigDecimal(180), Threshold.mc).multiply(new BigDecimal(Math.PI)), flag, new BigDecimal[] { BigDecimal.ONE, BigDecimal.ZERO, BigDecimal.ZERO });
} else if (y) {
try {
target.Y.intValueExact();
switch (Math.abs(target.Y.intValue())) {
case 90:
flag = RotationSnap.DEG90;
break;
case 180:
flag = RotationSnap.DEG180;
break;
case 270:
flag = RotationSnap.DEG270;
break;
case 360:
flag = RotationSnap.DEG360;
break;
default:
flag = RotationSnap.COMPLEX;
break;
}
} catch (ArithmeticException ae) {
flag = RotationSnap.COMPLEX;
}
transformation = View.ACCURATE_ID.rotate(target.Y.divide(new BigDecimal(180), Threshold.mc).multiply(new BigDecimal(Math.PI)), flag, new BigDecimal[] { BigDecimal.ZERO, BigDecimal.ONE, BigDecimal.ZERO });
} else {
try {
target.Z.intValueExact();
switch (Math.abs(target.Z.intValue())) {
case 90:
flag = RotationSnap.DEG90;
break;
case 180:
flag = RotationSnap.DEG180;
break;
case 270:
flag = RotationSnap.DEG270;
break;
case 360:
flag = RotationSnap.DEG360;
break;
default:
flag = RotationSnap.COMPLEX;
break;
}
} catch (ArithmeticException ae) {
flag = RotationSnap.COMPLEX;
}
transformation = View.ACCURATE_ID.rotate(target.Z.divide(new BigDecimal(180), Threshold.mc).multiply(new BigDecimal(Math.PI)), flag, new BigDecimal[] { BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ONE });
}
break;
case SCALE:
BigDecimal sx = target.X;
BigDecimal sy = target.Y;
BigDecimal sz = target.Z;
int count = 0;
int cmp1 = 0;
int cmp2 = 0;
int cmp3 = 0;
if ((cmp1 = sx.compareTo(BigDecimal.ZERO)) == 0) sx = new BigDecimal("0.000000001"); //$NON-NLS-1$
if ((cmp2 = sy.compareTo(BigDecimal.ZERO)) == 0) sy = new BigDecimal("0.000000001"); //$NON-NLS-1$
if ((cmp3 = sz.compareTo(BigDecimal.ZERO)) == 0) sz = new BigDecimal("0.000000001"); //$NON-NLS-1$
if (cmp1 < 0) count++;
if (cmp2 < 0) count++;
if (cmp3 < 0) count++;
swapWinding = count == 1 || count == 3;
transformation = new Matrix(
x ? sx : BigDecimal.ONE, BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO,
BigDecimal.ZERO, y ? sy : BigDecimal.ONE, BigDecimal.ZERO, BigDecimal.ZERO,
BigDecimal.ZERO, BigDecimal.ZERO, z ? sz : BigDecimal.ONE, BigDecimal.ZERO,
BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ONE);
break;
case SET:
break;
case TRANSLATE:
transformation = new Matrix(
BigDecimal.ONE, BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO,
BigDecimal.ZERO, BigDecimal.ONE, BigDecimal.ZERO, BigDecimal.ZERO,
BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ONE, BigDecimal.ZERO,
offset.X, offset.Y, offset.Z, BigDecimal.ONE);
break;
default:
break;
}
if (tm == TransformationMode.SET) {
transformSelection(View.ACCURATE_ID, new Vector3d(x ? target.X : null, y ? target.Y : null, z ? target.Z : null), moveAdjacentData);
} else {
Composite3D c3d = linkedDatFile.getLastSelectedComposite();
if (scope == ManipulatorScope.LOCAL && c3d != null) {
Manipulator mani = c3d.getManipulator();
BigDecimal[] X = mani.getAccurateXaxis();
BigDecimal[] Y = mani.getAccurateYaxis();
BigDecimal[] Z = mani.getAccurateZaxis();
final Matrix m = new Matrix(
X[0], X[1], X[2], BigDecimal.ZERO,
Y[0], Y[1], Y[2], BigDecimal.ZERO,
Z[0], Z[1], Z[2], BigDecimal.ZERO,
BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ONE);
final Matrix mi = m.invert();
transformation = Matrix.mul(m, transformation);
transformation = Matrix.mul(transformation, mi);
}
final Matrix forward = Matrix.mul(View.ACCURATE_ID.translate(new BigDecimal[] { pivot.X.negate(), pivot.Y.negate(), pivot.Z.negate() }), View.ACCURATE_ID);
final Matrix backward = Matrix.mul(View.ACCURATE_ID.translate(new BigDecimal[] { pivot.X, pivot.Y, pivot.Z }), View.ACCURATE_ID);
transformation = Matrix.mul(backward, transformation);
transformation = Matrix.mul(transformation, forward);
transformSelection(transformation, null, moveAdjacentData);
if (swapWinding) {
backupHideShowState();
ArrayList<GData1> backupSubfiles = new ArrayList<GData1>();
backupSubfiles.addAll(selectedSubfiles);
selectedData.removeAll(selectedSubfiles);
selectedSubfiles.clear();
windingChangeSelection(syncWithTextEditors);
selectedData.addAll(backupSubfiles);
selectedSubfiles.addAll(backupSubfiles);
}
}
IdenticalVertexRemover.removeIdenticalVertices(this, linkedDatFile, false, true);
if (syncWithTextEditors) syncWithTextEditors(true);
updateUnsavedStatus();
selectedVertices.retainAll(vertexLinkedToPositionInFile.keySet());
}
public void transformSubfile(GData1 g, Matrix M, boolean clearSelection, boolean syncWithTextEditor) {
HashBiMap<Integer, GData> drawPerLine = linkedDatFile.getDrawPerLine_NOCLONE();
StringBuilder colourBuilder = new StringBuilder();
if (g.colourNumber == -1) {
colourBuilder.append("0x2"); //$NON-NLS-1$
colourBuilder.append(MathHelper.toHex((int) (255f * g.r)).toUpperCase());
colourBuilder.append(MathHelper.toHex((int) (255f * g.g)).toUpperCase());
colourBuilder.append(MathHelper.toHex((int) (255f * g.b)).toUpperCase());
} else {
colourBuilder.append(g.colourNumber);
}
// Clear the cache..
GData.parsedLines.clear();
GData.CACHE_parsedFilesSource.clear();
GData1 reloadedSubfile = (GData1) DatParser
.parseLine("1 " + colourBuilder.toString() + M.toLDrawString() + g.shortName , 0, 0, 0.5f, 0.5f, 0.5f, 1f, View.DUMMY_REFERENCE, View.ID, View.ACCURATE_ID, linkedDatFile, false, //$NON-NLS-1$
new HashSet<String>(), false).get(0).getGraphicalData();
// Clear the cache..
GData.parsedLines.clear();
GData.CACHE_parsedFilesSource.clear();
GData oldNext = g.getNext();
GData oldBefore = g.getBefore();
oldBefore.setNext(reloadedSubfile);
reloadedSubfile.setNext(oldNext);
Integer oldNumber = drawPerLine.getKey(g);
if (oldNumber != null)
drawPerLine.put(oldNumber, reloadedSubfile);
remove(g);
if (clearSelection) {
clearSelection();
} else {
selectedData.remove(g);
selectedSubfiles.remove(g);
}
selectedData.add(reloadedSubfile);
selectedSubfiles.add(reloadedSubfile);
selectWholeSubfiles();
if (syncWithTextEditor) {
restoreHideShowState();
setModified(true, true);
} else {
setModified_NoSync();
}
}
} |
package com.exedio.cronjob.example;
import com.exedio.cope.util.JobContext;
final class InterruptableJob extends AbstractJob
{
InterruptableJob()
{
super("Interruptable", 1000, 0);
}
@Override
public void run(final JobContext ctx)
{
System.out.println(name + ".run start");
try
{
for(int i = 0; i<10; i++)
{
//noinspection BusyWait
Thread.sleep(1000);
System.out.println(name + ".run slept " + i);
ctx.incrementProgress(result++);
System.out.println(name + ".run interrupted?");
ctx.stopIfRequested();
System.out.println(name + ".run interrupted!");
}
}
catch(final InterruptedException e)
{
throw new RuntimeException(e);
}
System.out.println(name + ".run ready");
ctx.incrementProgress(result++);
}
} |
import java.util.ArrayList;
import java.util.List;
class BowlingGame {
private static final int NUMBER_OF_FRAMES = 10;
private static final int MAXIMUM_FRAME_SCORE = 10;
private List<Integer> rolls = new ArrayList<>();
void roll(int pins) {
rolls.add(pins);
}
int score() {
int score = 0;
int frameIndex = 0;
for (int i = 1; i <= NUMBER_OF_FRAMES; i++) {
if (rolls.size() <= frameIndex) {
throw new IllegalStateException("Score cannot be taken until the end of the game");
}
if (isStrike(frameIndex)) {
if (rolls.size() <= frameIndex + 2) {
throw new IllegalStateException("Score cannot be taken until the end of the game");
}
int strikeBonus = strikeBonus(frameIndex);
if (strikeBonus > MAXIMUM_FRAME_SCORE && !isStrike(frameIndex + 1) && spareBonus(frameIndex) > 10) {
throw new IllegalStateException("Pin count exceeds pins on the lane");
}
score += 10 + strikeBonus;
frameIndex += i == NUMBER_OF_FRAMES ? 3 : 1;
} else if (isSpare(frameIndex)) {
if (rolls.size() <= frameIndex + 2) {
throw new IllegalStateException("Score cannot be taken until the end of the game");
}
score += 10 + spareBonus(frameIndex);
frameIndex += i == NUMBER_OF_FRAMES ? 3 : 2;
} else {
int frameScore = frameScore(frameIndex);
if (frameScore < 0) {
throw new IllegalStateException("Negative roll is invalid");
} else if (frameScore > 10) {
throw new IllegalStateException("Pin count exceeds pins on the lane");
}
score += frameScore;
frameIndex += 2;
}
}
if (!correctNumberOfRolls(frameIndex)) {
throw new IllegalStateException("Cannot roll after game is over");
}
return score;
}
private boolean correctNumberOfRolls(int frameIndex) {
return frameIndex == rolls.size();
}
private boolean isStrike(int frameIndex) {
return rolls.get(frameIndex) == MAXIMUM_FRAME_SCORE;
}
private boolean isSpare(int frameIndex) {
return rolls.get(frameIndex) + rolls.get(frameIndex + 1) == MAXIMUM_FRAME_SCORE;
}
private int strikeBonus(int frameIndex) {
return rolls.get(frameIndex + 1) + rolls.get(frameIndex + 2);
}
private int spareBonus(int frameIndex) {
return rolls.get(frameIndex + 2);
}
private int frameScore(int frameIndex) {
return rolls.get(frameIndex) + rolls.get(frameIndex + 1);
}
} |
package cgeo.geocaching;
import cgeo.geocaching.activity.AbstractListActivity;
import cgeo.geocaching.ui.AddressListAdapter;
import org.apache.commons.collections.CollectionUtils;
import android.app.ProgressDialog;
import android.location.Address;
import android.location.Geocoder;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import java.util.List;
import java.util.Locale;
public class AdressListActivity extends AbstractListActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTheme();
setContentView(R.layout.addresses);
setTitle(res.getString(R.string.search_address_result));
// get parameters
final String keyword = getIntent().getStringExtra("keyword");
if (keyword == null) {
showToast(res.getString(R.string.err_search_address_forgot));
finish();
return;
}
final AddressListAdapter adapter = new AddressListAdapter(this);
setListAdapter(adapter);
final ProgressDialog waitDialog =
ProgressDialog.show(this, res.getString(R.string.search_address_started), keyword, true);
waitDialog.setCancelable(true);
new AsyncTask<Void, Void, List<Address>>() {
@Override
protected List<Address> doInBackground(Void... params) {
final Geocoder geocoder = new Geocoder(AdressListActivity.this, Locale.getDefault());
try {
return geocoder.getFromLocationName(keyword, 20);
} catch (Exception e) {
Log.e(Settings.tag, "AdressListActivity.doInBackground", e);
return null;
}
}
@Override
protected void onPostExecute(final List<Address> addresses) {
waitDialog.dismiss();
try {
if (CollectionUtils.isEmpty(addresses)) {
showToast(res.getString(R.string.err_search_address_no_match));
finish();
return;
} else {
for (Address address : addresses) {
adapter.add(address); // don't use addAll, it's only available with API >= 11
}
}
} catch (Exception e) {
Log.e(Settings.tag, "AdressListActivity.onPostExecute", e);
}
}
}.execute();
}
} |
package net.lucenews.opensearch;
import java.util.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
public class OpenSearchResponse {
private String title;
private String id;
private Calendar updated;
private String description;
private String topUrl;
private Integer totalResults;
private Integer startIndex;
private Integer itemsPerPage;
private OpenSearchLink link;
private List<OpenSearchLink> links;
private List<OpenSearchQuery> queries;
private List<OpenSearchResult> results;
public OpenSearchResponse () {
links = new LinkedList<OpenSearchLink>();
queries = new LinkedList<OpenSearchQuery>();
results = new LinkedList<OpenSearchResult>();
}
public String getTopUrl(){
return topUrl;
}
public void setTopUrl(String url){
this.topUrl = url;
}
public String getTitle () {
return title;
}
public void setTitle (String title) {
this.title = title;
}
public String getDescription () {
return description;
}
public void setDescription (String description) {
this.description = description;
}
public String getId () {
return id;
}
public void setId (String id) {
this.id = id;
}
public Calendar getUpdated () {
return updated;
}
public void setUpdated (Calendar updated) {
this.updated = updated;
}
/**
* totalResults - the maximum number of results available for these
* search terms
*
* Restrictions: An integer greater than or equal to 0.
* Default: The number of items that were returned in this set of
* results.
* Requirements: May appear zero or one time.
*/
public Integer getTotalResults () {
return totalResults;
}
public void setTotalResults (Integer totalResults) {
this.totalResults = totalResults;
}
/**
* startIndex - the index of the first item returned in the result.
*
* Restrictions: An integer greater than or equal to 1.
* Note: The first result is 1.
* Default: 1
* Requirements: May appear zero or one time.
*/
public Integer getStartIndex () {
return startIndex;
}
public void setStartIndex (Integer startIndex) {
this.startIndex = startIndex;
}
/**
* itemsPerPage - the maximum number of items that can appear in
* one page of results.
*
* Restrictions: An integer greater than or equal to 1.
* Default: The number of items that were returned in this set of
* results.
* Requirements: May appear zero or one time.
*/
public Integer getItemsPerPage () {
return itemsPerPage;
}
public void setItemsPerPage (Integer itemsPerPage) {
this.itemsPerPage = itemsPerPage;
}
/**
* link - a reference back to the OpenSearch Description file
*
* Attributes: This is a clone of the link element in Atom,
* including href, hreflang, rel, and type attributes.
* Restrictions: The rel attribute must equal search.
* Note: New in version 1.1.
* Requirements: May appear zero or one time.
*/
public OpenSearchLink getLink () {
return link;
}
public void setLink (OpenSearchLink link) {
this.link = link;
}
public List<OpenSearchLink> getLinks () {
return links;
}
public void addLink (OpenSearchLink link) {
links.add( link );
}
public boolean removeLink (OpenSearchLink link) {
return links.remove( link );
}
public OpenSearchLink getRelatedLink (String rel) {
Iterator<OpenSearchLink> iterator = getLinks().iterator();
while ( iterator.hasNext() ) {
OpenSearchLink link = iterator.next();
if (link.getRel() != null && link.getRel().toLowerCase().trim().equals(rel.toLowerCase().trim())) {
return link;
}
}
return null;
}
/**
* Query - in an OpenSearch Response, can be used both to echo back
* the original query and to suggest new searches. Please see the
* OpenSearch Query specification for more information.
*
* Note: New in version 1.1.
* Requirements: May appear zero or more times. Note that the "Q"
* is capitalized.
*/
public List<OpenSearchQuery> getQueries () {
return queries;
}
public OpenSearchQuery getRequestQuery () {
return getRelatedQuery("request");
}
public OpenSearchQuery getRelatedQuery (String role) {
Iterator<OpenSearchQuery> iterator = getQueries().iterator();
while ( iterator.hasNext() ) {
OpenSearchQuery query = iterator.next();
if (query.getRole() != null && query.getRole().toLowerCase().trim().equals(role.toLowerCase().trim())) {
return query;
}
}
return null;
}
public void addQuery (OpenSearchQuery query) {
queries.add( query );
}
public void addQueries (OpenSearchQuery... queries) {
this.queries.addAll( Arrays.asList( queries ) );
}
public void addQueries (List<OpenSearchQuery> queries) {
this.queries.addAll( queries );
}
public boolean removeQuery (OpenSearchQuery query) {
return queries.remove( query );
}
public List<OpenSearchResult> getResults () {
return results;
}
public void addResult (OpenSearchResult result) {
results.add( result );
}
public boolean removeResult (OpenSearchResult result) {
return results.remove( result );
}
public static OpenSearchResponse asOpenSearchResponse (Element element) {
OpenSearchResponse response = new OpenSearchResponse();
// Atom
return response;
}
public Document asDocument (OpenSearch.Format format)
throws OpenSearchException, ParserConfigurationException
{
Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
document.appendChild(asElement( document, format ));
return document;
}
public Document asDocument (OpenSearch.Format format, OpenSearch.Mode mode)
throws OpenSearchException, ParserConfigurationException
{
Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
document.appendChild(asElement( document, format, mode ));
return document;
}
public Element asElement (Document document, OpenSearch.Format format) throws OpenSearchException {
return asElement(document, format, OpenSearch.getDefaultMode());
}
public Element asElement (Document document, OpenSearch.Format format, OpenSearch.Mode mode) throws OpenSearchException {
OpenSearchQuery requestQuery = getRequestQuery();
/**
* Atom
*/
if (format == OpenSearch.ATOM) {
Element element = document.createElement("feed");
element.setAttribute("xmlns:opensearch","http://a9.com/-/spec/opensearch/1.1/");
element.setAttribute("xmlns:relevance","http://a9.com/-/opensearch/extensions/relevance/1.0/");
element.setAttribute("xmlns","http:
// Top Link
if (getTopUrl() != null){
element.appendChild(asElement(document, getTopUrl()));
}
// title
if (getTitle() != null) {
element.appendChild( asElement( document, "title", getTitle() ) );
}
if (getId() != null) {
element.appendChild( asElement( document, "id", getId() ) );
}
// updated
if (getUpdated() != null) {
element.appendChild( asElement( document, "updated", net.lucenews.atom.Entry.asString( getUpdated() ) ) );
}
// Link
if (getLink() != null) {
if (getLink().getRel() != null) {
if (!getLink().getRel().equals("search")) {
if (mode == OpenSearch.STRICT) {
throw new OpenSearchException("Link relation must be 'search'");
}
else if (mode == OpenSearch.ADAPTIVE) {
OpenSearchLink link = getLink().clone();
link.setRel("search");
element.appendChild( link.asElement( document, format, mode ) );
}
else {
element.appendChild( getLink().asElement( document, format, mode ) );
}
}
else {
element.appendChild( getLink().asElement( document, format, mode ) );
}
}
else {
if (mode == OpenSearch.STRICT) {
throw new OpenSearchException("Link relation must be 'search'");
}
element.appendChild( getLink().asElement( document, format, mode ) );
}
}
// Query
Iterator<OpenSearchQuery> queryIterator = getQueries().iterator();
while (queryIterator.hasNext()) {
OpenSearchQuery query = queryIterator.next();
element.appendChild( query.asElement( document, format, mode ) );
}
// totalResults
Integer totalResults = getTotalResults();
if (totalResults == null && requestQuery != null) { totalResults = requestQuery.getTotalResults(); }
if (totalResults != null) {
element.appendChild(asElementNS(document, "http://a9.com/-/spec/opensearch/1.1/", "opensearch:totalResults", String.valueOf(totalResults)));
}
// startIndex
Integer startIndex = getStartIndex();
if (startIndex == null && requestQuery != null) { startIndex = requestQuery.getStartIndex(); }
if (startIndex != null) {
element.appendChild(asElementNS(document, "http://a9.com/-/spec/opensearch/1.1/", "opensearch:startIndex", String.valueOf(startIndex)));
}
// itemsPerPage
Integer itemsPerPage = getItemsPerPage();
if (itemsPerPage == null && requestQuery != null) { itemsPerPage = requestQuery.getCount(); }
if (itemsPerPage != null) {
element.appendChild(asElementNS(document, "http://a9.com/-/spec/opensearch/1.1/", "opensearch:itemsPerPage", String.valueOf(itemsPerPage)));
}
// Links
Iterator<OpenSearchLink> linksIterator = getLinks().iterator();
while (linksIterator.hasNext()) {
OpenSearchLink link = linksIterator.next();
element.appendChild( link.asElement( document, format, mode ) );
}
Iterator<OpenSearchResult> resultsIterator = getResults().iterator();
while (resultsIterator.hasNext()) {
OpenSearchResult result = resultsIterator.next();
element.appendChild( result.asElement( document, format, mode ) );
}
return element;
}
/**
* RSS
*/
if (format == OpenSearch.RSS) {
Element element = document.createElement("rss");
element.setAttribute("version", "2.0");
element.setAttribute("xmlns:opensearch","http://a9.com/-/spec/opensearch/1.1/");
Element channel = document.createElement("channel");
// title
if (getTitle() != null) {
channel.appendChild( asElement( document, "title", getTitle() ) );
}
// link
if (getLink() != null && getLink().getHref() != null) {
channel.appendChild( asElement( document, "link", getLink().getHref() ) );
}
// description
if (getDescription() != null) {
channel.appendChild( asElement( document, "description", getDescription() ) );
}
// totalResults
if (getTotalResults() != null) {
channel.appendChild(asElementNS(document, "http://a9.com/-/spec/opensearch/1.1/", "opensearch:totalResults", String.valueOf(getTotalResults())));
}
// startIndex
if (getStartIndex() != null) {
channel.appendChild(asElementNS(document, "http://a9.com/-/spec/opensearch/1.1/", "opensearch:startIndex", String.valueOf(getStartIndex())));
}
// itemsPerPage
if (getItemsPerPage() != null) {
channel.appendChild(asElementNS(document, "http://a9.com/-/spec/opensearch/1.1/", "opensearch:itemsPerPage", String.valueOf(getItemsPerPage())));
}
// Links
Iterator<OpenSearchLink> linksIterator = getLinks().iterator();
while (linksIterator.hasNext()) {
OpenSearchLink link = linksIterator.next();
channel.appendChild( link.asElement( document, format, mode ) );
}
// items
Iterator<OpenSearchResult> resultsIterator = getResults().iterator();
while (resultsIterator.hasNext()) {
OpenSearchResult result = resultsIterator.next();
channel.appendChild( result.asElement( document, format, mode ) );
}
element.appendChild( channel );
return element;
}
throw new OpenSearchException("Unknown format");
}
protected Element asElement (Document document, String name, String value) throws OpenSearchException {
Element element = document.createElement(name);
element.appendChild( document.createTextNode(value) );
return element;
}
protected Element asElementNS (Document document, String namespaceURI, String qualifiedName, String value) throws OpenSearchException {
Element element = document.createElementNS(namespaceURI, qualifiedName);
element.appendChild( document.createTextNode(value) );
return element;
}
protected Element asElement(Document document, String value) throws OpenSearchException{
Element element = document.createElement("link");
element.setAttribute("href",value);
element.setAttribute("rel","self");
element.appendChild( document.createTextNode(value) );
return element;
}
} |
package caris.framework.handlers;
import caris.framework.basehandlers.Handler;
import caris.framework.basereactions.MultiReaction;
import caris.framework.basereactions.Reaction;
import caris.framework.library.Constants;
import caris.framework.library.Variables;
import caris.framework.reactions.ReactionMessage;
import caris.framework.reactions.ReactionUserOfflineUpdate;
import caris.framework.utilities.Logger;
import sx.blah.discord.api.events.Event;
import sx.blah.discord.handle.impl.events.user.PresenceUpdateEvent;
import sx.blah.discord.handle.obj.IGuild;
import sx.blah.discord.handle.obj.StatusType;
public class UserOnlineHandler extends Handler {
public UserOnlineHandler() {
super("UserOnline Handler");
}
@Override
protected boolean isTriggered(Event event) {
return event instanceof PresenceUpdateEvent;
}
@Override
protected Reaction process(Event event) {
Logger.debug("PresenceUpdate detected", 2);
PresenceUpdateEvent presenceUpdateEvent = (PresenceUpdateEvent) event;
MultiReaction userOnline = new MultiReaction(-1);
if( presenceUpdateEvent.getNewPresence().getStatus().equals(StatusType.OFFLINE) && !Variables.globalUserInfo.get(presenceUpdateEvent.getUser()).hasGoneOffline ) {
userOnline.reactions.add(new ReactionUserOfflineUpdate(presenceUpdateEvent.getUser(), true));
} else if( presenceUpdateEvent.getNewPresence().getStatus().equals(StatusType.ONLINE) && Variables.globalUserInfo.get(presenceUpdateEvent.getUser()).hasGoneOffline ) {
Logger.print(" User [" + presenceUpdateEvent.getUser().getName() + "#" + presenceUpdateEvent.getUser().getDiscriminator() + "]" + "(" + presenceUpdateEvent.getUser().getLongID() + ") has come online.");
userOnline.reactions.add(new ReactionUserOfflineUpdate(presenceUpdateEvent.getUser(), false));
for( IGuild guild : Variables.guildIndex.keySet() ) {
if( guild.getUsers().contains(presenceUpdateEvent.getUser()) ) {
if( !Variables.guildIndex.get(guild).userIndex.get(presenceUpdateEvent.getUser()).mailbox.isEmpty() ) {
userOnline.reactions.add(new ReactionMessage("Welcome back, " + presenceUpdateEvent.getUser().mention() + "! You have incoming mail!"
+ "\nType `" + Constants.INVOCATION_PREFIX + " mail check` to read it!", Variables.guildIndex.get(guild).getDefaultChannel()));
}
}
}
}
Logger.print("Reaction produced from " + name, 1);
return userOnline;
}
} |
package org.exist.xslt.expression;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import org.exist.xquery.AnalyzeContextInfo;
import org.exist.xquery.Expression;
import org.exist.xquery.LocationStep;
import org.exist.xquery.NodeTest;
import org.exist.xquery.TextConstructor;
import org.exist.xquery.TypeTest;
import org.exist.xquery.Variable;
import org.exist.xquery.XPathException;
import org.exist.xquery.util.ExpressionDumper;
import org.exist.xquery.value.Item;
import org.exist.xquery.value.NodeValue;
import org.exist.xquery.value.Sequence;
import org.exist.xquery.value.SequenceIterator;
import org.exist.xslt.ErrorCodes;
import org.exist.xslt.XSLContext;
import org.exist.dom.QName;
import org.exist.interpreter.ContextAtExist;
import org.exist.xslt.expression.i.Parameted;
import org.exist.xslt.pattern.Pattern;
import org.exist.xslt.XSLExceptions;
import org.w3c.dom.Attr;
/**
* <!-- Category: declaration -->
* <xsl:template
* match? = pattern
* name? = qname
* priority? = number
* mode? = tokens
* as? = sequence-type>
* <!-- Content: (xsl:param*, sequence-constructor) -->
* </xsl:template>
*
* @author <a href="mailto:shabanovd@gmail.com">Dmitriy Shabanov</a>
*
*/
public class Template extends Declaration implements Parameted, Comparable<Template> {
private String attr_match = null;
private String attr_priority = null;
private XSLPathExpr match = null;
private QName name = null;
private QName[] mode = null;
private Double priority = null;
private String as = null;
private Map<QName, org.exist.xquery.Variable> params = null;
public Template(XSLContext context) {
super(context);
}
public void setToDefaults() {
attr_match = null;
attr_priority = null;
match = null;
name = null;
mode = null;
priority = 0.5;//UNDERSTAND: what should be default
as = "item()*";
}
public void prepareAttribute(ContextAtExist context, Attr attr) throws XPathException {
String attr_name = attr.getLocalName();
if (attr_name.equals(MATCH)) {
attr_match = attr.getValue();
} else if (attr_name.equals(NAME)) {
name = new QName(attr.getValue());
} else if (attr_name.equals(PRIORITY)) {
attr_priority = attr.getValue();
} else if (attr_name.equals(MODE)) {
// mode = attr.getValue();//TODO: write
} else if (attr_name.equals(AS)) {
as = attr.getValue();
}
}
// public void add(SimpleConstructor s) {
// if (s instanceof Text) {
// return; //ignore text nodes
// steps.add(s);
public void analyze(AnalyzeContextInfo contextInfo) throws XPathException {
if (isRootMatch())
contextInfo.addFlag(DOT_TEST);
super.analyze(contextInfo);
if (attr_match != null) {
match = new XSLPathExpr(getXSLContext());
Pattern.parse(contextInfo.getContext(), attr_match, match);
_check_(match);
}
if (attr_priority != null)
try {
priority = Double.valueOf(attr_priority);
} catch (NumberFormatException e) {
compileError(XSLExceptions.ERR_XTSE0530);
}
else
priority = computedPriority();
setUseStaticContext(true);
}
public void validate() throws XPathException {
boolean canBeParam = true;
for (int pos = 0; pos < this.getLength(); pos++) {
Expression expr = this.getExpression(pos);
if (expr instanceof TextConstructor) {
continue;//ignore text elements
}
//validate instruction order
if (expr instanceof Param) {
if (!canBeParam) {
compileError(ErrorCodes.XTSE0010, "<xsl:param> must be before any other tag");
}
} else
canBeParam = false;
//validate sub-instructions
if (expr instanceof XSLPathExpr) {
XSLPathExpr xsl = (XSLPathExpr) expr;
xsl.validate();
}
}
}
private double computedPriority() {
double priority = 0.5;
if (match != null)
if (match.getLength() > 0) {
Expression expr = match.getExpression(0);
if (expr instanceof LocationStep) {
LocationStep locationStep = (LocationStep) expr;
NodeTest test = locationStep.getTest();
if ((test.getName() == null)
|| (test.getName().getLocalPart() == null))
priority = -0.5;
else if (locationStep.getPredicates().size() > 0)
priority = 0.25;
else
priority = 0;
//TODO: else (element(E,T) 0.25 (matches by name and type) ...)
}
}
return priority;
}
public boolean isSmallWildcard() {
if (match != null)
if (match.getLength() > 0) {
Expression expr = match.getExpression(0);
if (expr instanceof LocationStep) {
LocationStep locationStep = (LocationStep) expr;
NodeTest test = locationStep.getTest();
if (test instanceof TypeTest) {
if (test.getName() == null)
return true;
}
}
}
return false;
}
// private void _check_(PathExpr path) {
// for (int pos = 0; pos < path.getLength(); pos++) {
// Expression expr = path.getExpression(pos);
// if ((pos == 0) && (expr instanceof LocationStep)) {
// LocationStep location = (LocationStep) expr;
// if (location.getAxis() == Constants.CHILD_AXIS) {
// location.setAxis(Constants.SELF_AXIS);
// } else if (expr instanceof PathExpr) {
// _check_((PathExpr) expr);
public Sequence eval(Sequence contextSequence, Item contextItem) throws XPathException {
context.pushDocumentContext();
try {
return super.eval(contextSequence, contextItem);
} finally {
context.popDocumentContext();
}
}
// public Sequence eval(Sequence contextSequence, Item contextItem) throws XPathException {
// Sequence result = new ValueSequence();
// if ((contextItem == null) && (isSmallWildcard()))
// return result; //UNDERSTAND: is it ok??? maybe better null or check at XSLComp
//// if ((contextSequence == null) && (isBigWildcard()))
//// return result; //UNDERSTAND: is it ok??? maybe better null or check at XSLComp
// Sequence matched = match.eval(contextSequence, contextItem);
// for (Item item : matched) {
// Sequence answer = super.eval(item.toSequence(), item);//item
// result.addAll(answer);
// return result;
public int compareTo(Template template) {
if (priority == null)
throw new RuntimeException("Priority can't be null.");
if (template.priority == null)
throw new RuntimeException("Priority can't be null.");
//-compareTo to make order from high to low
int compared = priority.compareTo(template.priority);
if (compared == 0) {
int thisVal = getExpressionId();
int anotherVal = template.getExpressionId();
return (thisVal<anotherVal ? +1 : (thisVal==anotherVal ? 0 : -1));
}
return -compared;
}
/* (non-Javadoc)
* @see org.exist.xquery.Expression#dump(org.exist.xquery.util.ExpressionDumper)
*/
public void dump(ExpressionDumper dumper) {
dumper.display("<xsl:template");
if (match != null) {
dumper.display(" match = ");
match.dump(dumper);
}
if (name != null)
dumper.display(" name = "+name);
if (mode != null)
dumper.display(" mode = " + Arrays.toString(mode));
if (attr_priority != null)
dumper.display(" priority = "+attr_priority);
if (as != null)
dumper.display(" as = "+as);
dumper.display("> ");
super.dump(dumper);
dumper.display("</xsl:template>");
}
public String toString() {
StringBuilder result = new StringBuilder();
result.append("<xsl:template");
if (match != null)
result.append(" match = "+match.toString());
if (name != null)
result.append(" name = "+name.getStringValue());
if (mode != null)
result.append(" mode = " + Arrays.toString(mode));
if (attr_priority != null)
result.append(" priority = "+attr_priority);
if (as != null)
result.append(" as = "+as);
result.append("> ");
// result.append(super.toString());
// result.append("</xsl:template> ");
return result.toString();
}
public boolean matched(Sequence contextSequence, Item item) throws XPathException {
if (match == null)
return false;
boolean matched = false;
for (int i = match.getLength()-1; i >= 0; i
Expression expr = match.getExpression(i);
if (!expr.match(contextSequence, item))
return false;
if (expr instanceof LocationStep) {
item = (Item)((NodeValue)item).getNode().getParentNode();
}
matched = true;
}
return matched;
}
public boolean isRootMatch() {
return ("/".equals(attr_match));
}
public boolean isPrioritySet() {
return attr_priority != null;
}
public double getPriority() {
return priority;
}
public Map<QName, org.exist.xquery.Variable> getXSLParams() {
if (params == null)
params = new HashMap<QName, org.exist.xquery.Variable>();
return params;
}
/* (non-Javadoc)
* @see org.exist.xslt.expression.i.Parameted#addXSLParam(org.exist.xslt.expression.Param)
*/
public void addXSLParam(Param param) throws XPathException {
Map<QName, org.exist.xquery.Variable> params = getXSLParams();
if (params.containsKey(param.getName()))
compileError(XSLExceptions.ERR_XTSE0580);
Variable variable = context.declareVariable(param.getName(), param);
params.put(param.getName(), variable);
}
public QName getName() {
return name;
}
/**
* @deprecated Use {@link #process(XSLContext,SequenceIterator)} instead
*/
public void process(SequenceIterator sequenceIterator, XSLContext context) {
process(context, sequenceIterator);
}
public void process(XSLContext context, SequenceIterator sequenceIterator) {
super.process(context, sequenceIterator);
}
} |
package cgeo.geocaching;
import cgeo.geocaching.compatibility.Compatibility;
import cgeo.geocaching.concurrent.BlockingThreadPool;
import cgeo.geocaching.files.LocalStorage;
import cgeo.geocaching.geopoint.GeopointFormatter.Format;
import cgeo.geocaching.network.Network;
import cgeo.geocaching.network.Parameters;
import cgeo.geocaching.utils.Log;
import ch.boye.httpclientandroidlib.HttpResponse;
import org.apache.commons.lang3.StringUtils;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.WindowManager;
import java.io.File;
import java.util.concurrent.TimeUnit;
public class StaticMapsProvider {
private static final String PREFIX_PREVIEW = "preview";
private static final String GOOGLE_STATICMAP_URL = "http://maps.google.com/maps/api/staticmap";
private static final String SATELLITE = "satellite";
private static final String ROADMAP = "roadmap";
private static final String WAYPOINT_PREFIX = "wp";
private static final String MAP_FILENAME_PREFIX = "map_";
private static final String MARKERS_URL = "http://status.cgeo.org/assets/markers/";
/** We assume there is no real usable image with less than 1k */
private static final int MIN_MAP_IMAGE_BYTES = 1000;
/** ThreadPool restricting this to 1 Thread. **/
private static final BlockingThreadPool pool = new BlockingThreadPool(1, Thread.MIN_PRIORITY);
private static File getMapFile(final String geocode, String prefix, final boolean createDirs) {
return LocalStorage.getStorageFile(geocode, MAP_FILENAME_PREFIX + prefix, false, createDirs);
}
private static void downloadDifferentZooms(final String geocode, String markerUrl, String prefix, String latlonMap, int edge, final Parameters waypoints) {
downloadMap(geocode, 20, SATELLITE, markerUrl, prefix + '1', "", latlonMap, edge, edge, waypoints);
downloadMap(geocode, 18, SATELLITE, markerUrl, prefix + '2', "", latlonMap, edge, edge, waypoints);
downloadMap(geocode, 16, ROADMAP, markerUrl, prefix + '3', "", latlonMap, edge, edge, waypoints);
downloadMap(geocode, 14, ROADMAP, markerUrl, prefix + '4', "", latlonMap, edge, edge, waypoints);
downloadMap(geocode, 11, ROADMAP, markerUrl, prefix + '5', "", latlonMap, edge, edge, waypoints);
}
private static void downloadMap(String geocode, int zoom, String mapType, String markerUrl, String prefix, String shadow, String latlonMap, int width, int height, final Parameters waypoints) {
final Parameters params = new Parameters(
"center", latlonMap,
"zoom", String.valueOf(zoom),
"size", String.valueOf(width) + 'x' + String.valueOf(height),
"maptype", mapType,
"markers", "icon:" + markerUrl + '|' + shadow + latlonMap,
"sensor", "false");
if (waypoints != null) {
params.addAll(waypoints);
}
final HttpResponse httpResponse = Network.getRequest(GOOGLE_STATICMAP_URL, params);
if (httpResponse == null) {
Log.e("StaticMapsProvider.downloadMap: httpResponse is null");
return;
}
if (httpResponse.getStatusLine().getStatusCode() != 200) {
Log.d("StaticMapsProvider.downloadMap: httpResponseCode = " + httpResponse.getStatusLine().getStatusCode());
return;
}
final File file = getMapFile(geocode, prefix, true);
if (LocalStorage.saveEntityToFile(httpResponse, file)) {
// Delete image if it has no contents
final long fileSize = file.length();
if (fileSize < MIN_MAP_IMAGE_BYTES) {
file.delete();
}
}
}
public static void downloadMaps(Geocache cache) {
if ((!Settings.isStoreOfflineMaps() && !Settings.isStoreOfflineWpMaps()) || StringUtils.isBlank(cache.getGeocode())) {
return;
}
int edge = guessMaxDisplaySide();
if (Settings.isStoreOfflineMaps() && cache.getCoords() != null) {
storeCachePreviewMap(cache);
storeCacheStaticMap(cache, edge, false);
}
// clean old and download static maps for waypoints if one is missing
if (Settings.isStoreOfflineWpMaps()) {
for (final Waypoint waypoint : cache.getWaypoints()) {
if (!hasAllStaticMapsForWaypoint(cache.getGeocode(), waypoint)) {
refreshAllWpStaticMaps(cache, edge);
}
}
}
}
/**
* Deletes and download all Waypoints static maps.
*
* @param cache
* The cache instance
* @param edge
* The boundings
*/
private static void refreshAllWpStaticMaps(Geocache cache, int edge) {
LocalStorage.deleteFilesWithPrefix(cache.getGeocode(), MAP_FILENAME_PREFIX + WAYPOINT_PREFIX);
for (Waypoint waypoint : cache.getWaypoints()) {
storeWaypointStaticMap(cache.getGeocode(), edge, waypoint, false);
}
}
public static void storeWaypointStaticMap(Geocache cache, Waypoint waypoint, boolean waitForResult) {
int edge = StaticMapsProvider.guessMaxDisplaySide();
storeWaypointStaticMap(cache.getGeocode(), edge, waypoint, waitForResult);
}
private static void storeWaypointStaticMap(final String geocode, int edge, Waypoint waypoint, final boolean waitForResult) {
if (geocode == null) {
Log.e("storeWaypointStaticMap - missing input parameter geocode");
return;
}
if (waypoint == null) {
Log.e("storeWaypointStaticMap - missing input parameter waypoint");
return;
}
if (waypoint.getCoords() == null) {
return;
}
String wpLatlonMap = waypoint.getCoords().format(Format.LAT_LON_DECDEGREE_COMMA);
String wpMarkerUrl = getWpMarkerUrl(waypoint);
if (!hasAllStaticMapsForWaypoint(geocode, waypoint)) {
// download map images in separate background thread for higher performance
downloadMaps(geocode, wpMarkerUrl, WAYPOINT_PREFIX + waypoint.getId() + '_' + waypoint.getStaticMapsHashcode() + "_", wpLatlonMap, edge, null, waitForResult);
}
}
public static void storeCacheStaticMap(Geocache cache, final boolean waitForResult) {
int edge = guessMaxDisplaySide();
storeCacheStaticMap(cache, edge, waitForResult);
}
private static void storeCacheStaticMap(final Geocache cache, final int edge, final boolean waitForResult) {
final String latlonMap = cache.getCoords().format(Format.LAT_LON_DECDEGREE_COMMA);
final Parameters waypoints = new Parameters();
for (final Waypoint waypoint : cache.getWaypoints()) {
if (waypoint.getCoords() == null) {
continue;
}
final String wpMarkerUrl = getWpMarkerUrl(waypoint);
waypoints.put("markers", "icon:" + wpMarkerUrl + '|' + waypoint.getCoords().format(Format.LAT_LON_DECDEGREE_COMMA));
}
// download map images in separate background thread for higher performance
final String cacheMarkerUrl = getCacheMarkerUrl(cache);
downloadMaps(cache.getGeocode(), cacheMarkerUrl, "", latlonMap, edge, waypoints, waitForResult);
}
public static void storeCachePreviewMap(final Geocache cache) {
final String latlonMap = cache.getCoords().format(Format.LAT_LON_DECDEGREE_COMMA);
final Display display = ((WindowManager) cgeoapplication.getInstance().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
DisplayMetrics metrics = new DisplayMetrics();
display.getMetrics(metrics);
final int width = metrics.widthPixels;
final int height = (int) (110 * metrics.density);
final String markerUrl = MARKERS_URL + "my_location_mdpi.png";
downloadMap(cache.getGeocode(), 15, ROADMAP, markerUrl, PREFIX_PREVIEW, "shadow:false|", latlonMap, width, height, null);
}
private static int guessMaxDisplaySide() {
Point displaySize = Compatibility.getDisplaySize();
return Math.max(displaySize.x, displaySize.y) - 25;
}
private static void downloadMaps(final String geocode, final String markerUrl, final String prefix, final String latlonMap, final int edge,
final Parameters waypoints, boolean waitForResult) {
if (waitForResult) {
downloadDifferentZooms(geocode, markerUrl, prefix, latlonMap, edge, waypoints);
}
else {
final Runnable currentTask = new Runnable() {
@Override
public void run() {
downloadDifferentZooms(geocode, markerUrl, prefix, latlonMap, edge, waypoints);
}
};
try {
pool.add(currentTask, 20, TimeUnit.SECONDS);
} catch (InterruptedException e) {
Log.e("StaticMapsProvider.downloadMaps error adding task", e);
}
}
}
private static String getCacheMarkerUrl(final Geocache cache) {
StringBuilder url = new StringBuilder(MARKERS_URL);
url.append("marker_cache_").append(cache.getType().id);
if (cache.isFound()) {
url.append("_found");
} else if (cache.isDisabled()) {
url.append("_disabled");
}
url.append(".png");
return url.toString();
}
private static String getWpMarkerUrl(final Waypoint waypoint) {
String type = waypoint.getWaypointType() != null ? waypoint.getWaypointType().id : null;
return MARKERS_URL + "marker_waypoint_" + type + ".png";
}
public static void removeWpStaticMaps(Waypoint waypoint, final String geocode) {
if (waypoint == null) {
return;
}
int waypointId = waypoint.getId();
int waypointMapHash = waypoint.getStaticMapsHashcode();
for (int level = 1; level <= 5; level++) {
try {
StaticMapsProvider.getMapFile(geocode, WAYPOINT_PREFIX + waypointId + "_" + waypointMapHash + '_' + level, false).delete();
} catch (Exception e) {
Log.e("StaticMapsProvider.removeWpStaticMaps", e);
}
}
}
/**
* Check if at least one map file exists for the given cache.
*
* @param cache
* @return <code>true</code> if at least one map file exists; <code>false</code> otherwise
*/
public static boolean hasStaticMap(final Geocache cache) {
if (cache == null) {
return false;
}
final String geocode = cache.getGeocode();
if (StringUtils.isBlank(geocode)) {
return false;
}
for (int level = 1; level <= 5; level++) {
File mapFile = StaticMapsProvider.getMapFile(geocode, String.valueOf(level), false);
if (mapFile.exists()) {
return true;
}
}
return false;
}
/**
* Checks if at least one map file exists for the given geocode and waypoint ID.
*
* @param geocode
* @param waypoint
* @return <code>true</code> if at least one map file exists; <code>false</code> otherwise
*/
public static boolean hasStaticMapForWaypoint(String geocode, Waypoint waypoint) {
int waypointId = waypoint.getId();
int waypointMapHash = waypoint.getStaticMapsHashcode();
for (int level = 1; level <= 5; level++) {
File mapFile = StaticMapsProvider.getMapFile(geocode, WAYPOINT_PREFIX + waypointId + "_" + waypointMapHash + "_" + level, false);
if (mapFile.exists()) {
return true;
}
}
return false;
}
/**
* Checks if all map files exist for the given geocode and waypoint ID.
*
* @param geocode
* @param waypoint
* @return <code>true</code> if all map files exist; <code>false</code> otherwise
*/
public static boolean hasAllStaticMapsForWaypoint(String geocode, Waypoint waypoint) {
int waypointId = waypoint.getId();
int waypointMapHash = waypoint.getStaticMapsHashcode();
for (int level = 1; level <= 5; level++) {
File mapFile = StaticMapsProvider.getMapFile(geocode, WAYPOINT_PREFIX + waypointId + "_" + waypointMapHash + "_" + level, false);
boolean mapExists = mapFile.exists();
if (!mapExists) {
return false;
}
}
return true;
}
public static Bitmap getPreviewMap(final String geocode) {
return decodeFile(StaticMapsProvider.getMapFile(geocode, PREFIX_PREVIEW, false));
}
public static Bitmap getWaypointMap(final String geocode, Waypoint waypoint, int level) {
int waypointId = waypoint.getId();
int waypointMapHash = waypoint.getStaticMapsHashcode();
return decodeFile(StaticMapsProvider.getMapFile(geocode, WAYPOINT_PREFIX + waypointId + "_" + waypointMapHash + "_" + level, false));
}
public static Bitmap getCacheMap(final String geocode, int level) {
return decodeFile(StaticMapsProvider.getMapFile(geocode, String.valueOf(level), false));
}
private static Bitmap decodeFile(final File mapFile) {
// avoid exception in system log, if we got nothing back from Google.
if (mapFile.exists()) {
return BitmapFactory.decodeFile(mapFile.getPath());
}
return null;
}
} |
package net.mafro.android.wakeonlan;
import android.app.PendingIntent;
import android.database.Cursor;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Intent;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.RemoteViews;
import android.util.Log;
/**
* @desc This class is used to setup the home screen widget, as well as handle click events
*/
public class WidgetProvider extends AppWidgetProvider
{
public static final String TAG = "WidgetProvider";
public static final String SETTINGS_PREFIX = "widget_";
public static final String WIDGET_ONCLICK = "net.mafro.android.wakeonlan.WidgetOnClick";
/**
* @desc this method is called once when the WidgetHost starts (usually when the OS boots).
*/
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds)
{
SharedPreferences settings = context.getSharedPreferences(WakeOnLanActivity.TAG, 0);
final int N = appWidgetIds.length;
for(int i=0; i<N; i++) {
int widget_id = appWidgetIds[i];
HistoryItem item = loadItemPref(context, settings, widget_id);
if(item == null) {
// item or prefrences missing.
// TODO delete the widget probably (cant find a way to do this).
// maybe set the title of the widget to ERROR
continue;
}
configureWidget(widget_id, item, context);
}
}
@Override
public void onReceive(Context context, Intent intent)
{
super.onReceive(context, intent);
if(intent.getAction().startsWith(WIDGET_ONCLICK)) {
SharedPreferences settings = context.getSharedPreferences(WakeOnLanActivity.TAG, 0);
// get the widget id
int widget_id = getWidgetId(intent);
if(widget_id == AppWidgetManager.INVALID_APPWIDGET_ID) {
return;
}
// get the HistoryItem associated with the widget_id
HistoryItem item = loadItemPref(context, settings, widget_id);
// send the packet
WakeOnLanActivity.sendPacket(context, item.title, item.mac, item.ip, item.port);
}
}
@Override
public void onDeleted(Context context, int[] id)
{
SharedPreferences settings = context.getSharedPreferences(WakeOnLanActivity.TAG, 0);
final int N = id.length;
for(int i=0; i<N; i++) {
deleteItemPref(settings, id[i]);
}
}
/**
* @desc gets the widget id from an intent
*/
public static int getWidgetId(Intent intent)
{
Bundle extras = intent.getExtras();
if(extras != null) {
return extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
}
return AppWidgetManager.INVALID_APPWIDGET_ID;
}
/**
* @desc configures a widget for the first time. Usually called when creating a widget
* for the first time or initialising existing widgets when the AppWidgetManager
* restarts (usually when the phone reboots).
*/
public static void configureWidget(int widget_id, HistoryItem item, Context context)
{
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget);
views.setTextViewText(R.id.appwidget_text, item.title);
// append id to action to prevent clearing the extras bundle
views.setOnClickPendingIntent(R.id.appwidget_button, getPendingSelfIntent(context, widget_id, WIDGET_ONCLICK + widget_id));
// tell the widget manager
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
appWidgetManager.updateAppWidget(widget_id, views);
}
private static PendingIntent getPendingSelfIntent(Context context, int widget_id, String action)
{
Intent intent = new Intent(context, WidgetProvider.class);
intent.setAction(action);
Bundle bundle = new Bundle();
bundle.putInt(AppWidgetManager.EXTRA_APPWIDGET_ID, widget_id);
intent.putExtras(bundle);
return PendingIntent.getBroadcast(context, 0, intent, 0);
}
/**
* @desc saves the given history item/widget_id combination
*/
public static void saveItemPref(SharedPreferences settings, HistoryItem item, int widget_id)
{
SharedPreferences.Editor editor = settings.edit();
// store HistoryItem details in settings
editor.putInt(SETTINGS_PREFIX + widget_id, item.id);
editor.putString(SETTINGS_PREFIX + widget_id + History.Items.TITLE, item.title);
editor.putString(SETTINGS_PREFIX + widget_id + History.Items.MAC, item.mac);
editor.putString(SETTINGS_PREFIX + widget_id + History.Items.IP, item.ip);
editor.putInt(SETTINGS_PREFIX + widget_id + History.Items.PORT, item.port);
editor.commit();
}
public static void deleteItemPref(SharedPreferences settings, int widget_id)
{
SharedPreferences.Editor editor = settings.edit();
editor.remove(SETTINGS_PREFIX + widget_id);
editor.remove(SETTINGS_PREFIX + widget_id + History.Items.TITLE);
editor.remove(SETTINGS_PREFIX + widget_id + History.Items.MAC);
editor.remove(SETTINGS_PREFIX + widget_id + History.Items.IP);
editor.remove(SETTINGS_PREFIX + widget_id + History.Items.PORT);
editor.commit();
}
/**
* @desc load the HistoryItem associated with a widget_id
*/
public static HistoryItem loadItemPref(Context context, SharedPreferences settings, int widget_id)
{
// get item_id
int item_id = settings.getInt(SETTINGS_PREFIX + widget_id, -1);
if(item_id == -1) {
// No item_id found for given widget return null
return null;
}
String title = settings.getString(SETTINGS_PREFIX + widget_id + History.Items.TITLE, "");
String mac = settings.getString(SETTINGS_PREFIX + widget_id + History.Items.MAC, "");
String ip = settings.getString(SETTINGS_PREFIX + widget_id + History.Items.IP, "");
int port = settings.getInt(SETTINGS_PREFIX + widget_id + History.Items.PORT, -1);
return new HistoryItem(item_id, title, mac, ip, port);
}
} |
package cgeo.geocaching.maps;
import cgeo.geocaching.Settings;
import cgeo.geocaching.cgCoord;
import cgeo.geocaching.cgeopopup;
import cgeo.geocaching.cgeowaypoint;
import cgeo.geocaching.enumerations.CacheType;
import cgeo.geocaching.geopoint.Geopoint;
import cgeo.geocaching.maps.interfaces.CachesOverlayItemImpl;
import cgeo.geocaching.maps.interfaces.GeoPointImpl;
import cgeo.geocaching.maps.interfaces.ItemizedOverlayImpl;
import cgeo.geocaching.maps.interfaces.MapProjectionImpl;
import cgeo.geocaching.maps.interfaces.MapProvider;
import cgeo.geocaching.maps.interfaces.MapViewImpl;
import org.apache.commons.lang3.StringUtils;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.PaintFlagsDrawFilter;
import android.graphics.Point;
import android.location.Location;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
public class CachesOverlay extends AbstractItemizedOverlay {
private List<CachesOverlayItemImpl> items = new ArrayList<CachesOverlayItemImpl>();
private Context context = null;
private boolean fromDetail = false;
private boolean displayCircles = false;
private ProgressDialog waitDialog = null;
private Point center = new Point();
private Point left = new Point();
private Paint blockedCircle = null;
private PaintFlagsDrawFilter setfil = null;
private PaintFlagsDrawFilter remfil = null;
private MapProvider mapProvider = null;
public CachesOverlay(ItemizedOverlayImpl ovlImpl, Context contextIn, boolean fromDetailIn) {
super(ovlImpl);
populate();
context = contextIn;
fromDetail = fromDetailIn;
mapProvider = Settings.getMapProvider();
}
public void updateItems(CachesOverlayItemImpl item) {
List<CachesOverlayItemImpl> itemsPre = new ArrayList<CachesOverlayItemImpl>();
itemsPre.add(item);
updateItems(itemsPre);
}
public void updateItems(List<CachesOverlayItemImpl> itemsPre) {
if (itemsPre == null) {
return;
}
for (CachesOverlayItemImpl item : itemsPre) {
item.setMarker(boundCenterBottom(item.getMarker(0)));
}
// ensure no interference between the draw and content changing routines
getOverlayImpl().lock();
try {
items = new ArrayList<CachesOverlayItemImpl>(itemsPre);
setLastFocusedItemIndex(-1); // to reset tap during data change
populate();
} finally {
getOverlayImpl().unlock();
}
}
public boolean getCircles() {
return displayCircles;
}
public void switchCircles() {
displayCircles = !displayCircles;
}
@Override
public void draw(Canvas canvas, MapViewImpl mapView, boolean shadow) {
drawInternal(canvas, mapView.getMapProjection());
super.draw(canvas, mapView, false);
}
@Override
public void drawOverlayBitmap(Canvas canvas, Point drawPosition,
MapProjectionImpl projection, byte drawZoomLevel) {
drawInternal(canvas, projection);
super.drawOverlayBitmap(canvas, drawPosition, projection, drawZoomLevel);
}
private void drawInternal(Canvas canvas, MapProjectionImpl projection) {
// prevent content changes
getOverlayImpl().lock();
try {
if (displayCircles) {
if (blockedCircle == null) {
blockedCircle = new Paint();
blockedCircle.setAntiAlias(true);
blockedCircle.setStrokeWidth(2.0f);
blockedCircle.setARGB(127, 0, 0, 0);
blockedCircle.setPathEffect(new DashPathEffect(new float[] { 3, 2 }, 0));
}
if (setfil == null) {
setfil = new PaintFlagsDrawFilter(0, Paint.FILTER_BITMAP_FLAG);
}
if (remfil == null) {
remfil = new PaintFlagsDrawFilter(Paint.FILTER_BITMAP_FLAG, 0);
}
canvas.setDrawFilter(setfil);
for (CachesOverlayItemImpl item : items) {
final cgCoord itemCoord = item.getCoord();
float[] result = new float[1];
Location.distanceBetween(itemCoord.getCoords().getLatitude(), itemCoord.getCoords().getLongitude(),
itemCoord.getCoords().getLatitude(), itemCoord.getCoords().getLongitude() + 1, result);
final float longitudeLineDistance = result[0];
GeoPointImpl itemGeo = mapProvider.getGeoPointBase(itemCoord.getCoords());
final Geopoint leftCoords = new Geopoint(itemCoord.getCoords().getLatitude(),
itemCoord.getCoords().getLongitude() - 161 / longitudeLineDistance);
GeoPointImpl leftGeo = mapProvider.getGeoPointBase(leftCoords);
projection.toPixels(itemGeo, center);
projection.toPixels(leftGeo, left);
int radius = center.x - left.x;
final CacheType type = item.getType();
if (type == null || type == CacheType.MULTI || type == CacheType.MYSTERY || type == CacheType.VIRTUAL) {
blockedCircle.setColor(0x66000000);
blockedCircle.setStyle(Style.STROKE);
canvas.drawCircle(center.x, center.y, radius, blockedCircle);
} else {
blockedCircle.setColor(0x66BB0000);
blockedCircle.setStyle(Style.STROKE);
canvas.drawCircle(center.x, center.y, radius, blockedCircle);
blockedCircle.setColor(0x44BB0000);
blockedCircle.setStyle(Style.FILL);
canvas.drawCircle(center.x, center.y, radius, blockedCircle);
}
}
canvas.setDrawFilter(remfil);
}
} finally {
getOverlayImpl().unlock();
}
}
@Override
public boolean onTap(int index) {
try {
if (items.size() <= index) {
return false;
}
if (waitDialog == null) {
waitDialog = new ProgressDialog(context);
waitDialog.setMessage("loading details...");
waitDialog.setCancelable(false);
}
waitDialog.show();
CachesOverlayItemImpl item = null;
// prevent concurrent changes
getOverlayImpl().lock();
try {
if (index < items.size()) {
item = items.get(index);
}
} finally {
getOverlayImpl().unlock();
}
if (item == null) {
return false;
}
cgCoord coordinate = item.getCoord();
if (StringUtils.isNotBlank(coordinate.getCoordType()) && coordinate.getCoordType().equalsIgnoreCase("cache") && StringUtils.isNotBlank(coordinate.getGeocode())) {
Intent popupIntent = new Intent(context, cgeopopup.class);
popupIntent.putExtra("fromdetail", fromDetail);
popupIntent.putExtra("geocode", coordinate.getGeocode());
context.startActivity(popupIntent);
} else if (coordinate.getCoordType() != null && coordinate.getCoordType().equalsIgnoreCase("waypoint") && coordinate.getId() > 0) {
Intent popupIntent = new Intent(context, cgeowaypoint.class);
popupIntent.putExtra("waypoint", coordinate.getId());
popupIntent.putExtra("geocode", coordinate.getGeocode());
context.startActivity(popupIntent);
} else {
waitDialog.dismiss();
return false;
}
waitDialog.dismiss();
} catch (Exception e) {
Log.e(Settings.tag, "cgMapOverlay.onTap: " + e.toString());
}
return false;
}
@Override
public CachesOverlayItemImpl createItem(int index) {
try {
return items.get(index);
} catch (Exception e) {
Log.e(Settings.tag, "cgMapOverlay.createItem: " + e.toString());
}
return null;
}
@Override
public int size() {
try {
return items.size();
} catch (Exception e) {
Log.e(Settings.tag, "cgMapOverlay.size: " + e.toString());
}
return 0;
}
} |
package net.finkn.inputspec.tools;
import net.finkn.inputspec.tools.X;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* A parameter configuration. This class is immutable.
*
* @version 1.0
* @author Christoffer Fink
*/
public class ParamCfg {
/** Default parameter ID used by the Builder. */
public static final String DEFAULT_ID = "X";
/** Default parameter type used by the Builder. */
public static final String DEFAULT_TYPE = "integer";
// TODO: Use Optionals?
private final String id;
private final String type;
private final String fixed;
private final Range range;
private final Collection<ParamCfg> nested;
private final ParamType paramType;
private final Xml xml = Xml.getInstance().prefix(X.PREFIX);
private ParamCfg(String id, String type, String fixed, Range range,
Collection<ParamCfg> nested, ParamType paramType) {
this.id = id;
this.type = type;
this.fixed = fixed;
this.range = range;
this.nested = new ArrayList<>(nested);
this.paramType = paramType;
if (range == null) {
throw new IllegalArgumentException("null Range is illegal.");
}
}
public String getId() {
return id;
}
public String getType() {
return type;
}
public String getFixed() {
return fixed;
}
public Range getRange() {
return range;
}
public Stream<ParamCfg> getNested() {
return nested.stream();
}
/** Returns a builder that can create instances of this class. */
public static Builder builder() {
return new Builder();
}
public String xml() {
return xml(0);
}
String xml(int level) {
return xml.level(level).e(getTag(), getAttributes(), getChildren(level));
}
private String getTag() {
return paramType.equals(ParamType.NUMERIC) ? X.NPARAM : X.SPARAM;
}
private Map<String, Optional<? extends Object>> getAttributes() {
Map<String, Optional<? extends Object>> attrib = new HashMap<>();
attrib.put(X.ID, Optional.ofNullable(getId()));
attrib.put(X.TYPE, Optional.ofNullable(getType()));
attrib.put(X.FIXED, Optional.ofNullable(getFixed()));
attrib.put(X.INCLMIN, range.inclMin());
attrib.put(X.EXCLMIN, range.exclMin());
attrib.put(X.INCLMAX, range.inclMax());
attrib.put(X.EXCLMAX, range.exclMax());
return attrib;
}
private List<String> getChildren(int level) {
return getNested().map(x -> x.xml(level + 1)).collect(Collectors.toList());
}
/**
* Builder of parameter configurations.
* The defaults will create the simplest possible parameter. The default
* parameter is an integer NParam with id "X" and no limits. The
* builder makes some unsafe assumptions in order to simplify testing as much
* as possible. In other words, it will not hold the user's hand and attempt
* to prevent invalid configurations.
* <p>
* When creating a structured parameter, any range is ignored. When creating
* a numeric parameter, any nested parameters are ignored.
* <p>
* There are three ways to add a nested parameter to the builder:
* <ol>
* <li>{@code builder.add(param1, param2, ..., paramN)}</li>
* <li>{@code builder.add()}</li>
* <li>{@code builder.nest()}</li>
* </ol>
* {@link #add(ParamCfg...)} adds a given parameter. {@link #add()} constructs
* a new parameter using the current state of the builder, and then adds
* that parameter to the collection of nested parameters. {@link #nest()} is
* the most advanced version. It works like {@link #add()} in that it
* constructs a new parameter and adds it to the collection of nested
* parameters. However, the new parameter absorbs the currently nested
* parameters. This means that the new parameter replaces the old collection.
* This seems like the natural way to build a hierarchy of nested parameters.
* As a rule of thumb, {@link #add()} is suitable for numeric parameters,
* while {@link #nest()} is suitable for structured parameters.
* <p>
* Note: the builder should be used under the assumption that it is immutable.
* That is, the builder that is returned by a method invocation should be
* assumed to be a new instance. The recommended way to use the builder is to
* chain multiple calls:
* {@code builder.id("X").inclMin("5").build()}
*
* @version 0.9
* @author Christoffer Fink
*/
public static class Builder {
private final static List<ParamCfg> EMPTY_LIST = Collections.emptyList();
private String id = ParamCfg.DEFAULT_ID;
private String type;
private String fixed;
private final List<ParamCfg> nested = new ArrayList<>();
private ParamType paramType = ParamType.NUMERIC;
private Range range = Range.EMPTY;
private Builder() {
}
/** Returns a Builder with the id set to {@code id}. */
public Builder id(String id) {
this.id = id;
return this;
}
/** Returns a Builder with the type set to {@code type}. */
public Builder type(String type) {
this.type = type;
return this;
}
/** Returns a Builder with a fixed value of {@code value}. */
public Builder fixed(String value) {
this.fixed = value;
return this;
}
/** Returns a Builder with an updated range. */
public Builder inclMin(String limit) {
this.range = range.withInclMin(limit);
return this;
}
/** Returns a Builder with an updated range. */
public Builder exclMin(String limit) {
this.range = range.withExclMin(limit);
return this;
}
/** Returns a Builder with an updated range. */
public Builder inclMax(String limit) {
this.range = range.withInclMax(limit);
return this;
}
/** Returns a Builder with an updated range. */
public Builder exclMax(String limit) {
this.range = range.withExclMax(limit);
return this;
}
/** Returns a Builder with an updated range. */
public Builder interval(String interval) {
this.range = range.withInterval(interval);
return this;
}
/** Configures the builder for building numeric parameters. */
public Builder numeric() {
paramType = ParamType.NUMERIC;
return this;
}
/** Configures the builder for building structured parameters. */
public Builder structured() {
paramType = ParamType.STRUCTURED;
return this;
}
/**
* Resets everything except for nested parameters. This behavior allows a
* parameter to accumulate nested parameters (using {@code #add()}) without
* forcing the user to manually reset or override each attribute.
*/
public Builder resetAttributes() {
this.range = Range.getInstance();
return id(DEFAULT_ID).type(null).interval(null);
}
/**
* Adds these parameters to the nested parameters.
*
* @see #add()
*/
public Builder add(ParamCfg... params) {
for (ParamCfg param : params) {
nested.add(param);
}
return this;
}
/**
* Adds the current parameter configuration to the nested parameters.
* {@code builder.add()} has the same effect as
* {@code builder.add(builder.build())}.
*
* @see #nest()
*/
public Builder add() {
return add(build());
}
/**
* Adds the current parameter configuration to the nested parameters,
* replacing any existing nested parameters.
* This method is useful for building a structured parameter from the inside
* out.
*
* @see #add()
*/
public Builder nest() {
ParamCfg param = build();
nested.clear();
nested.add(param);
return this;
}
/** Creates a ParamCfg based on the current builder state. */
public ParamCfg build() {
if (paramType == ParamType.NUMERIC) {
String npType = getNParamType(type);
return new ParamCfg(id, npType, fixed, range, EMPTY_LIST, paramType);
} else {
return new ParamCfg(id, type, fixed, Range.EMPTY, nested, paramType);
}
}
private static String getNParamType(String type) {
return type != null ? type : DEFAULT_TYPE;
}
}
private enum ParamType {
NUMERIC, STRUCTURED,
}
} |
package com.example;
import armyc2.c2sd.JavaLineArray.CELineArray;
import android.graphics.Typeface;
import java.util.ArrayList;
import armyc2.c2sd.JavaLineArray.TacticalLines;
import armyc2.c2sd.JavaLineArray.POINT2;
import armyc2.c2sd.JavaTacticalRenderer.clsMETOC;
import armyc2.c2sd.JavaRendererServer.RenderMultipoints.clsRenderer;
import armyc2.c2sd.graphics2d.*;
import armyc2.c2sd.renderer.utilities.*;
import armyc2.c2sd.JavaLineArray.lineutility;
import java.util.Iterator;
import java.util.List;
import android.graphics.Paint;
import android.graphics.Canvas;
import android.graphics.Path;
import android.content.Context;
import android.util.SparseArray;
import static armyc2.c2sd.JavaLineArray.lineutility.CalcDistanceDouble;
import sec.web.json.utilities.JSONObject;
import sec.web.render.SECWebRenderer;
import sec.web.render.PointConverter;
import sec.web.render.utilities.JavaRendererUtilities;
import java.io.File;
import java.io.BufferedWriter;
import java.io.FileWriter;
///**
// *
// * @author Michael Deutch
// */
public final class utility {
protected static double leftLongitude;
protected static double rightLongitude;
protected static double upperLatitude;
protected static double lowerLatitude;
public static String linetype = "";
public static String T = "";
public static String T1 = "";
public static String H = "";
public static String H1 = "";
public static String W = "";
public static String W1 = "";
public static String linecolor = "";
public static String textcolor = "";
public static String fillcolor = "";
public static String AM="";
public static String AN="";
public static String X="";
public static String lineWidth="";
//public static String extents="";
public static String Rev="";
/**
* uses the PointConversion to convert to geo
*
* @param pts
* @param converter
* @return
*/
private static ArrayList<POINT2> PixelsToLatLong(ArrayList<Point> pts,
IPointConversion converter) {
int j = 0;
Point pt = null;
Point2D pt2d = null;
ArrayList<Point2D> pts2d = new ArrayList();
for (j = 0; j < pts.size(); j++) {
pt = pts.get(j);
pt2d=new Point2D.Double(pt.x,pt.y);
pt2d = converter.PixelsToGeo(pt2d);
pts2d.add(pt2d);
}
ArrayList<POINT2> pts2 = new ArrayList();
int n=pts2d.size();
//for (j = 0; j < pts2d.size(); j++)
for (j = 0; j < n; j++)
{
pts2.add(new POINT2(pts2d.get(j).getX(), pts2d.get(j).getY()));
}
return pts2;
}
// imported from tactical test for the channel types
private static Point ComputeLastPoint(ArrayList<Point> arrLocation) {
Point locD = new Point(0, 0);
try {
Point locA = new Point(arrLocation.get(1).x, arrLocation.get(1).y);
// Get the first point (b) in pixels.
// var locB:Point=new Point(arrLocation[0].x,arrLocation[0].y);
Point locB = new Point(arrLocation.get(0).x, arrLocation.get(0).y);
// diagnostic 2-27-13
double dist = lineutility.CalcDistanceDouble(new POINT2(locA.x,
locA.y), new POINT2(locB.x, locB.y));
// Compute the distance in pixels from (a) to (b).
double dblDx = locB.x - locA.x;
double dblDy = locB.y - locA.y;
// Compute the dblAngle in radians from (a) to (b).
double dblTheta = Math.atan2(-dblDy, dblDx);
// Compute a reasonable intermediate point along the line from (a)
// to (b).
Point locC = new Point(0, 0);
locC.x = (int) (locA.x + 0.85 * dblDx);
locC.y = (int) (locA.y + 0.85 * dblDy);
// Put the last point on the left side of the line from (a) to (b).
double dblAngle = dblTheta + Math.PI / 2.0;
if (dblAngle > Math.PI) {
dblAngle = dblAngle - 2.0 * Math.PI;
}
if (dblAngle < -Math.PI) {
dblAngle = dblAngle + 2.0 * Math.PI;
}
// Set the magnitude of the dblWidth in pixels. Make sure it is at
// least 15 pixels.
double dblWidth = 30;// was 15
// diagnostic 2-27-13
if (dblWidth > dist) {
dblWidth = dist;
}
if (dblWidth < 10) {
dblWidth = 10;
}
// Compute the last point in pixels.
locD.x = (int) (locC.x + dblWidth * Math.cos(dblAngle));
locD.y = (int) (locC.y - dblWidth * Math.sin(dblAngle));
} catch (Exception e) {
// CJMTKExceptions.LogException(ex, ex.Source);
// throw e;
}
return locD;
} // End ComputeLastPoint
private static double displayWidth;
private static double displayHeight;
protected static void set_displayPixelsWidth(double value) {
displayWidth = value;
}
protected static void set_displayPixelsHeight(double value) {
displayHeight = value;
}
protected static void SetExtents(double ullon, double lrlon, double ullat,
double lrlat) {
leftLongitude = ullon;// -95.5;
rightLongitude = lrlon;
upperLatitude = ullat;// 33.5;
lowerLatitude = lrlat;
}
private static String TableType(int lineType) {
String str = "";
switch (lineType) {
case TacticalLines.DUMMY:
case TacticalLines.BS_AREA:
case TacticalLines.GENERAL:
case TacticalLines.NFA:
case TacticalLines.FFA:
case TacticalLines.DMAF:
case TacticalLines.DMA:
case TacticalLines.AIRFIELD:
case TacticalLines.ENCIRCLE:
case TacticalLines.STRONG:
case TacticalLines.FORT:
case TacticalLines.ZONE:
case TacticalLines.BELT:
case TacticalLines.DRCL:
case TacticalLines.DEPICT:
case TacticalLines.OBSAREA:
case TacticalLines.OBSFAREA:
case TacticalLines.RFA:
case TacticalLines.WFZ:
case TacticalLines.ASSY:
// from list
case TacticalLines.LAA:
case TacticalLines.RAD:
case TacticalLines.BIO:
case TacticalLines.CHEM:
case TacticalLines.UXO:
case TacticalLines.MINED:
case TacticalLines.PEN:
case TacticalLines.AIRHEAD:
case TacticalLines.AO:
case TacticalLines.ATKPOS:
case TacticalLines.ASSAULT:
case TacticalLines.PNO:
case TacticalLines.RSA:
case TacticalLines.RHA:
case TacticalLines.EPW:
case TacticalLines.DHA:
case TacticalLines.BOMB:
case TacticalLines.SERIES:
case TacticalLines.SMOKE:
case TacticalLines.AT:
case TacticalLines.FARP:
case TacticalLines.NAI:
case TacticalLines.EA1:
case TacticalLines.EA:
case TacticalLines.DSA:
case TacticalLines.BSA:
case TacticalLines.OBJ:
case TacticalLines.TAI:
case TacticalLines.BATTLE:
case TacticalLines.PZ:
case TacticalLines.LZ:
case TacticalLines.DZ:
case TacticalLines.FAADZ:
case TacticalLines.HIMEZ:
case TacticalLines.LOMEZ:
case TacticalLines.MEZ:
case TacticalLines.ROZ:
case TacticalLines.EZ:
case TacticalLines.HIDACZ:
case TacticalLines.FSA: // change 1
case TacticalLines.ATI:
case TacticalLines.CFFZ:
case TacticalLines.SENSOR:
case TacticalLines.CENSOR:
case TacticalLines.DA:
case TacticalLines.CFZ:
case TacticalLines.ZOR:
case TacticalLines.TBA:
case TacticalLines.TVAR:
case TacticalLines.KILLBOXBLUE:
case TacticalLines.KILLBOXPURPLE:
case TacticalLines.ACA:
case TacticalLines.BEACH:
case TacticalLines.BEACH_SLOPE_MODERATE:
case TacticalLines.BEACH_SLOPE_STEEP:
case TacticalLines.FOUL_GROUND:
case TacticalLines.KELP:
case TacticalLines.SWEPT_AREA:
case TacticalLines.OIL_RIG_FIELD:
case TacticalLines.WEIRS:
case TacticalLines.OPERATOR_DEFINED:
case TacticalLines.VDR_LEVEL_12:
case TacticalLines.VDR_LEVEL_23:
case TacticalLines.VDR_LEVEL_34:
case TacticalLines.VDR_LEVEL_45:
case TacticalLines.VDR_LEVEL_56:
case TacticalLines.VDR_LEVEL_67:
case TacticalLines.VDR_LEVEL_78:
case TacticalLines.VDR_LEVEL_89:
case TacticalLines.VDR_LEVEL_910:
case TacticalLines.IFR:
case TacticalLines.MVFR:
case TacticalLines.TURBULENCE:
case TacticalLines.ICING:
case TacticalLines.NON_CONVECTIVE:
case TacticalLines.CONVECTIVE:
case TacticalLines.FROZEN:
case TacticalLines.THUNDERSTORMS:
case TacticalLines.FOG:
case TacticalLines.SAND:
case TacticalLines.FREEFORM:
case TacticalLines.DEPTH_AREA:
case TacticalLines.ISLAND:
case TacticalLines.ANCHORAGE_AREA:
case TacticalLines.WATER:
case TacticalLines.FORESHORE_AREA:
case TacticalLines.DRYDOCK:
case TacticalLines.LOADING_FACILITY_AREA:
case TacticalLines.PERCHES:
case TacticalLines.UNDERWATER_HAZARD:
case TacticalLines.TRAINING_AREA:
case TacticalLines.DISCOLORED_WATER:
case TacticalLines.BEACH_SLOPE_FLAT:
case TacticalLines.BEACH_SLOPE_GENTLE:
case TacticalLines.SOLID_ROCK:
case TacticalLines.CLAY:
case TacticalLines.VERY_COARSE_SAND:
case TacticalLines.COARSE_SAND:
case TacticalLines.MEDIUM_SAND:
case TacticalLines.FINE_SAND:
case TacticalLines.VERY_FINE_SAND:
case TacticalLines.VERY_FINE_SILT:
case TacticalLines.FINE_SILT:
case TacticalLines.MEDIUM_SILT:
case TacticalLines.COARSE_SILT:
case TacticalLines.SAND_AND_SHELLS:
case TacticalLines.PEBBLES:
case TacticalLines.OYSTER_SHELLS:
case TacticalLines.BOULDERS:
case TacticalLines.BOTTOM_SEDIMENTS_LAND:
case TacticalLines.BOTTOM_SEDIMENTS_NO_DATA:
case TacticalLines.BOTTOM_ROUGHNESS_SMOOTH:
case TacticalLines.BOTTOM_ROUGHNESS_MODERATE:
case TacticalLines.BOTTOM_ROUGHNESS_ROUGH:
case TacticalLines.CLUTTER_HIGH:
case TacticalLines.CLUTTER_MEDIUM:
case TacticalLines.CLUTTER_LOW:
case TacticalLines.IMPACT_BURIAL_0:
case TacticalLines.IMPACT_BURIAL_10:
case TacticalLines.IMPACT_BURIAL_20:
case TacticalLines.IMPACT_BURIAL_75:
case TacticalLines.IMPACT_BURIAL_100:
case TacticalLines.BOTTOM_TYPE_A1:
case TacticalLines.BOTTOM_TYPE_A2:
case TacticalLines.BOTTOM_TYPE_A3:
case TacticalLines.BOTTOM_TYPE_B1:
case TacticalLines.BOTTOM_TYPE_B2:
case TacticalLines.BOTTOM_TYPE_B3:
case TacticalLines.BOTTOM_TYPE_C1:
case TacticalLines.BOTTOM_TYPE_C2:
case TacticalLines.BOTTOM_TYPE_C3:
case TacticalLines.BOTTOM_CATEGORY_A:
case TacticalLines.BOTTOM_CATEGORY_B:
case TacticalLines.BOTTOM_CATEGORY_C:
case TacticalLines.MARITIME_AREA:
case TacticalLines.SUBMERGED_CRIB:
case TacticalLines.TGMF:
case TacticalLines.TEST:
str = "polygon";
break;
case TacticalLines.FORTL:
str = "polyline";
break;
default:
str = "polyline";
break;
}
return str;
}
protected static int GetLinetype(String str, int rev) {
int linetype = -1;
linetype = clsMETOC.IsWeather(str);
if (linetype < 0) {
linetype = CELineArray.CGetLinetypeFromString(str, rev);
}
if (linetype >= 0) {
return linetype;
}
if (str.equalsIgnoreCase("track")) {
return -1;
}
if (str.equalsIgnoreCase("route")) {
return -1;
}
if (str.equalsIgnoreCase("cylinder")) {
return -1;
}
if (str.equalsIgnoreCase("curtain")) {
return -1;
}
if (str.equalsIgnoreCase("polyarc")) {
return -1;
}
if (str.equalsIgnoreCase("polygon")) {
return -1;
}
if (str.equalsIgnoreCase("radarc")) {
return -1;
}
if (str.equalsIgnoreCase("BS_AREA")) {
linetype = TacticalLines.BS_AREA;
} else if (str.equalsIgnoreCase("BS_LINE")) {
linetype = TacticalLines.BS_LINE;
} else if (str.equalsIgnoreCase("BS_CROSS")) {
linetype = TacticalLines.BS_CROSS;
} else if (str.equalsIgnoreCase("BS_ELLIPSE")) {
linetype = TacticalLines.BS_ELLIPSE;
} else if (str.equalsIgnoreCase("BS_RECTANGLE")) {
linetype = TacticalLines.BS_RECTANGLE;
} else if (str.equalsIgnoreCase("CFL")) {
linetype = TacticalLines.CFL;
} else if (str.equalsIgnoreCase("OVERHEAD_WIRE")) {
linetype = TacticalLines.OVERHEAD_WIRE;
} else if (str.equalsIgnoreCase("AMBUSH")) {
linetype = TacticalLines.AMBUSH;
} else if (str.equalsIgnoreCase("EASY")) {
linetype = TacticalLines.EASY;
} else if (str.equalsIgnoreCase("FOXHOLE")) {
linetype = TacticalLines.FOXHOLE;
} // TASKS
else if (str.equalsIgnoreCase("BLOCK")) {
linetype = TacticalLines.BLOCK;
} else if (str.equalsIgnoreCase("BREACH")) {
linetype = TacticalLines.BREACH;
} else if (str.equalsIgnoreCase("BYPASS")) {
linetype = TacticalLines.BYPASS;
} else if (str.equalsIgnoreCase("CANALIZE")) {
linetype = TacticalLines.CANALIZE;
} else if (str.equalsIgnoreCase("CLEAR")) {
linetype = TacticalLines.CLEAR;
} else if (str.equalsIgnoreCase("CONTAIN")) {
linetype = TacticalLines.CONTAIN;
} else if (str.equalsIgnoreCase("DELAY")) {
linetype = TacticalLines.DELAY;
} else if (str.equalsIgnoreCase("DISRUPT")) {
linetype = TacticalLines.DISRUPT;
} else if (str.equalsIgnoreCase("FIX")) {
linetype = TacticalLines.FIX;
} else if (str.equalsIgnoreCase("MNFLDFIX")) {
linetype = TacticalLines.MNFLDFIX;
} else if (str.equalsIgnoreCase("FOLLA")) {
linetype = TacticalLines.FOLLA;
} else if (str.equalsIgnoreCase("FOLSP")) {
linetype = TacticalLines.FOLSP;
} else if (str.equalsIgnoreCase("ISOLATE")) {
linetype = TacticalLines.ISOLATE;
} else if (str.equalsIgnoreCase("OCCUPY")) {
linetype = TacticalLines.OCCUPY;
} else if (str.equalsIgnoreCase("PENETRATE")) {
linetype = TacticalLines.PENETRATE;
} else if (str.equalsIgnoreCase("RIP")) {
linetype = TacticalLines.RIP;
} else if (str.equalsIgnoreCase("RETAIN")) {
linetype = TacticalLines.RETAIN;
} else if (str.equalsIgnoreCase("RETIRE")) {
linetype = TacticalLines.RETIRE;
} else if (str.equalsIgnoreCase("SECURE")) {
linetype = TacticalLines.SECURE;
} else if (str.equalsIgnoreCase("SCREEN")) {
linetype = TacticalLines.SCREEN;
} else if (str.equalsIgnoreCase("COVER")) {
linetype = TacticalLines.COVER;
} else if (str.equalsIgnoreCase("GUARD")) {
linetype = TacticalLines.GUARD;
} else if (str.equalsIgnoreCase("SEIZE")) {
linetype = TacticalLines.SEIZE;
} else if (str.equalsIgnoreCase("WITHDRAW")) {
linetype = TacticalLines.WITHDRAW;
} else if (str.equalsIgnoreCase("WDRAWUP")) {
linetype = TacticalLines.WDRAWUP;
} else if (str.equalsIgnoreCase("BOUNDARY")) {
linetype = TacticalLines.BOUNDARY;
} else if (str.equalsIgnoreCase("FLOT")) {
linetype = TacticalLines.FLOT;
} else if (str.equalsIgnoreCase("PL")) {
linetype = TacticalLines.PL;
} else if (str.equalsIgnoreCase("LL")) {
linetype = TacticalLines.LL;
} else if (str.equalsIgnoreCase("GENERAL")) {
linetype = TacticalLines.GENERAL;
} else if (str.equalsIgnoreCase("GENERIC")) {
linetype = TacticalLines.GENERIC;
} else if (str.equalsIgnoreCase("ASSY")) {
linetype = TacticalLines.ASSY;
} else if (str.equalsIgnoreCase("EA")) {
linetype = TacticalLines.EA;
} else if (str.equalsIgnoreCase("FORT")) {
linetype = TacticalLines.FORT;
} else if (str.equalsIgnoreCase("DZ")) {
linetype = TacticalLines.DZ;
} else if (str.equalsIgnoreCase("EZ")) {
linetype = TacticalLines.EZ;
} else if (str.equalsIgnoreCase("LZ")) {
linetype = TacticalLines.LZ;
} else if (str.equalsIgnoreCase("PZ")) {
linetype = TacticalLines.PZ;
} else if (str.equalsIgnoreCase("SARA")) {
linetype = TacticalLines.SARA;
} else if (str.equalsIgnoreCase("LAA")) {
linetype = TacticalLines.LAA;
} else if (str.equalsIgnoreCase("AIRFIELD")) {
linetype = TacticalLines.AIRFIELD;
} else if (str.equalsIgnoreCase("AC")) {
linetype = TacticalLines.AC;
} else if (str.equalsIgnoreCase("MRR")) {
linetype = TacticalLines.MRR;
} else if (str.equalsIgnoreCase("MRR_USAS")) {
linetype = TacticalLines.MRR_USAS;
} else if (str.equalsIgnoreCase("SAAFR")) {
linetype = TacticalLines.SAAFR;
} else if (str.equalsIgnoreCase("UAV")) {
linetype = TacticalLines.UAV;
} else if (str.equalsIgnoreCase("UAV_USAS")) {
linetype = TacticalLines.UAV_USAS;
} else if (str.equalsIgnoreCase("LLTR")) {
linetype = TacticalLines.LLTR;
} else if (str.equalsIgnoreCase("ROZ")) {
linetype = TacticalLines.ROZ;
} else if (str.equalsIgnoreCase("FAADZ")) {
linetype = TacticalLines.FAADZ;
} else if (str.equalsIgnoreCase("HIDACZ")) {
linetype = TacticalLines.HIDACZ;
} else if (str.equalsIgnoreCase("MEZ")) {
linetype = TacticalLines.MEZ;
} else if (str.equalsIgnoreCase("LOMEZ")) {
linetype = TacticalLines.LOMEZ;
} else if (str.equalsIgnoreCase("HIMEZ")) {
linetype = TacticalLines.HIMEZ;
} else if (str.equalsIgnoreCase("WFZ")) {
linetype = TacticalLines.WFZ;
} else if (str.equalsIgnoreCase("DECEIVE")) {
linetype = TacticalLines.DECEIVE;
} else if (str.equalsIgnoreCase("DIRATKFNT")) {
linetype = TacticalLines.DIRATKFNT;
} else if (str.equalsIgnoreCase("DMA")) {
linetype = TacticalLines.DMA;
} else if (str.equalsIgnoreCase("LINTGT")) {
linetype = TacticalLines.LINTGT;
} else if (str.equalsIgnoreCase("LINTGTS")) {
linetype = TacticalLines.LINTGTS;
} else if (str.equalsIgnoreCase("FPF")) {
linetype = TacticalLines.FPF;
} else if (str.equalsIgnoreCase("DMAF")) {
linetype = TacticalLines.DMAF;
} else if (str.equalsIgnoreCase("DUMMY")) {
linetype = TacticalLines.DUMMY;
} else if (str.equalsIgnoreCase("FEBA")) {
linetype = TacticalLines.FEBA;
} else if (str.equalsIgnoreCase("PDF")) {
linetype = TacticalLines.PDF;
} else if (str.equalsIgnoreCase("BATTLE")) {
linetype = TacticalLines.BATTLE;
} else if (str.equalsIgnoreCase("PNO")) {
linetype = TacticalLines.PNO;
} else if (str.equalsIgnoreCase("EA1")) {
linetype = TacticalLines.EA1;
} else if (str.equalsIgnoreCase("DIRATKAIR")) {
linetype = TacticalLines.DIRATKAIR;
} else if (str.equalsIgnoreCase("DIRATKGND")) {
linetype = TacticalLines.DIRATKGND;
} else if (str.equalsIgnoreCase("DIRATKSPT")) {
linetype = TacticalLines.DIRATKSPT;
} else if (str.equalsIgnoreCase("FCL")) {
linetype = TacticalLines.FCL;
} else if (str.equalsIgnoreCase("IL")) {
linetype = TacticalLines.IL;
} else if (str.equalsIgnoreCase("LOA")) {
linetype = TacticalLines.LOA;
} else if (str.equalsIgnoreCase("LOD")) {
linetype = TacticalLines.LOD;
} else if (str.equalsIgnoreCase("LDLC")) {
linetype = TacticalLines.LDLC;
} else if (str.equalsIgnoreCase("PLD")) {
linetype = TacticalLines.PLD;
} else if (str.equalsIgnoreCase("ASSAULT")) {
linetype = TacticalLines.ASSAULT;
} else if (str.equalsIgnoreCase("ATKPOS")) {
linetype = TacticalLines.ATKPOS;
} else if (str.equalsIgnoreCase("ATKBYFIRE")) {
linetype = TacticalLines.ATKBYFIRE;
} else if (str.equalsIgnoreCase("SPTBYFIRE")) {
linetype = TacticalLines.SPTBYFIRE;
} else if (str.equalsIgnoreCase("OBJ")) {
linetype = TacticalLines.OBJ;
} else if (str.equalsIgnoreCase("PEN")) {
linetype = TacticalLines.PEN;
} else if (str.equalsIgnoreCase("HOLD")) {
linetype = TacticalLines.HOLD;
} else if (str.equalsIgnoreCase("RELEASE")) {
linetype = TacticalLines.RELEASE;
} else if (str.equalsIgnoreCase("BRDGHD")) {
linetype = TacticalLines.BRDGHD;
} else if (str.equalsIgnoreCase("AO")) {
linetype = TacticalLines.AO;
} else if (str.equalsIgnoreCase("AIRHEAD")) {
linetype = TacticalLines.AIRHEAD;
} else if (str.equalsIgnoreCase("ENCIRCLE")) {
linetype = TacticalLines.ENCIRCLE;
} else if (str.equalsIgnoreCase("NAI")) {
linetype = TacticalLines.NAI;
} else if (str.equalsIgnoreCase("TAI")) {
linetype = TacticalLines.TAI;
} else if (str.equalsIgnoreCase("BELT")) {
linetype = TacticalLines.BELT;
} else if (str.equalsIgnoreCase("LINE")) {
linetype = TacticalLines.LINE;
} else if (str.equalsIgnoreCase("ZONE")) {
linetype = TacticalLines.ZONE;
} else if (str.equalsIgnoreCase("OBSFAREA")) {
linetype = TacticalLines.OBSFAREA;
} else if (str.equalsIgnoreCase("OBSAREA")) {
linetype = TacticalLines.OBSAREA;
} else if (str.equalsIgnoreCase("ABATIS")) {
linetype = TacticalLines.ABATIS;
} else if (str.equalsIgnoreCase("ATDITCH")) {
linetype = TacticalLines.ATDITCH;
} else if (str.equalsIgnoreCase("ATDITCHC")) {
linetype = TacticalLines.ATDITCHC;
} else if (str.equalsIgnoreCase("ATDITCHM")) {
linetype = TacticalLines.ATDITCHM;
} else if (str.equalsIgnoreCase("ATWALL")) {
linetype = TacticalLines.ATWALL;
} else if (str.equalsIgnoreCase("CLUSTER")) {
linetype = TacticalLines.CLUSTER;
} else if (str.equalsIgnoreCase("DEPICT")) {
linetype = TacticalLines.DEPICT;
} else if (str.equalsIgnoreCase("GAP")) {
linetype = TacticalLines.GAP;
} else if (str.equalsIgnoreCase("MINED")) {
linetype = TacticalLines.MINED;
} else if (str.equalsIgnoreCase("MNFLDBLK")) {
linetype = TacticalLines.MNFLDBLK;
} else if (str.equalsIgnoreCase("TURN")) {
linetype = TacticalLines.TURN;
} else if (str.equalsIgnoreCase("MNFLDDIS")) {
linetype = TacticalLines.MNFLDDIS;
} else if (str.equalsIgnoreCase("UXO")) {
linetype = TacticalLines.UXO;
} else if (str.equalsIgnoreCase("PLANNED")) {
linetype = TacticalLines.PLANNED;
} else if (str.equalsIgnoreCase("ESR1")) {
linetype = TacticalLines.ESR1;
} else if (str.equalsIgnoreCase("ESR2")) {
linetype = TacticalLines.ESR2;
} else if (str.equalsIgnoreCase("ROADBLK")) {
linetype = TacticalLines.ROADBLK;
} else if (str.equalsIgnoreCase("TRIP")) {
linetype = TacticalLines.TRIP;
} else if (str.equalsIgnoreCase("UNSP")) {
linetype = TacticalLines.UNSP;
} else if (str.equalsIgnoreCase("BYDIF")) {
linetype = TacticalLines.BYDIF;
} else if (str.equalsIgnoreCase("BYIMP")) {
linetype = TacticalLines.BYIMP;
} else if (str.equalsIgnoreCase("ASLTXING")) {
linetype = TacticalLines.ASLTXING;
} else if (str.equalsIgnoreCase("BRIDGE")) {
linetype = TacticalLines.BRIDGE;
} else if (str.equalsIgnoreCase("FERRY")) {
linetype = TacticalLines.FERRY;
} else if (str.equalsIgnoreCase("FORDSITE")) {
linetype = TacticalLines.FORDSITE;
} else if (str.equalsIgnoreCase("FORDIF")) {
linetype = TacticalLines.FORDIF;
} else if (str.equalsIgnoreCase("MFLANE")) {
linetype = TacticalLines.MFLANE;
} else if (str.equalsIgnoreCase("RAFT")) {
linetype = TacticalLines.RAFT;
} else if (str.equalsIgnoreCase("STRONG")) {
linetype = TacticalLines.STRONG;
} else if (str.equalsIgnoreCase("MSDZ")) {
linetype = TacticalLines.MSDZ;
} else if (str.equalsIgnoreCase("RAD")) {
linetype = TacticalLines.RAD;
} else if (str.equalsIgnoreCase("CHEM")) {
linetype = TacticalLines.CHEM;
} else if (str.equalsIgnoreCase("BIO")) {
linetype = TacticalLines.BIO;
} else if (str.equalsIgnoreCase("DRCL")) {
linetype = TacticalLines.DRCL;
} else if (str.equalsIgnoreCase("FSCL")) {
linetype = TacticalLines.FSCL;
} else if (str.equalsIgnoreCase("NFL")) {
linetype = TacticalLines.NFL;
} else if (str.equalsIgnoreCase("MFP")) {
linetype = TacticalLines.MFP;
} else if (str.equalsIgnoreCase("RFL")) {
linetype = TacticalLines.RFL;
} else if (str.equalsIgnoreCase("AT")) {
linetype = TacticalLines.AT;
} else if (str.equalsIgnoreCase("RECTANGULAR")) {
linetype = TacticalLines.RECTANGULAR;
} else if (str.equalsIgnoreCase("CIRCULAR")) {
linetype = TacticalLines.CIRCULAR;
} else if (str.equalsIgnoreCase("SERIES")) {
linetype = TacticalLines.SERIES;
} else if (str.equalsIgnoreCase("SMOKE")) {
linetype = TacticalLines.SMOKE;
} else if (str.equalsIgnoreCase("BOMB")) {
linetype = TacticalLines.BOMB;
} else if (str.equalsIgnoreCase("FORTL")) {
linetype = TacticalLines.FORTL;
} // FIRE SUPPORT AREAS
else if (str.equalsIgnoreCase("FSA")) {
linetype = TacticalLines.FSA;
} else if (str.equalsIgnoreCase("FSA_RECTANGULAR")) {
linetype = TacticalLines.FSA_RECTANGULAR;
} else if (str.equalsIgnoreCase("FSA_CIRCULAR")) {
linetype = TacticalLines.FSA_CIRCULAR;
} else if (str.equalsIgnoreCase("ACA")) {
linetype = TacticalLines.ACA;
} else if (str.equalsIgnoreCase("ACA_RECTANGULAR")) {
linetype = TacticalLines.ACA_RECTANGULAR;
} else if (str.equalsIgnoreCase("ACA_CIRCULAR")) {
linetype = TacticalLines.ACA_CIRCULAR;
} else if (str.equalsIgnoreCase("FFA")) {
linetype = TacticalLines.FFA;
} else if (str.equalsIgnoreCase("FFA_RECTANGULAR")) {
linetype = TacticalLines.FFA_RECTANGULAR;
} else if (str.equalsIgnoreCase("FFA_CIRCULAR")) {
linetype = TacticalLines.FFA_CIRCULAR;
} else if (str.equalsIgnoreCase("NFA")) {
linetype = TacticalLines.NFA;
} else if (str.equalsIgnoreCase("NFA_RECTANGULAR")) {
linetype = TacticalLines.NFA_RECTANGULAR;
} else if (str.equalsIgnoreCase("NFA_CIRCULAR")) {
linetype = TacticalLines.NFA_CIRCULAR;
} else if (str.equalsIgnoreCase("RFA")) {
linetype = TacticalLines.FFA;
} else if (str.equalsIgnoreCase("RFA_RECTANGULAR")) {
linetype = TacticalLines.RFA_RECTANGULAR;
} else if (str.equalsIgnoreCase("RFA_CIRCULAR")) {
linetype = TacticalLines.RFA_CIRCULAR;
} else if (str.equalsIgnoreCase("PAA")) {
linetype = TacticalLines.PAA;
} else if (str.equalsIgnoreCase("PAA_RECTANGULAR")) {
linetype = TacticalLines.PAA_RECTANGULAR;
} else if (str.equalsIgnoreCase("PAA_RECTANGULAR_REVC")) {
linetype = TacticalLines.PAA_RECTANGULAR_REVC;
} else if (str.equalsIgnoreCase("PAA_CIRCULAR")) {
linetype = TacticalLines.PAA_CIRCULAR;
} else if (str.equalsIgnoreCase("ATI")) {
linetype = TacticalLines.ATI;
} else if (str.equalsIgnoreCase("ATI_RECTANGULAR")) {
linetype = TacticalLines.ATI_RECTANGULAR;
} else if (str.equalsIgnoreCase("ATI_CIRCULAR")) {
linetype = TacticalLines.ATI_CIRCULAR;
} else if (str.equalsIgnoreCase("CFFZ")) {
linetype = TacticalLines.CFFZ;
} else if (str.equalsIgnoreCase("CFFZ_RECTANGULAR")) {
linetype = TacticalLines.CFFZ_RECTANGULAR;
} else if (str.equalsIgnoreCase("CFFZ_CIRCULAR")) {
linetype = TacticalLines.CFFZ_CIRCULAR;
} else if (str.equalsIgnoreCase("SENSOR")) {
linetype = TacticalLines.SENSOR;
} else if (str.equalsIgnoreCase("SENSOR_RECTANGULAR")) {
linetype = TacticalLines.SENSOR_RECTANGULAR;
} else if (str.equalsIgnoreCase("SENSOR_CIRCULAR")) {
linetype = TacticalLines.SENSOR_CIRCULAR;
} else if (str.equalsIgnoreCase("CENSOR")) {
linetype = TacticalLines.CENSOR;
} else if (str.equalsIgnoreCase("CENSOR_RECTANGULAR")) {
linetype = TacticalLines.CENSOR_RECTANGULAR;
} else if (str.equalsIgnoreCase("CENSOR_CIRCULAR")) {
linetype = TacticalLines.CENSOR_CIRCULAR;
} else if (str.equalsIgnoreCase("DA")) {
linetype = TacticalLines.DA;
} else if (str.equalsIgnoreCase("DA_RECTANGULAR")) {
linetype = TacticalLines.DA_RECTANGULAR;
} else if (str.equalsIgnoreCase("DA_CIRCULAR")) {
linetype = TacticalLines.DA_CIRCULAR;
} else if (str.equalsIgnoreCase("CFZ")) {
linetype = TacticalLines.CFZ;
} else if (str.equalsIgnoreCase("CFZ_RECTANGULAR")) {
linetype = TacticalLines.CFZ_RECTANGULAR;
} else if (str.equalsIgnoreCase("CFZ_CIRCULAR")) {
linetype = TacticalLines.CFZ_CIRCULAR;
} else if (str.equalsIgnoreCase("ZOR")) {
linetype = TacticalLines.ZOR;
} else if (str.equalsIgnoreCase("ZOR_RECTANGULAR")) {
linetype = TacticalLines.ZOR_RECTANGULAR;
} else if (str.equalsIgnoreCase("ZOR_CIRCULAR")) {
linetype = TacticalLines.ZOR_CIRCULAR;
} else if (str.equalsIgnoreCase("TBA")) {
linetype = TacticalLines.TBA;
} else if (str.equalsIgnoreCase("TBA_RECTANGULAR")) {
linetype = TacticalLines.TBA_RECTANGULAR;
} else if (str.equalsIgnoreCase("TBA_CIRCULAR")) {
linetype = TacticalLines.TBA_CIRCULAR;
} else if (str.equalsIgnoreCase("TVAR")) {
linetype = TacticalLines.TVAR;
} else if (str.equalsIgnoreCase("TVAR_RECTANGULAR")) {
linetype = TacticalLines.TVAR_RECTANGULAR;
} else if (str.equalsIgnoreCase("TVAR_CIRCULAR")) {
linetype = TacticalLines.TVAR_CIRCULAR;
} else if (str.equalsIgnoreCase("KILLBOXBLUE")) {
linetype = TacticalLines.KILLBOXBLUE;
} else if (str.equalsIgnoreCase("KILLBOXBLUE_RECTANGULAR")) {
linetype = TacticalLines.KILLBOXBLUE_RECTANGULAR;
} else if (str.equalsIgnoreCase("KILLBOXBLUE_CIRCULAR")) {
linetype = TacticalLines.KILLBOXBLUE_CIRCULAR;
} else if (str.equalsIgnoreCase("KILLBOXPURPLE")) {
linetype = TacticalLines.KILLBOXPURPLE;
} else if (str.equalsIgnoreCase("KILLBOXPURPLE_RECTANGULAR")) {
linetype = TacticalLines.KILLBOXPURPLE_RECTANGULAR;
} else if (str.equalsIgnoreCase("KILLBOXPURPLE_CIRCULAR")) {
linetype = TacticalLines.KILLBOXPURPLE_CIRCULAR;
} // RANGE FANS
else if (str.equalsIgnoreCase("RANGE_FAN")) {
linetype = TacticalLines.RANGE_FAN;
} else if (str.equalsIgnoreCase("SECTOR")) {
linetype = TacticalLines.RANGE_FAN_SECTOR;
} else if (str.equalsIgnoreCase("RANGE_FAN_SECTOR")) {
linetype = TacticalLines.RANGE_FAN_SECTOR;
} else if (str.equalsIgnoreCase("CONVOY")) {
linetype = TacticalLines.CONVOY;
} else if (str.equalsIgnoreCase("HCONVOY")) {
linetype = TacticalLines.HCONVOY;
} else if (str.equalsIgnoreCase("MSR")) {
linetype = TacticalLines.MSR;
} else if (str.equalsIgnoreCase("ASR")) {
linetype = TacticalLines.ASR;
} else if (str.equalsIgnoreCase("ONEWAY")) {
linetype = TacticalLines.ONEWAY;
} else if (str.equalsIgnoreCase("TWOWAY")) {
linetype = TacticalLines.TWOWAY;
} else if (str.equalsIgnoreCase("ALT")) {
linetype = TacticalLines.ALT;
} else if (str.equalsIgnoreCase("DHA")) {
linetype = TacticalLines.DHA;
} else if (str.equalsIgnoreCase("EPW")) {
linetype = TacticalLines.EPW;
} else if (str.equalsIgnoreCase("FARP")) {
linetype = TacticalLines.FARP;
} else if (str.equalsIgnoreCase("RHA")) {
linetype = TacticalLines.RHA;
} else if (str.equalsIgnoreCase("BSA")) {
linetype = TacticalLines.BSA;
} else if (str.equalsIgnoreCase("DSA")) {
linetype = TacticalLines.DSA;
} else if (str.equalsIgnoreCase("RSA")) {
linetype = TacticalLines.RSA;
} else if (str.equalsIgnoreCase("NAVIGATION")) {
linetype = TacticalLines.NAVIGATION;
} else if (str.equalsIgnoreCase("BEARING")) {
linetype = TacticalLines.BEARING;
} else if (str.equalsIgnoreCase("ELECTRO")) {
linetype = TacticalLines.ELECTRO;
} else if (str.equalsIgnoreCase("ACOUSTIC")) {
linetype = TacticalLines.ACOUSTIC;
} else if (str.equalsIgnoreCase("TORPEDO")) {
linetype = TacticalLines.TORPEDO;
} else if (str.equalsIgnoreCase("OPTICAL")) {
linetype = TacticalLines.OPTICAL;
} // the channel types
else if (str.equalsIgnoreCase("CATK")) {
linetype = TacticalLines.CATK;
} else if (str.equalsIgnoreCase("AAFNT")) {
linetype = TacticalLines.AAFNT;
} else if (str.equalsIgnoreCase("AXAD")) {
linetype = TacticalLines.AXAD;
} else if (str.equalsIgnoreCase("MAIN")) {
linetype = TacticalLines.MAIN;
} else if (str.equalsIgnoreCase("AIRAOA")) {
linetype = TacticalLines.AIRAOA;
} else if (str.equalsIgnoreCase("SPT")) {
linetype = TacticalLines.SPT;
} else if (str.equalsIgnoreCase("CATKBYFIRE")) {
linetype = TacticalLines.CATKBYFIRE;
} else if (str.equalsIgnoreCase("AAAAA")) {
linetype = TacticalLines.AAAAA;
} else if (str.equalsIgnoreCase("ROTARY")) {
linetype = TacticalLines.AAAAA;
} else if (str.equalsIgnoreCase("TRIPLE")) {
linetype = TacticalLines.TRIPLE;
} else if (str.equalsIgnoreCase("DOUBLEC")) {
linetype = TacticalLines.DOUBLEC;
} else if (str.equalsIgnoreCase("SINGLEC")) {
linetype = TacticalLines.SINGLEC;
} else if (str.equalsIgnoreCase("SINGLE")) {
linetype = TacticalLines.SINGLEC;
} else if (str.equalsIgnoreCase("HWFENCE")) {
linetype = TacticalLines.HWFENCE;
} else if (str.equalsIgnoreCase("LWFENCE")) {
linetype = TacticalLines.LWFENCE;
} // else if(str.equalsIgnoreCase("UNSP"))
// linetype=TacticalLines.UNSP;
else if (str.equalsIgnoreCase("DOUBLEA")) {
linetype = TacticalLines.DOUBLEA;
} else if (str.equalsIgnoreCase("SFENCE")) {
linetype = TacticalLines.SFENCE;
} else if (str.equalsIgnoreCase("DFENCE")) {
linetype = TacticalLines.DFENCE;
} else if (str.equalsIgnoreCase("LC")) {
linetype = TacticalLines.LC;
}
// rev C settings
if (RendererSettings.getInstance().getSymbologyStandard() == RendererSettings.Symbology_2525C) {
if (str.equalsIgnoreCase("SCREEN")) {
linetype = TacticalLines.SCREEN_REVC;
} else if (str.equalsIgnoreCase("COVER")) {
linetype = TacticalLines.COVER_REVC;
} else if (str.equalsIgnoreCase("GUARD")) {
linetype = TacticalLines.GUARD_REVC;
} else if (str.equalsIgnoreCase("SEIZE")) {
linetype = TacticalLines.SEIZE_REVC;
}
}
return linetype;
}
protected static int GetAutoshapeQty(String str, int rev) {
int numPts = -1;
// linetype=utility.GetLinetype(jTextField1.getText());
int linetype = GetLinetype(str, rev);
if (str.equalsIgnoreCase("cylinder"))
return 1;
if (str.equalsIgnoreCase("cylinder
return 1;
if (str.equalsIgnoreCase("radarc"))
return 1;
if (str.equalsIgnoreCase("radarc
return 1;
switch (linetype) {
case TacticalLines.RANGE_FAN_SECTOR:
case TacticalLines.RANGE_FAN:
numPts=1;
break;
case TacticalLines.FIX:
case TacticalLines.FOLLA:
case TacticalLines.FOLSP:
case TacticalLines.ISOLATE:
case TacticalLines.CORDONKNOCK:
case TacticalLines.CORDONSEARCH:
case TacticalLines.OCCUPY:
case TacticalLines.RETAIN:
case TacticalLines.SECURE:
case TacticalLines.MRR:
case TacticalLines.UAV:
// case TacticalLines.LLTR:
case TacticalLines.CLUSTER:
case TacticalLines.MNFLDFIX:
case TacticalLines.FERRY:
case TacticalLines.MFLANE:
case TacticalLines.RAFT:
case TacticalLines.FOXHOLE:
// case TacticalLines.LINTGT:
// case TacticalLines.LINTGTS:
case TacticalLines.FPF:
case TacticalLines.CONVOY:
case TacticalLines.HCONVOY:
case TacticalLines.BEARING:
case TacticalLines.NAVIGATION:
case TacticalLines.ELECTRO:
case TacticalLines.ACOUSTIC:
case TacticalLines.TORPEDO:
case TacticalLines.OPTICAL:
numPts = 2;
break;
case TacticalLines.RECTANGULAR:
case TacticalLines.BS_CROSS:
// case TacticalLines.RANGE_FAN://rev c
// case TacticalLines.RANGE_FAN_SECTOR://rev c
numPts = 1; // for RECTANGULAR change to 3 if using points
break;
case TacticalLines.PAA_CIRCULAR:
case TacticalLines.FSA_CIRCULAR:
case TacticalLines.ACA_CIRCULAR:
case TacticalLines.FFA_CIRCULAR:
case TacticalLines.NFA_CIRCULAR:
case TacticalLines.RFA_CIRCULAR:
case TacticalLines.ATI_CIRCULAR:
case TacticalLines.CFFZ_CIRCULAR:
case TacticalLines.SENSOR_CIRCULAR:
case TacticalLines.CENSOR_CIRCULAR:
case TacticalLines.DA_CIRCULAR:
case TacticalLines.CFZ_CIRCULAR:
case TacticalLines.ZOR_CIRCULAR:
case TacticalLines.TBA_CIRCULAR:
case TacticalLines.TVAR_CIRCULAR:
case TacticalLines.CIRCULAR:
case TacticalLines.KILLBOXBLUE_CIRCULAR:
case TacticalLines.KILLBOXPURPLE_CIRCULAR:
numPts = 1; // change to 2 if using points
break;
case TacticalLines.PAA_RECTANGULAR:
case TacticalLines.PAA_RECTANGULAR_REVC:
case TacticalLines.FSA_RECTANGULAR:
case TacticalLines.ACA_RECTANGULAR:
case TacticalLines.FFA_RECTANGULAR:
case TacticalLines.NFA_RECTANGULAR:
case TacticalLines.RFA_RECTANGULAR:
case TacticalLines.ATI_RECTANGULAR:
case TacticalLines.CFFZ_RECTANGULAR:
case TacticalLines.SENSOR_RECTANGULAR:
case TacticalLines.CENSOR_RECTANGULAR:
case TacticalLines.DA_RECTANGULAR:
case TacticalLines.CFZ_RECTANGULAR:
case TacticalLines.ZOR_RECTANGULAR:
case TacticalLines.TBA_RECTANGULAR:
case TacticalLines.TVAR_RECTANGULAR:
case TacticalLines.KILLBOXBLUE_RECTANGULAR:
case TacticalLines.KILLBOXPURPLE_RECTANGULAR:
case TacticalLines.BS_RECTANGLE:
numPts = 2; // change to 3 if using points
break;
case TacticalLines.BLOCK:
case TacticalLines.BREACH:
case TacticalLines.BYPASS:
case TacticalLines.CANALIZE:
case TacticalLines.CLEAR:
case TacticalLines.CONTAIN:
case TacticalLines.DELAY:
case TacticalLines.DISRUPT:
case TacticalLines.PENETRATE:
case TacticalLines.RETIRE:
case TacticalLines.SCREEN:
case TacticalLines.COVER:
case TacticalLines.GUARD:
case TacticalLines.SEIZE:
case TacticalLines.WDRAWUP:
case TacticalLines.WITHDRAW:
case TacticalLines.SARA:
case TacticalLines.DECEIVE:
// case TacticalLines.DUMMY:
case TacticalLines.PDF:
case TacticalLines.ATKBYFIRE:
case TacticalLines.AMBUSH:
// case TacticalLines.HOLD:
// case TacticalLines.BRDGHD:
case TacticalLines.MNFLDBLK:
case TacticalLines.TURN:
case TacticalLines.MNFLDDIS:
case TacticalLines.PLANNED:
case TacticalLines.ESR1:
case TacticalLines.ESR2:
case TacticalLines.ROADBLK:
case TacticalLines.TRIP:
case TacticalLines.EASY:
case TacticalLines.BYDIF:
case TacticalLines.BYIMP:
case TacticalLines.FORDSITE:
case TacticalLines.FORDIF:
case TacticalLines.IL:
case TacticalLines.BS_ELLIPSE:
// case TacticalLines.JET: //test only, then remove
numPts = 3;
break;
case TacticalLines.RIP:
case TacticalLines.SPTBYFIRE:
case TacticalLines.GAP:
case TacticalLines.ASLTXING:
case TacticalLines.BRIDGE:
case TacticalLines.MSDZ:
numPts = 4;
break;
// rev c
case TacticalLines.SCREEN_REVC:
case TacticalLines.COVER_REVC:
case TacticalLines.GUARD_REVC:
case TacticalLines.SEIZE_REVC:
numPts = 4;
break;
default:
numPts = 1000;
break;
}
if (rev == RendererSettings.Symbology_2525C) {
switch (linetype) {
case TacticalLines.UAV:
case TacticalLines.MRR:
numPts = 1000;
break;
}
}
return numPts;
}
private static ArrayList<POINT2> PointsToPOINT2(ArrayList<Point> pts) {
ArrayList<POINT2> pts2 = new ArrayList();
int j = 0;
Point pt = null;
POINT2 pt2 = null;
int n=pts.size();
//for (j = 0; j < pts.size(); j++)
for (j = 0; j < n; j++)
{
pt = pts.get(j);
pt2 = new POINT2(pt.getX(), pt.getY());
pts2.add(pt2);
}
return pts2;
}
private static ArrayList<Point2D> POINT2ToPoint2D(
ArrayList<POINT2> pts) {
ArrayList<Point2D> pts2d = new ArrayList();
int n=pts.size();
//for (int j = 0; j < pts.size(); j++)
for (int j = 0; j < n; j++)
{
pts2d.add(new Point2D.Double(pts.get(j).x, pts.get(j).y));
}
return pts2d;
}
/**
* Creates an MSS from the points and symbolid for testing
*
* @param symbolId
* @param uniqueId
* @param pts
* @return
*/
private static MilStdSymbol CreateMSS(String symbolId, String uniqueId,
ArrayList<POINT2> pts) {
// geo points
//ArrayList<Point2D.Double> pts2d = POINT2ToPoint2D(pts);
ArrayList<Point2D> pts2d = POINT2ToPoint2D(pts);
int rev = RendererSettings.getInstance().getSymbologyStandard();
int linetype = CELineArray.CGetLinetypeFromString(symbolId, rev);
MilStdSymbol mss = null;
try {
mss = new MilStdSymbol(symbolId, uniqueId, pts2d, null);
} catch (Exception e) {
}
//mss.setSymbologyStandard(RendererSettings.Symbology_2525C);
Color fillColor = null;
if(fillcolor.isEmpty()==false)
{
fillColor=SymbolUtilities.getColorFromHexString(fillcolor);
}
if(fillColor != null)
mss.setFillColor(fillColor);
Color lineColor = null;
Color textColor = null;
if(linecolor.isEmpty())
{
if(SymbolUtilities.isWeather(symbolId))
lineColor = SymbolUtilities.getLineColorOfWeather(symbolId);
else
lineColor=SymbolUtilities.getLineColorOfAffiliation(symbolId);
}
else
{
lineColor=SymbolUtilities.getColorFromHexString(linecolor);
}
if(textcolor.isEmpty())
textColor=lineColor;
else
textColor=SymbolUtilities.getColorFromHexString(textcolor);
if(AM.isEmpty())
AM="7000,6000,5000";
if(AN.isEmpty())
AN="45,315";
if(X.isEmpty())
X="27,54";
String[]am=AM.split(",");
String[] an=AN.split(",");
String[]x=X.split(",");
Double[]amd=new Double[am.length];
Double[]and=new Double[an.length];
Double[]xd=new Double[x.length];
int j=0;
for(j=0;j<am.length;j++)
amd[j]=Double.parseDouble(am[j]);
for(j=0;j<an.length;j++)
and[j]=Double.parseDouble(an[j]);
for(j=0;j<x.length;j++)
xd[j]=Double.parseDouble(x[j]);
mss.setLineColor(lineColor);
mss.setTextColor(textColor);
//mss.setLineWidth(2);
if(!lineWidth.isEmpty())
mss.setLineWidth(Integer.parseInt(lineWidth));
else
mss.setLineWidth(2);
mss.setModifier(ModifiersTG.T_UNIQUE_DESIGNATION_1, T);
mss.setModifier(ModifiersTG.T1_UNIQUE_DESIGNATION_2, T1);
mss.setModifier(ModifiersTG.H_ADDITIONAL_INFO_1, H);
mss.setModifier(ModifiersTG.H1_ADDITIONAL_INFO_2, H1);
mss.setModifier(ModifiersTG.H2_ADDITIONAL_INFO_3, "H2");
mss.setModifier(ModifiersTG.W_DTG_1, W);
mss.setModifier(ModifiersTG.W1_DTG_2, W1);
mss.setModifier(ModifiersTG.N_HOSTILE, "ENY");
for(j=0;j<amd.length;j++)
mss.setModifier_AM_AN_X(ModifiersTG.AM_DISTANCE, amd[j], j);
for(j=0;j<and.length;j++)
mss.setModifier_AM_AN_X(ModifiersTG.AN_AZIMUTH, and[j], j);
for(j=0;j<xd.length;j++)
mss.setModifier_AM_AN_X(ModifiersTG.X_ALTITUDE_DEPTH, xd[j], j);
// if (linetype == TacticalLines.AC || linetype == TacticalLines.SAAFR
// || linetype == TacticalLines.LLTR
// || linetype == TacticalLines.UAV
// || linetype == TacticalLines.MRR) {
// // try custon sizes
// mss.setModifier_AM_AN_X(ModifiersTG.AM_DISTANCE, amd[0], 0); // 4000
// mss.setModifier_AM_AN_X(ModifiersTG.AM_DISTANCE, amd[1], 1); // 3000
// mss.setModifier_AM_AN_X(ModifiersTG.X_ALTITUDE_DEPTH, xd[0], 0);//27
// mss.setModifier_AM_AN_X(ModifiersTG.X_ALTITUDE_DEPTH, xd[1], 1);//54
// } else if (linetype == TacticalLines.RANGE_FAN
// || linetype == TacticalLines.RANGE_FAN_SECTOR) {
// for(j=0;j<amd.length;j++)
// mss.setModifier_AM_AN_X(ModifiersTG.AM_DISTANCE, amd[j], j);
// for(j=0;j<amd.length;j++)
// mss.setModifier_AM_AN_X(ModifiersTG.AN_AZIMUTH, and[j], j);
// for(j=0;j<xd.length;j++)
// mss.setModifier_AM_AN_X(ModifiersTG.X_ALTITUDE_DEPTH, xd[j], j);
// } else// fire support areas
// mss.setModifier_AM_AN_X(ModifiersTG.AM_DISTANCE, amd[0], 0);// radius
// // for
// // circles
// // width
// // for
// // rectangles,
// // rectangular
// // tgt
// mss.setModifier_AM_AN_X(ModifiersTG.AM_DISTANCE, amd[0], 1);// length
// // rectangular
// // tgt
// mss.setModifier_AM_AN_X(ModifiersTG.AN_AZIMUTH, and[0], 0); // attitude
// // rectangulat
// // tgt
// mss.setModifier_AM_AN_X(ModifiersTG.X_ALTITUDE_DEPTH, xd[0], 0);// alt
// // kill
// // box
// // purple
// mss.setModifier_AM_AN_X(ModifiersTG.X_ALTITUDE_DEPTH, xd[1], 1);// alt
// // kill
// // box
// // purple
return mss;
}
private static String addAltitudes(String controlPtsStr) {
//ArrayList<String>alStr=new ArrayList();
String result = "";
String[] origPts = controlPtsStr.split(" ");
int j = 0;
String coords = "";
int n=origPts.length;
//for (j = 0; j < origPts.length; j++)
for (j = 0; j < n; j++)
{
coords = origPts[j];
coords += ",0";
if (j < origPts.length - 1) {
coords += " ";
}
result += coords;
}
return result;
}
/**
* string format is lon,lat lon,lat ...
*
* @param pts
* @return
*/
private static String controlPointsToString(ArrayList<POINT2> pts) {
String str = "";
int j = 0;
int n=pts.size();
//for (j = 0; j < pts.size(); j++)
for (j = 0; j < n; j++)
{
str += Double.toString(pts.get(j).x);
str += ",";
str += Double.toString(pts.get(j).y);
if (j < pts.size() - 1) {
str += " ";
}
}
return str;
}
private static String GetLinetype2(String str, int rev) {
//String str2=str.toString();
int linetype = GetLinetype(str, rev);
String str2 = str;
str2=str2.toUpperCase();
if (linetype < 0) {
//return a valid string the client can use for the symbol id
int n=str2.length();
//for (int j = str2.length(); j < 15; j++)
for (int j = n; j < 15; j++)
{
str2 += "-";
}
}
return str2;
}
/**
* computes the channel point for axis of advance symbols
* @param pts
* @param linetype
*/
private static void computePoint(ArrayList<Point>pts,int linetype)
{
switch (linetype) {
case TacticalLines.CATK:
case TacticalLines.CATKBYFIRE:
case TacticalLines.AAFNT:
case TacticalLines.AAAAA:
case TacticalLines.AIRAOA:
case TacticalLines.MAIN:
case TacticalLines.SPT:
case TacticalLines.AXAD:
case TacticalLines.CHANNEL:
Point pt = utility.ComputeLastPoint(pts);
pts.add(pt);
break;
default:
break;
}
}
/**
* The tester for the Google Earth plugin. Assumes pixels only are provided.
* If the linetype is fire support area then assume they are geo coords.
* Then use a best fit approach to convert them to pixels.
*
* @param pts
* @param defaultText
* @param g
*/
protected static String DoubleClickGE(ArrayList<Point> pts,
String defaultText, Canvas g2d, Context context) {
String strResult = "";
boolean renderAirControls = isAirspace(defaultText);
if (renderAirControls) {
return strResult;
}
//test text scaling
//RendererSettings.getInstance().setMPModifierFont("arial", Typeface.BOLD, 18, 2f);
//Object obj = System.getProperty("java.version");
ArrayList<Point2D> clipArea = new ArrayList();
defaultText=defaultText.toUpperCase();
clipArea.add(new Point2D.Double(0, 0));
clipArea.add(new Point2D.Double(displayWidth, 0));
clipArea.add(new Point2D.Double(displayWidth, displayHeight));
clipArea.add(new Point2D.Double(0, displayHeight));
clipArea.add(new Point2D.Double(0, 0));
int rev = 1;
if(Rev.isEmpty()==false)
{
if(Rev.equalsIgnoreCase("B"))
rev=0;
else
rev=1;
}
RendererSettings.getInstance().setSymbologyStandard(rev);
int linetype = utility.GetLinetype(defaultText, rev);
if (linetype < 0) {
defaultText = utility.GetLinetype2(defaultText, rev);
linetype = utility.GetLinetype(defaultText, rev);
}
//compute channel point for axis of advance
computePoint(pts,linetype);
//utility.ClosePolygon(pts, linetype);
IPointConversion converter = new PointConversion((int) displayWidth,
(int) displayHeight, upperLatitude, leftLongitude,
lowerLatitude, rightLongitude);
String symbolCode = clsSymbolCodeUtility.GetSymbolCode(linetype, rev);
if (defaultText.substring(0, 2).equalsIgnoreCase("10"))
{
if (defaultText.length() == 16) {
defaultText += "0000";
}
String symbolSet=defaultText.substring(4, 6);
String entityCode=defaultText.substring(10,16);
linetype=clsRenderer.getCMLineType(symbolSet, entityCode);
computePoint(pts,linetype);
symbolCode=defaultText;
}
ArrayList<POINT2> pts2 = PixelsToLatLong(pts, converter);
if (defaultText.length() == 15) {
symbolCode = defaultText;
}
MilStdSymbol mss = CreateMSS(symbolCode, "0", pts2);
boolean useDashArray=false;
//uncomment following line if client intends to calculate dashed lines to improve performance
//comment the line to allow renderer to calculate the dashes
useDashArray=true;
mss.setUseDashArray(useDashArray);
mss.setSymbologyStandard(rev);
clsRenderer.renderWithPolylines(mss, converter, clipArea, context);
drawShapeInfosGE(g2d, mss.getSymbolShapes(),useDashArray,mss.getSymbolID());
drawShapeInfosText(g2d, mss.getModifierShapes());
return strResult;
}
private static void drawSECRendererCoords3d(Canvas g, ArrayList<String> coordStrings, IPointConversion converter) {
Paint paint = new Paint();
//BasicStroke stroke = new BasicStroke(2);
paint.setStyle(Paint.Style.FILL);
String coords = "";
String[] coordArray = null;
int j = 0, k = 0;
String[] triple = null;
double x1 = 0, y1 = 0, x2, y2;
int n=coordStrings.size();
//for (j = 0; j < coordStrings.size(); j++)
for (j = 0; j < n; j++)
{
coords = coordStrings.get(j);
coordArray = coords.split(" ");
int t=coordArray.length;
//for (k = 0; k < coordArray.length - 1; k++)
for (k = 0; k < t - 1; k++)
{
triple = coordArray[k].split(",");
if (triple.length < 3) {
continue;
}
x1 = Double.parseDouble(triple[0]);
y1 = Double.parseDouble(triple[1]);
//Point2D pt=new Point2D.Double(x1,y1);
Point2D pt = new Point2D.Double(x1, y1);
pt = converter.GeoToPixels(pt);
x1 = pt.getX();
y1 = pt.getY();
triple = coordArray[k + 1].split(",");
if (triple.length < 3) {
continue;
}
x2 = Double.parseDouble(triple[0]);
y2 = Double.parseDouble(triple[1]);
//pt=new Point2D.Double(x2,y2);
pt = new Point2D.Double(x2, y2);
pt = converter.GeoToPixels(pt);
x2 = pt.getX();
y2 = pt.getY();
g.drawLine((float) x1, (float) y1, (float) x2, (float) y2, paint);
}
}
}
private static String getRectString(double deltax, double deltay) {
String str = "";
// normalize deltas to start
deltax = Math.abs(deltax);
deltay = Math.abs(deltay);
double deltaLHS = 0, deltaRHS = 0, deltaTop = 0, deltaBottom = 0;
if (leftLongitude - rightLongitude > 180)// 179 to -179
{
deltaLHS = deltax;
deltaRHS = -deltax;
} else if (leftLongitude - rightLongitude < -180)// -179 to 179
{
deltaLHS = -deltax;
deltaRHS = deltax;
} else if (leftLongitude < rightLongitude) {
deltaLHS = deltax;
deltaRHS = -deltax;
} else if (leftLongitude > rightLongitude) {
deltaLHS = -deltax;
deltaRHS = deltax;
}
if (upperLatitude > lowerLatitude) {
deltaTop = -deltay;
deltaBottom = deltay;
} else {
deltaTop = deltay;
deltaBottom = -deltay;
}
str += Double.toString(leftLongitude + deltaLHS) + ",";
str += Double.toString(lowerLatitude + deltaBottom) + ",";
str += Double.toString(rightLongitude + deltaRHS) + ",";
str += Double.toString(upperLatitude + deltaTop);
return str;
}
/**
* draw the ArrayLists of polylines for the GoogleEarth project tester
*
* @param g
* @param l
*/
private static void drawShapeInfosGE(Canvas canvas, List<ShapeInfo> l, boolean useDashedLines, String symbolId) {
try {
Iterator i = l.iterator();
int j = 0;
ArrayList<ArrayList<Point2D>> polylines = null;
ArrayList<Point2D> polyline = null;
int type = -1;
Path path = new Path();
Paint paint = new Paint();
BasicStroke stroke = null;
while (i.hasNext()) {
ShapeInfo spec = (ShapeInfo) i.next();
polylines = spec.getPolylines();
type = spec.getShapeType();
stroke = (BasicStroke) spec.getStroke();
if (spec.getFillColor() != null) {
paint.setColor(spec.getFillColor().toARGB());
}
paint.setStyle(Paint.Style.FILL);
if (spec.getShader() != null) {
paint.setShader(spec.getShader());
}
if (spec.getFillColor() != null && spec.getFillColor().getAlpha() > 0) {
int n=polylines.size();
//for (j = 0; j < polylines.size(); j++)
for (j = 0; j < n; j++)
{
path = new Path();
polyline = polylines.get(j);
//poly=new java.awt.Polygon();
path.moveTo((int) polyline.get(0).getX(), (int) polyline.get(0).getY());
int t=polyline.size();
//for (int k = 1; k < polyline.size(); k++)
for (int k = 1; k < t; k++)
{
path.lineTo((int) polyline.get(k).getX(), (int) polyline.get(k).getY());
}
canvas.drawPath(path, paint);
}
}
BasicStroke s = (BasicStroke) spec.getStroke();
float[] dash = s.getDashArray();
if (spec.getLineColor() != null)
if(dash==null || useDashedLines==false)
{
paint = new Paint();
paint.setColor(spec.getLineColor().toARGB());
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(stroke.getLineWidth());
int n=polylines.size();
//for (j = 0; j < polylines.size(); j++)
for (j = 0; j < n; j++)
{
polyline = polylines.get(j);
path = new Path();
path.moveTo((int) polyline.get(0).getX(), (int) polyline.get(0).getY());
int t=polyline.size();
//for (int k = 1; k < polyline.size(); k++)
for (int k = 1; k < t; k++)
{
path.lineTo((int) polyline.get(k).getX(), (int) polyline.get(k).getY());
}
canvas.drawPath(path, paint);
}
}
if (spec.getLineColor() != null && dash!=null && useDashedLines==true)
{
drawDashedPolylines(symbolId,polylines,spec,canvas);
}
}
} catch (Exception e) {
String s = e.getMessage();
return;
}
}
/**
*
* @param g
* @param l
*/
private static void drawShapeInfosText(Canvas g2d, List<ShapeInfo> l) {
try {
Iterator i = l.iterator();
AffineTransform tx = null;
Point2D position = null;
double stringAngle = 0;
Paint paint = null;
int size = 0;
float x = 0, y = 0;
String str = "";
while (i.hasNext()) {
int n = g2d.save();
ShapeInfo spec = (ShapeInfo) i.next();
TextLayout tl = spec.getTextLayout();
size = tl.getBounds().height;
position = spec.getGlyphPosition();
stringAngle = spec.getModifierStringAngle();
g2d.rotate((float) stringAngle, (float) position.getX(), (float) position.getY());
//draw the text twice
paint = new Paint();
paint.setTextAlign(Paint.Align.CENTER);
paint.setStrokeWidth(2);
//paint.setColor(Color.WHITE.toARGB());
if(textcolor != null && !textcolor.isEmpty())
paint.setColor(SymbolUtilities.getColorFromHexString(textcolor).toARGB());
else
paint.setColor(spec.getLineColor().toARGB());
paint.setTextSize(size);
paint.setStyle(Paint.Style.STROKE);
//paint.setTextAlign(Paint.Align.LEFT);
x = (float) position.getX();
y = (float) position.getY();
str = spec.getModifierString();
g2d.drawText(str, x, y, paint);
//g2d.drawText(spec.getModifierString(), (float)position.getX(), (float)position.getY(),paint);
//g2d.rotate(-(float)stringAngle);
paint = new Paint();
paint.setTextSize(size);
paint.setTextAlign(Paint.Align.CENTER);
paint.setColor(spec.getLineColor().toARGB());
paint.setStyle(Paint.Style.FILL);
//paint.setTextAlign(Paint.Align.LEFT);
//g2d.drawText(spec.getModifierString(), (float)position.getX(), (float)position.getY(),paint);
g2d.drawText(str, x, y, paint);
g2d.restore();
//g2d.rotate(-(float)stringAngle);
//paint.setTextSize(10);
}//end whilc
}//end try
catch (Exception e) {
String s = e.getMessage();
return;
}
}
private static Boolean isAirspace(String defaultText) {
if (defaultText.equalsIgnoreCase("cake")) {
defaultText = "CAKE
}
if (defaultText.equalsIgnoreCase("line")) {
defaultText = "LINE
}
if (defaultText.equalsIgnoreCase("radarc")) {
defaultText = "RADARC
}
if (defaultText.equalsIgnoreCase("polyarc")) {
defaultText = "POLYARC
}
if (defaultText.equalsIgnoreCase("polygon")) {
defaultText = "POLYGON
}
if (defaultText.equalsIgnoreCase("cylinder")) {
defaultText = "CYLINDER
}
if (defaultText.equalsIgnoreCase("track")) {
defaultText = "TRACK
}
if (defaultText.equalsIgnoreCase("route")) {
defaultText = "ROUTE
}
if (defaultText.equalsIgnoreCase("orbit")) {
defaultText = "ORBIT
}
if (defaultText.equalsIgnoreCase("curtain")) {
defaultText = "CURTAIN
}
//boolean renderWithPolylines = true;
boolean renderAirControls = false;
if (defaultText.equals("CAKE
renderAirControls = true;
} else if (defaultText.equals("CYLINDER
renderAirControls = true;
} else if (defaultText.equals("ROUTE
renderAirControls = true;
} else if (defaultText.equals("RADARC
renderAirControls = true;
} else if (defaultText.equals("POLYARC
renderAirControls = true;
} else if (defaultText.equals("POLYGON
renderAirControls = true;
} else if (defaultText.equals("TRACK
renderAirControls = true;
} else if (defaultText.equals("ORBIT
renderAirControls = true;
} else if (defaultText.equals("CURTAIN
renderAirControls = true;
} else if (defaultText.equals("LINE
renderAirControls = true;
}
return renderAirControls;
}
protected static String DoubleClickSECRenderer(ArrayList<Point> pts,
String defaultText, Canvas g2d) {
String strResult = "";
int rev = 1;
if(Rev.isEmpty()==false)
{
if(Rev.equalsIgnoreCase("B"))
rev=0;
else
rev=1;
}
RendererSettings.getInstance().setSymbologyStandard(rev);
int linetype = utility.GetLinetype(defaultText, rev);
if (linetype < 0) {
defaultText = utility.GetLinetype2(defaultText, rev);
linetype = utility.GetLinetype(defaultText, rev);
}
if (linetype > 0 && defaultText.length() != 15) {
defaultText = clsSymbolCodeUtility.GetSymbolCode(linetype, rev);
linetype = utility.GetLinetype(defaultText, rev);
}
//utility.ClosePolygon(pts, linetype);
ArrayList<POINT2> pts2 = PointsToPOINT2(pts);
double sizeSquare = Math.abs(rightLongitude - leftLongitude);
if (sizeSquare > 180) {
sizeSquare = 360 - sizeSquare;
}
double scale = 541463 * sizeSquare;
Point2D ptPixels = null;
Point2D ptGeo = null;
IPointConversion converter = null;
converter = new PointConverter(leftLongitude, upperLatitude, scale);
int j = 0;
POINT2 pt2 = null;
POINT2 pt2Geo = null;
ArrayList<POINT2> latLongs = new ArrayList();
int n=pts2.size();
//for (j = 0; j < pts2.size(); j++)
for (j = 0; j < n; j++)
{
pt2 = pts2.get(j);
ptPixels = new Point2D.Double(pt2.x, pt2.y);
ptGeo = converter.PixelsToGeo(ptPixels);
pt2Geo = new POINT2(ptGeo.getX(), ptGeo.getY());
latLongs.add(pt2Geo);
}
String hString = "0:FFFF00FF,1:FFFF00FF,2:FFFF00FF,3:FFFF00FF,4:FFFF00FF,5:FF00FFFF,6:FF00FFFF,7:FF00FFFF,8:FF00FFFF,9:FF00FFFF,10:FF00FFFF,11:FF00FFFF,12:FFFFFF00,13:FFFFFF00,14:FFFFFF00,15:FFFFFF00,16:FFFFFF00,17:FFFFFF00,18:FFFFFF00,19:FF0000FF,20:FF0000FF,21:FF0000FF,22:FF0000FF,23:FF0000FF,24:FFFF00FF,25:FFFF00FF,26:FFFF00FF,27:FFFF00FF,28:FFFF00FF,29:FFFF0000,30:FFFF0000,31:FFFF0000,32:FFFF0000,33:FFFF0000,34:FF00FFFF,35:FF00FFFF,36:FF00FFFF,37:FF00FFFF,38:FF00FFFF";
SparseArray<String> modifiers = new SparseArray<String>();
modifiers.put(ModifiersTG.T_UNIQUE_DESIGNATION_1, T);
modifiers.put(ModifiersTG.T1_UNIQUE_DESIGNATION_2, T1);
modifiers.put(ModifiersTG.H_ADDITIONAL_INFO_1, H);
modifiers.put(ModifiersTG.H1_ADDITIONAL_INFO_2, H1);
modifiers.put(ModifiersTG.H1_ADDITIONAL_INFO_2, "H2");
modifiers.put(ModifiersTG.W_DTG_1, W);
modifiers.put(ModifiersTG.W1_DTG_2, W1);
SparseArray<String> attributes = new SparseArray<String>();
String rectStr = getRectString(0, 0);
String controlPtsStr = controlPointsToString(latLongs);
String altitudeMode = "";
boolean renderAirControls=isAirspace(defaultText);
//Mil-Std-2525 symbols
if (!renderAirControls) {
modifiers.put(ModifiersTG.T_UNIQUE_DESIGNATION_1, T);
modifiers.put(ModifiersTG.T1_UNIQUE_DESIGNATION_2, T1);
modifiers.put(ModifiersTG.AM_DISTANCE, AM);
modifiers.put(ModifiersTG.AN_AZIMUTH, AN);
modifiers.put(ModifiersTG.X_ALTITUDE_DEPTH, X);
modifiers.put(ModifiersTG.H1_ADDITIONAL_INFO_2, H1);
modifiers.put(ModifiersTG.W_DTG_1, W);
modifiers.put(ModifiersTG.W1_DTG_2, W1);
attributes.put(MilStdAttributes.FillColor, fillcolor);
attributes.put(MilStdAttributes.LineColor, linecolor);
attributes.put(MilStdAttributes.TextColor, textcolor);
attributes.put(MilStdAttributes.SymbologyStandard, Integer.toString(rev));
if (JavaRendererUtilities.is3dSymbol(defaultText, modifiers)) {
attributes.put(MilStdAttributes.FillColor, "FF00FF00");
}
SECWebRenderer sec = new SECWebRenderer();
int format=0;
//format=2;
String strRender="";
boolean twod=false;
//twod=true;
if(!twod)
strRender = sec.RenderSymbol("id", "name", "description", defaultText, controlPtsStr, altitudeMode, scale, rectStr, modifiers, attributes, format, rev);
else
strRender = sec.RenderSymbol2D("id", "name", "description", defaultText, controlPtsStr, (int)displayWidth, (int)displayHeight, rectStr, modifiers, attributes, format, rev);
//WriteKMLFile(strRender);
strResult = strRender;
}
else //Airspaces
{
if(AM.isEmpty())
{
AM="6000,10000,4000,4000,5000,2000";
AN="15,345,60,100,30,150";
X="200,500,300,600,100,400";
}
String[]am=AM.split(",");
String[]an=AN.split(",");
String[]x=X.split(",");
//{attributes:[{radius1:5000, radius2:7500, minalt:0, maxalt:4000, leftAzimuth:180, rightAzimuth:270},{radius1:6000, radius2:8000, minalt:0, maxalt:8000, leftAzimuth:160, rightAzimuth:230}]}
String str="";
try
{
//attributesJSON=new JSONObject();
for(j=0;j<am.length/2;j++)
{
str+="{radius1:"+am[2*j]+", "+"radius2:"+am[2*j+1]+", "+"minalt:"+x[2*j]+", "+"maxalt:"+x[2*j+1]+", "+"leftAzimuth:"+an[2*j]+", "+"rightAzimuth:"+an[2*j+1]+"}";
if(j<am.length/2-1)
str+=",";
}
}
catch(Exception e)
{
}
str="["+str+"]";
String acAttributes="{attributes:"+str+"}";
//must add altitudes to control pts
controlPtsStr = addAltitudes(controlPtsStr);
//String acAttributes = "{attributes:[{radius1:5000, radius2:7500, minalt:0, maxalt:100, leftAzimuth:20, rightAzimuth:180}]}";
//acAttributes = "{attributes:[{radius1:5000, radius2:7500, minalt:0, maxalt:100, leftAzimuth:120, rightAzimuth:180},{radius1:6000, radius2:8000, minalt:0, maxalt:70, leftAzimuth:160, rightAzimuth:230}]}";
//acAttributes = "{attributes:[{radius1:5000, radius2:7500, minalt:0, maxalt:4000, leftAzimuth:180, rightAzimuth:270},{radius1:6000, radius2:8000, minalt:0, maxalt:8000, leftAzimuth:160, rightAzimuth:230}]}";
String strCake = "";
SECWebRenderer sec = new SECWebRenderer();
//acAttributes=str;
strCake = sec.Render3dSymbol("name", "id", defaultText, "", "ff0000ff", "800000ff", "", controlPtsStr, acAttributes);
strResult = strCake;
ArrayList<String> coordStrings = new ArrayList();
try {
//parseKML.parseLLTR(strRender,coordStrings);
parseKML.parseLLTR(strCake, coordStrings);
} catch (Exception exc) {
}
if (coordStrings.size() > 0) {
drawSECRendererCoords3d(g2d, coordStrings, converter);
}
}
return strResult;
}
private static Point2D ExtendAlongLineDouble2(POINT2 pt1, POINT2 pt2, double dist) {
double x = 0, y = 0;
try {
double dOriginalDistance = CalcDistanceDouble(pt1, pt2);
if (dOriginalDistance == 0 || dist == 0) {
return new Point2D.Double(pt1.x, pt1.y);
}
x = (dist / dOriginalDistance * (pt2.x - pt1.x) + pt1.x);
y = (dist / dOriginalDistance * (pt2.y - pt1.y) + pt1.y);
} catch (Exception exc) {
ErrorLogger.LogException("utility", "ExtendAlongLineDouble2",
new RendererException("Failed inside ExtendAlongLineDouble2", exc));
}
//return pt3;
return new Point2D.Double(x, y);
}
/**
* This function was added as a performance enhancement. The renderer normally creates a new array of length 2 points
* for each dash in the polyline. If the client sets useDashArray then the renderer skips this step so the client must compute
* the dashes based on the stroke dash array in the shape object.
*
* @param symbolId
* @param polylines
* @param shape
*/
private static void drawDashedPolylines(String symbolId, ArrayList<ArrayList<Point2D>> polylines, ShapeInfo shape, Canvas g2d) {
try {
//android.graphics.Point aPt = new android.graphics.Point();
int rev = RendererSettings.getInstance().getSymbologyStandard();
int linetype = GetLinetype(symbolId, rev);
Paint paint = new Paint();
paint.setColor(shape.getLineColor().toARGB());
paint.setStyle(Paint.Style.STROKE);
BasicStroke stroke=(BasicStroke)shape.getStroke();
paint.setStrokeWidth(stroke.getLineWidth());
if (shape.getLineColor() == null) {
return;
}
float[] dash = stroke.getDashArray();
float lineThickness = stroke.getLineWidth();
if (dash == null || dash.length < 2) {
return;
}
if (dash.length == 8)//dotted line
{
dash = new float[2];
dash[0] = 2f;
dash[1] = 2f;
stroke = new BasicStroke(2, BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER, 2f, dash, 0f);
shape.setStroke(stroke);
}
if (dash.length == 4) {
if (dash[0] == lineThickness * 2f && dash[1] == lineThickness * 2f && dash[2] == lineThickness * 2f && dash[3] == lineThickness * 2f)//this really looks awful in GE
{
dash = new float[2];
dash[0] = lineThickness;
dash[1] = lineThickness;
}
}
int j = 0, k = 0, i = 0, l = 0, n = 0;
ArrayList<Point2D> polyline = null;
Point2D pt2d0 = null, pt2d1 = null, pt2d2 = null, pt2d3 = null;
POINT2 pt0 = null, pt1 = null;
double dist = 0;
double patternLength = 0;
int numSegments = 0;
int t = dash.length;
for (j = 0; j < t; j++) {
patternLength += dash[j];
}
//sum is the end length of eash dash element
float sum[] = new float[dash.length];
double remainder = 0;
t = sum.length;
for (j = 0; j < t; j++) {
for (k = 0; k <= j; k++) {
sum[j] += dash[k];
}
}
boolean noShortSegments = false;
switch (linetype) {
case TacticalLines.LINTGT:
case TacticalLines.LINTGTS:
case TacticalLines.FPF:
case TacticalLines.HWFENCE:
case TacticalLines.LWFENCE:
case TacticalLines.DOUBLEA:
case TacticalLines.DFENCE:
case TacticalLines.SFENCE:
case TacticalLines.UNSP:
noShortSegments = true;
break;
default:
break;
}
t = polylines.size();
for (j = 0; j < t; j++) {
polyline = polylines.get(j);
int u = polyline.size();
for (k = 0; k < u - 1; k++) {
pt2d0 = polyline.get(k);
pt2d1 = polyline.get(k + 1);
pt0 = new POINT2(pt2d0.getX(), pt2d0.getY());
pt1 = new POINT2(pt2d1.getX(), pt2d1.getY());
dist = lineutility.CalcDistanceDouble(pt0, pt1);
numSegments = (int) (dist / patternLength);
if (noShortSegments) {
if (dist < 25) {
numSegments = 1;
}
}
for (l = 0; l < numSegments; l++) {
int v = dash.length;
for (i = 0; i < v; i++) {
//latlngs.clear();
if (i % 2 == 0) {
if (i == 0) {
pt2d2 = ExtendAlongLineDouble2(pt0, pt1, l * patternLength);
} else {
pt2d2 = ExtendAlongLineDouble2(pt0, pt1, l * patternLength + sum[i - 1]);
}
pt2d3 = ExtendAlongLineDouble2(pt0, pt1, l * patternLength + sum[i]);
g2d.drawLine((float)pt2d2.getX(), (float)pt2d2.getY(), (float)pt2d3.getX(), (float)pt2d3.getY(), paint);
}
}
}//end l loop
//for the remainder split the difference
remainder = dist - numSegments * patternLength;
if (remainder > 0) {
pt2d2 = ExtendAlongLineDouble2(pt0, pt1, numSegments * patternLength + remainder / 2);
g2d.drawLine((float)pt2d1.getX(), (float)pt2d1.getY(), (float)pt2d2.getX(), (float)pt2d2.getY(), paint);
}
}//end k loop
}//end j loop
} catch (Exception exc) {
ErrorLogger.LogException("utility", "createDashedPolylines",
new RendererException("Failed inside createDashedPolylines", exc));
}
}
} |
package com.deuteriumlabs.dendrite.view;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.jsp.PageContext;
import com.deuteriumlabs.dendrite.model.PageId;
import com.deuteriumlabs.dendrite.model.StoryBeginning;
import com.deuteriumlabs.dendrite.model.StoryOption;
import com.deuteriumlabs.dendrite.model.StoryPage;
import com.deuteriumlabs.dendrite.model.User;
import com.google.appengine.api.datastore.Text;
/**
* Represents a story page.
*/
public class ReadView extends View {
public enum Format {
BOLD, BOLD_ITALIC, ITALIC, NONE
}
public static String getAvatarDesc(final int id) {
return User.getAvatarDesc(id);
}
private User author;
private StoryBeginning beginning;
private StoryPage page;
private PageId pageId;
public ReadView() { }
public List<PageId> getAncestry() {
return page.getAncestry();
}
private User getAuthor() {
if (this.author == null) {
final String userId = page.getAuthorId();
this.author = new User();
this.author.setId(userId);
this.author.read();
}
return this.author;
}
public int getAuthorAvatarId() {
final User user = getAuthor();
return user.getAvatarId();
}
public String getAuthorId() {
return page.getAuthorId();
}
public String getAuthorName() {
return page.getAuthorName();
}
private StoryBeginning getBeginning() {
return this.beginning;
}
public String getFirstUrl() {
final PageId firstPageId = page.getBeginning();
return "read?p=" + firstPageId;
}
public int getNumberOfOptions() {
final PageId source = this.getPageId();
return StoryOption.countOptions(source);
}
public String getOptionLink(final int index) {
final StoryOption option = getOptionByIndex(index);
final int target = option.getTarget();
if (target == 0) {
final PageId source = this.getPageId();
final String from = source.toString();
return "/write?from=" + from + "&linkIndex=" + index;
} else {
return "/read?p=" + target;
}
}
public String getOptionText(final int index) {
final StoryOption option = getOptionByIndex(index);
return option.getText();
}
private StoryOption getOptionByIndex(final int index) {
final StoryOption option = new StoryOption();
final PageId source = this.getPageId();
option.setSource(source);
option.setListIndex(index);
option.read();
return option;
}
public boolean isOptionWritten(final int index) {
final StoryOption option = getOptionByIndex(index);
return option.isConnected();
}
public PageId getPageId() {
return this.pageId;
}
public String getPageNumber() {
final PageId id = this.getPageId();
final int number = id.getNumber();
return Integer.toString(number);
}
public String getPageText() {
final Text text = page.getText();
if (text != null)
return text.getValue();
else
return null;
}
public List<String> getParagraphs() {
final String text = this.getPageText();
List<String> list = new ArrayList<String>();
if (text != null) {
String[] array = text.split("\n");
for (String paragraph : array) {
paragraph = paragraph.replaceAll("[\n\r]", "");
if (paragraph.length() > 0) {
list.add(paragraph);
}
}
}
return list;
}
private PageId getSpecificPageId(final String string) {
final PageId id = new PageId(string);
String version = id.getVersion();
if (version == null) {
version = StoryPage.getRandomVersion(id);
id.setVersion(version);
}
return id;
}
public String getTitle() {
final StoryBeginning beginning = this.getBeginning();
return beginning.getTitle();
}
/*
* (non-Javadoc)
*
* @see com.deuteriumlabs.dendrite.view.View#getUrl()
*/
@Override
public String getUrl() {
final PageId idValue = this.getPageId();
final String idString = idValue.toString();
return "/read?p=" + idString;
}
public boolean isAuthorAnonymous() {
final String authorId = page.getAuthorId();
return (authorId == null);
}
public boolean isAvatarAvailable() {
final User user = getAuthor();
return user.isAvatarAvailable();
}
public boolean isBeginning() {
final PageId currPageId = this.getPageId();
final int currPageNumber = currPageId.getNumber();
final StoryBeginning beginning = this.getBeginning();
final int beginningPageNumber = beginning.getPageNumber();
return (currPageNumber == beginningPageNumber);
}
public boolean isPageInStore() {
return page.isInStore();
}
public boolean isShowingFirstPage() {
final PageId id = this.getPageId();
final int num = id.getNumber();
return (num == 1);
}
public void prepareNextPageNum() {
final PageContext pageContext = this.getPageContext();
final PageId id = this.getPageId();
final int currPageNum = id.getNumber();
final int nextPageNum = currPageNum + 1;
pageContext.setAttribute("nextPageNum", nextPageNum);
}
public void preparePrevPageNum() {
final PageContext pageContext = this.getPageContext();
final PageId id = this.getPageId();
final int currPageNum = id.getNumber();
final int prevPageNum = currPageNum - 1;
pageContext.setAttribute("prevPageNum", prevPageNum);
}
private void setBeginning(final StoryBeginning beginning) {
this.beginning = beginning;
}
private void setPage(final StoryPage page) {
this.page = page;
}
private void setPageId(final PageId id) {
this.pageId = id;
final StoryPage page = new StoryPage();
page.setId(id);
page.read();
this.setPage(page);
final PageId beginningId = page.getBeginning();
final StoryBeginning beginning = new StoryBeginning();
final int pageNumber = beginningId.getNumber();
beginning.setPageNumber(pageNumber);
beginning.read();
this.setBeginning(beginning);
}
public void setPageId(final String idString) {
final PageId id = getSpecificPageId(idString);
this.setPageId(id);
}
public String getParentId() {
final List<PageId> ancestry = this.getAncestry();
if (ancestry.size() > 1) {
final PageId parentId = ancestry.get(ancestry.size() - 2);
return parentId.toString();
} else {
return null;
}
}
public String getChance() {
return page.getChance();
}
public boolean isNotLoved() {
final boolean isLoved = this.isLoved();
return (isLoved == false);
}
/**
* @return
*/
public boolean isLoved() {
final String userId = View.getMyUserId();
return page.isLovedBy(userId);
}
public int getNumLovingUsers() {
return page.getNumLovingUsers();
}
public String getNumLovingUsersString() {
final int numLovingUsers = this.getNumLovingUsers();
if (numLovingUsers > 0) {
return Integer.toString(numLovingUsers);
} else {
return "";
}
}
public void prepareTag(final String tag) {
final PageContext pageContext = this.getPageContext();
pageContext.setAttribute("tagClass", tag.toLowerCase());
pageContext.setAttribute("tagName", tag.toUpperCase());
}
public List<String> getTags() {
final List<String> tags = page.getTags();
return tags;
}
public void preparePgId() {
final PageId id = this.getPageId();
final PageContext pageContext = this.getPageContext();
pageContext.setAttribute("pgId", id.toString());
}
public void prepareTagName(final String tag) {
final PageContext pageContext = this.getPageContext();
pageContext.setAttribute("tagName", tag);
}
public void prepareIsNotLoved() {
final boolean isNotLoved = this.isNotLoved();
final PageContext pageContext = this.getPageContext();
pageContext.setAttribute("isNotLoved", isNotLoved);
}
public void prepareMyUserId() {
final String userId = View.getMyUserId();
final PageContext pageContext = this.getPageContext();
pageContext.setAttribute("myUserId", userId);
}
public void prepareNumLovers() {
final String num = this.getNumLovingUsersString();
final PageContext pageContext = this.getPageContext();
pageContext.setAttribute("numLovers", num);
}
public void prepareParentId() {
final String id = this.getParentId();
final PageContext pageContext = this.getPageContext();
pageContext.setAttribute("parentId", id);
}
@Override
protected String getMetaDesc() {
return page.getLongSummary();
}
} |
package pt.webdetails.cda.utils.kettle;
import java.util.concurrent.Callable;
import javax.swing.table.TableModel;
import org.pentaho.di.core.row.RowMeta;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.core.row.ValueMeta;
import org.pentaho.di.core.row.ValueMetaInterface;
public class TableModelInput extends RowProducerBridge
{
public synchronized Callable<Boolean> getCallableRowProducer(final TableModel tableModel, final boolean markFinished)
{
final Callable<Boolean> callable = new Callable<Boolean>()
{
public Boolean call()
{
final RowMetaInterface rowMeta = getRowMetaForTableModel(tableModel);
start(rowMeta);
for (int i = 0; i < tableModel.getRowCount(); i++)
{
final Object[] row = new Object[tableModel.getColumnCount()];
for (int j = 0; j < tableModel.getColumnCount(); j++)
{
row[j] = getDataObjectForColumn(rowMeta.getValueMeta(j), tableModel.getValueAt(i, j));
}
putRow(row);
}
if (markFinished)
{
finish();
}
return true;
}
};
return callable;
}
private Object getDataObjectForColumn(final ValueMetaInterface valueMeta, final Object value)
{
// Handle null case
if (value == null)
{
return null;
}
Object newValue;
switch (valueMeta.getType())
{
case ValueMetaInterface.TYPE_STRING:
newValue = String.valueOf(value);
break;
case ValueMetaInterface.TYPE_NUMBER:
if (value instanceof Double)
{
newValue = value;
}
else
{
newValue = Double.valueOf(value.toString());
}
break;
case ValueMetaInterface.TYPE_INTEGER:
if (value instanceof Long)
{
newValue = value;
}
else
{
newValue = Long.valueOf(value.toString());
}
break;
case ValueMetaInterface.TYPE_DATE:
newValue = value;
break;
case ValueMetaInterface.TYPE_BIGNUMBER:
if (value instanceof java.math.BigDecimal)
{
newValue = value;
}
else
{
newValue = java.math.BigDecimal.valueOf(((java.math.BigInteger) value).doubleValue());
}
break;
case ValueMetaInterface.TYPE_BOOLEAN:
newValue = value;
break;
default:
throw new IllegalArgumentException(String.format("ValueMeta mismatch %s (%s)", valueMeta.toString(), value));
}
return newValue;
}
private RowMetaInterface getRowMetaForTableModel(final TableModel tableModel) throws IllegalArgumentException
{
final RowMetaInterface rowMeta = new RowMeta();
for (int i = 0; i < tableModel.getColumnCount(); i++)
{
Class<?> columnClass = tableModel.getColumnClass(i);
while (columnClass != Object.class)
{
if (columnClass == String.class)
{
rowMeta.addValueMeta(new ValueMeta(tableModel.getColumnName(i), ValueMetaInterface.TYPE_STRING));
break;
}
else if (columnClass == java.util.Date.class)
{
rowMeta.addValueMeta(new ValueMeta(tableModel.getColumnName(i), ValueMetaInterface.TYPE_DATE));
break;
}
else if (columnClass == Boolean.class)
{
rowMeta.addValueMeta(new ValueMeta(tableModel.getColumnName(i), ValueMetaInterface.TYPE_BOOLEAN));
break;
}
else if (columnClass == java.math.BigDecimal.class || columnClass == java.math.BigInteger.class)
{
rowMeta.addValueMeta(new ValueMeta(tableModel.getColumnName(i), ValueMetaInterface.TYPE_BIGNUMBER));
break;
}
else if (columnClass == Long.class || columnClass == Short.class || columnClass == Integer.class || columnClass == Byte.class)
{
rowMeta.addValueMeta(new ValueMeta(tableModel.getColumnName(i), ValueMetaInterface.TYPE_INTEGER));
break;
}
else if (columnClass == Double.class || columnClass == Float.class)
{
rowMeta.addValueMeta(new ValueMeta(tableModel.getColumnName(i), ValueMetaInterface.TYPE_NUMBER));
break;
}
else
{
columnClass = columnClass.getSuperclass();
}
}
if (columnClass == Object.class)
//TODO Maybe a warning log entry or something for this case?
{
rowMeta.addValueMeta(new ValueMeta(tableModel.getColumnName(i), ValueMetaInterface.TYPE_STRING));
}
}
return rowMeta;
}
} |
package org.bimserver.plugins;
import java.io.ByteArrayInputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.FileSystem;
import java.nio.file.FileSystemNotFoundException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.JarInputStream;
import java.util.zip.ZipEntry;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import org.apache.maven.artifact.versioning.ArtifactVersion;
import org.apache.maven.artifact.versioning.DefaultArtifactVersion;
import org.apache.maven.artifact.versioning.VersionRange;
import org.apache.maven.model.Model;
import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
import org.bimserver.emf.MetaDataManager;
import org.bimserver.emf.Schema;
import org.bimserver.interfaces.objects.SPluginBundle;
import org.bimserver.interfaces.objects.SPluginBundleType;
import org.bimserver.interfaces.objects.SPluginBundleVersion;
import org.bimserver.interfaces.objects.SPluginInformation;
import org.bimserver.interfaces.objects.SPluginType;
import org.bimserver.models.store.Parameter;
import org.bimserver.models.store.ServiceDescriptor;
import org.bimserver.plugins.classloaders.DelegatingClassLoader;
import org.bimserver.plugins.classloaders.EclipsePluginClassloader;
import org.bimserver.plugins.classloaders.FileJarClassLoader;
import org.bimserver.plugins.classloaders.JarClassLoader;
import org.bimserver.plugins.classloaders.PublicFindClassClassLoader;
import org.bimserver.plugins.deserializers.DeserializeException;
import org.bimserver.plugins.deserializers.DeserializerPlugin;
import org.bimserver.plugins.deserializers.StreamingDeserializerPlugin;
import org.bimserver.plugins.modelchecker.ModelCheckerPlugin;
import org.bimserver.plugins.modelcompare.ModelComparePlugin;
import org.bimserver.plugins.modelmerger.ModelMergerPlugin;
import org.bimserver.plugins.objectidms.ObjectIDM;
import org.bimserver.plugins.objectidms.ObjectIDMException;
import org.bimserver.plugins.objectidms.ObjectIDMPlugin;
import org.bimserver.plugins.queryengine.QueryEnginePlugin;
import org.bimserver.plugins.renderengine.RenderEnginePlugin;
import org.bimserver.plugins.serializers.MessagingSerializerPlugin;
import org.bimserver.plugins.serializers.MessagingStreamingSerializerPlugin;
import org.bimserver.plugins.serializers.SerializerPlugin;
import org.bimserver.plugins.serializers.StreamingSerializerPlugin;
import org.bimserver.plugins.services.BimServerClientInterface;
import org.bimserver.plugins.services.NewExtendedDataOnProjectHandler;
import org.bimserver.plugins.services.NewExtendedDataOnRevisionHandler;
import org.bimserver.plugins.services.NewRevisionHandler;
import org.bimserver.plugins.services.ServicePlugin;
import org.bimserver.plugins.stillimagerenderer.StillImageRenderPlugin;
import org.bimserver.plugins.web.WebModulePlugin;
import org.bimserver.shared.AuthenticationInfo;
import org.bimserver.shared.BimServerClientFactory;
import org.bimserver.shared.ChannelConnectionException;
import org.bimserver.shared.ServiceFactory;
import org.bimserver.shared.exceptions.PluginException;
import org.bimserver.shared.exceptions.ServiceException;
import org.bimserver.shared.exceptions.UserException;
import org.bimserver.shared.meta.SServicesMap;
import org.bimserver.utils.FakeClosingInputStream;
import org.bimserver.utils.PathUtils;
import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
import org.eclipse.aether.artifact.Artifact;
import org.eclipse.aether.artifact.DefaultArtifact;
import org.eclipse.aether.collection.CollectRequest;
import org.eclipse.aether.collection.DependencyCollectionException;
import org.eclipse.aether.graph.Dependency;
import org.eclipse.aether.graph.DependencyNode;
import org.eclipse.aether.resolution.ArtifactRequest;
import org.eclipse.aether.resolution.ArtifactResolutionException;
import org.eclipse.aether.resolution.ArtifactResult;
import org.eclipse.aether.resolution.DependencyRequest;
import org.eclipse.aether.resolution.DependencyResolutionException;
import org.eclipse.aether.util.graph.visitor.PreorderNodeListGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
public class PluginManager implements PluginManagerInterface {
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
private static final Logger LOGGER = LoggerFactory.getLogger(PluginManager.class);
private final Map<Class<? extends Plugin>, Set<PluginContext>> implementations = new LinkedHashMap<>();
private final Map<Plugin, PluginContext> pluginToPluginContext = new HashMap<>();
private final Map<PluginBundleIdentifier, PluginBundle> pluginBundleIdentifierToPluginBundle = new HashMap<>();
private final Map<PluginBundleVersionIdentifier, PluginBundle> pluginBundleVersionIdentifierToPluginBundle = new HashMap<>();
private final Map<PluginBundleIdentifier, PluginBundleVersionIdentifier> pluginBundleIdentifierToCurrentPluginBundleVersionIdentifier = new HashMap<>();
private final Path tempDir;
private final String baseClassPath;
private final ServiceFactory serviceFactory;
private final NotificationsManagerInterface notificationsManagerInterface;
private final SServicesMap servicesMap;
private final Path pluginsDir;
private PluginChangeListener pluginChangeListener;
private BimServerClientFactory bimServerClientFactory;
private MetaDataManager metaDataManager;
private MavenPluginRepository mavenPluginRepository;
private final List<FileJarClassLoader> jarClassLoaders = new ArrayList<>();
public PluginManager(Path tempDir, Path pluginsDir, MavenPluginRepository mavenPluginRepository, String baseClassPath, ServiceFactory serviceFactory, NotificationsManagerInterface notificationsManagerInterface, SServicesMap servicesMap) {
this.mavenPluginRepository = mavenPluginRepository;
LOGGER.debug("Creating new PluginManager");
this.pluginsDir = pluginsDir;
this.tempDir = tempDir;
this.baseClassPath = baseClassPath;
this.serviceFactory = serviceFactory;
this.notificationsManagerInterface = notificationsManagerInterface;
this.servicesMap = servicesMap;
if (pluginsDir != null) {
if (!Files.isDirectory(pluginsDir)) {
try {
Files.createDirectories(pluginsDir);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
// public void installLocalPlugins() {
// if (pluginsDir != null) {
// if (!Files.isDirectory(pluginsDir)) {
// try {
// Files.createDirectories(pluginsDir);
// } catch (IOException e) {
// e.printStackTrace();
// } else {
// try {
// for (Path file : PathUtils.list(pluginsDir)) {
// try {
// PluginBundleVersionIdentifier pluginBundleVersionIdentifier = PluginBundleVersionIdentifier.fromFileName(file.getFileName().toString());
// SPluginBundle extractPluginBundleFromJar = extractPluginBundleFromJar(file);
// install(pluginBundleVersionIdentifier, pluginBundleVersionIdentifier.getPluginBundleIdentifier(), pluginBundleVersionIdentifier, file, pomFile, plugins, false);
//// loadPluginsFromJar(pluginBundleVersionIdentifier, file, extractPluginBundleFromJar(file), extractPluginBundleVersionFromJar(file));
// LOGGER.info("Loading " + pluginBundleVersionIdentifier.getHumanReadable());
// } catch (PluginException e) {
// LOGGER.error("", e);
// } catch (IOException e) {
// LOGGER.error("", e);
public void loadPluginsFromEclipseProjectNoExceptions(Path projectRoot) {
try {
loadPluginsFromEclipseProject(projectRoot);
} catch (PluginException e) {
LOGGER.error("", e);
}
}
public PluginBundle loadJavaProject(Path projectRoot, Path pomFile, Path pluginFolder, PluginDescriptor pluginDescriptor) throws PluginException, FileNotFoundException, IOException, XmlPullParserException {
MavenXpp3Reader mavenreader = new MavenXpp3Reader();
Model model = null;
try (FileReader reader = new FileReader(pomFile.toFile())) {
model = mavenreader.read(reader);
}
PluginBundleVersionIdentifier pluginBundleVersionIdentifier = new PluginBundleVersionIdentifier(model.getGroupId(), model.getArtifactId(), model.getVersion());
if (pluginBundleIdentifierToPluginBundle.containsKey(pluginBundleVersionIdentifier.getPluginBundleIdentifier())) {
throw new PluginException("Plugin " + pluginBundleVersionIdentifier.getPluginBundleIdentifier().getHumanReadable() + " already loaded (version " + pluginBundleIdentifierToPluginBundle.get(pluginBundleVersionIdentifier.getPluginBundleIdentifier()).getPluginBundleVersion().getVersion() + ")");
}
DelegatingClassLoader delegatingClassLoader = new DelegatingClassLoader(getClass().getClassLoader());
PublicFindClassClassLoader previous = new PublicFindClassClassLoader(getClass().getClassLoader()) {
@Override
public Class<?> findClass(String name) throws ClassNotFoundException {
return null;
}
@Override
public URL findResource(String name) {
return null;
}
@Override
public void dumpStructure(int indent) {
}
};
Set<org.bimserver.plugins.Dependency> bimServerDependencies = new HashSet<>();
pluginBundleVersionIdentifier = new PluginBundleVersionIdentifier(new PluginBundleIdentifier(model.getGroupId(), model.getArtifactId()), model.getVersion());
List<org.apache.maven.model.Dependency> dependencies = model.getDependencies();
Iterator<org.apache.maven.model.Dependency> it = dependencies.iterator();
Path workspaceDir = Paths.get("..");
bimServerDependencies.add(new org.bimserver.plugins.Dependency(workspaceDir.resolve("PluginBase/target/classes")));
bimServerDependencies.add(new org.bimserver.plugins.Dependency(workspaceDir.resolve("Shared/target/classes")));
while (it.hasNext()) {
org.apache.maven.model.Dependency depend = it.next();
try {
if (depend.getGroupId().equals("org.opensourcebim") && (depend.getArtifactId().equals("shared") || depend.getArtifactId().equals("pluginbase"))) {
// Skip this one, because we have already
// TODO we might want to check the version though
continue;
}
Dependency dependency2 = new Dependency(new DefaultArtifact(depend.getGroupId() + ":" + depend.getArtifactId() + ":jar:" + depend.getVersion()), "compile");
if (!dependency2.getArtifact().isSnapshot()) {
if (dependency2.getArtifact().getFile() != null) {
bimServerDependencies.add(new org.bimserver.plugins.Dependency(dependency2.getArtifact().getFile().toPath()));
} else {
ArtifactRequest request = new ArtifactRequest();
request.setArtifact(dependency2.getArtifact());
request.setRepositories(mavenPluginRepository.getRepositories());
try {
ArtifactResult resolveArtifact = mavenPluginRepository.getSystem().resolveArtifact(mavenPluginRepository.getSession(), request);
if (resolveArtifact.getArtifact().getFile() != null) {
bimServerDependencies.add(new org.bimserver.plugins.Dependency(resolveArtifact.getArtifact().getFile().toPath()));
} else {
// TODO error?
}
} catch (ArtifactResolutionException e) {
e.printStackTrace();
}
}
} else {
// Snapshot projects linked in Eclipse
ArtifactRequest request = new ArtifactRequest();
if (!"test".equals(depend.getScope())) {
request.setArtifact(dependency2.getArtifact());
request.setRepositories(mavenPluginRepository.getLocalRepositories());
try {
ArtifactResult resolveArtifact = mavenPluginRepository.getSystem().resolveArtifact(mavenPluginRepository.getSession(), request);
if (resolveArtifact.getArtifact().getFile() != null) {
bimServerDependencies.add(new org.bimserver.plugins.Dependency(resolveArtifact.getArtifact().getFile().toPath()));
} else {
// TODO error?
}
} catch (Exception e) {
e.printStackTrace();
}
// bimServerDependencies.add(new org.bimserver.plugins.Dependency(resolveArtifact.getArtifact().getFile().toPath()));
}
}
CollectRequest collectRequest = new CollectRequest();
collectRequest.setRoot(dependency2);
DependencyNode node = mavenPluginRepository.getSystem().collectDependencies(mavenPluginRepository.getSession(), collectRequest).getRoot();
DependencyRequest dependencyRequest = new DependencyRequest();
dependencyRequest.setRoot(node);
try {
mavenPluginRepository.getSystem().resolveDependencies(mavenPluginRepository.getSession(), dependencyRequest);
} catch (DependencyResolutionException e) {
// Ignore
}
PreorderNodeListGenerator nlg = new PreorderNodeListGenerator();
node.accept(nlg);
DelegatingClassLoader depDelLoader = new DelegatingClassLoader(previous);
for (Artifact artifact : nlg.getArtifacts(false)) {
Path jarFile = Paths.get(artifact.getFile().getAbsolutePath());
LOGGER.debug("Loading " + jarFile);
// Path path =
// projectRoot.getParent().resolve(nlg.getClassPath());
loadDependencies(jarFile, depDelLoader);
// EclipsePluginClassloader depLoader = new EclipsePluginClassloader(depDelLoader, projectRoot);
bimServerDependencies.add(new org.bimserver.plugins.Dependency(jarFile));
}
previous = depDelLoader;
} catch (DependencyCollectionException e) {
e.printStackTrace();
}
}
delegatingClassLoader.add(previous);
// Path libFolder = projectRoot.resolve("lib");
// loadDependencies(libFolder, delegatingClassLoader);
EclipsePluginClassloader pluginClassloader = new EclipsePluginClassloader(delegatingClassLoader, projectRoot);
// pluginClassloader.dumpStructure(0);
ResourceLoader resourceLoader = new ResourceLoader() {
@Override
public InputStream load(String name) {
try {
return Files.newInputStream(pluginFolder.resolve(name));
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
};
SPluginBundle sPluginBundle = new SPluginBundle();
sPluginBundle.setOrganization(model.getOrganization().getName());
sPluginBundle.setName(model.getName());
SPluginBundleVersion sPluginBundleVersion = createPluginBundleVersionFromMavenModel(model, true);
Path icon = projectRoot.resolve("icon.png");
if (Files.exists(icon)) {
byte[] iconBytes = Files.readAllBytes(icon);
sPluginBundleVersion.setIcon(iconBytes);
}
sPluginBundle.setInstalledVersion(sPluginBundleVersion);
return loadPlugins(pluginBundleVersionIdentifier, resourceLoader, pluginClassloader, projectRoot.toUri(), projectRoot.resolve("target/classes").toString(), pluginDescriptor, PluginSourceType.ECLIPSE_PROJECT, bimServerDependencies, sPluginBundle, sPluginBundleVersion);
}
public PluginBundle loadPluginsFromEclipseProject(Path projectRoot) throws PluginException {
try {
if (!Files.isDirectory(projectRoot)) {
throw new PluginException("No directory: " + projectRoot.toString());
}
final Path pluginFolder = projectRoot.resolve("plugin");
if (!Files.isDirectory(pluginFolder)) {
throw new PluginException("No 'plugin' directory found in " + projectRoot.toString());
}
Path pluginFile = pluginFolder.resolve("plugin.xml");
if (!Files.exists(pluginFile)) {
throw new PluginException("No 'plugin.xml' found in " + pluginFolder.toString());
}
PluginDescriptor pluginDescriptor = getPluginDescriptor(Files.newInputStream(pluginFile));
Path pomFile = projectRoot.resolve("pom.xml");
if (!Files.exists(pomFile)) {
throw new PluginException("No pom.xml found in " + projectRoot);
}
// Path packageFile = projectRoot.resolve("package.json");
// if (Files.exists(packageFile)) {
// return loadJavaScriptProject(projectRoot, packageFile, pluginFolder, pluginDescriptor);
// } else if (Files.exists(pomFile)) {
PluginBundle pluginBundle = loadJavaProject(projectRoot, pomFile, pluginFolder, pluginDescriptor);
// } else {
// throw new PluginException("No pom.xml or package.json found in " + projectRoot.toString());
List<SPluginInformation> plugins = new ArrayList<>();
processPluginDescriptor(pluginDescriptor, plugins);
for (SPluginInformation sPluginInformation : plugins) {
if (sPluginInformation.isEnabled()) {
// For local plugins, we assume to install for all users
sPluginInformation.setInstallForAllUsers(true);
sPluginInformation.setInstallForNewUsers(true);
PluginContext pluginContext = pluginBundle.getPluginContext(sPluginInformation.getIdentifier());
if (pluginContext == null) {
throw new PluginException("No plugin context found for " + sPluginInformation.getIdentifier());
}
pluginContext.getPlugin().init(pluginContext);
}
}
try {
long pluginBundleVersionId = pluginChangeListener.pluginBundleInstalled(pluginBundle);
for (SPluginInformation sPluginInformation : plugins) {
if (sPluginInformation.isEnabled()) {
PluginContext pluginContext = pluginBundle.getPluginContext(sPluginInformation.getIdentifier());
pluginChangeListener.pluginInstalled(pluginBundleVersionId, pluginContext, sPluginInformation);
}
}
} catch (Exception e) {
LOGGER.error("", e);
throw new PluginException(e);
}
return pluginBundle;
} catch (JAXBException e) {
throw new PluginException(e);
} catch (FileNotFoundException e) {
throw new PluginException(e);
} catch (IOException e) {
throw new PluginException(e);
} catch (XmlPullParserException e) {
throw new PluginException(e);
}
}
@SuppressWarnings("unused")
private PluginBundle loadJavaScriptProject(Path projectRoot, Path packageFile, Path pluginFolder, PluginDescriptor pluginDescriptor) {
ObjectNode packageModel;
try {
packageModel = OBJECT_MAPPER.readValue(packageFile.toFile(), ObjectNode.class);
SPluginBundle sPluginBundle = new SPluginBundle();
if (!packageModel.has("organization")) {
throw new PluginException("package.json does not contain 'organization'");
}
sPluginBundle.setOrganization(packageModel.get("organization").asText());
sPluginBundle.setName(packageModel.get("name").asText());
SPluginBundleVersion sPluginBundleVersion = new SPluginBundleVersion();
sPluginBundleVersion.setType(SPluginBundleType.GITHUB);
if (!packageModel.has("organization")) {
throw new PluginException("package.json does not contain 'groupId'");
}
sPluginBundleVersion.setGroupId(packageModel.get("groupId").asText());
if (!packageModel.has("organization")) {
throw new PluginException("package.json does not contain 'artifactId'");
}
sPluginBundleVersion.setArtifactId(packageModel.get("artifactId").asText());
if (!packageModel.has("organization")) {
throw new PluginException("package.json does not contain 'version'");
}
sPluginBundleVersion.setVersion(packageModel.get("version").asText());
if (!packageModel.has("organization")) {
throw new PluginException("package.json does not contain 'description'");
}
sPluginBundleVersion.setDescription(packageModel.get("description").asText());
sPluginBundleVersion.setRepository("local");
sPluginBundleVersion.setType(SPluginBundleType.LOCAL);
sPluginBundleVersion.setMismatch(false); // TODO
sPluginBundle.setInstalledVersion(sPluginBundleVersion);
PluginBundleVersionIdentifier pluginBundleVersionIdentifier = new PluginBundleVersionIdentifier(new PluginBundleIdentifier(packageModel.get("groupId").asText(), packageModel.get("artifactId").asText()), packageModel.get("version").asText());
ResourceLoader resourceLoader = new ResourceLoader() {
@Override
public InputStream load(String name) {
try {
return Files.newInputStream(pluginFolder.resolve(name));
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
};
return loadPlugins(pluginBundleVersionIdentifier, resourceLoader, null, projectRoot.toUri(), null, pluginDescriptor, PluginSourceType.ECLIPSE_PROJECT, null, sPluginBundle, sPluginBundleVersion);
} catch (JsonParseException e1) {
e1.printStackTrace();
} catch (JsonMappingException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
} catch (PluginException e) {
e.printStackTrace();
}
return null;
}
private void loadDependencies(Path libFile, DelegatingClassLoader classLoader) throws FileNotFoundException, IOException {
if (libFile.getFileName().toString().toLowerCase().endsWith(".jar")) {
FileJarClassLoader jarClassLoader = new FileJarClassLoader(this, classLoader, libFile);
jarClassLoaders.add(jarClassLoader);
classLoader.add(jarClassLoader);
}
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private PluginBundle loadPlugins(PluginBundleVersionIdentifier pluginBundleVersionIdentifier, ResourceLoader resourceLoader, ClassLoader classLoader, URI location, String classLocation, PluginDescriptor pluginDescriptor, PluginSourceType pluginType,
Set<org.bimserver.plugins.Dependency> dependencies, SPluginBundle sPluginBundle, SPluginBundleVersion sPluginBundleVersion) throws PluginException {
sPluginBundle.setInstalledVersion(sPluginBundleVersion);
PluginBundle pluginBundle = new PluginBundleImpl(pluginBundleVersionIdentifier, sPluginBundle, sPluginBundleVersion, pluginDescriptor);
if (classLoader != null && classLoader instanceof Closeable) {
pluginBundle.addCloseable((Closeable) classLoader);
}
for (AbstractPlugin pluginImplementation : pluginDescriptor.getPlugins()) {
if (pluginImplementation instanceof JavaPlugin) {
JavaPlugin javaPlugin = (JavaPlugin)pluginImplementation;
String interfaceClassName = javaPlugin.getInterfaceClass().trim().replace("\n", "");
try {
Class interfaceClass = getClass().getClassLoader().loadClass(interfaceClassName);
if (javaPlugin.getImplementationClass() != null) {
String implementationClassName = javaPlugin.getImplementationClass().trim().replace("\n", "");
try {
Class implementationClass = classLoader.loadClass(implementationClassName);
Plugin plugin = (Plugin) implementationClass.newInstance();
pluginBundle.add(loadPlugin(pluginBundle, interfaceClass, location, classLocation, plugin, classLoader, pluginType, pluginImplementation, dependencies, plugin.getClass().getName()));
} catch (NoClassDefFoundError e) {
throw new PluginException("Implementation class '" + implementationClassName + "' not found", e);
} catch (ClassNotFoundException e) {
throw new PluginException("Implementation class '" + e.getMessage() + "' not found in " + location, e);
} catch (InstantiationException e) {
throw new PluginException(e);
} catch (IllegalAccessException e) {
throw new PluginException(e);
}
}
} catch (ClassNotFoundException e) {
throw new PluginException("Interface class '" + interfaceClassName + "' not found", e);
} catch (Error e) {
throw new PluginException(e);
}
} else if (pluginImplementation instanceof org.bimserver.plugins.WebModulePlugin) {
org.bimserver.plugins.WebModulePlugin webModulePlugin = (org.bimserver.plugins.WebModulePlugin)pluginImplementation;
JsonWebModule jsonWebModule = new JsonWebModule(webModulePlugin);
pluginBundle.add(loadPlugin(pluginBundle, WebModulePlugin.class, location, classLocation, jsonWebModule, classLoader, pluginType, pluginImplementation, dependencies, webModulePlugin.getIdentifier()));
}
}
pluginBundleIdentifierToPluginBundle.put(pluginBundleVersionIdentifier.getPluginBundleIdentifier(), pluginBundle);
pluginBundleVersionIdentifierToPluginBundle.put(pluginBundleVersionIdentifier, pluginBundle);
pluginBundleIdentifierToCurrentPluginBundleVersionIdentifier.put(pluginBundleVersionIdentifier.getPluginBundleIdentifier(), pluginBundleVersionIdentifier);
return pluginBundle;
}
public PluginDescriptor getPluginDescriptor(InputStream inputStream) throws JAXBException, IOException {
try {
JAXBContext jaxbContext = JAXBContext.newInstance(PluginDescriptor.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
PluginDescriptor pluginDescriptor = (PluginDescriptor) unmarshaller.unmarshal(inputStream);
return pluginDescriptor;
} finally {
inputStream.close();
}
}
public PluginDescriptor getPluginDescriptor(byte[] bytes) throws JAXBException, IOException {
return getPluginDescriptor(new ByteArrayInputStream(bytes));
}
// public void loadAllPluginsFromDirectoryOfJars(Path directory) throws PluginException, IOException {
// LOGGER.debug("Loading all plugins from " + directory.toString());
// if (!Files.isDirectory(directory)) {
// throw new PluginException("No directory: " + directory.toString());
// for (Path file : PathUtils.list(directory)) {
// if (file.getFileName().toString().toLowerCase().endsWith(".jar")) {
// try {
// PluginBundleVersionIdentifier pluginBundleVersionIdentifier = PluginBundleVersionIdentifier.fromFileName(file.getFileName().toString());
// loadPluginsFromJar(pluginBundleVersionIdentifier, file, extractPluginBundleFromJar(file), extractPluginBundleVersionFromJar(file));
// } catch (PluginException e) {
// LOGGER.error("", e);
public SPluginBundle extractPluginBundleFromJar(Path jarFilePath) throws PluginException {
String filename = jarFilePath.getFileName().toString();
PluginBundleVersionIdentifier pluginBundleVersionIdentifier = PluginBundleVersionIdentifier.fromFileName(filename);
try (JarFile jarFile = new JarFile(jarFilePath.toFile())) {
String pomLocation = "META-INF/maven/" + pluginBundleVersionIdentifier.getPluginBundleIdentifier().getGroupId() + "/" + pluginBundleVersionIdentifier.getPluginBundleIdentifier().getArtifactId() + "/" + "pom.xml";
ZipEntry pomEntry = jarFile.getEntry(pomLocation);
if (pomEntry == null) {
throw new PluginException("No pom.xml found in JAR file " + jarFilePath.toString() + ", " + pomLocation);
}
MavenXpp3Reader mavenreader = new MavenXpp3Reader();
Model model = mavenreader.read(jarFile.getInputStream(pomEntry));
SPluginBundle sPluginBundle = new SPluginBundle();
sPluginBundle.setOrganization(model.getOrganization().getName());
sPluginBundle.setName(model.getName());
return sPluginBundle;
} catch (IOException e) {
throw new PluginException(e);
} catch (XmlPullParserException e) {
throw new PluginException(e);
}
}
public SPluginBundleVersion extractPluginBundleVersionFromJar(Path jarFilePath, boolean isLocal) throws PluginException {
String filename = jarFilePath.getFileName().toString();
PluginBundleVersionIdentifier pluginBundleVersionIdentifier = PluginBundleVersionIdentifier.fromFileName(filename);
PluginBundleIdentifier pluginBundleIdentifier = pluginBundleVersionIdentifier.getPluginBundleIdentifier();
try (JarFile jarFile = new JarFile(jarFilePath.toFile())) {
ZipEntry pomEntry = jarFile.getEntry("META-INF/maven/" + pluginBundleIdentifier.getGroupId() + "/" + pluginBundleIdentifier.getArtifactId() + "/" + "pom.xml");
if (pomEntry == null) {
throw new PluginException("No pom.xml found in JAR file " + jarFilePath.toString());
}
MavenXpp3Reader mavenreader = new MavenXpp3Reader();
Model model = mavenreader.read(jarFile.getInputStream(pomEntry));
SPluginBundleVersion sPluginBundleVersion = createPluginBundleVersionFromMavenModel(model, isLocal);
return sPluginBundleVersion;
} catch (IOException e) {
throw new PluginException(e);
} catch (XmlPullParserException e) {
throw new PluginException(e);
}
}
private SPluginBundleVersion createPluginBundleVersionFromMavenModel(Model model, boolean isLocal) {
SPluginBundleVersion sPluginBundleVersion = new SPluginBundleVersion();
sPluginBundleVersion.setType(isLocal ? SPluginBundleType.LOCAL : SPluginBundleType.MAVEN);
sPluginBundleVersion.setGroupId(model.getGroupId());
sPluginBundleVersion.setArtifactId(model.getArtifactId());
sPluginBundleVersion.setVersion(model.getVersion());
sPluginBundleVersion.setDescription(model.getDescription());
sPluginBundleVersion.setRepository("local");
sPluginBundleVersion.setMismatch(false); // TODO
sPluginBundleVersion.setOrganization(model.getOrganization().getName());
sPluginBundleVersion.setName(model.getName());
return sPluginBundleVersion;
}
public PluginBundle loadPluginsFromJar(PluginBundleVersionIdentifier pluginBundleVersionIdentifier, Path file, SPluginBundle sPluginBundle, SPluginBundleVersion pluginBundleVersion, ClassLoader parentClassLoader) throws PluginException {
PluginBundleIdentifier pluginBundleIdentifier = pluginBundleVersionIdentifier.getPluginBundleIdentifier();
if (pluginBundleIdentifierToPluginBundle.containsKey(pluginBundleIdentifier)) {
throw new PluginException("Plugin " + pluginBundleIdentifier.getHumanReadable() + " already loaded (version " + pluginBundleIdentifierToPluginBundle.get(pluginBundleIdentifier).getPluginBundleVersion().getVersion() + ")");
}
LOGGER.debug("Loading plugins from " + file.toString());
if (!Files.exists(file)) {
throw new PluginException("Not a file: " + file.toString());
}
FileJarClassLoader jarClassLoader = null;
try {
jarClassLoader = new FileJarClassLoader(this, parentClassLoader, file);
jarClassLoaders.add(jarClassLoader);
final JarClassLoader finalLoader = jarClassLoader;
InputStream pluginStream = jarClassLoader.getResourceAsStream("plugin/plugin.xml");
if (pluginStream == null) {
jarClassLoader.close();
throw new PluginException("No plugin/plugin.xml found in " + file.getFileName().toString());
}
PluginDescriptor pluginDescriptor = getPluginDescriptor(pluginStream);
if (pluginDescriptor == null) {
jarClassLoader.close();
throw new PluginException("No plugin descriptor could be created");
}
LOGGER.debug(pluginDescriptor.toString());
URI fileUri = file.toAbsolutePath().toUri();
URI jarUri = new URI("jar:" + fileUri.toString());
ResourceLoader resourceLoader = new ResourceLoader() {
@Override
public InputStream load(String name) {
return finalLoader.getResourceAsStream(name);
}
};
return loadPlugins(pluginBundleVersionIdentifier, resourceLoader, jarClassLoader, jarUri, file.toAbsolutePath().toString(), pluginDescriptor, PluginSourceType.JAR_FILE, new HashSet<org.bimserver.plugins.Dependency>(), sPluginBundle, pluginBundleVersion);
} catch (Exception e) {
if (jarClassLoader != null) {
try {
jarClassLoader.close();
} catch (IOException e1) {
LOGGER.error("", e1);
}
}
throw new PluginException(e);
}
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private <T> Map<PluginContext, T> getPlugins(Class<T> requiredInterfaceClass, boolean onlyEnabled) {
Map<PluginContext, T> plugins = new HashMap<>();
for (Class interfaceClass : implementations.keySet()) {
if (requiredInterfaceClass.isAssignableFrom(interfaceClass)) {
for (PluginContext pluginContext : implementations.get(interfaceClass)) {
if (!onlyEnabled || pluginContext.isEnabled()) {
plugins.put(pluginContext, (T) pluginContext.getPlugin());
}
}
}
}
return plugins;
}
public Map<PluginContext, ObjectIDMPlugin> getAllObjectIDMPlugins(boolean onlyEnabled) {
return getPlugins(ObjectIDMPlugin.class, onlyEnabled);
}
public Map<PluginContext, RenderEnginePlugin> getAllRenderEnginePlugins(boolean onlyEnabled) {
return getPlugins(RenderEnginePlugin.class, onlyEnabled);
}
public Map<PluginContext, StillImageRenderPlugin> getAllStillImageRenderPlugins(boolean onlyEnabled) {
return getPlugins(StillImageRenderPlugin.class, onlyEnabled);
}
public Map<PluginContext, QueryEnginePlugin> getAllQueryEnginePlugins(boolean onlyEnabled) {
return getPlugins(QueryEnginePlugin.class, onlyEnabled);
}
public Map<PluginContext, SerializerPlugin> getAllSerializerPlugins(boolean onlyEnabled) {
return getPlugins(SerializerPlugin.class, onlyEnabled);
}
public Map<PluginContext, MessagingSerializerPlugin> getAllMessagingSerializerPlugins(boolean onlyEnabled) {
return getPlugins(MessagingSerializerPlugin.class, onlyEnabled);
}
public Map<PluginContext, MessagingStreamingSerializerPlugin> getAllMessagingStreamingSerializerPlugins(boolean onlyEnabled) {
return getPlugins(MessagingStreamingSerializerPlugin.class, onlyEnabled);
}
public Map<PluginContext, DeserializerPlugin> getAllDeserializerPlugins(boolean onlyEnabled) {
return getPlugins(DeserializerPlugin.class, onlyEnabled);
}
public Map<PluginContext, StreamingDeserializerPlugin> getAllStreamingDeserializerPlugins(boolean onlyEnabled) {
return getPlugins(StreamingDeserializerPlugin.class, onlyEnabled);
}
public Map<PluginContext, StreamingSerializerPlugin> getAllStreamingSeserializerPlugins(boolean onlyEnabled) {
return getPlugins(StreamingSerializerPlugin.class, onlyEnabled);
}
public Map<PluginContext, Plugin> getAllPlugins(boolean onlyEnabled) {
return getPlugins(Plugin.class, onlyEnabled);
}
public PluginContext getPluginContext(Plugin plugin) {
PluginContext pluginContext = pluginToPluginContext.get(plugin);
if (pluginContext == null) {
throw new RuntimeException("No plugin context found for " + plugin);
}
return pluginContext;
}
public void enablePlugin(String name) {
for (Set<PluginContext> pluginContexts : implementations.values()) {
for (PluginContext pluginContext : pluginContexts) {
if (pluginContext.getPlugin().getClass().getName().equals(name)) {
pluginContext.setEnabled(true, true);
}
}
}
}
public void disablePlugin(String name) {
for (Set<PluginContext> pluginContexts : implementations.values()) {
for (PluginContext pluginContext : pluginContexts) {
if (pluginContext.getPlugin().getClass().getName().equals(name)) {
pluginContext.setEnabled(false, true);
}
}
}
}
public Plugin getPlugin(String identifier, boolean onlyEnabled) {
for (Set<PluginContext> pluginContexts : implementations.values()) {
for (PluginContext pluginContext : pluginContexts) {
if (pluginContext.getIdentifier().equals(identifier)) {
if (!onlyEnabled || pluginContext.isEnabled()) {
return pluginContext.getPlugin();
}
}
}
}
return null;
}
public boolean isEnabled(String className) {
return getPlugin(className, true) != null;
}
public void setPluginChangeListener(PluginChangeListener pluginChangeListener) {
this.pluginChangeListener = pluginChangeListener;
}
public Collection<DeserializerPlugin> getAllDeserializerPlugins(String extension, boolean onlyEnabled) {
Collection<DeserializerPlugin> allDeserializerPlugins = getAllDeserializerPlugins(onlyEnabled).values();
Iterator<DeserializerPlugin> iterator = allDeserializerPlugins.iterator();
while (iterator.hasNext()) {
DeserializerPlugin deserializerPlugin = iterator.next();
if (!deserializerPlugin.canHandleExtension(extension)) {
iterator.remove();
}
}
return allDeserializerPlugins;
}
public DeserializerPlugin requireDeserializer(String extension) throws DeserializeException {
Collection<DeserializerPlugin> allDeserializerPlugins = getAllDeserializerPlugins(extension, true);
if (allDeserializerPlugins.size() == 0) {
throw new DeserializeException("No deserializers found for type '" + extension + "'");
} else {
return allDeserializerPlugins.iterator().next();
}
}
public Path getTempDir() {
if (!Files.isDirectory(tempDir)) {
try {
Files.createDirectories(tempDir);
} catch (IOException e) {
e.printStackTrace();
}
}
return tempDir;
}
public PluginContext loadPlugin(PluginBundle pluginBundle, Class<? extends Plugin> interfaceClass, URI location, String classLocation, Plugin plugin, ClassLoader classLoader, PluginSourceType pluginType,
AbstractPlugin pluginImplementation, Set<org.bimserver.plugins.Dependency> dependencies, String identifier) throws PluginException {
LOGGER.debug("Loading plugin " + plugin.getClass().getSimpleName() + " of type " + interfaceClass.getSimpleName());
if (!Plugin.class.isAssignableFrom(interfaceClass)) {
throw new PluginException("Given interface class (" + interfaceClass.getName() + ") must be a subclass of " + Plugin.class.getName());
}
if (!implementations.containsKey(interfaceClass)) {
implementations.put(interfaceClass, new LinkedHashSet<PluginContext>());
}
Set<PluginContext> set = (Set<PluginContext>) implementations.get(interfaceClass);
try {
PluginContext pluginContext = new PluginContext(this, pluginBundle, interfaceClass, classLoader, pluginType, pluginImplementation.getDescription(), location, plugin, classLocation, dependencies, identifier);
pluginToPluginContext.put(plugin, pluginContext);
set.add(pluginContext);
return pluginContext;
} catch (IOException e) {
throw new PluginException(e);
}
}
/**
* This method will initialize all the loaded plugins
*
* @throws PluginException
*/
public void initAllLoadedPlugins() throws PluginException {
LOGGER.debug("Initializig all loaded plugins");
for (Class<? extends Plugin> pluginClass : implementations.keySet()) {
Set<PluginContext> set = implementations.get(pluginClass);
for (PluginContext pluginContext : set) {
try {
pluginContext.initialize();
} catch (Throwable e) {
LOGGER.error("", e);
pluginContext.setEnabled(false, false);
}
}
}
}
/*
* Returns a complete classpath for all loaded plugins
*/
public String getCompleteClassPath() {
StringBuilder sb = new StringBuilder();
if (baseClassPath != null) {
sb.append(baseClassPath + File.pathSeparator);
}
for (Class<? extends Plugin> pluginClass : implementations.keySet()) {
Set<PluginContext> set = implementations.get(pluginClass);
for (PluginContext pluginContext : set) {
sb.append(pluginContext.getClassLocation() + File.pathSeparator);
}
}
return sb.toString();
}
public DeserializerPlugin getFirstDeserializer(String extension, Schema schema, boolean onlyEnabled) throws PluginException {
Collection<DeserializerPlugin> allDeserializerPlugins = getAllDeserializerPlugins(extension, onlyEnabled);
Iterator<DeserializerPlugin> iterator = allDeserializerPlugins.iterator();
while (iterator.hasNext()) {
DeserializerPlugin next = iterator.next();
if (!next.getSupportedSchemas().contains(schema)) {
iterator.remove();
}
}
if (allDeserializerPlugins.size() == 0) {
throw new PluginException("No deserializers with extension " + extension + " found");
}
return allDeserializerPlugins.iterator().next();
}
public ObjectIDMPlugin getObjectIDMByName(String className, boolean onlyEnabled) {
return getPluginByClassName(ObjectIDMPlugin.class, className, onlyEnabled);
}
public RenderEnginePlugin getRenderEnginePlugin(String className, boolean onlyEnabled) {
return getPluginByClassName(RenderEnginePlugin.class, className, onlyEnabled);
}
private <T extends Plugin> T getPluginByClassName(Class<T> clazz, String className, boolean onlyEnabled) {
Collection<T> allPlugins = getPlugins(clazz, onlyEnabled).values();
for (T t : allPlugins) {
if (t.getClass().getName().equals(className)) {
return t;
}
}
return null;
}
public QueryEnginePlugin getQueryEngine(String className, boolean onlyEnabled) {
return getPluginByClassName(QueryEnginePlugin.class, className, onlyEnabled);
}
public void loadAllPluginsFromEclipseWorkspace(Path file, boolean showExceptions) throws PluginException, IOException {
if (file != null && Files.isDirectory(file)) {
for (Path project : PathUtils.list(file)) {
if (Files.isDirectory(project)) {
Path pluginDir = project.resolve("plugin");
if (Files.exists(pluginDir)) {
Path pluginFile = pluginDir.resolve("plugin.xml");
if (Files.exists(pluginFile)) {
if (showExceptions) {
loadPluginsFromEclipseProject(project);
} else {
loadPluginsFromEclipseProjectNoExceptions(project);
}
}
}
}
}
}
}
public void loadAllPluginsFromEclipseWorkspaces(Path directory, boolean showExceptions) throws PluginException, IOException {
if (!Files.isDirectory(directory)) {
return;
}
if (Files.exists(directory.resolve("plugin/plugin.xml"))) {
if (showExceptions) {
loadPluginsFromEclipseProject(directory);
} else {
loadPluginsFromEclipseProjectNoExceptions(directory);
}
}
loadAllPluginsFromEclipseWorkspace(directory, showExceptions);
for (Path workspace : PathUtils.list(directory)) {
if (Files.isDirectory(workspace)) {
loadAllPluginsFromEclipseWorkspace(workspace, showExceptions);
}
}
}
public Map<PluginContext, ModelMergerPlugin> getAllModelMergerPlugins(boolean onlyEnabled) {
return getPlugins(ModelMergerPlugin.class, onlyEnabled);
}
public Map<PluginContext, ModelComparePlugin> getAllModelComparePlugins(boolean onlyEnabled) {
return getPlugins(ModelComparePlugin.class, onlyEnabled);
}
public ModelMergerPlugin getModelMergerPlugin(String className, boolean onlyEnabled) {
return getPluginByClassName(ModelMergerPlugin.class, className, onlyEnabled);
}
public ModelComparePlugin getModelComparePlugin(String className, boolean onlyEnabled) {
return getPluginByClassName(ModelComparePlugin.class, className, onlyEnabled);
}
public Map<PluginContext, ServicePlugin> getAllServicePlugins(boolean onlyEnabled) {
return getPlugins(ServicePlugin.class, onlyEnabled);
}
public ServicePlugin getServicePlugin(String className, boolean onlyEnabled) {
return getPluginByClassName(ServicePlugin.class, className, onlyEnabled);
}
public ServiceFactory getServiceFactory() {
return serviceFactory;
}
public void registerNewRevisionHandler(long uoid, ServiceDescriptor serviceDescriptor, NewRevisionHandler newRevisionHandler) {
if (notificationsManagerInterface != null) {
notificationsManagerInterface.registerInternalNewRevisionHandler(uoid, serviceDescriptor, newRevisionHandler);
}
}
public void unregisterNewRevisionHandler(long uoid, ServiceDescriptor serviceDescriptor) {
if (notificationsManagerInterface != null) {
notificationsManagerInterface.unregisterInternalNewRevisionHandler(uoid, serviceDescriptor.getIdentifier());
}
}
public SServicesMap getServicesMap() {
return servicesMap;
}
// public StillImageRenderPlugin getFirstStillImageRenderPlugin() throws
// PluginException {
// Collection<StillImageRenderPlugin> allPlugins =
// getAllStillImageRenderPlugins(true).values();
// if (allPlugins.size() == 0) {
// throw new PluginException("No still image render plugins found");
// StillImageRenderPlugin plugin = allPlugins.iterator().next();
// if (!plugin.isInitialized()) {
// plugin.init(this);
// return plugin;
public Parameter getParameter(PluginContext pluginContext, String name) {
return null;
}
public SerializerPlugin getSerializerPlugin(String className, boolean onlyEnabled) {
return (SerializerPlugin) getPlugin(className, onlyEnabled);
}
public MessagingSerializerPlugin getMessagingSerializerPlugin(String className, boolean onlyEnabled) {
return (MessagingSerializerPlugin) getPlugin(className, onlyEnabled);
}
public WebModulePlugin getWebModulePlugin(String className, boolean onlyEnabled) {
return (WebModulePlugin) getPlugin(className, onlyEnabled);
}
public Map<PluginContext, WebModulePlugin> getAllWebPlugins(boolean onlyEnabled) {
return getPlugins(WebModulePlugin.class, onlyEnabled);
}
public Map<PluginContext, ModelCheckerPlugin> getAllModelCheckerPlugins(boolean onlyEnabled) {
return getPlugins(ModelCheckerPlugin.class, onlyEnabled);
}
public ModelCheckerPlugin getModelCheckerPlugin(String className, boolean onlyEnabled) {
return getPluginByClassName(ModelCheckerPlugin.class, className, onlyEnabled);
}
public BimServerClientInterface getLocalBimServerClientInterface(AuthenticationInfo tokenAuthentication) throws ServiceException, ChannelConnectionException {
return bimServerClientFactory.create(tokenAuthentication);
}
public void setBimServerClientFactory(BimServerClientFactory bimServerClientFactory) {
this.bimServerClientFactory = bimServerClientFactory;
}
public void registerNewExtendedDataOnProjectHandler(long uoid, ServiceDescriptor serviceDescriptor, NewExtendedDataOnProjectHandler newExtendedDataHandler) {
if (notificationsManagerInterface != null) {
notificationsManagerInterface.registerInternalNewExtendedDataOnProjectHandler(uoid, serviceDescriptor, newExtendedDataHandler);
}
}
public void registerNewExtendedDataOnRevisionHandler(long uoid, ServiceDescriptor serviceDescriptor, NewExtendedDataOnRevisionHandler newExtendedDataHandler) {
if (notificationsManagerInterface != null) {
notificationsManagerInterface.registerInternalNewExtendedDataOnRevisionHandler(uoid, serviceDescriptor, newExtendedDataHandler);
}
}
public DeserializerPlugin getDeserializerPlugin(String pluginClassName, boolean onlyEnabled) {
return getPluginByClassName(DeserializerPlugin.class, pluginClassName, onlyEnabled);
}
public StreamingDeserializerPlugin getStreamingDeserializerPlugin(String pluginClassName, boolean onlyEnabled) {
return getPluginByClassName(StreamingDeserializerPlugin.class, pluginClassName, onlyEnabled);
}
public StreamingSerializerPlugin getStreamingSerializerPlugin(String pluginClassName, boolean onlyEnabled) {
return getPluginByClassName(StreamingSerializerPlugin.class, pluginClassName, onlyEnabled);
}
public MetaDataManager getMetaDataManager() {
return metaDataManager;
}
public void setMetaDataManager(MetaDataManager metaDataManager) {
this.metaDataManager = metaDataManager;
}
public FileSystem getOrCreateFileSystem(URI uri) throws IOException {
FileSystem fileSystem = null;
try {
fileSystem = FileSystems.getFileSystem(uri);
} catch (FileSystemNotFoundException e) {
Map<String, String> env = new HashMap<>();
env.put("create", "true");
fileSystem = FileSystems.newFileSystem(uri, env, null);
LOGGER.debug("Created VFS for " + uri);
}
return fileSystem;
}
public MessagingStreamingSerializerPlugin getMessagingStreamingSerializerPlugin(String className, boolean onlyEnabled) {
return (MessagingStreamingSerializerPlugin) getPlugin(className, onlyEnabled);
}
public List<SPluginInformation> getPluginInformationFromJar(Path file) throws PluginException, FileNotFoundException, IOException, JAXBException {
try (JarFile jarFile = new JarFile(file.toFile())) {
ZipEntry entry = jarFile.getEntry("plugin/plugin.xml");
if (entry == null) {
throw new PluginException("No plugin/plugin.xml found in " + file.getFileName().toString());
}
InputStream pluginStream = jarFile.getInputStream(entry);
return getPluginInformationFromPluginFile(pluginStream);
}
}
public List<SPluginInformation> getPluginInformationFromJar(InputStream jarInputStream) throws PluginException, FileNotFoundException, IOException, JAXBException {
try (JarInputStream jarInputStream2 = new JarInputStream(jarInputStream)) {
JarEntry next = jarInputStream2.getNextJarEntry();
while (next != null) {
if (next.getName().equals("plugin/plugin.xml")) {
return getPluginInformationFromPluginFile(jarInputStream2);
}
next = jarInputStream2.getNextJarEntry();
}
}
return null;
}
public List<SPluginInformation> getPluginInformationFromPluginFile(InputStream inputStream) throws PluginException, FileNotFoundException, IOException, JAXBException {
PluginDescriptor pluginDescriptor = getPluginDescriptor(inputStream);
if (pluginDescriptor == null) {
throw new PluginException("No plugin descriptor could be created");
}
List<SPluginInformation> list = new ArrayList<>();
processPluginDescriptor(pluginDescriptor, list);
return list;
}
private void processPluginDescriptor(PluginDescriptor pluginDescriptor, List<SPluginInformation> list) {
for (AbstractPlugin pluginImplementation : pluginDescriptor.getPlugins()) {
if (pluginImplementation instanceof JavaPlugin) {
JavaPlugin javaPlugin = (JavaPlugin)pluginImplementation;
SPluginInformation sPluginInformation = new SPluginInformation();
String name = javaPlugin.getName();
// TODO when all plugins have a name, this code can go
if (name == null) {
name = javaPlugin.getImplementationClass();
}
sPluginInformation.setName(name);
sPluginInformation.setDescription(javaPlugin.getDescription());
sPluginInformation.setEnabled(true);
// For java plugins we use the implementation class as identifier
sPluginInformation.setIdentifier(javaPlugin.getImplementationClass());
sPluginInformation.setType(getPluginTypeFromClass(javaPlugin.getInterfaceClass()));
list.add(sPluginInformation);
} else if (pluginImplementation instanceof org.bimserver.plugins.WebModulePlugin) {
org.bimserver.plugins.WebModulePlugin webModulePlugin = (org.bimserver.plugins.WebModulePlugin)pluginImplementation;
SPluginInformation sPluginInformation = new SPluginInformation();
sPluginInformation.setIdentifier(webModulePlugin.getIdentifier());
sPluginInformation.setName(webModulePlugin.getName());
sPluginInformation.setDescription(webModulePlugin.getDescription());
sPluginInformation.setType(SPluginType.WEB_MODULE);
sPluginInformation.setEnabled(true);
list.add(sPluginInformation);
}
}
}
public List<SPluginInformation> getPluginInformationFromPluginFile(Path file) throws PluginException, FileNotFoundException, IOException, JAXBException {
List<SPluginInformation> list = new ArrayList<>();
try (InputStream pluginStream = Files.newInputStream(file)) {
PluginDescriptor pluginDescriptor = getPluginDescriptor(pluginStream);
if (pluginDescriptor == null) {
throw new PluginException("No plugin descriptor could be created");
}
processPluginDescriptor(pluginDescriptor, list);
}
return list;
}
public SPluginType getPluginTypeFromClass(String className) {
switch (className) {
case "org.bimserver.plugins.deserializers.DeserializerPlugin":
return SPluginType.DESERIALIZER;
case "org.bimserver.plugins.deserializers.StreamingDeserializerPlugin":
return SPluginType.DESERIALIZER;
case "org.bimserver.plugins.serializers.SerializerPlugin":
return SPluginType.SERIALIZER;
case "org.bimserver.plugins.serializers.StreamingSerializerPlugin":
return SPluginType.SERIALIZER;
case "org.bimserver.plugins.serializers.MessagingStreamingSerializerPlugin":
return SPluginType.SERIALIZER;
case "org.bimserver.plugins.serializers.MessagingSerializerPlugin":
return SPluginType.SERIALIZER;
case "org.bimserver.plugins.modelchecker.ModelCheckerPlugin":
return SPluginType.MODEL_CHECKER;
case "org.bimserver.plugins.modelmerger.ModelMergerPlugin":
return SPluginType.MODEL_MERGER;
case "org.bimserver.plugins.modelcompare.ModelComparePlugin":
return SPluginType.MODEL_COMPARE;
case "org.bimserver.plugins.objectidms.ObjectIDMPlugin":
return SPluginType.OBJECT_IDM;
case "org.bimserver.plugins.queryengine.QueryEnginePlugin":
return SPluginType.QUERY_ENGINE;
case "org.bimserver.plugins.services.ServicePlugin":
return SPluginType.SERVICE;
case "org.bimserver.plugins.renderengine.RenderEnginePlugin":
return SPluginType.RENDER_ENGINE;
case "org.bimserver.plugins.stillimagerenderer.StillImageRenderPlugin":
return SPluginType.STILL_IMAGE_RENDER;
case "org.bimserver.plugins.web.WebModulePlugin":
return SPluginType.WEB_MODULE;
}
return null;
}
public PluginBundle loadFromPluginDir(PluginBundleVersionIdentifier pluginBundleVersionIdentifier, SPluginBundleVersion pluginBundleVersion, List<SPluginInformation> plugins, boolean strictDependencyChecking) throws Exception {
Path target = pluginsDir.resolve(pluginBundleVersionIdentifier.getFileName());
if (!Files.exists(target)) {
throw new PluginException(target.toString() + " not found");
}
SPluginBundle sPluginBundle = new SPluginBundle();
MavenXpp3Reader mavenreader = new MavenXpp3Reader();
try (JarFile jarFile = new JarFile(target.toFile())) {
ZipEntry entry = jarFile.getEntry("META-INF/maven/" + pluginBundleVersion.getGroupId() + "/" + pluginBundleVersion.getArtifactId() + "/pom.xml");
Model model = mavenreader.read(jarFile.getInputStream(entry));
sPluginBundle.setOrganization(model.getOrganization().getName());
sPluginBundle.setName(model.getName());
DelegatingClassLoader delegatingClassLoader = new DelegatingClassLoader(getClass().getClassLoader());
for (org.apache.maven.model.Dependency dependency : model.getDependencies()) {
if (dependency.getGroupId().equals("org.opensourcebim") && (dependency.getArtifactId().equals("shared") || dependency.getArtifactId().equals("pluginbase"))) {
// TODO Skip, we should also check the version though
} else {
PluginBundleIdentifier pluginBundleIdentifier = new PluginBundleIdentifier(dependency.getGroupId(), dependency.getArtifactId());
if (pluginBundleIdentifierToPluginBundle.containsKey(pluginBundleIdentifier)) {
if (strictDependencyChecking) {
VersionRange versionRange = VersionRange.createFromVersion(dependency.getVersion());
String version = pluginBundleIdentifierToPluginBundle.get(pluginBundleIdentifier).getPluginBundleVersion().getVersion();
ArtifactVersion artifactVersion = new DefaultArtifactVersion(version);
if (versionRange.containsVersion(artifactVersion)) {
} else {
throw new Exception("Required dependency " + pluginBundleIdentifier + " is installed, but it's version (" + version + ") does not comply to the required version (" + dependency.getVersion() + ")");
}
} else {
LOGGER.info("Skipping strict dependency checking for dependency " + dependency.getArtifactId());
}
} else {
if (pluginBundleIdentifier.getGroupId().equals("org.opensourcebim")) {
throw new Exception("Required dependency " + pluginBundleIdentifier + " is not installed");
} else {
MavenPluginLocation mavenPluginLocation = mavenPluginRepository.getPluginLocation(model.getRepositories().get(0).getUrl(), dependency.getGroupId(), dependency.getArtifactId());
try {
Path depJarFile = mavenPluginLocation.getVersionJar(dependency.getVersion());
FileJarClassLoader jarClassLoader = new FileJarClassLoader(this, delegatingClassLoader, depJarFile);
jarClassLoaders.add(jarClassLoader);
delegatingClassLoader.add(jarClassLoader);
} catch (Exception e) {
}
}
}
}
}
return loadPlugin(pluginBundleVersionIdentifier, target, sPluginBundle, pluginBundleVersion, plugins, delegatingClassLoader);
}
}
public PluginBundle loadPlugin(PluginBundleVersionIdentifier pluginBundleVersionIdentifier, Path target, SPluginBundle sPluginBundle, SPluginBundleVersion pluginBundleVersion, List<SPluginInformation> plugins, ClassLoader parentClassLoader) throws Exception {
PluginBundle pluginBundle = null;
// Stage 1, load all plugins from the JAR file and initialize them
try {
pluginBundle = loadPluginsFromJar(pluginBundleVersionIdentifier, target, sPluginBundle, pluginBundleVersion, parentClassLoader);
if (plugins.isEmpty()) {
LOGGER.warn("No plugins given to install for bundle " + sPluginBundle.getName());
}
for (SPluginInformation sPluginInformation : plugins) {
if (sPluginInformation.isEnabled()) {
PluginContext pluginContext = pluginBundle.getPluginContext(sPluginInformation.getIdentifier());
if (pluginContext == null) {
LOGGER.info("No plugin context found for " + sPluginInformation.getIdentifier());
}
pluginContext.getPlugin().init(pluginContext);
}
}
} catch (Exception e) {
e.printStackTrace();
if (pluginBundle != null) {
pluginBundle.close();
}
pluginBundleVersionIdentifierToPluginBundle.remove(pluginBundleVersionIdentifier);
pluginBundleIdentifierToPluginBundle.remove(pluginBundleVersionIdentifier.getPluginBundleIdentifier());
Files.delete(target);
LOGGER.error("", e);
throw e;
}
// Stage 2, if all went well, notify the listeners of this plugin, if
// anything goes wrong in the notifications, the plugin bundle will be
// uninstalled
try {
long pluginBundleVersionId = pluginChangeListener.pluginBundleInstalled(pluginBundle);
for (SPluginInformation sPluginInformation : plugins) {
if (sPluginInformation.isEnabled()) {
PluginContext pluginContext = pluginBundle.getPluginContext(sPluginInformation.getIdentifier());
pluginChangeListener.pluginInstalled(pluginBundleVersionId, pluginContext, sPluginInformation);
}
}
return pluginBundle;
} catch (Exception e) {
uninstall(pluginBundleVersionIdentifier);
LOGGER.error("", e);
throw e;
}
}
public PluginBundle install(MavenPluginBundle mavenPluginBundle, boolean strictDependencyChecking) throws Exception {
return install(mavenPluginBundle, null, strictDependencyChecking);
}
public PluginBundle install(MavenPluginBundle mavenPluginBundle, List<SPluginInformation> plugins, boolean strictDependencyChecking) throws Exception {
PluginBundleVersionIdentifier pluginBundleVersionIdentifier = mavenPluginBundle.getPluginVersionIdentifier();
MavenXpp3Reader mavenreader = new MavenXpp3Reader();
Model model = null;
try (InputStream pomInputStream = mavenPluginBundle.getPomInputStream()) {
model = mavenreader.read(pomInputStream);
}
if (plugins == null) {
try (JarInputStream jarInputStream = new JarInputStream(mavenPluginBundle.getJarInputStream())) {
JarEntry nextJarEntry = jarInputStream.getNextJarEntry();
while (nextJarEntry != null) {
if (nextJarEntry.getName().equals("plugin/plugin.xml")) {
// Install all plugins
PluginDescriptor pluginDescriptor = getPluginDescriptor(new FakeClosingInputStream(jarInputStream));
plugins = new ArrayList<>();
processPluginDescriptor(pluginDescriptor, plugins);
for (SPluginInformation info : plugins) {
info.setInstallForAllUsers(true);
info.setInstallForNewUsers(true);
}
break;
}
nextJarEntry = jarInputStream.getNextJarEntry();
}
}
}
DelegatingClassLoader delegatingClassLoader = new DelegatingClassLoader(getClass().getClassLoader());
for (org.apache.maven.model.Dependency dependency : model.getDependencies()) {
if (dependency.getGroupId().equals("org.opensourcebim") && (dependency.getArtifactId().equals("shared") || dependency.getArtifactId().equals("pluginbase"))) {
// TODO Skip, we should also check the version though
} else {
PluginBundleIdentifier pluginBundleIdentifier = new PluginBundleIdentifier(dependency.getGroupId(), dependency.getArtifactId());
if (pluginBundleIdentifierToPluginBundle.containsKey(pluginBundleIdentifier)) {
if (strictDependencyChecking) {
VersionRange versionRange = VersionRange.createFromVersion(dependency.getVersion());
// String version = pluginBundleIdentifierToPluginBundle.get(pluginBundleIdentifier).getPluginBundleVersion().getVersion();
ArtifactVersion artifactVersion = new DefaultArtifactVersion(mavenPluginBundle.getVersion());
if (versionRange.containsVersion(artifactVersion)) {
} else {
throw new Exception("Required dependency " + pluginBundleIdentifier + " is installed, but it's version (" + mavenPluginBundle.getVersion() + ") does not comply to the required version (" + dependency.getVersion() + ")");
}
} else {
LOGGER.info("Skipping strict dependency checking for dependency " + dependency.getArtifactId());
}
} else {
try {
MavenPluginLocation mavenPluginLocation = mavenPluginRepository.getPluginLocation(dependency.getGroupId(), dependency.getArtifactId());
Path depJarFile = mavenPluginLocation.getVersionJar(dependency.getVersion());
FileJarClassLoader jarClassLoader = new FileJarClassLoader(this, delegatingClassLoader, depJarFile);
jarClassLoaders.add(jarClassLoader);
delegatingClassLoader.add(jarClassLoader);
} catch (Exception e) {
throw new Exception("Required dependency " + pluginBundleIdentifier + " is not installed");
}
}
}
}
Path target = pluginsDir.resolve(pluginBundleVersionIdentifier.getFileName());
if (Files.exists(target)) {
throw new PluginException("This plugin has already been installed " + target.getFileName().toString());
}
Files.copy(mavenPluginBundle.getJarInputStream(), target);
return loadPlugin(pluginBundleVersionIdentifier, target, mavenPluginBundle.getPluginBundle(), mavenPluginBundle.getPluginBundleVersion(), plugins, delegatingClassLoader);
}
// public PluginBundle install(PluginBundleVersionIdentifier pluginBundleVersionIdentifier, SPluginBundle sPluginBundle, SPluginBundleVersion pluginBundleVersion, List<SPluginInformation> plugins, boolean strictDependencyChecking) throws Exception {
// MavenXpp3Reader mavenreader = new MavenXpp3Reader();
// Model model = mavenreader.read(new FileReader(pomFile.toFile()));
// DelegatingClassLoader delegatingClassLoader = new DelegatingClassLoader(getClass().getClassLoader());
// for (org.apache.maven.model.Dependency dependency : model.getDependencies()) {
// if (dependency.getGroupId().equals("org.opensourcebim") && (dependency.getArtifactId().equals("shared") || dependency.getArtifactId().equals("pluginbase"))) {
// // TODO Skip, we should also check the version though
// } else {
// PluginBundleIdentifier pluginBundleIdentifier = new PluginBundleIdentifier(dependency.getGroupId(), dependency.getArtifactId());
// if (pluginBundleIdentifierToPluginBundle.containsKey(pluginBundleIdentifier)) {
// if (strictDependencyChecking) {
// VersionRange versionRange = VersionRange.createFromVersion(dependency.getVersion());
// String version = pluginBundleIdentifierToPluginBundle.get(pluginBundleIdentifier).getPluginBundleVersion().getVersion();
// ArtifactVersion artifactVersion = new DefaultArtifactVersion(version);
// if (versionRange.containsVersion(artifactVersion)) {
// } else {
// throw new Exception("Required dependency " + pluginBundleIdentifier + " is installed, but it's version (" + version + ") does not comply to the required version (" + dependency.getVersion() + ")");
// } else {
// LOGGER.info("Skipping strict dependency checking for dependency " + dependency.getArtifactId());
// } else {
// try {
// MavenPluginLocation mavenPluginLocation = mavenPluginRepository.getPluginLocation(dependency.getGroupId(), dependency.getArtifactId());
// Path depJarFile = mavenPluginLocation.getVersionJar(dependency.getVersion());
// FileJarClassLoader jarClassLoader = new FileJarClassLoader(this, delegatingClassLoader, depJarFile);
// delegatingClassLoader.add(jarClassLoader);
// } catch (Exception e) {
// throw new Exception("Required dependency " + pluginBundleIdentifier + " is not installed");
// Path target = pluginsDir.resolve(pluginBundleVersionIdentifier.getFileName());
// if (Files.exists(target)) {
// throw new PluginException("This plugin has already been installed " + target.getFileName().toString());
// Files.copy(jarFile, target);
// return loadPlugin(pluginBundleVersionIdentifier, target, sPluginBundle, pluginBundleVersion, plugins, delegatingClassLoader);
public void uninstall(PluginBundleVersionIdentifier pluginBundleVersionIdentifier) {
PluginBundle pluginBundle = pluginBundleVersionIdentifierToPluginBundle.get(pluginBundleVersionIdentifier);
if (pluginBundle == null) {
return;
}
try {
pluginBundle.close();
pluginBundleVersionIdentifierToPluginBundle.remove(pluginBundleVersionIdentifier);
pluginBundleIdentifierToPluginBundle.remove(pluginBundleVersionIdentifier.getPluginBundleIdentifier());
pluginBundleIdentifierToCurrentPluginBundleVersionIdentifier.remove(pluginBundleVersionIdentifier.getPluginBundleIdentifier());
for (PluginContext pluginContext : pluginBundle) {
Set<PluginContext> set = implementations.get(pluginContext.getPluginInterface());
set.remove(pluginContext);
}
Path target = pluginsDir.resolve(pluginBundleVersionIdentifier.getFileName());
Files.delete(target);
for (PluginContext pluginContext : pluginBundle) {
pluginChangeListener.pluginUninstalled(pluginContext);
}
pluginChangeListener.pluginBundleUninstalled(pluginBundle);
} catch (IOException e) {
LOGGER.error("", e);
}
}
public PluginBundle getPluginBundle(PluginBundleIdentifier pluginIdentifier) {
return pluginBundleIdentifierToPluginBundle.get(pluginIdentifier);
}
public Collection<PluginBundle> getPluginBundles() {
return pluginBundleVersionIdentifierToPluginBundle.values();
}
@Override
public ObjectIDM getDefaultObjectIDM() throws ObjectIDMException {
// TODO add a mechanism that can be used to ask a database what the
// default plugin is
return null;
}
@Override
public void notifyPluginStateChange(PluginContext pluginContext, boolean enabled) {
if (pluginChangeListener != null) {
pluginChangeListener.pluginStateChanged(pluginContext, enabled);
}
}
public PluginBundle update(PluginBundleVersionIdentifier pluginBundleVersionIdentifier, SPluginBundle sPluginBundle, SPluginBundleVersion pluginBundleVersion, Path jarFile, Path pomFile, List<SPluginInformation> plugins) throws Exception {
PluginBundle existingPluginBundle = pluginBundleIdentifierToPluginBundle.get(pluginBundleVersionIdentifier.getPluginBundleIdentifier());
if (existingPluginBundle == null) {
throw new UserException("No previous version of plugin bundle " + pluginBundleVersionIdentifier.getPluginBundleIdentifier() + " found");
}
try {
existingPluginBundle.close();
if (pluginBundleIdentifierToPluginBundle.remove(pluginBundleVersionIdentifier.getPluginBundleIdentifier()) == null) {
LOGGER.warn("Previous version of " + pluginBundleVersionIdentifier.getPluginBundleIdentifier() + " not found");
}
PluginBundleVersionIdentifier currentVersion = pluginBundleIdentifierToCurrentPluginBundleVersionIdentifier.get(pluginBundleVersionIdentifier.getPluginBundleIdentifier());
if (pluginBundleIdentifierToCurrentPluginBundleVersionIdentifier.remove(pluginBundleVersionIdentifier.getPluginBundleIdentifier()) == null) {
LOGGER.warn("Previous version of " + pluginBundleVersionIdentifier.getPluginBundleIdentifier() + " not found");
}
if (pluginBundleVersionIdentifierToPluginBundle.remove(currentVersion) == null) {
LOGGER.warn("Previous version (" + currentVersion + ") of " + pluginBundleVersionIdentifier.getPluginBundleIdentifier() + " not found");
}
for (PluginContext pluginContext : existingPluginBundle) {
Set<PluginContext> set = implementations.get(pluginContext.getPluginInterface());
set.remove(pluginContext);
}
if (existingPluginBundle.getPluginBundle().getInstalledVersion().getType() == SPluginBundleType.MAVEN) {
Path target = pluginsDir.resolve(currentVersion.getFileName());
Files.delete(target);
}
// for (PluginContext pluginContext : existingPluginBundle) {
// pluginChangeListener.pluginUninstalled(pluginContext);
} catch (IOException e) {
LOGGER.error("", e);
}
Path target = pluginsDir.resolve(pluginBundleVersionIdentifier.getFileName());
if (Files.exists(target)) {
throw new PluginException("This plugin has already been installed " + target.getFileName().toString());
}
Files.copy(jarFile, target);
MavenXpp3Reader mavenreader = new MavenXpp3Reader();
Model model = null;
try (FileReader fileReader = new FileReader(pomFile.toFile())) {
model = mavenreader.read(fileReader);
}
DelegatingClassLoader delegatingClassLoader = new DelegatingClassLoader(getClass().getClassLoader());
for (org.apache.maven.model.Dependency dependency : model.getDependencies()) {
if (dependency.getGroupId().equals("org.opensourcebim") && (dependency.getArtifactId().equals("shared") || dependency.getArtifactId().equals("pluginbase"))) {
// TODO Skip, we should also check the version though
} else {
PluginBundleIdentifier pluginBundleIdentifier = new PluginBundleIdentifier(dependency.getGroupId(), dependency.getArtifactId());
if (pluginBundleIdentifierToPluginBundle.containsKey(pluginBundleIdentifier)) {
// if (false) {
// VersionRange versionRange = VersionRange.createFromVersion(dependency.getVersion());
// String version = pluginBundleIdentifierToPluginBundle.get(pluginBundleIdentifier).getPluginBundleVersion().getVersion();
// ArtifactVersion artifactVersion = new DefaultArtifactVersion(version);
// if (versionRange.containsVersion(artifactVersion)) {
// } else {
// throw new Exception("Required dependency " + pluginBundleIdentifier + " is installed, but it's version (" + version + ") does not comply to the required version (" + dependency.getVersion() + ")");
// } else {
LOGGER.info("Skipping strict dependency checking for dependency " + dependency.getArtifactId());
} else {
if (dependency.getGroupId().equals("org.opensourcebim") && (dependency.getArtifactId().equals("shared") || dependency.getArtifactId().equals("pluginbase"))) {
throw new Exception("Required dependency " + pluginBundleIdentifier + " is not installed");
} else {
MavenPluginLocation mavenPluginLocation = mavenPluginRepository.getPluginLocation(model.getRepositories().get(0).getUrl(), dependency.getGroupId(), dependency.getArtifactId());
try {
Path depJarFile = mavenPluginLocation.getVersionJar(dependency.getVersion());
FileJarClassLoader jarClassLoader = new FileJarClassLoader(this, delegatingClassLoader, depJarFile);
jarClassLoaders.add(jarClassLoader);
delegatingClassLoader.add(jarClassLoader);
} catch (Exception e) {
}
}
}
}
}
PluginBundle pluginBundle = null;
// Stage 1, load all plugins from the JAR file and initialize them
try {
pluginBundle = loadPluginsFromJar(pluginBundleVersionIdentifier, target, sPluginBundle, pluginBundleVersion, delegatingClassLoader);
for (SPluginInformation sPluginInformation : plugins) {
if (sPluginInformation.isEnabled()) {
PluginContext pluginContext = pluginBundle.getPluginContext(sPluginInformation.getIdentifier());
pluginContext.getPlugin().init(pluginContext);
}
}
} catch (Exception e) {
Files.delete(target);
LOGGER.error("", e);
throw e;
}
// Stage 2, if all went well, notify the listeners of this plugin, if
// anything goes wrong in the notifications, the plugin bundle will be
// uninstalled
try {
long pluginBundleVersionId = pluginChangeListener.pluginBundleUpdated(pluginBundle);
for (SPluginInformation sPluginInformation : plugins) {
if (sPluginInformation.isEnabled()) {
PluginContext pluginContext = pluginBundle.getPluginContext(sPluginInformation.getIdentifier());
pluginChangeListener.pluginUpdated(pluginBundleVersionId, pluginContext, sPluginInformation);
}
}
return pluginBundle;
} catch (Exception e) {
uninstall(pluginBundleVersionIdentifier);
LOGGER.error("", e);
throw e;
}
}
@Override
public SerializerPlugin getSerializerPlugin(String pluginClassName) {
return getPluginByClassName(SerializerPlugin.class, pluginClassName, true);
}
public void close() {
for (FileJarClassLoader fileJarClassLoader : jarClassLoaders) {
try {
fileJarClassLoader.close();
} catch (IOException e) {
LOGGER.error("", e);
}
}
}
} |
package io.flutter.sdk;
import com.google.common.annotations.VisibleForTesting;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.intellij.execution.ExecutionException;
import com.intellij.ide.util.PropertiesComponent;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ApplicationNamesInfo;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectManager;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.ArrayUtil;
import com.intellij.util.Url;
import com.intellij.util.Urls;
import com.jetbrains.lang.dart.sdk.DartSdkUpdateOption;
import io.flutter.FlutterBundle;
import io.flutter.dart.DartPlugin;
import io.flutter.pub.PubRoot;
import io.flutter.pub.PubRoots;
import io.flutter.utils.FlutterModuleUtils;
import io.flutter.utils.JsonUtils;
import io.flutter.utils.SystemUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.*;
public class FlutterSdkUtil {
/**
* The environment variable to use to tell the flutter tool which app is driving it.
*/
public static final String FLUTTER_HOST_ENV = "FLUTTER_HOST";
private static final String FLUTTER_SDK_KNOWN_PATHS = "FLUTTER_SDK_KNOWN_PATHS";
private static final Logger LOG = Logger.getInstance(FlutterSdkUtil.class);
private static final String FLUTTER_SNAP_SDK_PATH = "/snap/flutter/common/flutter";
public FlutterSdkUtil() {
}
/**
* Return the environment variable value to use when shelling out to the Flutter command-line tool.
*/
public String getFlutterHostEnvValue() {
final String clientId = ApplicationNamesInfo.getInstance().getFullProductName().replaceAll(" ", "-");
final String existingVar = java.lang.System.getenv(FLUTTER_HOST_ENV);
return existingVar == null ? clientId : (existingVar + ":" + clientId);
}
public static void updateKnownSdkPaths(@NotNull final String newSdkPath) {
updateKnownPaths(FLUTTER_SDK_KNOWN_PATHS, newSdkPath);
}
private static void updateKnownPaths(@SuppressWarnings("SameParameterValue") @NotNull final String propertyKey,
@NotNull final String newPath) {
final Set<String> allPaths = new LinkedHashSet<>();
// Add the new value first; this ensures that it's the 'default' flutter sdk.
allPaths.add(newPath);
final PropertiesComponent props = PropertiesComponent.getInstance();
// Add the existing known paths.
final String[] oldPaths = props.getValues(propertyKey);
if (oldPaths != null) {
allPaths.addAll(Arrays.asList(oldPaths));
}
// Store the values back.
if (allPaths.isEmpty()) {
props.unsetValue(propertyKey);
}
else {
props.setValues(propertyKey, ArrayUtil.toStringArray(allPaths));
}
}
/**
* Adds the current path and other known paths to the combo, most recently used first.
*/
public static void addKnownSDKPathsToCombo(@NotNull JComboBox combo) {
final Set<String> pathsToShow = new LinkedHashSet<>();
final String currentPath = combo.getEditor().getItem().toString().trim();
if (!currentPath.isEmpty()) {
pathsToShow.add(currentPath);
}
final String[] knownPaths = getKnownFlutterSdkPaths();
for (String path : knownPaths) {
if (FlutterSdk.forPath(path) != null) {
pathsToShow.add(FileUtil.toSystemDependentName(path));
}
}
//noinspection unchecked
combo.setModel(new DefaultComboBoxModel(ArrayUtil.toStringArray(pathsToShow)));
if (combo.getSelectedIndex() == -1 && combo.getItemCount() > 0) {
combo.setSelectedIndex(0);
}
}
@NotNull
public static String[] getKnownFlutterSdkPaths() {
final Set<String> paths = new HashSet<>();
// scan current projects for existing flutter sdk settings
for (Project project : ProjectManager.getInstance().getOpenProjects()) {
final FlutterSdk flutterSdk = FlutterSdk.getFlutterSdk(project);
if (flutterSdk != null) {
paths.add(flutterSdk.getHomePath());
}
}
// use the list of paths they've entered in the past
final String[] knownPaths = PropertiesComponent.getInstance().getValues(FLUTTER_SDK_KNOWN_PATHS);
if (knownPaths != null) {
paths.addAll(Arrays.asList(knownPaths));
}
// search the user's path
final String fromUserPath = locateSdkFromPath();
if (fromUserPath != null) {
paths.add(fromUserPath);
}
// Add the snap SDK path if it exists; note that this path is standard on all Linux platforms.
final File snapSdkPath = new File(System.getenv("HOME") + FLUTTER_SNAP_SDK_PATH);
if (snapSdkPath.exists()) {
paths.add(snapSdkPath.getAbsolutePath());
}
return paths.toArray(new String[0]);
}
@NotNull
public static String pathToFlutterTool(@NotNull String sdkPath) throws ExecutionException {
final String path = findDescendant(sdkPath, "/bin/" + flutterScriptName());
if (path == null) {
throw new ExecutionException("Flutter SDK is not configured");
}
return path;
}
@NotNull
public static String flutterScriptName() {
return SystemInfo.isWindows ? "flutter.bat" : "flutter";
}
/**
* Returns the path to the Dart SDK within a Flutter SDK, or null if it doesn't exist.
*/
@Nullable
public static String pathToDartSdk(@NotNull String flutterSdkPath) {
return findDescendant(flutterSdkPath, "/bin/cache/dart-sdk");
}
@Nullable
private static String findDescendant(@NotNull String flutterSdkPath, @NotNull String path) {
final VirtualFile file = LocalFileSystem.getInstance().refreshAndFindFileByPath(flutterSdkPath + path);
if (file == null || !file.exists()) {
return null;
}
return file.getPath();
}
public static boolean isFlutterSdkHome(@NotNull final String path) {
final File flutterPubspecFile = new File(path + "/packages/flutter/pubspec.yaml");
final File flutterToolFile = new File(path + "/bin/flutter");
final File dartLibFolder = new File(path + "/bin/cache/dart-sdk/lib");
return flutterPubspecFile.isFile() && flutterToolFile.isFile() && dartLibFolder.isDirectory();
}
private static boolean isFlutterSdkHomeWithoutDartSdk(@NotNull final String path) {
final File flutterPubspecFile = new File(path + "/packages/flutter/pubspec.yaml");
final File flutterToolFile = new File(path + "/bin/flutter");
final File dartLibFolder = new File(path + "/bin/cache/dart-sdk/lib");
return flutterPubspecFile.isFile() && flutterToolFile.isFile() && !dartLibFolder.isDirectory();
}
/**
* Checks the workspace for any open Flutter projects.
*
* @return true if an open Flutter project is found
*/
public static boolean hasFlutterModules() {
return Arrays.stream(ProjectManager.getInstance().getOpenProjects()).anyMatch(FlutterModuleUtils::hasFlutterModule);
}
public static boolean hasFlutterModules(@NotNull Project project) {
return FlutterModuleUtils.hasFlutterModule(project);
}
@Nullable
public static String getErrorMessageIfWrongSdkRootPath(final @NotNull String sdkRootPath) {
if (sdkRootPath.isEmpty()) {
return null;
}
final File sdkRoot = new File(sdkRootPath);
if (!sdkRoot.isDirectory()) return FlutterBundle.message("error.folder.specified.as.sdk.not.exists");
if (isFlutterSdkHomeWithoutDartSdk(sdkRootPath)) return FlutterBundle.message("error.flutter.sdk.without.dart.sdk");
if (!isFlutterSdkHome(sdkRootPath)) return FlutterBundle.message("error.sdk.not.found.in.specified.location");
return null;
}
public static void setFlutterSdkPath(@NotNull final Project project, @NotNull final String flutterSdkPath) {
// In reality this method sets Dart SDK (that is inside the Flutter SDK).
final String dartSdk = flutterSdkPath + "/bin/cache/dart-sdk";
ApplicationManager.getApplication().runWriteAction(() -> DartPlugin.ensureDartSdkConfigured(project, dartSdk));
// Checking for updates doesn't make sense since the channels don't correspond to Flutter...
DartSdkUpdateOption.setDartSdkUpdateOption(DartSdkUpdateOption.DoNotCheck);
// Update the list of known sdk paths.
FlutterSdkUtil.updateKnownSdkPaths(flutterSdkPath);
// Fire events for a Flutter SDK change, which updates the UI.
FlutterSdkManager.getInstance(project).checkForFlutterSdkChange();
}
// TODO(devoncarew): The Dart plugin supports specifying individual modules in the settings page.
/**
* Enable Dart support for the given project.
*/
public static void enableDartSdk(@NotNull final Project project) {
//noinspection ConstantConditions
for (Module module : ModuleManager.getInstance(project).getModules()) {
if (module != null && !PubRoots.forModule(module).isEmpty()) {
DartPlugin.enableDartSdk(module);
}
}
}
/**
* Parse packages meta-data file and infer the location of the Flutter SDK from that.
*/
@Nullable
public static String guessFlutterSdkFromPackagesFile(@NotNull Module module) {
// First, look for .dart_tool/package_config.json
final JsonArray packages = getPackagesFromPackageConfig(PubRoots.forModule(module));
for (int i = 0; i < packages.size(); i++) {
final JsonObject pack = packages.get(i).getAsJsonObject();
if ("flutter".equals(JsonUtils.getStringMember(pack, "name"))) {
final String uri = JsonUtils.getStringMember(pack, "rootUri");
if (uri == null) {
continue;
}
final String path = extractSdkPathFromUri(uri, false);
if (path == null) {
continue;
}
return path;
}
}
// Next, try the obsolete .packages
for (PubRoot pubRoot : PubRoots.forModule(module)) {
final VirtualFile packagesFile = pubRoot.getPackagesFile();
if (packagesFile == null) {
continue;
}
// parse it
try {
final String contents = new String(packagesFile.contentsToByteArray(true /* cache contents */));
return parseFlutterSdkPath(contents);
}
catch (IOException ignored) {
}
}
return null;
}
@Nullable
public static String getPathToCupertinoIconsPackage(@NotNull Project project) {
//noinspection ConstantConditions
if (ApplicationManager.getApplication().isUnitTestMode()) {
// TODO(messick): Configure the test framework to have proper pub data so we don't need this.
return "testData/sdk";
}
final JsonArray packages = getPackagesFromPackageConfig(PubRoots.forProject(project));
for (int i = 0; i < packages.size(); i++) {
final JsonObject pack = packages.get(i).getAsJsonObject();
if ("cupertino_icons".equals(JsonUtils.getStringMember(pack, "name"))) {
final String uri = JsonUtils.getStringMember(pack, "rootUri");
if (uri == null) {
continue;
}
try {
return new URI(uri).getPath();
}
catch (URISyntaxException ignored) {
}
}
}
return null;
}
private static JsonArray getPackagesFromPackageConfig(@NotNull List<PubRoot> pubRoots) {
final JsonArray entries = new JsonArray();
for (PubRoot pubRoot : pubRoots) {
final VirtualFile configFile = pubRoot.getPackageConfigFile();
if (configFile == null) {
continue;
}
// parse it
try {
final String contents = new String(configFile.contentsToByteArray(true /* cache contents */));
final JsonElement element = new JsonParser().parse(contents);
if (element == null) {
continue;
}
final JsonObject json = element.getAsJsonObject();
if (JsonUtils.getIntMember(json, "configVersion") < 2) continue;
final JsonArray packages = json.getAsJsonArray("packages");
if (packages == null || packages.size() == 0) {
continue;
}
entries.addAll(packages);
}
catch (IOException ignored) {
}
}
return entries;
}
@VisibleForTesting
public static String parseFlutterSdkPath(String packagesFileContent) {
for (String line : packagesFileContent.split("\n")) {
// flutter:file:///Users/.../flutter/packages/flutter/lib/
line = line.trim();
if (line.isEmpty() || line.startsWith("
continue;
}
final String flutterPrefix = "flutter:";
if (line.startsWith(flutterPrefix)) {
final String urlString = line.substring(flutterPrefix.length());
final String path = extractSdkPathFromUri(urlString, true);
if (path == null) {
continue;
}
return path;
}
}
return null;
}
private static String extractSdkPathFromUri(String urlString, boolean isLibIncluded) {
if (urlString.startsWith("file:")) {
final Url url = Urls.parseEncoded(urlString);
if (url == null) {
return null;
}
final String path = url.getPath();
// go up three levels for .packages or two for .dart_tool/package_config.json
File file = new File(url.getPath());
file = file.getParentFile().getParentFile();
if (isLibIncluded) {
file = file.getParentFile();
}
return file.getPath();
}
return null;
}
/**
* Locate the Flutter SDK using the user's PATH.
*/
@Nullable
public static String locateSdkFromPath() {
final String flutterBinPath = SystemUtils.which("flutter");
if (flutterBinPath == null) {
return null;
}
final File flutterBinFile = new File(flutterBinPath);
return flutterBinFile.getParentFile().getParentFile().getPath();
}
} |
package me.shzylo.mansionazazel.level;
import java.util.Random;
/**
* A randomly generated level
*/
public class RandomLevel extends Level {
public static final Random random = new Random();
public RandomLevel(int width, int height) {
super(width, height);
}
@Override
protected void generateLevel() {
for(int y = 0; y < height; y++) {
for(int x = 0; x < width; x++) {
tiles[x + y * width] = random.nextInt(4);
}
}
}
} |
package com.axelby.podax.ui;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import com.axelby.podax.R;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.Preference;
import android.preference.PreferenceGroup;
import android.preference.PreferenceManager;
import android.preference.PreferenceScreen;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.ListView;
public class PreferenceListFragment extends ListFragment {
private PreferenceManager mPreferenceManager;
/**
* The starting request code given out to preference framework.
*/
private static final int FIRST_REQUEST_CODE = 100;
private static final int MSG_BIND_PREFERENCES = 0;
@SuppressLint("HandlerLeak")
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_BIND_PREFERENCES:
bindPreferences();
break;
}
}
};
private ListView lv;
private int xmlId;
public PreferenceListFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle b) {
postBindPreferences();
return lv;
}
@Override
public void onDestroyView() {
super.onDestroyView();
ViewParent p = lv.getParent();
if (p != null)
((ViewGroup) p).removeView(lv);
}
@Override
public void onCreate(Bundle b) {
super.onCreate(b);
if (b != null)
xmlId = b.getInt("xml");
mPreferenceManager = onCreatePreferenceManager();
lv = (ListView) LayoutInflater.from(getActivity()).inflate(R.layout.preference_list_content, null);
lv.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
addPreferencesFromResource(xmlId);
postBindPreferences();
}
@Override
public void onStop() {
super.onStop();
try {
Method m = PreferenceManager.class.getDeclaredMethod("dispatchActivityStop");
m.setAccessible(true);
m.invoke(mPreferenceManager);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onDestroy() {
super.onDestroy();
lv = null;
try {
Method m = PreferenceManager.class.getDeclaredMethod("dispatchActivityDestroy");
m.setAccessible(true);
m.invoke(mPreferenceManager);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
outState.putInt("xml", xmlId);
super.onSaveInstanceState(outState);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
Method m = PreferenceManager.class.getDeclaredMethod("dispatchActivityResult", int.class, int.class, Intent.class);
m.setAccessible(true);
m.invoke(mPreferenceManager, requestCode, resultCode, data);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Posts a message to bind the preferences to the list view.
* <p>
* Binding late is preferred as any custom preference types created in
* {@link #onCreate(Bundle)} are able to have their views recycled.
*/
private void postBindPreferences() {
if (mHandler.hasMessages(MSG_BIND_PREFERENCES))
return;
mHandler.obtainMessage(MSG_BIND_PREFERENCES).sendToTarget();
}
private void bindPreferences() {
final PreferenceScreen preferenceScreen = getPreferenceScreen();
if (preferenceScreen != null && lv != null) {
preferenceScreen.bind(lv);
}
}
/**
* Creates the {@link PreferenceManager}.
*
* @return The {@link PreferenceManager} used by this activity.
*/
private PreferenceManager onCreatePreferenceManager() {
try {
Constructor<PreferenceManager> c = PreferenceManager.class.getDeclaredConstructor(Activity.class, int.class);
c.setAccessible(true);
PreferenceManager preferenceManager = c.newInstance(this.getActivity(), FIRST_REQUEST_CODE);
return preferenceManager;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* Returns the {@link PreferenceManager} used by this activity.
*
* @return The {@link PreferenceManager}.
*/
public PreferenceManager getPreferenceManager() {
return mPreferenceManager;
}
/**
* Sets the root of the preference hierarchy that this activity is showing.
*
* @param preferenceScreen
* The root {@link PreferenceScreen} of the preference hierarchy.
*/
public void setPreferenceScreen(PreferenceScreen preferenceScreen) {
try {
Method m = PreferenceManager.class.getDeclaredMethod("setPreferences", PreferenceScreen.class);
m.setAccessible(true);
boolean result = (Boolean) m.invoke(mPreferenceManager, preferenceScreen);
if (result && preferenceScreen != null) {
postBindPreferences();
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Gets the root of the preference hierarchy that this activity is showing.
*
* @return The {@link PreferenceScreen} that is the root of the preference
* hierarchy.
*/
public PreferenceScreen getPreferenceScreen() {
try {
Method m = PreferenceManager.class.getDeclaredMethod("getPreferenceScreen");
m.setAccessible(true);
return (PreferenceScreen) m.invoke(mPreferenceManager);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* Adds preferences from activities that match the given {@link Intent}.
*
* @param intent
* The {@link Intent} to query activities.
*/
public void addPreferencesFromIntent(Intent intent) {
throw new RuntimeException("too lazy to include this bs");
}
public PreferenceScreen inflateFromResource(int preferencesResId) {
try {
Method m = PreferenceManager.class.getDeclaredMethod("inflateFromResource", Context.class, int.class, PreferenceScreen.class);
m.setAccessible(true);
return (PreferenceScreen) m.invoke(mPreferenceManager, getActivity(), preferencesResId, getPreferenceScreen());
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* Inflates the given XML resource and adds the preference hierarchy to the
* current preference hierarchy.
*
* @param preferencesResId
* The XML resource ID to inflate.
*/
public void addPreferencesFromResource(int preferencesResId) {
try {
setPreferenceScreen(inflateFromResource(preferencesResId));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Finds a {@link Preference} based on its key.
*
* @param key
* The key of the preference to retrieve.
* @return The {@link Preference} with the key, or null.
* @see PreferenceGroup#findPreference(CharSequence)
*/
public Preference findPreference(CharSequence key) {
if (mPreferenceManager == null) {
return null;
}
return mPreferenceManager.findPreference(key);
}
} |
package br.com.fiap.teste;
import java.time.LocalDate;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import br.com.fiap.commands.NetgifxCommand;
import br.com.fiap.entity.Categoria;
import br.com.fiap.entity.Gif;
import br.com.fiap.entity.Usuario;
public class Main {
static NetgifxCommand netgifxCommand = new NetgifxCommand();
public static void main(String[] args) {
System.out.println("teste");
cargaInicial();
// listarCategorias();
// buscarUsuario();
// buscarGif();
// atualizarFavoritos();
// atualizarGifCategoria();
}
private static void atualizarFavoritos() {
Set<Gif> gifs = new HashSet<Gif>();
Gif gif1 = netgifxCommand.buscarGif(3);
Gif gif2 = netgifxCommand.buscarGif(2);
gifs.add(gif1);
gifs.add(gif2);
Usuario usuario = netgifxCommand.buscarUsuario("everton");
netgifxCommand.atualizarFavoritos(usuario, gifs);
}
private static void atualizarGifCategoria() {
Gif gif = netgifxCommand.buscarGif(2);
List<Categoria> categorias = netgifxCommand.listarCategorias();
netgifxCommand.atualizarGifCategoria(gif, categorias);
}
private static void buscarGif() {
Gif gif1 = netgifxCommand.buscarGif(2);
System.out.println(gif1.getNome());
Gif gif2 = netgifxCommand.buscarGif(3);
System.out.println(gif2.getNome());
}
private static void buscarUsuario() {
Usuario usuario = netgifxCommand.buscarUsuario("everton");
System.out.println(usuario.getApelido());
}
private static void listarCategorias() {
List<Categoria> categorias = netgifxCommand.listarCategorias();
for (Categoria categoria : categorias) {
System.out.println(categoria.getNome());
for (Gif gif : categoria.getGifs()) {
System.out.println(gif.getNome());
}
}
}
private static void cargaInicial() {
criarUsuario();
criarGifs();
criarCategorias();
}
private static void criarUsuario() {
Usuario usuario = new Usuario();
usuario.setNome("Everton");
usuario.setCpf("123");
usuario.setEmail("everton@everton.com");
usuario.setSenha("123");
usuario.setTelefone("123");
usuario.setApelido("everton");
Set<Usuario> usuarios = new HashSet<Usuario>();
usuarios.add(usuario);
//usuario.setGifs(criarGifs(usuarios));
netgifxCommand.cadastrarUsuario(usuario);
}
private static void criarGifs() {
Gif gif1 = new Gif();
gif1.setNome("primeiro");
gif1.setClassificacao(Double.valueOf("3"));
gif1.setCaminho("01");
gif1.setDescricao("primeiro");
gif1.setClassificacaoEtaria("Jovens");
gif1.setDataPublicacao(LocalDate.now());
gif1.setGenero("Nao sei");
gif1.setIdioma("Portugues");
Gif gif2 = new Gif();
gif2.setNome("Segundo");
gif2.setClassificacao(Double.valueOf("3"));
gif2.setCaminho("02");
gif2.setDescricao("segundo");
Gif gif3 = new Gif();
gif3.setNome("terceiro");
gif3.setClassificacao(Double.valueOf("5"));
gif3.setCaminho("03");
gif3.setDescricao("terceiro");
Set<Gif> gifs = new HashSet<Gif>();
gifs.add(gif1);
gifs.add(gif2);
gifs.add(gif3);
// Set<Categoria> categorias= criarCategorias(gifs);
// gif1.setCategorias(categorias);
// gif2.setCategorias(categorias);
// gif3.setCategorias(categorias);
// return gifs;
netgifxCommand.cadastrarGif(gif1);
// netgifxCommand.cadastrarGif(gif2);
// netgifxCommand.cadastrarGif(gif3);
}
private static void criarCategorias() {
Categoria categoria1 = new Categoria();
categoria1.setNome("suspense");
Categoria categoria2 = new Categoria();
categoria2.setNome("novidade");
Set<Categoria> categorias= new HashSet<Categoria>();
categorias.add(categoria1);
categorias.add(categoria2);
netgifxCommand.cadastrarCategoria(categoria1);
netgifxCommand.cadastrarCategoria(categoria2);
}
} |
package com.ecyrd.jspwiki.plugin;
import java.util.Map;
import com.ecyrd.jspwiki.WikiContext;
import com.ecyrd.jspwiki.parser.PluginContent;
/**
* Implements a Plugin interface for the parser stage. Please see PluginManager
* for further documentation.
*
* @author jalkanen
* @since 2.5.30
*/
public interface ParserStagePlugin
{
/**
* Method which is executed during parsing.
*
* @param element The JDOM element which has already been connected to the Document.
* @param context WikiContext, as usual.
* @param params Parsed parameters for the plugin.
*/
public void executeParser( PluginContent element, WikiContext context, Map params );
} |
package com.github.noxan.aves.demo.chat;
import java.io.IOException;
import com.github.noxan.aves.client.ClientAdapter;
import com.github.noxan.aves.client.SocketClient;
public class ChatClient extends ClientAdapter {
public static void main(String[] args) {
SocketClient client = new SocketClient(new ChatClient());
try {
client.connect();
} catch(IOException e) {
e.printStackTrace();
}
}
} |
package edu.umd.cs.findbugs;
import edu.umd.cs.daveho.ba.*;
import java.io.*;
import java.util.*;
import org.apache.bcel.classfile.JavaClass;
/**
* BugReporter to output warnings in Emacs format.
*
* @author David Li
*/
public class EmacsBugReporter extends TextUIBugReporter {
private HashSet<BugInstance> seenAlready = new HashSet<BugInstance>();
public void observeClass(JavaClass javaClass) {
// Don't need to do anything special, since we won't be
// reporting statistics.
}
protected void printBug(BugInstance bugInstance) {
SourceLineAnnotation line =
bugInstance.getPrimarySourceLineAnnotation();
if (line == null) {
outputStream.print(bugInstance.getMessage());
} else {
SourceFinder sourceFinder = AnalysisContext.instance().getSourceFinder();
String fullPath;
String pkgName = line.getPackageName();
try {
fullPath = sourceFinder.findSourceFile(pkgName, line.getSourceFile()).getFullFileName();
} catch (IOException e) {
if (pkgName.equals(""))
fullPath = line.getSourceFile();
else
fullPath = pkgName.replace('.', '/') + "/" + line.getSourceFile();
}
outputStream.print(fullPath + ":"
+ line.getStartLine() + ":"
+ line.getEndLine() + " "
+ bugInstance.getMessage());
}
switch(bugInstance.getPriority()) {
case Detector.LOW_PRIORITY:
outputStream.print(" (L) ");
break;
case Detector.NORMAL_PRIORITY:
outputStream.print(" (M) ");
break;
case Detector.HIGH_PRIORITY:
outputStream.print(" (H) ");
break;
}
outputStream.println();
}
protected void doReportBug(BugInstance bugInstance) {
if (seenAlready.add(bugInstance)) {
printBug(bugInstance);
notifyObservers(bugInstance);
}
}
public void finish() {
outputStream.close();
}
}
/*
* Local Variables:
* eval: (c-set-style "bsd")
* End:
*/ |
package edu.umd.cs.findbugs;
import edu.umd.cs.pugh.visitclass.BetterVisitor;
import edu.umd.cs.pugh.visitclass.DismantleBytecode;
/**
* A BugAnnotation specifying a particular method in a particular class.
*
* @see BugAnnotation
* @author David Hovemeyer
*/
public class MethodAnnotation extends PackageMemberAnnotation {
private static final boolean UGLY_METHODS = Boolean.getBoolean("ma.ugly");
private String methodName;
private String methodSig;
private String fullMethod;
/**
* Constructor.
* @param className the name of the class containing the method
* @param methodName the name of the method
* @param methodSig the Java type signature of the method
*/
public MethodAnnotation(String className, String methodName, String methodSig) {
super(className);
this.methodName = methodName;
this.methodSig = methodSig;
fullMethod = null;
}
/**
* Constructor.
* The method annotation is initialized using the method the given
* visitor is currently visiting.
* @param visitor the BetterVisitor
*/
public MethodAnnotation(BetterVisitor visitor) {
super(visitor.getBetterClassName());
this.methodName = visitor.getMethodName();
this.methodSig = visitor.getMethodSig();
}
/** Get the method name. */
public String getMethodName() { return methodName; }
/** Get the method type signature. */
public String getMethodSignature() { return methodSig; }
public void accept(BugAnnotationVisitor visitor) {
visitor.visitMethodAnnotation(this);
}
protected String formatPackageMember(String key) {
if (key.equals(""))
return UGLY_METHODS ? getUglyMethod() : getFullMethod();
else if (key.equals("shortMethod"))
return className + "." + methodName + "()";
else
throw new IllegalArgumentException("unknown key " + key);
}
/**
* Get the "full" method name.
* This is a format which looks sort of like a method signature
* that would appear in Java source code.
*/
public String getFullMethod() {
if (fullMethod == null) {
// Convert to "nice" representation
SignatureConverter converter = new SignatureConverter(methodSig);
String pkgName = getPackageName();
StringBuffer args = new StringBuffer();
if (converter.getFirst() != '(')
throw new IllegalStateException("bad method signature " + methodSig);
converter.skip();
while (converter.getFirst() != ')') {
if (args.length() > 0)
args.append(',');
args.append(shorten(pkgName, converter.parseNext()));
}
converter.skip();
// NOTE: we omit the return type.
// It is not needed to disambiguate the method,
// and would just clutter the output.
// Actually, GJ implements covariant return types at the source level,
// so perhaps it really is necessary.
StringBuffer result = new StringBuffer();
result.append(className);
result.append('.');
result.append(methodName);
result.append('(');
result.append(args);
result.append(')');
fullMethod = result.toString();
}
return fullMethod;
}
private String getUglyMethod() {
return className + "." + methodName + " : " + methodSig.replace('/', '.');
}
public int hashCode() {
return className.hashCode() + methodName.hashCode() + methodSig.hashCode();
}
public boolean equals(Object o) {
if (!(o instanceof MethodAnnotation))
return false;
MethodAnnotation other = (MethodAnnotation) o;
return className.equals(other.className)
&& methodName.equals(other.methodName)
&& methodSig.equals(other.methodSig);
}
public int compareTo(BugAnnotation o) {
if (!(o instanceof MethodAnnotation)) // BugAnnotations must be Comparable with any type of BugAnnotation
return this.getClass().getName().compareTo(o.getClass().getName());
MethodAnnotation other = (MethodAnnotation) o;
int cmp;
cmp = className.compareTo(other.className);
if (cmp != 0)
return cmp;
cmp = methodName.compareTo(other.methodName);
if (cmp != 0)
return cmp;
return methodSig.compareTo(other.methodSig);
}
/*
public static void main(String[] argv) {
MethodAnnotation m = new MethodAnnotation("edu.umd.cs.daveho.ba.CFG", "fooIterator",
"(I[[BLjava/util/Iterator;Ljava/lang/String;)Ledu/umd/cs/daveho/ba/BasicBlock;");
System.out.println(m.toString());
}
*/
}
// vim:ts=4 |
//FILE: AcqControlDlg.java
//PROJECT: Micro-Manager
//SUBSYSTEM: mmstudio
// This file is distributed in the hope that it will be useful,
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES.
// CVS: $Id$
package org.micromanager;
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Vector;
import java.util.prefs.BackingStoreException;
import java.util.prefs.Preferences;
import javax.imageio.ImageIO;
import javax.swing.AbstractCellEditor;
import javax.swing.BorderFactory;
import javax.swing.DefaultComboBoxModel;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSpinner;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JToolTip;
import javax.swing.SpinnerModel;
import javax.swing.SpinnerNumberModel;
import javax.swing.WindowConstants;
import javax.swing.border.Border;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;
import org.micromanager.api.AcquisitionEngine;
import org.micromanager.api.DeviceControlGUI;
import org.micromanager.utils.AcqOrderMode;
import org.micromanager.utils.ChannelSpec;
import org.micromanager.utils.ColorEditor;
import org.micromanager.utils.ColorRenderer;
import org.micromanager.utils.ContrastSettings;
import org.micromanager.utils.DisplayMode;
import org.micromanager.utils.FileDialogs.FileType;
import org.micromanager.utils.GUIColors;
import org.micromanager.utils.MMException;
import org.micromanager.utils.NumberUtils;
import org.micromanager.utils.TooltipTextMaker;
import com.swtdesigner.SwingResourceManager;
import org.micromanager.acquisition.ComponentTitledBorder;
import org.micromanager.utils.FileDialogs;
import org.micromanager.utils.ReportingUtils;
/**
* Time-lapse, channel and z-stack acquisition setup dialog.
* This dialog specifies all parameters for the Image5D acquisition.
*
*/
public class AcqControlDlg extends JDialog implements PropertyChangeListener {
private static final long serialVersionUID = 1L;
protected JButton listButton_;
private JButton afButton_;
private JSpinner afSkipInterval_;
private JComboBox acqOrderBox_;
public static final String NEW_ACQFILE_NAME = "MMAcquistion.xml";
public static final String ACQ_SETTINGS_NODE = "AcquistionSettings";
public static final String COLOR_SETTINGS_NODE = "ColorSettings";
private JComboBox channelGroupCombo_;
private JTextArea commentTextArea_;
private JComboBox zValCombo_;
private JTextField nameField_;
private JTextField rootField_;
private JTextArea summaryTextArea_;
private JComboBox timeUnitCombo_;
private JFormattedTextField interval_;
private JFormattedTextField zStep_;
private JFormattedTextField zTop_;
private JFormattedTextField zBottom_;
private AcquisitionEngine acqEng_;
private JScrollPane channelTablePane_;
private JTable channelTable_;
private JSpinner numFrames_;
private ChannelTableModel model_;
private Preferences prefs_;
private Preferences acqPrefs_;
private Preferences colorPrefs_;
private File acqFile_;
private String acqDir_;
private int zVals_ = 0;
private JButton setBottomButton_;
private JButton setTopButton_;
protected JComboBox displayModeCombo_;
private DeviceControlGUI gui_;
private GUIColors guiColors_;
private NumberFormat numberFormat_;
private JLabel namePrefixLabel_;
private JLabel rootLabel_;
private JLabel commentLabel_;
private JButton browseRootButton_;
private JLabel displayMode_;
private JCheckBox stackKeepShutterOpenCheckBox_;
private JCheckBox chanKeepShutterOpenCheckBox_;
private AcqOrderMode[] acqOrderModes_;
// persistent properties (app settings)
private static final String ACQ_CONTROL_X = "acq_x";
private static final String ACQ_CONTROL_Y = "acq_y";
private static final String ACQ_FILE_DIR = "dir";
private static final String ACQ_INTERVAL = "acqInterval";
private static final String ACQ_TIME_UNIT = "acqTimeInit";
private static final String ACQ_ZBOTTOM = "acqZbottom";
private static final String ACQ_ZTOP = "acqZtop";
private static final String ACQ_ZSTEP = "acqZstep";
private static final String ACQ_ENABLE_SLICE_SETTINGS = "enableSliceSettings";
private static final String ACQ_ENABLE_MULTI_POSITION = "enableMultiPosition";
private static final String ACQ_ENABLE_MULTI_FRAME = "enableMultiFrame";
private static final String ACQ_ENABLE_MULTI_CHANNEL = "enableMultiChannels";
private static final String ACQ_ORDER_MODE = "acqOrderMode";
private static final String ACQ_NUMFRAMES = "acqNumframes";
private static final String ACQ_CHANNEL_GROUP = "acqChannelGroup";
private static final String ACQ_NUM_CHANNELS = "acqNumchannels";
private static final String ACQ_CHANNELS_KEEP_SHUTTER_OPEN = "acqChannelsKeepShutterOpen";
private static final String ACQ_STACK_KEEP_SHUTTER_OPEN = "acqStackKeepShutterOpen";
private static final String CHANNEL_NAME_PREFIX = "acqChannelName";
private static final String CHANNEL_USE_PREFIX = "acqChannelUse";
private static final String CHANNEL_EXPOSURE_PREFIX = "acqChannelExp";
private static final String CHANNEL_ZOFFSET_PREFIX = "acqChannelZOffset";
private static final String CHANNEL_DOZSTACK_PREFIX = "acqChannelDoZStack";
private static final String CHANNEL_CONTRAST8_MIN_PREFIX = "acqChannel8ContrastMin";
private static final String CHANNEL_CONTRAST8_MAX_PREFIX = "acqChannel8ContrastMax";
private static final String CHANNEL_CONTRAST16_MIN_PREFIX = "acqChannel16ContrastMin";
private static final String CHANNEL_CONTRAST16_MAX_PREFIX = "acqChannel16ContrastMax";
private static final String CHANNEL_COLOR_R_PREFIX = "acqChannelColorR";
private static final String CHANNEL_COLOR_G_PREFIX = "acqChannelColorG";
private static final String CHANNEL_COLOR_B_PREFIX = "acqChannelColorB";
private static final String CHANNEL_SKIP_PREFIX = "acqSkip";
private static final String ACQ_Z_VALUES = "acqZValues";
private static final String ACQ_DIR_NAME = "acqDirName";
private static final String ACQ_ROOT_NAME = "acqRootName";
private static final String ACQ_SAVE_FILES = "acqSaveFiles";
private static final String ACQ_DISPLAY_MODE = "acqDisplayMode";
private static final String ACQ_AF_ENABLE = "autofocus_enabled";
private static final String ACQ_AF_SKIP_INTERVAL = "autofocusSkipInterval";
private static final String ACQ_COLUMN_WIDTH = "column_width";
private static final String ACQ_COLUMN_ORDER = "column_order";
private static final int ACQ_DEFAULT_COLUMN_WIDTH = 77;
private static final FileType ACQ_SETTINGS_FILE = new FileType("ACQ_SETTINGS_FILE", "Acquisition settings",
System.getProperty("user.home") + "/AcqSettings.xml",
true, "xml");
private int columnWidth_[];
private int columnOrder_[];
private CheckBoxPanel framesPanel_;
private CheckBoxPanel channelsPanel_;
private CheckBoxPanel slicesPanel_;
protected CheckBoxPanel positionsPanel_;
private JPanel acquisitionOrderPanel_;
private CheckBoxPanel afPanel_;
private JPanel summaryPanel_;
private CheckBoxPanel savePanel_;
private Border dayBorder_;
private Border nightBorder_;
private Vector<JPanel> panelList_;
private boolean disableGUItoSettings_ = false;
/**
* Data representation class for the channels list
*/
public class ChannelTableModel extends AbstractTableModel implements TableModelListener {
private static final long serialVersionUID = 3290621191844925827L;
private ArrayList<ChannelSpec> channels_;
private AcquisitionEngine acqEng_;
public final String[] COLUMN_NAMES = new String[]{
"Use?",
"Configuration",
"Exposure",
"Z-offset",
"Z-stack",
"Skip Fr.",
"Color"
};
private final String[] TOOLTIPS = new String[]{
"Toggle channel/group on/off",
"Choose preset property values for channel or group",
"Set exposure time in ms",
TooltipTextMaker.addHTMLBreaksForTooltip("Set a Z offset specific to this channel/group (the main " +
"object in one of the channels/groups is in a different focal plane from the other channels/groups"),
"Collect images in multiple Z planes?",
TooltipTextMaker.addHTMLBreaksForTooltip("Setting 'Skip Frame' to a number other than " +
"0 will cause the acquisition to 'skip' taking images in " +
"that channel (after taking the first image) for the indicated " +
"number of time intervals. The 5D-Image Viewer will 'fill in' these skipped " +
"frames with the previous image. In some situations it may be " +
"desirable to acquire certain channels at lower sampling rates, " +
"to reduce photo-toxicity and to save disk space. "),
"Select channel/group color for display in viewer"};
public String getToolTipText(int columnIndex) {
return TOOLTIPS[columnIndex];
}
public ChannelTableModel(AcquisitionEngine eng) {
acqEng_ = eng;
addTableModelListener(this);
}
public int getRowCount() {
if (channels_ == null) {
return 0;
} else {
return channels_.size();
}
}
public int getColumnCount() {
return COLUMN_NAMES.length;
}
@Override
public String getColumnName(int columnIndex) {
return COLUMN_NAMES[columnIndex];
}
public Object getValueAt(int rowIndex, int columnIndex) {
if (channels_ != null && rowIndex < channels_.size()) {
if (columnIndex == 0) {
return new Boolean(channels_.get(rowIndex).useChannel_);
} else if (columnIndex == 1) {
return channels_.get(rowIndex).config_;
} else if (columnIndex == 2) {
return new Double(channels_.get(rowIndex).exposure_);
} else if (columnIndex == 3) {
return new Double(channels_.get(rowIndex).zOffset_);
} else if (columnIndex == 4) {
return new Boolean(channels_.get(rowIndex).doZStack_);
} else if (columnIndex == 5) {
return new Integer(channels_.get(rowIndex).skipFactorFrame_);
} else if (columnIndex == 6) {
return channels_.get(rowIndex).color_;
}
}
return null;
}
@Override
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
@Override
public void setValueAt(Object value, int row, int col) {
if (row >= channels_.size() || value == null) {
return;
}
ChannelSpec channel = channels_.get(row);
if (col == 0) {
channel.useChannel_ = ((Boolean) value).booleanValue();
} else if (col == 1) {
channel.config_ = value.toString();
} else if (col == 2) {
channel.exposure_ = ((Double) value).doubleValue();
} else if (col == 3) {
channel.zOffset_ = ((Double) value).doubleValue();
} else if (col == 4) {
channel.doZStack_ = (Boolean) value;
} else if (col == 5) {
channel.skipFactorFrame_ = ((Integer) value).intValue();
} else if (col == 6) {
channel.color_ = (Color) value;
}
acqEng_.setChannel(row, channel);
repaint();
}
public boolean isCellEditable(int nRow, int nCol) {
if (nCol == 4) {
if (!acqEng_.isZSliceSettingEnabled()) {
return false;
}
}
return true;
}
/*
* Catched events thrown by the ColorEditor
* Will write the new color into the Color Prefs
*/
public void tableChanged(TableModelEvent e) {
int row = e.getFirstRow();
if (row < 0) {
return;
}
int col = e.getColumn();
if (col < 0) {
return;
}
ChannelSpec channel = channels_.get(row);
TableModel model = (TableModel) e.getSource();
if (col == 6) {
Color color = (Color) model.getValueAt(row, col);
colorPrefs_.putInt("Color_" + acqEng_.getChannelGroup() + "_" + channel.config_, color.getRGB());
}
}
public void setChannels(ArrayList<ChannelSpec> ch) {
channels_ = ch;
}
public ArrayList<ChannelSpec> getChannels() {
return channels_;
}
public void addNewChannel() {
ChannelSpec channel = new ChannelSpec();
channel.config_ = "";
if (acqEng_.getChannelConfigs().length > 0) {
for (String config : acqEng_.getChannelConfigs()) {
boolean unique = true;
for (ChannelSpec chan : channels_) {
if (config.contentEquals(chan.config_)) {
unique = false;
}
}
if (unique) {
channel.config_ = config;
break;
}
}
if (channel.config_.length() == 0) {
ReportingUtils.showMessage("No more channels are available\nin this channel group.");
} else {
channel.color_ = new Color(colorPrefs_.getInt("Color_" + acqEng_.getChannelGroup() + "_" + channel.config_, Color.white.getRGB()));
channels_.add(channel);
}
}
}
public void removeChannel(int chIndex) {
if (chIndex >= 0 && chIndex < channels_.size()) {
channels_.remove(chIndex);
}
}
public int rowDown(int rowIdx) {
if (rowIdx >= 0 && rowIdx < channels_.size() - 1) {
ChannelSpec channel = channels_.get(rowIdx);
channels_.remove(rowIdx);
channels_.add(rowIdx + 1, channel);
return rowIdx + 1;
}
return rowIdx;
}
public int rowUp(int rowIdx) {
if (rowIdx >= 1 && rowIdx < channels_.size()) {
ChannelSpec channel = channels_.get(rowIdx);
channels_.remove(rowIdx);
channels_.add(rowIdx - 1, channel);
return rowIdx - 1;
}
return rowIdx;
}
public String[] getAvailableChannels() {
return acqEng_.getChannelConfigs();
}
/**
* Remove all channels from the list which are not compatible with
* the current acquisition settings
*/
public void cleanUpConfigurationList() {
String config;
for (Iterator<ChannelSpec> it = channels_.iterator(); it.hasNext();) {
config = it.next().config_;
if (!config.contentEquals("") && !acqEng_.isConfigAvailable(config)) {
it.remove();
}
}
fireTableStructureChanged();
}
/**
* reports if the same channel name is used twice
*/
public boolean duplicateChannels() {
for (int i = 0; i < channels_.size() - 1; i++) {
for (int j = i + 1; j < channels_.size(); j++) {
if (channels_.get(i).config_.equals(channels_.get(j).config_)) {
return true;
}
}
}
return false;
}
}
/**
* Cell editing using either JTextField or JComboBox depending on whether the
* property enforces a set of allowed values.
*/
public class ChannelCellEditor extends AbstractCellEditor implements TableCellEditor {
private static final long serialVersionUID = -8374637422965302637L;
JTextField text_ = new JTextField();
JComboBox combo_ = new JComboBox();
JCheckBox checkBox_ = new JCheckBox();
JLabel colorLabel_ = new JLabel();
int editCol_ = -1;
int editRow_ = -1;
ChannelSpec channel_ = null;
// This method is called when a cell value is edited by the user.
public Component getTableCellEditorComponent(JTable table, Object value,
boolean isSelected, int rowIndex, int colIndex) {
if (isSelected) {
// cell (and perhaps other cells) are selected
}
ChannelTableModel model = (ChannelTableModel) table.getModel();
ArrayList<ChannelSpec> channels = model.getChannels();
final ChannelSpec channel = channels.get(rowIndex);
channel_ = channel;
colIndex = table.convertColumnIndexToModel(colIndex);
// Configure the component with the specified value
editRow_ = rowIndex;
editCol_ = colIndex;
if (colIndex == 0) {
checkBox_.setSelected((Boolean) value);
return checkBox_;
} else if (colIndex == 2 || colIndex == 3) {
// exposure and z offset
text_.setText(((Double) value).toString());
return text_;
} else if (colIndex == 4) {
checkBox_.setSelected((Boolean) value);
return checkBox_;
} else if (colIndex == 5) {
// skip
text_.setText(((Integer) value).toString());
return text_;
} else if (colIndex == 1) {
// channel
combo_.removeAllItems();
// remove old listeners
ActionListener[] l = combo_.getActionListeners();
for (int i = 0; i < l.length; i++) {
combo_.removeActionListener(l[i]);
}
combo_.removeAllItems();
String configs[] = model.getAvailableChannels();
for (int i = 0; i < configs.length; i++) {
combo_.addItem(configs[i]);
}
combo_.setSelectedItem(channel.config_);
channel.color_ = new Color(colorPrefs_.getInt("Color_" + acqEng_.getChannelGroup() + "_" + channel.config_, Color.white.getRGB()));
// end editing on selection change
combo_.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
channel.color_ = new Color(colorPrefs_.getInt("Color_" + acqEng_.getChannelGroup() + "_" + channel.config_, Color.white.getRGB()));
fireEditingStopped();
}
});
// Return the configured component
return combo_;
} else {
// ColorEditor takes care of this
return colorLabel_;
}
}
// This method is called when editing is completed.
// It must return the new value to be stored in the cell.
public Object getCellEditorValue() {
// TODO: if content of column does not match type we get an exception
try {
if (editCol_ == 0) {
return checkBox_.isSelected();
} else if (editCol_ == 1) {
// As a side effect, change to the color of the new channel
channel_.color_ = new Color(colorPrefs_.getInt("Color_" + acqEng_.getChannelGroup() + "_" + combo_.getSelectedItem(), Color.white.getRGB()));
return combo_.getSelectedItem();
} else if (editCol_ == 2 || editCol_ == 3) {
return new Double(NumberUtils.displayStringToDouble(text_.getText()));
} else if (editCol_ == 4) {
return new Boolean(checkBox_.isSelected());
} else if (editCol_ == 5) {
return new Integer(NumberUtils.displayStringToInt(text_.getText()));
} else if (editCol_ == 6) {
Color c = colorLabel_.getBackground();
return c;
} else {
String err = new String("Internal error: unknown column");
return err;
}
} catch (ParseException p) {
ReportingUtils.showError(p);
}
String err = new String("Internal error: unknown column");
return err;
}
}
/**
* Renderer class for the channel table.
*/
public class ChannelCellRenderer extends JLabel implements TableCellRenderer {
private static final long serialVersionUID = -4328340719459382679L;
private AcquisitionEngine acqEng_;
// This method is called each time a cell in a column
// using this renderer needs to be rendered.
public ChannelCellRenderer(AcquisitionEngine acqEng) {
super();
acqEng_ = acqEng;
}
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int rowIndex, int colIndex) {
ChannelTableModel model = (ChannelTableModel) table.getModel();
ArrayList<ChannelSpec> channels = model.getChannels();
ChannelSpec channel = channels.get(rowIndex);
this.setEnabled(table.isEnabled() /*&&
((Boolean) model.getValueAt(rowIndex, 0) || colIndex == 0)*/);
if (hasFocus) {
// this cell is the anchor and the table has the focus
}
colIndex = table.convertColumnIndexToModel(colIndex);
setOpaque(false);
if (colIndex == 0) {
JCheckBox check = new JCheckBox("", channel.useChannel_);
check.setEnabled(table.isEnabled());
check.setOpaque(true);
if (isSelected) {
check.setBackground(table.getSelectionBackground());
check.setOpaque(true);
} else {
check.setOpaque(false);
check.setBackground(table.getBackground());
}
return check;
} else if (colIndex == 1) {
setText(channel.config_);
} else if (colIndex == 2) {
setText(NumberUtils.doubleToDisplayString(channel.exposure_));
} else if (colIndex == 3) {
setText(NumberUtils.doubleToDisplayString(channel.zOffset_));
} else if (colIndex == 4) {
JCheckBox check = new JCheckBox("", channel.doZStack_);
check.setEnabled(acqEng_.isZSliceSettingEnabled() && table.isEnabled());
if (isSelected) {
check.setBackground(table.getSelectionBackground());
check.setOpaque(true);
} else {
check.setOpaque(false);
check.setBackground(table.getBackground());
}
return check;
} else if (colIndex == 5) {
setText(Integer.toString(channel.skipFactorFrame_));
} else if (colIndex == 6) {
setText("");
setBackground(channel.color_);
setOpaque(true);
}
if (isSelected) {
setBackground(table.getSelectionBackground());
setOpaque(true);
} else {
setOpaque(false);
setBackground(table.getBackground());
}
// Since the renderer is a component, return itself
return this;
}
// The following methods override the defaults for performance reasons
@Override
public void validate() {
}
@Override
public void revalidate() {
}
@Override
protected void firePropertyChange(String propertyName, Object oldValue, Object newValue) {
}
@Override
public void firePropertyChange(String propertyName, boolean oldValue, boolean newValue) {
}
}
public void createChannelTable()
{
model_ = new ChannelTableModel(acqEng_);
channelTable_ = new JTable() {
protected JTableHeader createDefaultTableHeader() {
return new JTableHeader(columnModel) {
public String getToolTipText(MouseEvent e) {
String tip = null;
java.awt.Point p = e.getPoint();
int index = columnModel.getColumnIndexAtX(p.x);
int realIndex = columnModel.getColumn(index).getModelIndex();
return model_.getToolTipText(realIndex);
} }; }};
channelTable_.setFont(new Font("Dialog", Font.PLAIN, 10));
channelTable_.setAutoCreateColumnsFromModel(false);
channelTable_.setModel(model_);
model_.setChannels(acqEng_.getChannels());
ChannelCellEditor cellEditor = new ChannelCellEditor();
ChannelCellRenderer cellRenderer = new ChannelCellRenderer(acqEng_);
channelTable_.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
for (int k = 0; k < model_.getColumnCount(); k++) {
int colIndex = search(columnOrder_, k);
if (colIndex < 0) {
colIndex = k;
}
if (colIndex == model_.getColumnCount() - 1) {
ColorRenderer cr = new ColorRenderer(true);
ColorEditor ce = new ColorEditor(model_, model_.getColumnCount() - 1);
TableColumn column = new TableColumn(model_.getColumnCount() - 1, 200, cr, ce);
column.setPreferredWidth(columnWidth_[model_.getColumnCount() - 1]);
channelTable_.addColumn(column);
} else {
TableColumn column = new TableColumn(colIndex, 200, cellRenderer, cellEditor);
column.setPreferredWidth(columnWidth_[colIndex]);
channelTable_.addColumn(column);
}
}
channelTablePane_.setViewportView(channelTable_);
}
public JPanel createPanel(String text, int left, int top, int right, int bottom) {
return createPanel(text, left, top, right, bottom, false);
}
public JPanel createPanel(String text, int left, int top, int right, int bottom, boolean checkBox) {
ComponentTitledPanel thePanel;
if (checkBox) {
thePanel = new CheckBoxPanel(text);
} else {
thePanel = new LabelPanel(text);
}
thePanel.setTitleFont(new Font("Dialog", Font.BOLD, 12));
panelList_.add(thePanel);
thePanel.setBounds(left, top, right - left, bottom - top);
dayBorder_ = BorderFactory.createEtchedBorder();
nightBorder_ = BorderFactory.createEtchedBorder(Color.gray, Color.darkGray);
//updatePanelBorder(thePanel);
thePanel.setLayout(null);
getContentPane().add(thePanel);
return thePanel;
}
public void updatePanelBorder(JPanel thePanel) {
TitledBorder border = (TitledBorder) thePanel.getBorder();
if (gui_.getBackgroundStyle().contentEquals("Day")) {
border.setBorder(dayBorder_);
} else {
border.setBorder(nightBorder_);
}
}
public void createEmptyPanels() {
panelList_ = new Vector<JPanel>();
framesPanel_ = (CheckBoxPanel) createPanel("Time points", 5, 5, 220, 91, true); // (text, left, top, right, bottom)
positionsPanel_ = (CheckBoxPanel) createPanel("Multiple positions (XY)", 5, 93, 220, 154, true);
slicesPanel_ = (CheckBoxPanel) createPanel("Z-stacks (slices)", 5, 156, 220, 306, true);
acquisitionOrderPanel_ = createPanel("Acquisition order", 226, 5, 427, 63);
summaryPanel_ = createPanel("Summary", 226, 152, 510, 306);
afPanel_ = (CheckBoxPanel) createPanel("Autofocus", 226, 65, 427, 150, true);
channelsPanel_ = (CheckBoxPanel) createPanel("Channels", 5, 308, 510, 451, true);
savePanel_ = (CheckBoxPanel) createPanel("Save images", 5, 453, 510, 620, true);
}
private void createToolTips() {
framesPanel_.setToolTipText("Acquire images over a repeating time interval");
positionsPanel_.setToolTipText("Acquire images from a series of positions in the XY plane");
slicesPanel_.setToolTipText("Acquire images from a series of Z positions");
String imageName = this.getClass().getResource("icons/acq_order_figure.png").toString();
String acqOrderToolTip =
"<html>Lets you select the order of image acquisition when some combination of multiple dimensions<br>" +
"(i.e. time points, XY positions, Z-slices, or Channels) is selected. During image acquisition, the<br>" +
"values of each dimension are iterated in the reverse order of their listing here. \"Time\" and \"Position\" <br>" +
"always precede \"Slice\" and \"Channel\" <br><br>" +
"For example, suppose there are are two time points, two XY positions, and two Z slices, and Acquisition<br>" +
"order is set to \"Time, Position, Slice\". The microscope will acquire images in the following order: <br> " +
"Time point 1, XY position 1, Z-slice 1 <br>" +
"Time point 1, XY position 1, Z-slice 2 <br>" +
"Time point 1, XY position 2, Z-slice 1 <br>" +
"Time point 1, XY position 2, Z-slice 2 <br>" +
"Time point 2, XY position 1, Z-slice 1 <br>" +
"etc. <br><br>" +
"<img src="+imageName+"></html>";
acquisitionOrderPanel_.setToolTipText(acqOrderToolTip);
acqOrderBox_.setToolTipText(acqOrderToolTip);
afPanel_.setToolTipText("Toggle autofocus on/off");
channelsPanel_.setToolTipText("Lets you acquire images in multiple channels (groups of " +
"properties with multiple preset values" );
savePanel_.setToolTipText(TooltipTextMaker.addHTMLBreaksForTooltip("If the Save images option is selected, " +
"images will be saved to disk continuously during the acquisition. If this option is not selected, images " +
"are accumulated only in the 5D-Image window, and once the acquisition is finished, image data can be saved" +
" to disk. However, saving files automatically during acquisition secures the acquired data against an " +
"unexpected computer failure or accidental closing of image window. Even when saving to disk, some of the" +
" acquired images are still kept in memory, facilitating fast playback. If such behavior is not desired, " +
"check the 'Conserve RAM' option (Tools | Options)" ));
}
/**
* Acquisition control dialog box.
* Specification of all parameters required for the acquisition.
* @param acqEng - acquisition engine
* @param prefs - application preferences node
*/
public AcqControlDlg(AcquisitionEngine acqEng, Preferences prefs, DeviceControlGUI gui) {
super();
prefs_ = prefs;
gui_ = gui;
guiColors_ = new GUIColors();
Preferences root = Preferences.userNodeForPackage(this.getClass());
acqPrefs_ = root.node(root.absolutePath() + "/" + ACQ_SETTINGS_NODE);
colorPrefs_ = root.node(root.absolutePath() + "/" + COLOR_SETTINGS_NODE);
setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
numberFormat_ = NumberFormat.getNumberInstance();
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(final WindowEvent e) {
close();
}
});
acqEng_ = acqEng;
getContentPane().setLayout(null);
setResizable(false);
setTitle("Multi-dimensional Acquisition");
setBackground(guiColors_.background.get(gui_.getBackgroundStyle()));
createEmptyPanels();
// Frames panel
framesPanel_.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
applySettings();
}
});
final JLabel numberLabel = new JLabel();
numberLabel.setFont(new Font("Arial", Font.PLAIN, 10));
numberLabel.setText("Number");
framesPanel_.add(numberLabel);
numberLabel.setBounds(15, 25, 54, 24);
SpinnerModel sModel = new SpinnerNumberModel(
new Integer(1),
new Integer(1),
null,
new Integer(1));
numFrames_ = new JSpinner(sModel);
((JSpinner.DefaultEditor) numFrames_.getEditor()).getTextField().setFont(new Font("Arial", Font.PLAIN, 10));
//numFrames_.setValue((int) acqEng_.getNumFrames());
framesPanel_.add(numFrames_);
numFrames_.setBounds(60, 25, 70, 24);
numFrames_.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
applySettings();
}
});
final JLabel intervalLabel = new JLabel();
intervalLabel.setFont(new Font("Arial", Font.PLAIN, 10));
intervalLabel.setText("Interval");
intervalLabel.setToolTipText("Interval between successive time points. Setting an interval" +
"of 0 will cause micromanager to acquire 'burts' of images as fast as possible");
framesPanel_.add(intervalLabel);
intervalLabel.setBounds(15, 52, 43, 24);
interval_ = new JFormattedTextField(numberFormat_);
interval_.setFont(new Font("Arial", Font.PLAIN, 10));
interval_.setValue(new Double(1.0));
interval_.addPropertyChangeListener("value", this);
framesPanel_.add(interval_);
interval_.setBounds(60, 52, 55, 24);
timeUnitCombo_ = new JComboBox();
timeUnitCombo_.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
//interval_.setText(NumberUtils.doubleToDisplayString(convertMsToTime(acqEng_.getFrameIntervalMs(), timeUnitCombo_.getSelectedIndex())));
}
});
timeUnitCombo_.setModel(new DefaultComboBoxModel(new String[]{"ms", "s", "min"}));
timeUnitCombo_.setFont(new Font("Arial", Font.PLAIN, 10));
timeUnitCombo_.setBounds(120, 52, 67, 24);
framesPanel_.add(timeUnitCombo_);
// Positions (XY) panel
listButton_ = new JButton();
listButton_.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
gui_.showXYPositionList();
}
});
listButton_.setToolTipText("Open XY list dialog");
listButton_.setIcon(SwingResourceManager.getIcon(AcqControlDlg.class, "icons/application_view_list.png"));
listButton_.setText("Edit position list...");
listButton_.setMargin(new Insets(2, 5, 2, 5));
listButton_.setFont(new Font("Dialog", Font.PLAIN, 10));
listButton_.setBounds(42, 25, 136, 26);
positionsPanel_.add(listButton_);
// Slices panel
slicesPanel_.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
// enable disable all related contrtols
applySettings();
}
});
final JLabel zbottomLabel = new JLabel();
zbottomLabel.setFont(new Font("Arial", Font.PLAIN, 10));
zbottomLabel.setText("Z-start [um]");
zbottomLabel.setBounds(30, 30, 69, 15);
slicesPanel_.add(zbottomLabel);
zBottom_ = new JFormattedTextField(numberFormat_);
zBottom_.setFont(new Font("Arial", Font.PLAIN, 10));
zBottom_.setBounds(95, 27, 54, 21);
zBottom_.setValue(new Double(1.0));
zBottom_.addPropertyChangeListener("value", this);
slicesPanel_.add(zBottom_);
setBottomButton_ = new JButton();
setBottomButton_.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
setBottomPosition();
}
});
setBottomButton_.setMargin(new Insets(-5, -5, -5, -5));
setBottomButton_.setFont(new Font("", Font.PLAIN, 10));
setBottomButton_.setText("Set");
setBottomButton_.setToolTipText("Set value as microscope's current Z position");
setBottomButton_.setBounds(150, 27, 50, 22);
slicesPanel_.add(setBottomButton_);
final JLabel ztopLabel = new JLabel();
ztopLabel.setFont(new Font("Arial", Font.PLAIN, 10));
ztopLabel.setText("Z-end [um]");
ztopLabel.setBounds(30, 53, 69, 15);
slicesPanel_.add(ztopLabel);
zTop_ = new JFormattedTextField(numberFormat_);
zTop_.setFont(new Font("Arial", Font.PLAIN, 10));
zTop_.setBounds(95, 50, 54, 21);
zTop_.setValue(new Double(1.0));
zTop_.addPropertyChangeListener("value", this);
slicesPanel_.add(zTop_);
setTopButton_ = new JButton();
setTopButton_.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
setTopPosition();
}
});
setTopButton_.setMargin(new Insets(-5, -5, -5, -5));
setTopButton_.setFont(new Font("Dialog", Font.PLAIN, 10));
setTopButton_.setText("Set");
setTopButton_.setToolTipText("Set value as microscope's current Z position");
setTopButton_.setBounds(150, 50, 50, 22);
slicesPanel_.add(setTopButton_);
final JLabel zstepLabel = new JLabel();
zstepLabel.setFont(new Font("Arial", Font.PLAIN, 10));
zstepLabel.setText("Z-step [um]");
zstepLabel.setBounds(30, 76, 69, 15);
slicesPanel_.add(zstepLabel);
zStep_ = new JFormattedTextField(numberFormat_);
zStep_.setFont(new Font("Arial", Font.PLAIN, 10));
zStep_.setBounds(95, 73, 54, 21);
zStep_.setValue(new Double(1.0));
zStep_.addPropertyChangeListener("value", this);
slicesPanel_.add(zStep_);
zValCombo_ = new JComboBox();
zValCombo_.setFont(new Font("Arial", Font.PLAIN, 10));
zValCombo_.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
zValCalcChanged();
}
});
zValCombo_.setModel(new DefaultComboBoxModel(new String[]{"relative Z", "absolute Z"}));
zValCombo_.setBounds(30, 97, 110, 22);
slicesPanel_.add(zValCombo_);
stackKeepShutterOpenCheckBox_ = new JCheckBox();
stackKeepShutterOpenCheckBox_.setText("Keep shutter open");
stackKeepShutterOpenCheckBox_.setFont(new Font("Arial", Font.PLAIN, 10));
stackKeepShutterOpenCheckBox_.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
applySettings();
}
});
stackKeepShutterOpenCheckBox_.setSelected(false);
stackKeepShutterOpenCheckBox_.setBounds(60, 121, 150, 22);
slicesPanel_.add(stackKeepShutterOpenCheckBox_);
// Acquisition order panel
acqOrderBox_ = new JComboBox();
acqOrderBox_.setFont(new Font("", Font.PLAIN, 10));
acqOrderBox_.setBounds(2, 26, 195, 22);
acquisitionOrderPanel_.add(acqOrderBox_);
acqOrderModes_ = new AcqOrderMode[4];
acqOrderModes_[0] = new AcqOrderMode(AcqOrderMode.TIME_POS_CHANNEL_SLICE);
acqOrderModes_[1] = new AcqOrderMode(AcqOrderMode.TIME_POS_SLICE_CHANNEL);
acqOrderModes_[2] = new AcqOrderMode(AcqOrderMode.POS_TIME_CHANNEL_SLICE);
acqOrderModes_[3] = new AcqOrderMode(AcqOrderMode.POS_TIME_SLICE_CHANNEL);
acqOrderBox_.addItem(acqOrderModes_[0]);
acqOrderBox_.addItem(acqOrderModes_[1]);
acqOrderBox_.addItem(acqOrderModes_[2]);
acqOrderBox_.addItem(acqOrderModes_[3]);
// Summary panel
summaryTextArea_ = new JTextArea();
summaryTextArea_.setFont(new Font("Arial", Font.PLAIN, 11));
summaryTextArea_.setEditable(false);
summaryTextArea_.setBounds(4, 19, 350, 120);
summaryTextArea_.setMargin(new Insets(2, 2, 2, 2));
summaryTextArea_.setOpaque(false);
summaryPanel_.add(summaryTextArea_);
// Autofocus panel
afPanel_.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
applySettings();
}
});
afButton_ = new JButton();
afButton_.setToolTipText("Set autofocus options");
afButton_.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
afOptions();
}
});
afButton_.setText("Options...");
afButton_.setIcon(SwingResourceManager.getIcon(AcqControlDlg.class, "icons/wrench_orange.png"));
afButton_.setMargin(new Insets(2, 5, 2, 5));
afButton_.setFont(new Font("Dialog", Font.PLAIN, 10));
afButton_.setBounds(50, 21, 100, 28);
afPanel_.add(afButton_);
final JLabel afSkipFrame1 = new JLabel();
afSkipFrame1.setFont(new Font("Dialog", Font.PLAIN, 10));
afSkipFrame1.setText("Skip frame(s): ");
afSkipFrame1.setToolTipText(TooltipTextMaker.addHTMLBreaksForTooltip("The number of 'frames skipped' corresponds" +
"to the number of time intervals of image acquisition that pass before micromanager autofocuses again. Micromanager " +
"will always autofocus when moving to a new position regardless of this value"));
afSkipFrame1.setBounds(35, 54, 70, 21);
afPanel_.add(afSkipFrame1);
afSkipInterval_ = new JSpinner(new SpinnerNumberModel(0, 0, null, 1));
((JSpinner.DefaultEditor) afSkipInterval_.getEditor()).getTextField().setFont(new Font("Arial", Font.PLAIN, 10));
afSkipInterval_.setBounds(105, 54, 55, 22);
afSkipInterval_.setValue(new Integer(acqEng_.getAfSkipInterval()));
afSkipInterval_.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
applySettings();
afSkipInterval_.setValue(new Integer(acqEng_.getAfSkipInterval()));
}
});
afPanel_.add(afSkipInterval_);
// Channels panel
channelsPanel_.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
applySettings();
}
});
final JLabel channelsLabel = new JLabel();
channelsLabel.setFont(new Font("Arial", Font.PLAIN, 10));
channelsLabel.setBounds(90, 19, 80, 24);
channelsLabel.setText("Channel group:");
channelsPanel_.add(channelsLabel);
channelGroupCombo_ = new JComboBox();
channelGroupCombo_.setFont(new Font("", Font.PLAIN, 10));
updateGroupsCombo();
channelGroupCombo_.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String newGroup = (String) channelGroupCombo_.getSelectedItem();
if (acqEng_.setChannelGroup(newGroup)) {
model_.cleanUpConfigurationList();
if (gui_.getAutofocusManager() != null) {
try {
gui_.getAutofocusManager().refresh();
} catch (MMException e) {
ReportingUtils.showError(e);
}
}
} else {
updateGroupsCombo();
}
}
});
channelGroupCombo_.setBounds(165, 20, 150, 22);
channelsPanel_.add(channelGroupCombo_);
channelTablePane_ = new JScrollPane();
channelTablePane_.setFont(new Font("Arial", Font.PLAIN, 10));
channelTablePane_.setBounds(10, 45, 414, 90);
channelsPanel_.add(channelTablePane_);
final JButton addButton = new JButton();
addButton.setFont(new Font("Arial", Font.PLAIN, 10));
addButton.setMargin(new Insets(0, 0, 0, 0));
addButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
applySettings();
model_.addNewChannel();
model_.fireTableStructureChanged();
}
});
addButton.setText("New");
addButton.setToolTipText("Create new channel for currently selected channel group");
addButton.setBounds(430, 45, 68, 22);
channelsPanel_.add(addButton);
final JButton removeButton = new JButton();
removeButton.setFont(new Font("Arial", Font.PLAIN, 10));
removeButton.setMargin(new Insets(-5, -5, -5, -5));
removeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int sel = channelTable_.getSelectedRow();
if (sel > -1) {
applySettings();
model_.removeChannel(sel);
model_.fireTableStructureChanged();
if (channelTable_.getRowCount() > sel) {
channelTable_.setRowSelectionInterval(sel, sel);
}
}
}
});
removeButton.setText("Remove");
removeButton.setToolTipText("Remove currently selected channel");
removeButton.setBounds(430, 69, 68, 22);
channelsPanel_.add(removeButton);
final JButton upButton = new JButton();
upButton.setFont(new Font("Arial", Font.PLAIN, 10));
upButton.setMargin(new Insets(0, 0, 0, 0));
upButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int sel = channelTable_.getSelectedRow();
if (sel > -1) {
applySettings();
int newSel = model_.rowUp(sel);
model_.fireTableStructureChanged();
channelTable_.setRowSelectionInterval(newSel, newSel);
//applySettings();
}
}
});
upButton.setText("Up");
upButton.setToolTipText(TooltipTextMaker.addHTMLBreaksForTooltip(
"Move currently selected channel up (Channels higher on list are acquired first)"));
upButton.setBounds(430, 93, 68, 22);
channelsPanel_.add(upButton);
final JButton downButton = new JButton();
downButton.setFont(new Font("Arial", Font.PLAIN, 10));
downButton.setMargin(new Insets(0, 0, 0, 0));
downButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int sel = channelTable_.getSelectedRow();
if (sel > -1) {
applySettings();
int newSel = model_.rowDown(sel);
model_.fireTableStructureChanged();
channelTable_.setRowSelectionInterval(newSel, newSel);
//applySettings();
}
}
});
downButton.setText("Down");
downButton.setToolTipText(TooltipTextMaker.addHTMLBreaksForTooltip(
"Move currently selected channel down (Channels lower on list are acquired later)"));
downButton.setBounds(430, 117, 68, 22);
channelsPanel_.add(downButton);
chanKeepShutterOpenCheckBox_ = new JCheckBox();
chanKeepShutterOpenCheckBox_.setText("Keep shutter open");
chanKeepShutterOpenCheckBox_.setFont(new Font("Arial", Font.PLAIN, 10));
chanKeepShutterOpenCheckBox_.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
applySettings();
}
});
chanKeepShutterOpenCheckBox_.setSelected(false);
chanKeepShutterOpenCheckBox_.setBounds(330, 20, 150, 22);
channelsPanel_.add(chanKeepShutterOpenCheckBox_);
// Save panel
savePanel_.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
if (!savePanel_.isSelected()) {
displayModeCombo_.setSelectedIndex(0);
}
commentTextArea_.setEnabled(savePanel_.isSelected());
applySettings();
}
});
displayMode_ = new JLabel();
displayMode_.setFont(new Font("Arial", Font.PLAIN, 10));
displayMode_.setText("Display");
displayMode_.setBounds(150, 15, 49, 21);
//savePanel_.add(displayMode_);
displayModeCombo_ = new JComboBox();
displayModeCombo_.setFont(new Font("", Font.PLAIN, 10));
displayModeCombo_.setBounds(188, 14, 150, 24);
displayModeCombo_.addItem(new DisplayMode(DisplayMode.ALL));
displayModeCombo_.addItem(new DisplayMode(DisplayMode.LAST_FRAME));
displayModeCombo_.addItem(new DisplayMode(DisplayMode.SINGLE_WINDOW));
displayModeCombo_.setEnabled(false);
//savePanel_.add(displayModeCombo_);
rootLabel_ = new JLabel();
rootLabel_.setFont(new Font("Arial", Font.PLAIN, 10));
rootLabel_.setText("Directory root");
rootLabel_.setBounds(10, 30, 72, 22);
savePanel_.add(rootLabel_);
rootField_ = new JTextField();
rootField_.setFont(new Font("Arial", Font.PLAIN, 10));
rootField_.setBounds(90, 30, 354, 22);
savePanel_.add(rootField_);
browseRootButton_ = new JButton();
browseRootButton_.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
setRootDirectory();
}
});
browseRootButton_.setMargin(new Insets(2, 5, 2, 5));
browseRootButton_.setFont(new Font("Dialog", Font.PLAIN, 10));
browseRootButton_.setText("...");
browseRootButton_.setBounds(445, 30, 47, 24);
savePanel_.add(browseRootButton_);
browseRootButton_.setToolTipText("Browse");
namePrefixLabel_ = new JLabel();
namePrefixLabel_.setFont(new Font("Arial", Font.PLAIN, 10));
namePrefixLabel_.setText("Name prefix");
namePrefixLabel_.setBounds(10, 55, 76, 22);
savePanel_.add(namePrefixLabel_);
nameField_ = new JTextField();
nameField_.setFont(new Font("Arial", Font.PLAIN, 10));
nameField_.setBounds(90, 55, 354, 22);
savePanel_.add(nameField_);
commentLabel_ = new JLabel();
commentLabel_.setFont(new Font("Arial", Font.PLAIN, 10));
commentLabel_.setText("Comments");
commentLabel_.setBounds(10, 80, 76, 22);
savePanel_.add(commentLabel_);
JScrollPane commentScrollPane = new JScrollPane();
commentScrollPane.setBounds(90, 80, 354, 72);
savePanel_.add(commentScrollPane);
commentTextArea_ = new JTextArea();
commentScrollPane.setViewportView(commentTextArea_);
commentTextArea_.setFont(new Font("", Font.PLAIN, 10));
commentTextArea_.setToolTipText("Comment for the current acquistion");
commentTextArea_.setWrapStyleWord(true);
commentTextArea_.setLineWrap(true);
commentTextArea_.setBorder(new EtchedBorder(EtchedBorder.LOWERED));
//commentTextArea_.setBounds(91, 485, 354, 62);
//savePanel_.add(commentTextArea_);
// Main buttons
final JButton closeButton = new JButton();
closeButton.setFont(new Font("Arial", Font.PLAIN, 10));
closeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
saveSettings();
saveAcqSettings();
AcqControlDlg.this.dispose();
gui_.makeActive();
}
});
closeButton.setText("Close");
closeButton.setBounds(432, 10, 77, 22);
getContentPane().add(closeButton);
final JButton acquireButton = new JButton();
acquireButton.setMargin(new Insets(-9, -9, -9, -9));
acquireButton.setFont(new Font("Arial", Font.BOLD, 12));
acquireButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
AbstractCellEditor ae = (AbstractCellEditor) channelTable_.getCellEditor();
if (ae != null) {
ae.stopCellEditing();
}
runAcquisition();
}
});
acquireButton.setText("Acquire!");
acquireButton.setBounds(432, 44, 77, 22);
getContentPane().add(acquireButton);
final JButton stopButton = new JButton();
stopButton.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
acqEng_.abortRequest();
}
});
stopButton.setText("Stop");
stopButton.setFont(new Font("Arial", Font.BOLD, 12));
stopButton.setBounds(432, 68, 77, 22);
getContentPane().add(stopButton);
final JButton loadButton = new JButton();
loadButton.setFont(new Font("Arial", Font.PLAIN, 10));
loadButton.setMargin(new Insets(-5, -5, -5, -5));
loadButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
loadAcqSettingsFromFile();
}
});
loadButton.setText("Load...");
loadButton.setBounds(432, 102, 77, 22);
getContentPane().add(loadButton);
loadButton.setToolTipText("Load acquisition settings");
final JButton saveAsButton = new JButton();
saveAsButton.setFont(new Font("Arial", Font.PLAIN, 10));
saveAsButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
saveAsAcqSettingsToFile();
}
});
saveAsButton.setToolTipText("Save current acquisition settings as");
saveAsButton.setText("Save as...");
saveAsButton.setBounds(432, 126, 77, 22);
saveAsButton.setMargin(new Insets(-5, -5, -5, -5));
getContentPane().add(saveAsButton);
// update GUI contentss
// load window settings
int x = 100;
int y = 100;
this.setBounds(x, y, 521, 645);
if (prefs_ != null) {
x = prefs_.getInt(ACQ_CONTROL_X, x);
y = prefs_.getInt(ACQ_CONTROL_Y, y);
setLocation(x, y);
// load override settings
// enable/disable dependent controls
}
// add update event listeners
positionsPanel_.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
applySettings();
}
});
displayModeCombo_.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
applySettings();
}
});
acqOrderBox_.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
applySettings();
}
});
// load acquistion settings
loadAcqSettings();
// create the table of channels
createChannelTable();
// update summary
updateGUIContents();
// update settings in the acq engine
applySettings();
createToolTips();
}
/** Called when a field's "value" property changes. Causes the Summary to be updated*/
public void propertyChange(PropertyChangeEvent e) {
// update summary
applySettings();
summaryTextArea_.setText(acqEng_.getVerboseSummary());
}
protected void afOptions() {
if (gui_.getAutofocusManager().getDevice() != null) {
gui_.getAutofocusManager().showOptionsDialog();
}
}
public boolean inArray(String member, String[] group) {
for (int i = 0; i < group.length; i++) {
if (member.equals(group[i])) {
return true;
}
}
return false;
}
public void close() {
try {
saveSettings();
} catch (Throwable t) {
ReportingUtils.logError(t, "in saveSettings");
}
try {
saveAcqSettings();
} catch (Throwable t) {
ReportingUtils.logError(t, "in saveAcqSettings");
}
try {
dispose();
} catch (Throwable t) {
ReportingUtils.logError(t, "in dispose");
}
if (null != gui_) {
try {
gui_.makeActive();
} catch (Throwable t) {
ReportingUtils.logError(t, "in makeActive");
}
}
}
public void updateGroupsCombo() {
String groups[] = acqEng_.getAvailableGroups();
if (groups.length != 0) {
channelGroupCombo_.setModel(new DefaultComboBoxModel(groups));
if (!inArray(acqEng_.getChannelGroup(), groups)) {
acqEng_.setChannelGroup(acqEng_.getFirstConfigGroup());
}
channelGroupCombo_.setSelectedItem(acqEng_.getChannelGroup());
}
}
public void updateChannelAndGroupCombo() {
updateGroupsCombo();
model_.cleanUpConfigurationList();
}
public synchronized void loadAcqSettings() {
disableGUItoSettings_ = true;
// load acquisition engine preferences
acqEng_.clear();
int numFrames = acqPrefs_.getInt(ACQ_NUMFRAMES, 1);
double interval = acqPrefs_.getDouble(ACQ_INTERVAL, 0.0);
acqEng_.setFrames(numFrames, interval);
acqEng_.enableFramesSetting(acqPrefs_.getBoolean(ACQ_ENABLE_MULTI_FRAME, false));
framesPanel_.setSelected(acqEng_.isFramesSettingEnabled());
numFrames_.setValue(acqEng_.getNumFrames());
int unit = acqPrefs_.getInt(ACQ_TIME_UNIT, 0);
timeUnitCombo_.setSelectedIndex(unit);
double bottom = acqPrefs_.getDouble(ACQ_ZBOTTOM, 0.0);
double top = acqPrefs_.getDouble(ACQ_ZTOP, 0.0);
double step = acqPrefs_.getDouble(ACQ_ZSTEP, 1.0);
if (Math.abs(step) < Math.abs(acqEng_.getMinZStepUm())) {
step = acqEng_.getMinZStepUm();
}
zVals_ = acqPrefs_.getInt(ACQ_Z_VALUES, 0);
acqEng_.setSlices(bottom, top, step, zVals_ == 0 ? false : true);
acqEng_.enableZSliceSetting(acqPrefs_.getBoolean(ACQ_ENABLE_SLICE_SETTINGS, acqEng_.isZSliceSettingEnabled()));
acqEng_.enableMultiPosition(acqPrefs_.getBoolean(ACQ_ENABLE_MULTI_POSITION, acqEng_.isMultiPositionEnabled()));
positionsPanel_.setSelected(acqEng_.isMultiPositionEnabled());
slicesPanel_.setSelected(acqEng_.isZSliceSettingEnabled());
acqEng_.enableChannelsSetting(acqPrefs_.getBoolean(ACQ_ENABLE_MULTI_CHANNEL, false));
channelsPanel_.setSelected(acqEng_.isChannelsSettingEnabled());
savePanel_.setSelected(acqPrefs_.getBoolean(ACQ_SAVE_FILES, false));
nameField_.setText(acqPrefs_.get(ACQ_DIR_NAME, "Untitled"));
String os_name = System.getProperty("os.name", "");
rootField_.setText(acqPrefs_.get(ACQ_ROOT_NAME, System.getProperty("user.home") + "/AcquisitionData"));
acqEng_.setAcqOrderMode(acqPrefs_.getInt(ACQ_ORDER_MODE, acqEng_.getAcqOrderMode()));
acqEng_.setDisplayMode(acqPrefs_.getInt(ACQ_DISPLAY_MODE, acqEng_.getDisplayMode()));
acqEng_.enableAutoFocus(acqPrefs_.getBoolean(ACQ_AF_ENABLE, acqEng_.isAutoFocusEnabled()));
acqEng_.setAfSkipInterval(acqPrefs_.getInt(ACQ_AF_SKIP_INTERVAL, acqEng_.getAfSkipInterval()));
acqEng_.setChannelGroup(acqPrefs_.get(ACQ_CHANNEL_GROUP, acqEng_.getFirstConfigGroup()));
afPanel_.setSelected(acqEng_.isAutoFocusEnabled());
acqEng_.keepShutterOpenForChannels(acqPrefs_.getBoolean(ACQ_CHANNELS_KEEP_SHUTTER_OPEN, false));
acqEng_.keepShutterOpenForStack(acqPrefs_.getBoolean(ACQ_STACK_KEEP_SHUTTER_OPEN, false));
int numChannels = acqPrefs_.getInt(ACQ_NUM_CHANNELS, 0);
ChannelSpec defaultChannel = new ChannelSpec();
acqEng_.getChannels().clear();
for (int i = 0; i < numChannels; i++) {
String name = acqPrefs_.get(CHANNEL_NAME_PREFIX + i, "Undefined");
boolean use = acqPrefs_.getBoolean(CHANNEL_USE_PREFIX + i, true);
double exp = acqPrefs_.getDouble(CHANNEL_EXPOSURE_PREFIX + i, 0.0);
Boolean doZStack = acqPrefs_.getBoolean(CHANNEL_DOZSTACK_PREFIX + i, true);
double zOffset = acqPrefs_.getDouble(CHANNEL_ZOFFSET_PREFIX + i, 0.0);
ContrastSettings s8 = new ContrastSettings();
s8.min = acqPrefs_.getDouble(CHANNEL_CONTRAST8_MIN_PREFIX + i, defaultChannel.contrast8_.min);
s8.max = acqPrefs_.getDouble(CHANNEL_CONTRAST8_MAX_PREFIX + i, defaultChannel.contrast8_.max);
ContrastSettings s16 = new ContrastSettings();
s16.min = acqPrefs_.getDouble(CHANNEL_CONTRAST16_MIN_PREFIX + i, defaultChannel.contrast16_.min);
s16.max = acqPrefs_.getDouble(CHANNEL_CONTRAST16_MAX_PREFIX + i, defaultChannel.contrast16_.max);
int r = acqPrefs_.getInt(CHANNEL_COLOR_R_PREFIX + i, defaultChannel.color_.getRed());
int g = acqPrefs_.getInt(CHANNEL_COLOR_G_PREFIX + i, defaultChannel.color_.getGreen());
int b = acqPrefs_.getInt(CHANNEL_COLOR_B_PREFIX + i, defaultChannel.color_.getBlue());
int skip = acqPrefs_.getInt(CHANNEL_SKIP_PREFIX + i, defaultChannel.skipFactorFrame_);
Color c = new Color(r, g, b);
acqEng_.addChannel(name, exp, doZStack, zOffset, s8, s16, skip, c, use);
}
// Restore Column Width and Column order
int columnCount = 7;
columnWidth_ = new int[columnCount];
columnOrder_ = new int[columnCount];
for (int k = 0; k < columnCount; k++) {
columnWidth_[k] = acqPrefs_.getInt(ACQ_COLUMN_WIDTH + k, ACQ_DEFAULT_COLUMN_WIDTH);
columnOrder_[k] = acqPrefs_.getInt(ACQ_COLUMN_ORDER + k, k);
}
disableGUItoSettings_ = false;
}
public synchronized void saveAcqSettings() {
try {
acqPrefs_.clear();
} catch (BackingStoreException e) {
ReportingUtils.showError(e);
}
applySettings();
acqPrefs_.putBoolean(ACQ_ENABLE_MULTI_FRAME, acqEng_.isFramesSettingEnabled());
acqPrefs_.putBoolean(ACQ_ENABLE_MULTI_CHANNEL, acqEng_.isChannelsSettingEnabled());
acqPrefs_.putInt(ACQ_NUMFRAMES, acqEng_.getNumFrames());
acqPrefs_.putDouble(ACQ_INTERVAL, acqEng_.getFrameIntervalMs());
acqPrefs_.putInt(ACQ_TIME_UNIT, timeUnitCombo_.getSelectedIndex());
acqPrefs_.putDouble(ACQ_ZBOTTOM, acqEng_.getSliceZBottomUm());
acqPrefs_.putDouble(ACQ_ZTOP, acqEng_.getZTopUm());
acqPrefs_.putDouble(ACQ_ZSTEP, acqEng_.getSliceZStepUm());
acqPrefs_.putBoolean(ACQ_ENABLE_SLICE_SETTINGS, acqEng_.isZSliceSettingEnabled());
acqPrefs_.putBoolean(ACQ_ENABLE_MULTI_POSITION, acqEng_.isMultiPositionEnabled());
acqPrefs_.putInt(ACQ_Z_VALUES, zVals_);
acqPrefs_.putBoolean(ACQ_SAVE_FILES, savePanel_.isSelected());
acqPrefs_.put(ACQ_DIR_NAME, nameField_.getText());
acqPrefs_.put(ACQ_ROOT_NAME, rootField_.getText());
acqPrefs_.putInt(ACQ_ORDER_MODE, acqEng_.getAcqOrderMode());
acqPrefs_.putInt(ACQ_DISPLAY_MODE, acqEng_.getDisplayMode());
acqPrefs_.putBoolean(ACQ_AF_ENABLE, acqEng_.isAutoFocusEnabled());
acqPrefs_.putInt(ACQ_AF_SKIP_INTERVAL, acqEng_.getAfSkipInterval());
acqPrefs_.putBoolean(ACQ_CHANNELS_KEEP_SHUTTER_OPEN, acqEng_.isShutterOpenForChannels());
acqPrefs_.putBoolean(ACQ_STACK_KEEP_SHUTTER_OPEN, acqEng_.isShutterOpenForStack());
acqPrefs_.put(ACQ_CHANNEL_GROUP, acqEng_.getChannelGroup());
ArrayList<ChannelSpec> channels = acqEng_.getChannels();
acqPrefs_.putInt(ACQ_NUM_CHANNELS, channels.size());
for (int i = 0; i < channels.size(); i++) {
ChannelSpec channel = channels.get(i);
acqPrefs_.put(CHANNEL_NAME_PREFIX + i, channel.config_);
acqPrefs_.putBoolean(CHANNEL_USE_PREFIX + i, channel.useChannel_);
acqPrefs_.putDouble(CHANNEL_EXPOSURE_PREFIX + i, channel.exposure_);
acqPrefs_.putBoolean(CHANNEL_DOZSTACK_PREFIX + i, channel.doZStack_);
acqPrefs_.putDouble(CHANNEL_ZOFFSET_PREFIX + i, channel.zOffset_);
acqPrefs_.putDouble(CHANNEL_CONTRAST8_MIN_PREFIX + i, channel.contrast8_.min);
acqPrefs_.putDouble(CHANNEL_CONTRAST8_MAX_PREFIX + i, channel.contrast8_.max);
acqPrefs_.putDouble(CHANNEL_CONTRAST16_MIN_PREFIX + i, channel.contrast16_.min);
acqPrefs_.putDouble(CHANNEL_CONTRAST16_MAX_PREFIX + i, channel.contrast16_.max);
acqPrefs_.putInt(CHANNEL_COLOR_R_PREFIX + i, channel.color_.getRed());
acqPrefs_.putInt(CHANNEL_COLOR_G_PREFIX + i, channel.color_.getGreen());
acqPrefs_.putInt(CHANNEL_COLOR_B_PREFIX + i, channel.color_.getBlue());
acqPrefs_.putInt(CHANNEL_SKIP_PREFIX + i, channel.skipFactorFrame_);
}
// Save model column widths and order
for (int k = 0; k < model_.getColumnCount(); k++) {
acqPrefs_.putInt(ACQ_COLUMN_WIDTH + k, findTableColumn(channelTable_, k).getWidth());
acqPrefs_.putInt(ACQ_COLUMN_ORDER + k, channelTable_.convertColumnIndexToView(k));
}
try {
acqPrefs_.flush();
} catch (BackingStoreException ex) {
ReportingUtils.logError(ex);
}
}
// Returns the TableColumn associated with the specified column
// index in the model
public TableColumn findTableColumn(JTable table, int columnModelIndex) {
Enumeration<?> e = table.getColumnModel().getColumns();
for (; e.hasMoreElements();) {
TableColumn col = (TableColumn) e.nextElement();
if (col.getModelIndex() == columnModelIndex) {
return col;
}
}
return null;
}
protected void enableZSliceControls(boolean state) {
zBottom_.setEnabled(state);
zTop_.setEnabled(state);
zStep_.setEnabled(state);
zValCombo_.setEnabled(state);
}
protected void setRootDirectory() {
File result = FileDialogs.openDir(this,
"Please choose a directory root for image data",
MMStudioMainFrame.MM_DATA_SET);
if (result != null) {
rootField_.setText(result.getAbsolutePath());
acqEng_.setRootName(result.getAbsolutePath());
}
}
protected void setTopPosition() {
double z = acqEng_.getCurrentZPos();
zTop_.setText(NumberUtils.doubleToDisplayString(z));
applySettings();
// update summary
summaryTextArea_.setText(acqEng_.getVerboseSummary());
}
protected void setBottomPosition() {
double z = acqEng_.getCurrentZPos();
zBottom_.setText(NumberUtils.doubleToDisplayString(z));
applySettings();
// update summary
summaryTextArea_.setText(acqEng_.getVerboseSummary());
}
protected void loadAcqSettingsFromFile() {
File f = FileDialogs.openFile(this, "Load acquisition settings", ACQ_SETTINGS_FILE);
if (f != null) {
loadAcqSettingsFromFile(f.getAbsolutePath());
}
}
public void loadAcqSettingsFromFile(String path) {
acqFile_ = new File(path);
try {
FileInputStream in = new FileInputStream(acqFile_);
acqPrefs_.clear();
Preferences.importPreferences(in);
loadAcqSettings();
updateGUIContents();
in.close();
acqDir_ = acqFile_.getParent();
if (acqDir_ != null) {
prefs_.put(ACQ_FILE_DIR, acqDir_);
}
} catch (Exception e) {
ReportingUtils.showError(e);
return;
}
}
protected boolean saveAsAcqSettingsToFile() {
saveAcqSettings();
File f = FileDialogs.save(this, "Save the acquisition settings file", ACQ_SETTINGS_FILE);
if (f != null) {
FileOutputStream os;
try {
os = new FileOutputStream(f);
acqPrefs_.exportNode(os);
} catch (FileNotFoundException e) {
ReportingUtils.showError(e);
return false;
} catch (IOException e) {
ReportingUtils.showError(e);
return false;
} catch (BackingStoreException e) {
ReportingUtils.showError(e);
return false;
}
return true;
}
return false;
}
public void runAcquisition() {
if (acqEng_.isAcquisitionRunning()) {
JOptionPane.showMessageDialog(this, "Cannot start acquisition: previous acquisition still in progress.");
return;
}
try {
applySettings();
//saveAcqSettings(); // This is too slow.
ChannelTableModel model = (ChannelTableModel) channelTable_.getModel();
if (acqEng_.isChannelsSettingEnabled() && model.duplicateChannels()) {
JOptionPane.showMessageDialog(this, "Cannot start acquisition using the same channel twice");
return;
}
acqEng_.acquire();
} catch (MMException e) {
ReportingUtils.showError(e);
return;
}
}
public void runAcquisition(String acqName, String acqRoot) {
if (acqEng_.isAcquisitionRunning()) {
JOptionPane.showMessageDialog(this, "Unable to start the new acquisition task: previous acquisition still in progress.");
return;
}
try {
applySettings();
acqEng_.setDirName(acqName);
acqEng_.setRootName(acqRoot);
acqEng_.setSaveFiles(true);
acqEng_.acquire();
} catch (MMException e) {
ReportingUtils.showError(e);
return;
}
}
public boolean isAcquisitionRunning() {
return acqEng_.isAcquisitionRunning();
}
public static int search(int[] numbers, int key) {
for (int index = 0; index < numbers.length; index++) {
if (numbers[index] == key) {
return index;
}
}
return -1;
}
public void updateGUIContents() {
if (disableGUItoSettings_) {
return;
}
disableGUItoSettings_ = true;
// Disable update prevents action listener loops
// TODO: remove setChannels()
model_.setChannels(acqEng_.getChannels());
double intervalMs = acqEng_.getFrameIntervalMs();
interval_.setText(numberFormat_.format(convertMsToTime(intervalMs, timeUnitCombo_.getSelectedIndex())));
zBottom_.setText(NumberUtils.doubleToDisplayString(acqEng_.getSliceZBottomUm()));
zTop_.setText(NumberUtils.doubleToDisplayString(acqEng_.getZTopUm()));
zStep_.setText(NumberUtils.doubleToDisplayString(acqEng_.getSliceZStepUm()));
framesPanel_.setSelected(acqEng_.isFramesSettingEnabled());
slicesPanel_.setSelected(acqEng_.isZSliceSettingEnabled());
positionsPanel_.setSelected(acqEng_.isMultiPositionEnabled());
afPanel_.setSelected(acqEng_.isAutoFocusEnabled());
acqOrderBox_.setEnabled(positionsPanel_.isSelected() || framesPanel_.isSelected() ||
slicesPanel_.isSelected() || channelsPanel_.isSelected());
afSkipInterval_.setEnabled(acqEng_.isAutoFocusEnabled());
// These values need to be cached or we will loose them due to the Spinners OnChanged methods calling applySetting
Integer numFrames = new Integer(acqEng_.getNumFrames());
Integer afSkipInterval = new Integer(acqEng_.getAfSkipInterval());
if (acqEng_.isFramesSettingEnabled()) {
numFrames_.setValue(numFrames);
}
afSkipInterval_.setValue(afSkipInterval);
enableZSliceControls(acqEng_.isZSliceSettingEnabled());
model_.fireTableStructureChanged();
channelGroupCombo_.setSelectedItem(acqEng_.getChannelGroup());
try {
displayModeCombo_.setSelectedIndex(acqEng_.getDisplayMode());
} catch (IllegalArgumentException e) {
displayModeCombo_.setSelectedIndex(0);
}
for (AcqOrderMode mode : acqOrderModes_) {
mode.setEnabled(framesPanel_.isSelected(), positionsPanel_.isSelected(),
slicesPanel_.isSelected(), channelsPanel_.isSelected());
}
// add correct acquisition order options
int selectedIndex = acqEng_.getAcqOrderMode();
acqOrderBox_.removeAllItems();
if ( framesPanel_.isSelected() && positionsPanel_.isSelected() &&
slicesPanel_.isSelected() && channelsPanel_.isSelected() ) {
acqOrderBox_.addItem(acqOrderModes_[0]);
acqOrderBox_.addItem(acqOrderModes_[1]);
acqOrderBox_.addItem(acqOrderModes_[2]);
acqOrderBox_.addItem(acqOrderModes_[3]);
} else if ( framesPanel_.isSelected() && positionsPanel_.isSelected() ){
if (selectedIndex == 0 || selectedIndex == 2) {
acqOrderBox_.addItem(acqOrderModes_[0]);
acqOrderBox_.addItem(acqOrderModes_[2]);
} else {
acqOrderBox_.addItem(acqOrderModes_[1]);
acqOrderBox_.addItem(acqOrderModes_[3]);
}
} else if ( channelsPanel_.isSelected()&& slicesPanel_.isSelected() ){
if (selectedIndex == 0 || selectedIndex == 1) {
acqOrderBox_.addItem(acqOrderModes_[0]);
acqOrderBox_.addItem(acqOrderModes_[1]);
} else {
acqOrderBox_.addItem(acqOrderModes_[2]);
acqOrderBox_.addItem(acqOrderModes_[3]);
}
} else
acqOrderBox_.addItem(acqOrderModes_[selectedIndex]);
acqOrderBox_.setSelectedItem( acqOrderModes_[acqEng_.getAcqOrderMode()] );
zValCombo_.setSelectedIndex(zVals_);
stackKeepShutterOpenCheckBox_.setSelected(acqEng_.isShutterOpenForStack());
chanKeepShutterOpenCheckBox_.setSelected(acqEng_.isShutterOpenForChannels());
channelTable_.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
boolean selected = channelsPanel_.isSelected();
channelTable_.setEnabled(selected);
channelTable_.getTableHeader().setForeground(selected ? Color.black : Color.gray);
// update summary
summaryTextArea_.setText(acqEng_.getVerboseSummary());
disableGUItoSettings_ = false;
}
private void applySettings() {
if (disableGUItoSettings_) {
return;
}
disableGUItoSettings_ = true;
AbstractCellEditor ae = (AbstractCellEditor) channelTable_.getCellEditor();
if (ae != null) {
ae.stopCellEditing();
}
try {
double zStep = NumberUtils.displayStringToDouble(zStep_.getText());
if (Math.abs(zStep) < acqEng_.getMinZStepUm()) {
zStep = acqEng_.getMinZStepUm();
}
acqEng_.setSlices(NumberUtils.displayStringToDouble(zBottom_.getText()), NumberUtils.displayStringToDouble(zTop_.getText()), zStep, zVals_ == 0 ? false : true);
acqEng_.enableZSliceSetting(slicesPanel_.isSelected());
acqEng_.enableMultiPosition(positionsPanel_.isSelected());
acqEng_.setDisplayMode(((DisplayMode) displayModeCombo_.getSelectedItem()).getID());
acqEng_.setAcqOrderMode(((AcqOrderMode) acqOrderBox_.getSelectedItem()).getID() );
acqEng_.enableChannelsSetting(channelsPanel_.isSelected());
acqEng_.setChannels(((ChannelTableModel) channelTable_.getModel()).getChannels());
acqEng_.enableFramesSetting(framesPanel_.isSelected());
acqEng_.setFrames((Integer) numFrames_.getValue(),
convertTimeToMs(NumberUtils.displayStringToDouble(interval_.getText()), timeUnitCombo_.getSelectedIndex()));
acqEng_.setAfSkipInterval(NumberUtils.displayStringToInt(afSkipInterval_.getValue().toString()));
acqEng_.keepShutterOpenForChannels(chanKeepShutterOpenCheckBox_.isSelected());
acqEng_.keepShutterOpenForStack(stackKeepShutterOpenCheckBox_.isSelected());
} catch (ParseException p) {
ReportingUtils.showError(p);
// TODO: throw error
}
acqEng_.setSaveFiles(savePanel_.isSelected());
acqEng_.setDirName(nameField_.getText());
acqEng_.setRootName(rootField_.getText());
// update summary
acqEng_.setComment(commentTextArea_.getText());
acqEng_.enableAutoFocus(afPanel_.isSelected());
acqEng_.setParameterPreferences(acqPrefs_);
disableGUItoSettings_ = false;
updateGUIContents();
}
/**
* Save settings to application properties.
*
*/
private void saveSettings() {
Rectangle r = getBounds();
if (prefs_ != null) {
// save window position
prefs_.putInt(ACQ_CONTROL_X, r.x);
prefs_.putInt(ACQ_CONTROL_Y, r.y);
}
}
private double convertTimeToMs(double interval, int units) {
if (units == 1) {
return interval * 1000; // sec
} else if (units == 2) {
return interval * 60.0 * 1000.0; // min
} else if (units == 0) {
return interval;
}
ReportingUtils.showError("Unknown units supplied for acquisition interval!");
return interval;
}
private double convertMsToTime(double intervalMs, int units) {
if (units == 1) {
return intervalMs / 1000; // sec
} else if (units == 2) {
return intervalMs / (60.0 * 1000.0); // min
} else if (units == 0) {
return intervalMs;
}
ReportingUtils.showError("Unknown units supplied for acquisition interval!");
return intervalMs;
}
private void zValCalcChanged() {
if (zValCombo_.getSelectedIndex() == 0) {
setTopButton_.setEnabled(false);
setBottomButton_.setEnabled(false);
} else {
setTopButton_.setEnabled(true);
setBottomButton_.setEnabled(true);
}
if (zVals_ == zValCombo_.getSelectedIndex()) {
return;
}
zVals_ = zValCombo_.getSelectedIndex();
double zBottomUm, zTopUm;
try {
zBottomUm = NumberUtils.displayStringToDouble(zBottom_.getText());
zTopUm = NumberUtils.displayStringToDouble(zTop_.getText());
} catch (ParseException e) {
ReportingUtils.logError(e);
return;
}
double curZ = acqEng_.getCurrentZPos();
double newTop, newBottom;
if (zVals_ == 0) {
setTopButton_.setEnabled(false);
setBottomButton_.setEnabled(false);
// convert from absolute to relative
newTop = zTopUm - curZ;
newBottom = zBottomUm - curZ;
} else {
setTopButton_.setEnabled(true);
setBottomButton_.setEnabled(true);
// convert from relative to absolute
newTop = zTopUm + curZ;
newBottom = zBottomUm + curZ;
}
zBottom_.setText(NumberUtils.doubleToDisplayString(newBottom));
zTop_.setText(NumberUtils.doubleToDisplayString(newTop));
}
/**
* This method is called from the Options dialog, to set the background style
*/
public void setBackgroundStyle(String style) {
setBackground(guiColors_.background.get(style));
for (JPanel panel : panelList_) {
//updatePanelBorder(panel);
}
repaint();
}
public class ComponentTitledPanel extends JPanel {
public ComponentTitledBorder compTitledBorder;
public boolean borderSet_ = false;
public Component titleComponent;
@Override
public void setBorder(Border border) {
if (compTitledBorder != null && borderSet_) {
compTitledBorder.setBorder(border);
} else {
super.setBorder(border);
}
}
@Override
public Border getBorder() {
return compTitledBorder;
}
public void setTitleFont(Font font) {
titleComponent.setFont(font);
}
}
public class LabelPanel extends ComponentTitledPanel {
LabelPanel(String title) {
super();
titleComponent = new JLabel(title);
JLabel label = (JLabel) titleComponent;
label.setOpaque(true);
label.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
compTitledBorder = new ComponentTitledBorder(label, this, BorderFactory.createEtchedBorder());
this.setBorder(compTitledBorder);
borderSet_ = true;
}
}
public class CheckBoxPanel extends ComponentTitledPanel {
JCheckBox checkBox;
CheckBoxPanel(String title) {
super();
titleComponent = new JCheckBox(title);
checkBox = (JCheckBox) titleComponent;
compTitledBorder = new ComponentTitledBorder(checkBox, this, BorderFactory.createEtchedBorder());
this.setBorder(compTitledBorder);
borderSet_ = true;
final CheckBoxPanel thisPanel = this;
checkBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
boolean enable = checkBox.isSelected();
thisPanel.setChildrenEnabled(enable);
}
});
}
public void setChildrenEnabled(boolean enabled) {
Component comp[] = this.getComponents();
for (int i = 0; i < comp.length; i++) {
comp[i].setEnabled(enabled);
}
}
public boolean isSelected() {
return checkBox.isSelected();
}
public void setSelected(boolean selected) {
checkBox.setSelected(selected);
setChildrenEnabled(selected);
}
public void addActionListener(ActionListener actionListener) {
checkBox.addActionListener(actionListener);
}
public void removeActionListeners() {
for (ActionListener l : checkBox.getActionListeners()) {
checkBox.removeActionListener(l);
}
}
}
} |
// Package
package com.hp.hpl.jena.ontology.impl;
// Imports
import com.hp.hpl.jena.rdf.model.*;
import com.hp.hpl.jena.rdf.model.impl.*;
import com.hp.hpl.jena.util.iterator.*;
import com.hp.hpl.jena.vocabulary.*;
import com.hp.hpl.jena.ontology.*;
import com.hp.hpl.jena.graph.*;
import com.hp.hpl.jena.graph.compose.MultiUnion;
import com.hp.hpl.jena.graph.query.*;
import com.hp.hpl.jena.enhanced.*;
import java.io.*;
import java.util.*;
/**
* <p>
* Implementation of a model that can process general ontologies in OWL,
* DAML and similar languages.
* </p>
*
* @author Ian Dickinson, HP Labs
* (<a href="mailto:Ian.Dickinson@hp.com" >email</a>)
* @version CVS $Id: OntModelImpl.java,v 1.10 2003-04-18 10:42:58 jeremy_carroll Exp $
*/
public class OntModelImpl
extends ModelCom
implements OntModel
{
// Constants
// Static variables
// Instance variables
/** The document manager this ontology model is using to load imports */
protected OntDocumentManager m_docMgr;
/** The graph factory this ontology model is using to build the union graph of imports */
protected GraphFactory m_graphFactory;
/** The language profile that defines what we can do in this ontology */
protected Profile m_profile;
/** List of URI strings of documents that have been imported into this one */
protected Set m_imported = new HashSet();
/** Query that will access nodes with types whose type is Class */
protected BindingQueryPlan m_individualsQuery;
/** Query that will access nodes with types whose type is Class */
protected List m_individualsQueryAlias = null;
/** Mode switch for strict checking mode */
protected boolean m_strictMode = true;
// Constructors
/**
* <p>
* Construct a new ontology model, using the given model as a base. The document manager
* will be used to build the imports closure of the model if its policy permits.
* </p>
*
* @param languageURI Denotes the language profile that this ontology is using
* @param model The base model that may contain existing statements for the ontology
* @param docMgr The ontology document manager to use when building the imports closure
* @param gf The graph factory to use when building the union of the imported graphs
*/
public OntModelImpl( String languageURI, Model model, OntDocumentManager docMgr, GraphFactory gf ) {
// all ontologies are defined to be union graphs, to allow us to add the imports to the union
super( new OntologyGraph(), BuiltinPersonalities.model );
Profile lang = ProfileRegistry.getInstance().getProfile( languageURI );
if (lang == null) {
// can't proceed after this
throw new OntologyException( "Ontology model could not locate language profile for ontology language " + languageURI );
}
// add the base graph to the union first, so that it will receive updates
getUnionGraph().addGraph( model.getGraph() );
// record pointers to the helpers we're using
m_profile = lang;
m_docMgr = docMgr;
m_graphFactory = gf;
// cache the query plan for individuals
m_individualsQuery = queryXTypeOfType( lang.CLASS() );
// cache the query plan for individuals using class alias (if defined)
if (lang.hasAliasFor( lang.CLASS() )) {
m_individualsQueryAlias = new ArrayList();
for (Iterator j = lang.listAliasesFor( lang.CLASS() ); j.hasNext(); ) {
// add to the list of alternates for this query
m_individualsQueryAlias.add( queryXTypeOfType( (Resource) j.next() ) );
}
}
// load the imports closure, according to the policies in my document manager
m_docMgr.loadImports( this, new OntReadState( null, this ) );
((OntologyGraph) graph).bind();
}
// External signature methods
/**
* <p>
* Answer a reference to the document manager that this model is using to manage
* ontology <-> mappings, and to load the imports closure. <strong>Note</strong>
* by default, an ontology model is constructed with a reference to the shared,
* global document manager. Thus changing the settings via this model's document
* manager may affect other models also using the same instance.
* </p>
* @return A reference to this model's document manager
*/
public OntDocumentManager getDocumentManager() {
return m_docMgr;
}
/**
* <p>
* Answer an iterator that ranges over the ontology resources in this model, i.e.
* the resources with <code>rdf:type Ontology</code> or equivalent. These resources
* typically contain metadata about the ontology document that contains them.
* </p>
* <p>
* Specifically, the resources in this iterator will those whose type corresponds
* to the value given in the ontology vocabulary associated with this model, see
* {@link Profile#ONTOLOGY}.
* </p>
* <p>
* <strong>Note:</strong> the number of nodes returned by this iterator will vary according to
* the completeness of the deductive extension of the underlying graph. See class
* overview for more details.
* </p>
*
* @return An iterator over ontology resources.
*/
public Iterator listOntologies() {
return findByTypeAs( getProfile().ONTOLOGY(), Ontology.class );
}
/**
* <p>
* Answer an iterator that ranges over the property resources in this model, i.e.
* the resources with <code>rdf:type Property</code> or equivalent. An <code>OntProperty</code>
* is equivalent to an <code>rdfs:Property</code> in a normal RDF graph; this type is
* provided as a common super-type for the more specific {@link ObjectProperty} and
* {@link DatatypeProperty} property types.
* </p>
* <p>
* Specifically, the resources in this iterator will those whose type corresponds
* to the value given in the ontology vocabulary associated with this model.
* </p>
* <p>
* <strong>Note:</strong> the number of nodes returned by this iterator will vary according to
* the completeness of the deductive extension of the underlying graph. See class
* overview for more details.
* </p>
*
* @return An iterator over property resources.
*/
public Iterator listOntProperties() {
return findByTypeAs( RDF.Property, OntProperty.class );
}
/**
* <p>
* Answer an iterator that ranges over the object property resources in this model, i.e.
* the resources with <code>rdf:type ObjectProperty</code> or equivalent. An object
* property is a property that is defined in the ontology language semantics as a
* one whose range comprises individuals (rather than datatyped literals).
* </p>
* <p>
* Specifically, the resources in this iterator will those whose type corresponds
* to the value given in the ontology vocabulary associated with this model: see
* {@link Profile#OBJECT_PROPERTY}.
* </p>
* <p>
* <strong>Note:</strong> the number of nodes returned by this iterator will vary according to
* the completeness of the deductive extension of the underlying graph. See class
* overview for more details.
* </p>
*
* @return An iterator over object property resources.
*/
public Iterator listObjectProperties() {
return findByTypeAs( getProfile().OBJECT_PROPERTY(), ObjectProperty.class );
}
/**
* <p>
* Answer an iterator that ranges over the datatype property resources in this model, i.e.
* the resources with <code>rdf:type DatatypeProperty</code> or equivalent. An datatype
* property is a property that is defined in the ontology language semantics as a
* one whose range comprises datatyped literals (rather than individuals).
* </p>
* <p>
* Specifically, the resources in this iterator will those whose type corresponds
* to the value given in the ontology vocabulary associated with this model: see
* {@link Profile#DATATYPE_PROPERTY}.
* </p>
* <p>
* <strong>Note:</strong> the number of nodes returned by this iterator will vary according to
* the completeness of the deductive extension of the underlying graph. See class
* overview for more details.
* </p>
*
* @return An iterator over datatype property resources.
*/
public Iterator listDatatypeProperties() {
return findByTypeAs( getProfile().DATATYPE_PROPERTY(), DatatypeProperty.class );
}
/**
* <p>
* Answer an iterator that ranges over the individual resources in this model, i.e.
* the resources with <code>rdf:type</code> corresponding to a class defined
* in the ontology.
* </p>
* <p>
* <strong>Note:</strong> the number of nodes returned by this iterator will vary according to
* the completeness of the deductive extension of the underlying graph. See class
* overview for more details.
* </p>
*
* @return An iterator over Individuals.
*/
public Iterator listIndividuals() {
return queryFor( m_individualsQuery, m_individualsQueryAlias, Individual.class );
}
/**
* <p>
* Answer an iterator that ranges over the axiom resources in this model. Example
* axioms include the {@link AllDifferent} axiom in OWL, which allows an ontology
* conveniently to express the unique names assumption for a bounded set of class
* descriptions.
* </p>
* <p>
* <strong>Note:</strong> the number of nodes returned by this iterator will vary according to
* the completeness of the deductive extension of the underlying graph. See class
* overview for more details.
* </p>
*
* @return An iterator over axiom resources.
*/
public Iterator listAxioms() {
// Build a list queries for the axiom types in the language
// note I haven't pre-cached this query because it seems that it will not
// be called often! -ijd
List queries = new ArrayList();
Iterator i = getProfile().getAxiomTypes();
if (i.hasNext()) {
while (i.hasNext()) {
// create a query for each axiom type
Query q = new Query();
q.addMatch( Query.X, RDF.type.asNode(), ((Resource) i.next()).asNode() );
queries.add( queryHandler().prepareBindings( q, new Node[] {Query.X} ) );
}
// take the first query first
BindingQueryPlan first = (BindingQueryPlan) queries.remove( 0 );
// perform the query, mapping each result to an Axiom
return queryFor( first, queries, Axiom.class );
}
else {
// we can use i to indicate that there are no axioms
return i;
}
}
/**
* <p>
* Answer an iterator that ranges over all of the various forms of class description resource
* in this model. Class descriptions include {@link #listEnumeratedClasses enumerated}
* classes, {@link #listUnionClasses union} classes, {@link #listComplementClasses complement}
* classes, {@link #listIntersectionClasses intersection} classes, {@link #listClasses named}
* classes and {@link #listRestrictions property restrictions}.
* </p>
* <p>
* <strong>Note:</strong> the number of nodes returned by this iterator will vary according to
* the completeness of the deductive extension of the underlying graph. See class
* overview for more details.
* </p>
*
* @return An iterator over class description resources.
*/
public Iterator listClasses() {
return findByTypeAs( getProfile().getClassDescriptionTypes(), ClassDescription.class );
}
/**
* <p>
* Answer an iterator that ranges over the enumerated class class-descriptions
* in this model, i.e. the class resources specified to have a property
* <code>oneOf</code> (or equivalent) and a list of values.
* </p>
* <p>
* <strong>Note:</strong> the number of nodes returned by this iterator will vary according to
* the completeness of the deductive extension of the underlying graph. See class
* overview for more details.
* </p>
*
* @return An iterator over enumerated class resources.
* @see Profile#ONE_OF
*/
public Iterator listEnumeratedClasses() {
return findByDefiningPropertyAs( getProfile().ONE_OF(), ClassDescription.class );
}
/**
* <p>
* Answer an iterator that ranges over the union class-descriptions
* in this model, i.e. the class resources specified to have a property
* <code>unionOf</code> (or equivalent) and a list of values.
* </p>
* <p>
* <strong>Note:</strong> the number of nodes returned by this iterator will vary according to
* the completeness of the deductive extension of the underlying graph. See class
* overview for more details.
* </p>
*
* @return An iterator over union class resources.
* @see Profile#UNION_OF
*/
public Iterator listUnionClasses() {
return findByDefiningPropertyAs( getProfile().UNION_OF(), ClassDescription.class );
}
/**
* <p>
* Answer an iterator that ranges over the complement class-descriptions
* in this model, i.e. the class resources specified to have a property
* <code>complementOf</code> (or equivalent) and a list of values.
* </p>
* <p>
* <strong>Note:</strong> the number of nodes returned by this iterator will vary according to
* the completeness of the deductive extension of the underlying graph. See class
* overview for more details.
* </p>
*
* @return An iterator over complement class resources.
* @see Profile#COMPLEMENT_OF
*/
public Iterator listComplementClasses() {
return findByDefiningPropertyAs( getProfile().COMPLEMENT_OF(), ClassDescription.class );
}
/**
* <p>
* Answer an iterator that ranges over the intersection class-descriptions
* in this model, i.e. the class resources specified to have a property
* <code>intersectionOf</code> (or equivalent) and a list of values.
* </p>
* <p>
* <strong>Note:</strong> the number of nodes returned by this iterator will vary according to
* the completeness of the deductive extension of the underlying graph. See class
* overview for more details.
* </p>
*
* @return An iterator over complement class resources.
* @see Profile#INTERSECTION_OF
*/
public Iterator listIntersectionClasses() {
return findByDefiningPropertyAs( getProfile().INTERSECTION_OF(), ClassDescription.class );
}
/**
* <p>
* Answer an iterator that ranges over the named class-descriptions
* in this model, i.e. resources with <code>rdf:type
* Class</code> (or equivalent) and a node URI.
* </p>
* <p>
* <strong>Note:</strong> the number of nodes returned by this iterator will vary according to
* the completeness of the deductive extension of the underlying graph. See class
* overview for more details.
* </p>
*
* @return An iterator over named class resources.
*/
public Iterator listNamedClasses() {
return ((ExtendedIterator) listClasses()).filterDrop(
new Filter() {
public boolean accept( Object x ) {
return ((Resource) x).isAnon();
}
}
);
}
/**
* <p>
* Answer an iterator that ranges over the property restriction class-descriptions
* in this model, i.e. resources with <code>rdf:type
* Restriction</code> (or equivalent).
* </p>
* <p>
* <strong>Note:</strong> the number of nodes returned by this iterator will vary according to
* the completeness of the deductive extension of the underlying graph. See class
* overview for more details.
* </p>
*
* @return An iterator over restriction class resources.
* @see Profile#RESTRICTION
*/
public Iterator listRestrictions() {
return findByTypeAs( getProfile().RESTRICTION(), Restriction.class );
}
/**
* <p>
* Answer an iterator that ranges over the properties in this model that are declared
* to be annotation properties. Not all supported languages define annotation properties
* (the category of annotation properties is chiefly an OWL innovation).
* </p>
* <p>
* <strong>Note:</strong> the number of nodes returned by this iterator will vary according to
* the completeness of the deductive extension of the underlying graph. See class
* overview for more details.
* </p>
*
* @return An iterator over annotation properties.
* @see Profile#getAnnotationProperties()
*/
public Iterator listAnnotationProperties() {
Resource r = (Resource) getProfile().ANNOTATION_PROPERTY();
if (r == null) {
return new ArrayList().iterator();
}
else {
return findByType( r )
.andThen( WrappedIterator.create( getProfile().getAnnotationProperties() ) )
.mapWith( new SubjectNodeAs( AnnotationProperty.class ) );
}
}
/**
* <p>
* Answer a resource that represents an ontology description node in this model. If a resource
* with the given uri exists in the model, it will be re-used. If not, a new one is created in
* the updateable sub-graph of the ontology model.
* </p>
*
* @param uri The uri for the ontology node. Conventionally, this corresponds to the base URI
* of the document itself.
* @return An Ontology resource.
*/
public Ontology createOntology( String uri ) {
return (Ontology) createOntResource( Ontology.class, getProfile().ONTOLOGY(), uri );
}
/**
* <p>
* Answer a resource that represents an Indvidual node in this model. A new anonymous resource
* will be created in the updateable sub-graph of the ontology model.
* </p>
*
* @param cls The ontology class to which the individual belongs
* @return A new anoymous Individual of the given class.
*/
public Individual createIndividual( OntClass cls ) {
return (Individual) createOntResource( Individual.class, cls, null );
}
/**
* <p>
* Answer a resource that represents an Individual node in this model. If a resource
* with the given uri exists in the model, it will be re-used. If not, a new one is created in
* the updateable sub-graph of the ontology model.
* </p>
*
* @param uri The uri for the individual, or null for an anonymous individual.
* @return An Individual resource.
*/
public Individual createIndividual( OntClass cls, String uri ) {
return (Individual) createOntResource( Individual.class, cls, uri );
}
/**
* <p>
* Answer a resource that represents an object property in this model. An object property
* is defined to have a range of individuals, rather than datatypes.
* If a resource
* with the given uri exists in the model, it will be re-used. If not, a new one is created in
* the updateable sub-graph of the ontology model.
* </p>
*
* @param uri The uri for the object property. May not be null.
* @return An ObjectProperty resource.
*/
public ObjectProperty createObjectProperty( String uri ) {
return (ObjectProperty) createOntResource( ObjectProperty.class, getProfile().OBJECT_PROPERTY(), uri );
}
/**
* <p>
* Answer a resource that represents datatype property in this model. A datattype property
* is defined to have a range that is a concrete datatype, rather than an individual.
* If a resource
* with the given uri exists in the model, it will be re-used. If not, a new one is created in
* the updateable sub-graph of the ontology model.
* </p>
*
* @param uri The uri for the datatype property. May not be null.
* @return A DatatypeProperty resource.
*/
public DatatypeProperty createDatatypeProperty( String uri ) {
return (DatatypeProperty) createOntResource( DatatypeProperty.class, getProfile().DATATYPE_PROPERTY(), uri );
}
/**
* <p>
* Answer a resource that represents an annotation property in this model. If a resource
* with the given uri exists in the model, it will be re-used. If not, a new one is created in
* the updateable sub-graph of the ontology model.
* </p>
*
* @param uri The uri for the annotation property.
* @return An AnnotationProperty resource.
*/
public AnnotationProperty createAnnotationProperty( String uri ) {
return (AnnotationProperty) createOntResource( AnnotationProperty.class, getProfile().ANNOTATION_PROPERTY(), uri );
}
/**
* <p>
* Answer a resource that represents an axiom in this model. If a resource
* with the given uri exists in the model, it will be re-used. If not, a new one is created in
* the updateable sub-graph of the ontology model.
* </p>
*
* @param cls The class of axiom (e.g. <code>owl:AllDifferent</code>).
* @param uri The uri for the axiom, or null for an anonymous axiom.
* @return An Axiom resource.
*/
public Axiom createAxiom( Resource cls, String uri ) {
return (Axiom) createOntResource( Axiom.class, cls, uri );
}
/**
* <p>
* Answer a resource that represents an anonymous class description in this model. A new
* anonymous resource of <code>rdf:type C</code>, where C is the class type from the
* language profile.
* </p>
*
* @return An anonymous Class resource.
*/
public OntClass createClass() {
return (OntClass) createOntResource( OntClass.class, getProfile().CLASS(), null );
}
/**
* <p>
* Answer a resource that represents a class description node in this model. If a resource
* with the given uri exists in the model, it will be re-used. If not, a new one is created in
* the updateable sub-graph of the ontology model.
* </p>
*
* @param uri The uri for the class node, or null for an anonymous class.
* @return A Class resource.
*/
public OntClass createClass( String uri ) {
return (OntClass) createOntResource( OntClass.class, getProfile().CLASS(), uri );
}
/**
* <p>
* Answer a resource that represents an anonymous property restriction in this model. A new
* anonymous resource of <code>rdf:type R</code>, where R is the restriction type from the
* language profile.
* </p>
*
* @return An anonymous Restriction resource.
*/
public Restriction createRestriction() {
return (Restriction) createOntResource( Restriction.class, getProfile().RESTRICTION(), null );
}
/**
* <p>
* Answer a resource that represents a property restriction in this model. If a resource
* with the given uri exists in the model, it will be re-used. If not, a new one is created in
* the updateable sub-graph of the ontology model.
* </p>
*
* @param uri The uri for the restriction node, or null for an anonymous restriction.
* @return A Restriction resource.
*/
public Restriction createRestriction( String uri ) {
return (Restriction) createOntResource( Restriction.class, getProfile().RESTRICTION(), uri );
}
public OntResource createOntResource( Class javaClass, Resource rdfType, String uri ) {
return (OntResource) getResourceWithType( uri, rdfType ).as( javaClass );
}
/**
* <p>
* Answer the language profile (for example, OWL or DAML+OIL) that this model is
* working to.
* </p>
*
* @return A language profile
*/
public Profile getProfile() {
return m_profile;
}
/**
* <p>
* Answer true if this model has had the given URI document imported into it. This is
* important to know since an import only occurs once, and we also want to be able to
* detect cycles of imports.
* </p>
*
* @param uri An ontology URI
* @return True if the document corresponding to the URI has been successfully loaded
* into this model
*/
public boolean hasLoadedImport( String uri ) {
return m_imported.contains( uri );
}
/**
* <p>
* Record that this model has now imported the document with the given
* URI, so that it will not be re-imported in the future.
* </p>
*
* @param uri A document URI that has now been imported into the model.
*/
public void addLoadedImport( String uri ) {
m_imported.add( uri );
}
/**
* <p>
* Answer a list of the imported URI's in this ontology model. Detection of <code>imports</code>
* statments will be according to the local language profile
* </p>
*
* @return The imported ontology URI's as a list. Note that since the underlying graph is
* not ordered, the order of values in the list in successive calls to this method is
* not guaranteed to be preserved.
*/
public List listImportedOntologyURIs() {
List imports = new ArrayList();
// list the ontology nodes
for (StmtIterator i = listStatements( null, RDF.type, m_profile.ONTOLOGY() ); i.hasNext(); ) {
Resource ontology = i.nextStatement().getSubject();
for (StmtIterator j = ontology.listProperties( m_profile.IMPORTS() ); j.hasNext(); ) {
// add the imported URI to the list
imports.add( j.nextStatement().getResource().getURI() );
}
}
return imports;
}
/**
* <p>
* Answer the graph factory associated with this model (used for constructing the
* constituent graphs of the imports closure).
* </p>
*
* @return The local graph factory
*/
public GraphFactory getGraphFactory() {
return m_graphFactory;
}
/**
* <p>Read statements into the model from the given source, and then load
* imported ontologies (according to the document manager policy).</p>
* @param uri URI to read from, may be mapped to a local source by the document manager
*/
public Model read( String uri ) {
super.read( m_docMgr.getCacheURL( uri ) );
// cache this model against the public uri (if caching enabled)
m_docMgr.addGraph( uri, getGraph() );
m_docMgr.loadImports( this, new OntReadState( null, this ) );
((OntologyGraph) graph).bind();
return this;
}
/**
* <p>Read statements into the model from the given source, and then load
* imported ontologies (according to the document manager policy).</p>
* @param reader An input reader
* @param base The base URI
*/
public Model read(Reader reader, String base) {
super.read( reader, base );
m_docMgr.loadImports( this, new OntReadState( null, this ) );
((OntologyGraph) graph).bind();
return this;
}
/**
* <p>Read statements into the model from the given source, and then load
* imported ontologies (according to the document manager policy).</p>
* @param reader An input stream
* @param base The base URI
*/
public Model read(InputStream reader, String base) {
super.read( reader, base );
m_docMgr.loadImports( this, new OntReadState( null, this ) );
((OntologyGraph) graph).bind();
return this;
}
/**
* <p>Read statements into the model from the given source, and then load
* imported ontologies (according to the document manager policy).</p>
* @param uri URI to read from, may be mapped to a local source by the document manager
* @param lang The source syntax
*/
public Model read(String uri, String syntax) {
super.read( m_docMgr.getCacheURL( uri ), syntax );
// cache this model against the public uri (if caching enabled)
m_docMgr.addGraph( uri, getGraph() );
m_docMgr.loadImports( this, new OntReadState( syntax, this ) );
((OntologyGraph) graph).bind();
return this;
}
/**
* <p>Read statements into the model from the given source, and then load
* imported ontologies (according to the document manager policy).</p>
* @param reader An input reader
* @param base The base URI
* @param lang The source syntax
*/
public Model read(Reader reader, String base, String syntax) {
super.read( reader, base, syntax );
m_docMgr.loadImports( this, new OntReadState( syntax, this ) );
((OntologyGraph) graph).bind();
return this;
}
/**
* <p>Read statements into the model from the given source, and then load
* imported ontologies (according to the document manager policy).</p>
* @param reader An input stream
* @param base The base URI
* @param lang The source syntax
*/
public Model read(InputStream reader, String base, String syntax) {
super.read( reader, base, syntax );
m_docMgr.loadImports( this, new OntReadState( syntax, this ) );
((OntologyGraph) graph).bind();
return this;
}
/**
* <p>
* Read operation that is invoked while loading the imports closure of an
* ontology model. Not normally invoked by user code.
* </p>
*
* @param uri The URI to load from
* @param readState The read-state for this operation
*/
public void read( String uri, OntReadState readState ) {
super.read( m_docMgr.getCacheURL( uri ), readState.getSyntax() );
// cache this model against the public uri (if caching enabled)
m_docMgr.addGraph( uri, getGraph() );
m_docMgr.loadImports( this, readState );
}
/**
* <p>
* Answer the sub-graphs of this model. A sub-graph is defined as a graph that
* is used to contain the triples from an imported document.
* </p>
*
* @return A list of sub graphs for this ontology model
*/
public List getSubGraphs() {
return ((MultiUnion) getGraph()).getSubGraphs();
}
/**
* <p>
* Answer the base-graph of this model. The base-graph is the graph that
* contains the triples read from the source document for this ontology.
* </p>
*
* @return The base-graph for this ontology model
*/
public Graph getBaseGraph() {
return ((OntologyGraph) getGraph()).getUnion().getBaseGraph();
}
/**
* <p>
* Answer the base model of this model. The base model is the model wrapping
* the graph that contains the triples read from the source document for this
* ontology. It is therefore the model that will be updated if statements are
* added to a model that is built from a union of documents (via the
* <code>imports</code> statements in the source document).
* </p>
*
* @return The base model for this ontology model
*/
public Model getBaseModel() {
return ModelFactory.createModelForGraph( getBaseGraph() );
}
/**
* <p>
* Add the given graph as one of the sub-graphs of this ontology union graph
* </p>
*
* @param graph A sub-graph to add
*/
public void addSubGraph( Graph graph ) {
getUnionGraph().addGraph( graph );
}
/**
* <p>
* Answer true if this model is currently in <i>strict checking mode</i>. Strict
* mode means
* that converting a common resource to a particular language element, such as
* an ontology class, will be subject to some simple syntactic-level checks for
* appropriateness.
* </p>
*
* @return True if in strict checking mode
*/
public boolean strictMode() {
return m_strictMode;
}
/**
* <p>
* Set the checking mode to strict or non-strict.
* </p>
*
* @param strict
* @see #strictMode()
*/
public void setStrictMode( boolean strict ) {
m_strictMode = strict;
}
// Internal implementation methods
// jjc - want access for Syntax checker ....
public MultiUnion getUnionGraph() {
return ((OntologyGraph) graph).getUnion();
}
/**
* <p>
* Answer an iterator over all of the resources that have
* <code>rdf:type</code> type. No alias processing.
* </p>
*
* @param type The resource that is the value of <code>rdf:type</code> we
* want to match
* @return An iterator over all triples <code>_x rdf:type type</code>
*/
protected ExtendedIterator findByType( Resource type ) {
return getGraph().find( null, RDF.type.asNode(), type.asNode() );
}
/**
* <p>
* Answer an iterator over all of the resources that have
* <code>rdf:type type</code>, or optionally, one of the alternative types.
* </p>
*
* @param type The resource that is the value of <code>rdf:type</code> we
* want to match
* @param types An iterator over alternative types to search for, or null
* @return An iterator over all triples <code>_x rdf:type t</code> where t
* is <code>type</code> or one of the values from <code>types</code>.
*/
protected ExtendedIterator findByType( Resource type, Iterator types ) {
ExtendedIterator i = findByType( type );
// compose onto i the find iterators for the aliases
if (types != null) {
while (types.hasNext()) {
i = i.andThen( findByType( (Resource) types.next() ) );
}
}
return i;
}
/**
* <p>
* Answer an iterator over all of the resources that have
* <code>rdf:type type</code>, or optionally, one of its aliases.
* </p>
*
* @param type The resource that is the value of <code>rdf:type</code> we
* want to match
* @param aliased If true, check for aliases for <code>type</code> in the profile.
* @return An iterator over all triples <code>_x rdf:type type</code>
*/
protected ExtendedIterator findByType( Resource type, boolean aliases ) {
return findByType( type, aliases ? getProfile().listAliasesFor( type ) : null );
}
/**
* <p>
* Answer an iterator over all of the resources that have
* <code>rdf:type type</code>, or optionally, one of the alternative types,
* and present the results <code>as()</code> the given class.
* </p>
*
* @param type The resource that is the value of <code>rdf:type</code> we
* want to match
* @param types An iterator over alternative types to search for, or null
* @param asKey The value to use to present the polymorphic results
* @return An iterator over all triples <code>_x rdf:type type</code>
*/
protected ExtendedIterator findByTypeAs( Resource type, Iterator types, Class asKey ) {
return findByType( type, types ).mapWith( new SubjectNodeAs( asKey ) );
}
/**
* <p>
* Answer an iterator over all of the resources that has an
* <code>rdf:type</code> from the types iterator,
* and present the results <code>as()</code> the given class.
* </p>
*
* @param types An iterator over types to search for. An exception will
* be raised if this iterator does not have at least one next() element.
* @param asKey The value to use to present the polymorphic results
* @return An iterator over all triples <code>_x rdf:type type</code>
*/
protected ExtendedIterator findByTypeAs( Iterator types, Class asKey ) {
return findByTypeAs( (Resource) types.next(), types, asKey );
}
/**
* <p>
* Answer an iterator over resources with the given rdf:type; for each value
* in the iterator, ensure that is is presented <code>as()</code> the
* polymorphic object denoted by the given class key. Will process aliases.
* </p>
*
* @param type The rdf:type to search for
* @param asKey The key to pass to as() on the subject nodes
* @return An iterator over subjects with the given type, presenting as
* the given polymorphic class.
*/
protected ExtendedIterator findByTypeAs( Resource type, Class asKey ) {
return findByType( type, true ).mapWith( new SubjectNodeAs( asKey ) );
}
/**
* <p>
* Answer the iterator over the resources from the graph that satisfy the given
* query, followed by the answers to the alternative queries (if specified). A
* typical scenario is that the main query gets resources of a given class (say,
* <code>rdfs:Class</code>), while the altQueries query for aliases for that
* type (such as <code>daml:Class</code>).
* </p>
*
* @param query A query to run against the model
* @param altQueries An optional list of subsidiary queries to chain on to the first
* @return ExtendedIterator An iterator over the (assumed single) results of
* executing the queries.
*/
protected ExtendedIterator queryFor( BindingQueryPlan query, List altQueries, Class asKey ) {
GetBinding firstBinding = new GetBinding( 0 );
// get the results from the main query
ExtendedIterator mainQuery = query.executeBindings().mapWith( firstBinding );
// now add the alias queries, if defined
if (altQueries != null) {
for (Iterator i = altQueries.iterator(); i.hasNext(); ) {
ExtendedIterator aliasQuery = ((BindingQueryPlan) i.next()).executeBindings().mapWith( firstBinding );
mainQuery = mainQuery.andThen( aliasQuery );
}
}
// map each answer value to the appropriate ehnanced node
return mainQuery.mapWith( new SubjectNodeAs( asKey ) );
}
/**
* <p>
* Answer a binding query that will search for 'an X that has an
* rdf:type whose rdf:type is C' for some given resource C.
* </p>
*
* @param type The type of the type of the resources we're searching for
* @return BindingQueryPlan A binding query for the X resources.
*/
protected BindingQueryPlan queryXTypeOfType( Resource type ) {
Query q = new Query();
q.addMatch( Query.X, RDF.type.asNode(), Query.Y );
q.addMatch( Query.Y, RDF.type.asNode(), type.asNode() );
return queryHandler().prepareBindings( q, new Node[] {Query.X} );
}
/**
* <p>
* Answer an iterator over nodes that have p as a subject
* </p>
*
* @param p A property
* @return ExtendedIterator over subjects of p.
*/
protected ExtendedIterator findByDefiningProperty( Property p ) {
return getGraph().find( null, p.getNode(), null );
}
/**
* <p>
* Answer an iterator over nodes that have p as a subject, presented as
* polymorphic enh resources of the given facet.
* </p>
*
* @param p A property
* @param asKey A facet type
* @return ExtendedIterator over subjects of p, presented as the facet.
*/
protected ExtendedIterator findByDefiningPropertyAs( Property p, Class asKey ) {
return findByDefiningProperty( p ).mapWith( new SubjectNodeAs( asKey ) );
}
/**
* <p>
* Answer the resource with the given uri and that has the given rdf:type -
* creating the resource if necessary.
* </p>
*
* @param uri The uri to use, or null
* @param rdfType The resource to assert as the rdf:type
* @return A new or existing Resource
*/
protected Resource getResourceWithType( String uri, Resource rdfType ) {
return getResource( uri ).addProperty( RDF.type, rdfType );
}
// Inner class definitions
/** Map triple subjects or single nodes to subject enh nodes, presented as() the given class */
protected class SubjectNodeAs implements Map1
{
protected Class m_asKey;
protected SubjectNodeAs( Class asKey ) { m_asKey = asKey; }
public Object map1( Object x ) {
Node n = (x instanceof Triple)
? ((Triple) x).getSubject()
: ((x instanceof EnhNode) ? ((EnhNode) x).asNode() : (Node) x);
return getNodeAs( n, m_asKey );
}
}
/** Project out the first element of a list of bindings */
protected class GetBinding implements Map1
{
protected int m_index;
protected GetBinding( int index ) { m_index = index; }
public Object map1( Object x ) { return ((List) x).get( m_index ); }
}
} |
package com.jstewart.testamazonlogin;
import java.util.Iterator;
import android.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.Toast;
import com.amazon.identity.auth.device.AuthError;
import com.amazon.identity.auth.device.authorization.api.AmazonAuthorizationManager;
import com.amazon.identity.auth.device.authorization.api.AuthorizationListener;
import com.amazon.identity.auth.device.authorization.api.AuthzConstants;
import com.amazon.identity.auth.device.shared.APIListener;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.auth.AWSCredentialsProviderChain;
import com.amazonaws.auth.AWSSessionCredentials;
import com.amazonaws.auth.WebIdentityFederationSessionCredentialsProvider;
import com.amazonaws.services.securitytoken.AWSSecurityTokenServiceAsyncClient;
import com.amazonaws.services.securitytoken.AWSSecurityTokenServiceClient;
import com.amazonaws.services.securitytoken.model.AssumeRoleRequest;
import com.amazonaws.services.securitytoken.model.AssumeRoleWithWebIdentityRequest;
import com.amazonaws.services.securitytoken.model.AssumeRoleWithWebIdentityResult;
import com.amazonaws.services.securitytoken.model.Credentials;
public class LoginFragment extends Fragment {
private ImageButton loginButton;
private AmazonAuthorizationManager mAuthManager;
private String[] AUTH_SCOPES = new String[] { "profile" };
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mAuthManager = new AmazonAuthorizationManager(getActivity(),
Bundle.EMPTY);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_login, null);
loginButton = (ImageButton) view
.findViewById(R.id.login_with_amazon_button);
loginButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mAuthManager.authorize(AUTH_SCOPES, Bundle.EMPTY,
new AuthListener());
}
});
return view;
}
private class AuthListener implements AuthorizationListener {
@Override
public void onError(AuthError error) {
Log.e("Auth Listener - onError", "Error getting profile data: "
+ error.getMessage());
Toast.makeText(getActivity(), "Error getting profile data",
Toast.LENGTH_SHORT).show();
}
@Override
public void onSuccess(Bundle response) {
mAuthManager.getProfile(new ProfileListener());
}
@Override
public void onCancel(Bundle response) {
Toast.makeText(getActivity(), "Authorization canceled",
Toast.LENGTH_SHORT).show();
}
}
private class ProfileListener implements APIListener {
@Override
public void onError(AuthError response) {
Log.e("Profile Listener - onError", "Error getting profile data: "
+ response.getMessage());
Toast.makeText(getActivity(), "Error getting profile data",
Toast.LENGTH_SHORT).show();
}
@Override
public void onSuccess(Bundle response) {
Bundle profileData = response
.getBundle(AuthzConstants.BUNDLE_KEY.PROFILE.val);
String id = profileData
.getString(AuthzConstants.PROFILE_KEY.USER_ID.val);
String name = profileData
.getString(AuthzConstants.PROFILE_KEY.NAME.val);
String email = profileData
.getString(AuthzConstants.PROFILE_KEY.EMAIL.val);
Log.e("Profile Listener - onSuccess", "We have bundle data. Id: "
+ id + " Name: " + name + " Email: " + email);
mAuthManager.getToken(AUTH_SCOPES, new AuthTokenListener());
}
}
private class AuthTokenListener implements APIListener {
@Override
public void onError(AuthError response) {
Log.e("AuthToken Listener - onError",
"Error getting profile data: " + response.getMessage());
}
@Override
public void onSuccess(Bundle response) {
String token = "";
for (Iterator<String> itr = response.keySet().iterator(); itr
.hasNext();) {
String key = itr.next();
Log.i("AuthToken Listener - onSuccess",
"Successfully received auth token response with key: "
+ key);
Log.i("AuthToken Listener - onSuccess",
"The value of that key is: " + response.getString(key));
}
token = response
.getString("com.amazon.identity.auth.device.authorization.token");
AssumeRoleWithWebIdentityRequest request = new AssumeRoleWithWebIdentityRequest();
request.setProviderId("www.amazon.com");
request.setRoleArn("arn:aws:iam::541242782423:role/TestWebIdentityRole");
request.setRoleSessionName("AmazonTestLoginSession");
request.setWebIdentityToken(token);
request.setDurationSeconds(3600);
WebIdentityFederationSessionCredentialsProvider wif = new WebIdentityFederationSessionCredentialsProvider(
token, "www.amazon.com",
"arn:aws:iam::541242782423:role/TestWebIdentityRole");
String subjectFromWIF = wif.getSubjectFromWIF();
Log.d("AuthTokenListener - onSuccess",
"Got something from the wif: " + subjectFromWIF);
// AWSSecurityTokenServiceAsyncClient client = new
// AWSSecurityTokenServiceAsyncClient();
// AWSSecurityTokenServiceClient client = new
// AWSSecurityTokenServiceClient();
// AssumeRoleWithWebIdentityResult result = client
// .assumeRoleWithWebIdentity(request);
AWSCredentials credentials = wif.getCredentials();
Log.d("Auth token listener",
"Received temporary security credentials. The Access Key is: "
+ credentials.getAWSAccessKeyId()
+ " the secret key is: "
+ credentials.getAWSSecretKey()
+ " the session token is: "
);
}
}
} |
package com.monstarlab.servicedroid.util;
import com.monstarlab.servicedroid.R;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.text.TextUtils;
import android.webkit.WebView;
public class Changelog {
//private static final int STATUS_NEW = 1;
//private static final int STATUS_UPDATED = 2;
private static final int V_1_0 = 1;
private static final int V_1_1 = 2;
private static final int CURRENT_VERSION = V_1_1;
private static final String PREFS_NAME = "Changelog";
private static final String PREFS_CHANGELOG_VERSION = "lastSeenChangelogVersion";
public static void showFirstTime(final Context c) {
if (hasSeenMessage(c)) {
// do nothing
} else {
final AlertDialog.Builder builder = new AlertDialog.Builder(c);
final WebView webView = new WebView(c);
int title = R.string.whats_new;
builder.setTitle(title);
builder.setView(webView);
builder.setCancelable(false);
builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
markMessageSeen(c);
}
});
String message = getMessage(c);
if(TextUtils.isEmpty(message)) {
return;
}
//builder.setMessage(message);
webView.loadData(message, "text/html", "utf-8");
builder.show();
}
}
/*private static int isNewOrUpdated(Context c) {
SharedPreferences settings = c.getSharedPreferences(PREFS_NAME, 0);
int lastVersion = settings.getInt(LAST_VERSION, -1);
return lastVersion == -1 ? STATUS_NEW : STATUS_UPDATED;
}*/
private static int getVersion(Context c) {
int versionCode = 0;
try {
//current version
PackageInfo packageInfo = c.getPackageManager().getPackageInfo(c.getPackageName(), 0);
versionCode = packageInfo.versionCode;
} catch (NameNotFoundException e) {
//then just return 0
}
return versionCode;
}
private static boolean hasSeenMessage(Context c) {
SharedPreferences settings = c.getSharedPreferences(PREFS_NAME, 0);
return settings.getInt(PREFS_CHANGELOG_VERSION, 0) >= CURRENT_VERSION;
}
private static void markMessageSeen(Context c) {
SharedPreferences settings = c.getSharedPreferences(PREFS_NAME, 0);
Editor editor=settings.edit();
editor.putInt(PREFS_CHANGELOG_VERSION, CURRENT_VERSION);
editor.commit();
}
private static String getMessage(Context c) {
StringBuilder message = new StringBuilder();
String[] features = new String[] {
"Start a timer from the Time view when you enter service.",
"Switch between alphabetic sorting and since last visited sorting of calls.",
"The list of calls shows who is a Bible Study."
};
message.append("<html><body>");
message.append("<b>v1.1</b>");
message.append("<ul>");
for(int i = 0; i < features.length; i++) {
message.append("<li>" + features[i] + "</li>");
}
message.append("</ul>");
message.append("<b>Enjoy ServiceDroid?</b>");
message.append("<ul>");
message.append("<li>Consider giving a nice <a href=\"market://details?id=com.monstarlab.servicedroid\">review</a>.</li>");
message.append("</ul>");
message.append("</body></html>");
return message.toString();
}
} |
package com.openxc.gaugedriver;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import jp.ksksue.driver.serial.FTDriver;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.ToggleButton;
import com.openxc.VehicleManager;
import com.openxc.measurements.Odometer;
import com.openxc.measurements.FuelConsumed;
import com.openxc.measurements.Measurement;
import com.openxc.measurements.SteeringWheelAngle;
import com.openxc.measurements.UnrecognizedMeasurementTypeException;
import com.openxc.measurements.VehicleSpeed;
import com.openxc.remote.VehicleServiceException;
public class GaugeDriverActivity extends Activity {
static int mDebugCounter = 10;
private static String TAG = "GaugeDriver";
private static int mTimerPeriod = 10; //Time between Gauge updates, in milliseconds.
private VehicleManager mVehicleManager;
StringBuffer mBuffer;
private ToggleButton mToggleButton;
private TextView mStatusText;
private TextView mSendText;
private TextView mDebugText;
UsbManager mUsbManager = null;
private static int mDataUsed = 0;
private static boolean mNewData = false;
static double mGaugeMin = 0;
static double mGaugeRange = 80;
static FTDriver mSerialPort = null;
static private Timer mReceiveTimer = null;
static private boolean mColorToValue = false;
private CheckBox mColorCheckBox;
private SeekBar mColorSeekBar;
static private int mLastColor = 0;
static volatile double mSpeed = 0.0;
static volatile double mSteeringWheelAngle = 0.0;
static volatile double mMPG = 0.0;
static int mSpeedCount = 0;
static int mSteeringCount = 0;
static int mFuelCount = 0;
static int mOdoCount = 0;
static FuelOdoHandler mFuelTotal = new FuelOdoHandler(5000); //Delay time in milliseconds.
static FuelOdoHandler mOdoTotal = new FuelOdoHandler(5000);
VehicleSpeed.Listener mSpeedListener = new VehicleSpeed.Listener() {
public void receive(Measurement measurement) {
final VehicleSpeed speed = (VehicleSpeed) measurement;
mSpeed = speed.getValue().doubleValue();
mSpeedCount++;
if(mDataUsed == 0)
mNewData = true;
}
};
FuelConsumed.Listener mFuelConsumedListener = new FuelConsumed.Listener() {
public void receive(Measurement measurement) {
mFuelCount++;
final FuelConsumed fuel = (FuelConsumed) measurement;
long now = System.currentTimeMillis();
double fuelConsumed = fuel.getValue().doubleValue();
mFuelTotal.add(fuelConsumed, now);
double currentFuel = mFuelTotal.recalculate(now);
if(currentFuel > 0.00001) {
double currentOdo = mOdoTotal.recalculate(now);
mMPG = (currentOdo / currentFuel) * 2.35215; //Converting from km / l to mi / gal.
}
if(mDataUsed == 1) {
mNewData = true;
}
}
};
Odometer.Listener mFineOdometerListener = new Odometer.Listener() {
public void receive(Measurement measurement) {
mOdoCount++;
final Odometer odometer = (Odometer) measurement;
mOdoTotal.add(odometer.getValue().doubleValue(), System.currentTimeMillis());
}
};
SteeringWheelAngle.Listener mSteeringWheelListener = new SteeringWheelAngle.Listener() {
public void receive(Measurement measurement) {
mSteeringCount++;
final SteeringWheelAngle angle = (SteeringWheelAngle) measurement;
mSteeringWheelAngle = angle.getValue().doubleValue();
if(mDataUsed == 2)
mNewData = true;
}
};
private ServiceConnection mConnection = new ServiceConnection() {
// Called when the connection with the service is established
public void onServiceConnected(ComponentName className,
IBinder service) {
Log.i(TAG, "Bound to VehicleManager");
mVehicleManager = ((VehicleManager.VehicleBinder)service).getService();
try {
mVehicleManager.addListener(SteeringWheelAngle.class,
mSteeringWheelListener);
mVehicleManager.addListener(VehicleSpeed.class,
mSpeedListener);
mVehicleManager.addListener(FuelConsumed.class,
mFuelConsumedListener);
mVehicleManager.addListener(Odometer.class,
mFineOdometerListener);
} catch(VehicleServiceException e) {
Log.w(TAG, "Couldn't add listeners for measurements", e);
} catch(UnrecognizedMeasurementTypeException e) {
Log.w(TAG, "Couldn't add listeners for measurements", e);
}
}
// Called when the connection with the service disconnects unexpectedly
public void onServiceDisconnected(ComponentName className) {
Log.w(TAG, "VehicleService disconnected unexpectedly");
mVehicleManager = null;
}
};
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.i(TAG, "Gauge Driver created");
mColorCheckBox = (CheckBox) findViewById(R.id.checkBoxColor);
mColorCheckBox.setChecked(mColorToValue);
mColorSeekBar = (SeekBar) findViewById(R.id.seekBarColor);
mColorSeekBar.setMax(259);
mColorSeekBar.setEnabled(!mColorToValue);
mColorSeekBar.setProgress(mLastColor);
mColorSeekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
public void onProgressChanged(SeekBar seekbar, int progress, boolean fromUser) {
if(!mColorToValue){
writeStringToSerial( "<" + String.format("%03d", progress) + ">");
mLastColor = progress;
}
}
public void onStartTrackingTouch(SeekBar seekbar) {}
public void onStopTrackingTouch(SeekBar seekbar) {}
});
mStatusText = (TextView) findViewById(R.id.textViewStatus);
switch(mDataUsed){
case 0:
mStatusText.setText("Using Vehicle Speed Data");
break;
case 1:
mStatusText.setText("Using Vehicle Mileage Data");
break;
case 2:
mStatusText.setText("Using Steering Wheel Angle Data");
break;
default:
Log.d(TAG, "mDataUsed got screwed up somehow. Fixing in onCreate...");
mStatusText.setText("Using Vehicle Speed Data");
mDataUsed = 0;
}
mSendText = (TextView) findViewById(R.id.editTextManualData);
mDebugText = (TextView) findViewById(R.id.editTextDebug);
mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
IntentFilter filter = new IntentFilter();
filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
registerReceiver(mBroadcastReceiver, filter);
if(mReceiveTimer != null) {
onTimerToggle(null);
onTimerToggle(null); //Reset the timer so the slider updates are pointing at the right Activity.
}
mToggleButton = (ToggleButton) findViewById(R.id.toggleButtonTimer);
if(mReceiveTimer != null) { //If the timer is running
mToggleButton.setChecked(true);
} else {
mToggleButton.setChecked(false);
}
bindService(new Intent(this, VehicleManager.class),
mConnection, Context.BIND_AUTO_CREATE);
}
private void connectToDevice() {
if(mSerialPort == null) {
mSerialPort = new FTDriver(mUsbManager);
}
if(mSerialPort.isConnected()) {
//mSerialPort.end();
return;
}
mSerialPort.begin(9600);
if(!mSerialPort.isConnected()) {
Log.d(TAG, "mSerialPort.begin() failed.");
} else {
Log.d(TAG, "mSerialPort.begin() success!.");
if(mReceiveTimer == null) //Start the updates.
onTimerToggle(null);
}
}
private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
Log.d(TAG, "Device detached");
Bundle extras = intent.getExtras();
UsbDevice lostDevice = (UsbDevice)extras.get("device");
if(lostDevice.equals(mSerialPort.getDevice())) {
mSerialPort.end();
}
}
}
};
@Override
public void onResume() {
super.onResume();
connectToDevice();
}
private void updateStatus(String newMessage) {
final CharSequence outCS = newMessage;
runOnUiThread(new Runnable() {
public void run() {
mStatusText.setText(outCS);
}
});
}
private void updateDebug(final boolean clearFirst, String newMessage) {
final CharSequence outCS = newMessage;
runOnUiThread(new Runnable() {
public void run() {
if(clearFirst)
mDebugText.setText(outCS);
else
mDebugText.append(outCS);
}
});
}
private void checkUpdatedData() {
if(!mNewData)
return;
mNewData = false;
//Send data
double dValue = 0.0;
switch(mDataUsed) {
case 0: //Speed
dValue = mSpeed * 0.621371; //Converting from kph to mph.
updateStatus("Speed: " + dValue);
break;
case 1: //mpg
dValue = mMPG;
updateStatus("Mileage: " + dValue);
break;
case 2: //Steering wheel angle
dValue = mSteeringWheelAngle + 90.0;
//Make sure we're never sending a negative number here...
if(dValue < 0.0) {
dValue = 0.0;
} else if(dValue > 180.0) {
dValue = 180.0;
}
dValue /= 1.81;
updateStatus("Steering wheel angle: " + dValue);
break;
default:
Log.d(TAG, "mDataUsed got screwed up. Fixing in checkUpdatedData...");
mDataUsed = 0;
dValue = mSpeed;
runOnUiThread(new Runnable() {
public void run() {
mStatusText.setText("Using Vehicle Speed Data");
}
});
}
double dPercent = (dValue - mGaugeMin) / mGaugeRange;
if(dPercent > 1.0) {
dPercent = 1.0;
} else if(dPercent < 0.0) {
dPercent = 0.0;
}
if(mColorToValue) {
int thisColor = 0;
switch(mDataUsed) {
//colors: 0-259. Red == 0, Yellow == 65, Green == 110, Blue == 170, Purple == 260.
case 0: //Speed: 0mph = green, 80mph = red.
thisColor = 110 - (int)(dPercent * 110.0);
break;
case 1: //Mileage: 50mpg = green, 0mpg = red.
thisColor = (int)(dPercent * 110.0);
break;
case 2: //Steering wheel angle: Sweep through the spectrum.
thisColor = (int)(dPercent * 259.0);
break;
default:
Log.d(TAG, "mDataUsed got messed up in checkUpdatedData, in the percentage code!");
}
if(thisColor != mLastColor) {
mLastColor = thisColor;
String colorPacket = "<" + String.format("%03d", thisColor) + ">";
writeStringToSerial(colorPacket);
runOnUiThread(new Runnable() {
public void run() {
mColorSeekBar.setProgress(mLastColor);
}
});
}
}
int iPercent = (int)(100.0 * dPercent);
if(iPercent > 99) {
iPercent = 99;
} else if(iPercent < 0) {
iPercent = 0;
}
int value = (int)dValue;
if(value > 99) {
value = 99; //We've only got two digits to work with.
}
String dataPacket = "(" + String.format("%02d", value) + "|" +
String.format("%02d", iPercent) + ")";
writeStringToSerial(dataPacket);
}
private void writeStringToSerial(String outString){
if(mSerialPort.isConnected()) {
char[] outMessage = outString.toCharArray();
byte outBuffer[] = new byte[128];
for(int i=0; i<outString.length(); i++) {
outBuffer[i] = (byte)outMessage[i];
}
try {
mSerialPort.write(outBuffer, outString.length());
} catch(Exception e) {
Log.d(TAG, "mSerialPort.write() just threw an exception. Is the cable plugged in?");
}
}
}
public void onExit(View view){
if(mReceiveTimer != null){
mReceiveTimer.cancel();
}
if(mSerialPort != null){
mSerialPort.end();
}
if(mVehicleManager != null) {
Log.i(TAG, "Unbinding from vehicle service before exit");
unbindService(mConnection);
mVehicleManager = null;
}
finish();
System.exit(0);
}
public void onTimerToggle(View view) {
if(mReceiveTimer == null) {
mReceiveTimer = new Timer();
mReceiveTimer.schedule(new TimerTask() {
@Override
public void run() {
checkUpdatedData();
}
}, 0, mTimerPeriod);
Log.d(TAG, "Timer has been initialized.");
} else {
mReceiveTimer.cancel();
mReceiveTimer.purge();
mReceiveTimer = null;
Log.d(TAG, "Timer has been canceled.");
}
}
public void onSpeedClick(View view) {
mDataUsed = 0;
mStatusText.setText("Using Vehicle Speed Data");
mGaugeMin = 0.0;
mGaugeRange = 120.0;
mNewData = true;
}
public void onMPGClick(View view) {
mDataUsed = 1;
mStatusText.setText("Using Vehicle Mileage Data");
mGaugeMin = 0.0;
mGaugeRange = 50.0;
mNewData = true;
}
public void onSteeringClick(View view) {
mDataUsed = 2;
mStatusText.setText("Using SteeringWheel Angle Data");
mGaugeMin = 0.0;
mGaugeRange = 100.0;
mNewData = true;
}
public void onColorCheckBoxClick(View view) {
mColorToValue = mColorCheckBox.isChecked();
mColorSeekBar.setEnabled(!mColorToValue);
}
public void onSend(View view) {
writeStringToSerial(mSendText.getText().toString());
}
} |
package com.openxc.gaugedriver;
import java.util.Timer;
import java.util.TimerTask;
import jp.ksksue.driver.serial.FTDriver;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.ToggleButton;
import com.openxc.VehicleManager;
import com.openxc.measurements.Odometer;
import com.openxc.measurements.FuelConsumed;
import com.openxc.measurements.Measurement;
import com.openxc.measurements.SteeringWheelAngle;
import com.openxc.measurements.UnrecognizedMeasurementTypeException;
import com.openxc.measurements.VehicleSpeed;
import com.openxc.remote.VehicleServiceException;
public class GaugeDriverActivity extends Activity {
static int mDebugCounter = 10;
private static String TAG = "GaugeDriver";
private static int mTimerPeriod = 10; //Time between Gauge updates, in milliseconds.
private VehicleManager mVehicleManager;
StringBuffer mBuffer;
private ToggleButton mToggleButton;
private TextView mStatusText;
private TextView mSendText;
private TextView mDebugText;
UsbManager mUsbManager = null;
private static int mDataUsed = 0;
private static boolean mNewData = false;
static double mGaugeMin = 0;
static double mGaugeRange = 80;
static FTDriver mSerialPort = null;
static private Timer mReceiveTimer = null;
static private boolean mColorToValue = false;
private CheckBox mColorCheckBox;
private SeekBar mColorSeekBar;
static private int mLastColor = 0;
static volatile double mSpeed = 0.0;
static volatile double mSteeringWheelAngle = 0.0;
static volatile double mMPG = 0.0;
static int mSpeedCount = 0;
static int mSteeringCount = 0;
static int mFuelCount = 0;
static int mOdoCount = 0;
static FuelOdoHandler mFuelTotal = new FuelOdoHandler(5000); //Delay time in milliseconds.
static FuelOdoHandler mOdoTotal = new FuelOdoHandler(5000);
VehicleSpeed.Listener mSpeedListener = new VehicleSpeed.Listener() {
public void receive(Measurement measurement) {
final VehicleSpeed speed = (VehicleSpeed) measurement;
mSpeed = speed.getValue().doubleValue();
mSpeedCount++;
if(mDataUsed == 0)
mNewData = true;
}
};
FuelConsumed.Listener mFuelConsumedListener = new FuelConsumed.Listener() {
public void receive(Measurement measurement) {
mFuelCount++;
final FuelConsumed fuel = (FuelConsumed) measurement;
long now = System.currentTimeMillis();
double fuelConsumed = fuel.getValue().doubleValue();
mFuelTotal.Add(fuelConsumed, now);
double currentFuel = mFuelTotal.Recalculate(now);
if(currentFuel > 0.00001) {
double currentOdo = mOdoTotal.Recalculate(now);
mMPG = (currentOdo / currentFuel) * 2.35215; //Converting from km / l to mi / gal.
}
if(mDataUsed == 1) {
mNewData = true;
}
}
};
Odometer.Listener mFineOdometerListener = new Odometer.Listener() {
public void receive(Measurement measurement) {
mOdoCount++;
final Odometer odometer = (Odometer) measurement;
mOdoTotal.Add(odometer.getValue().doubleValue(), System.currentTimeMillis());
}
};
SteeringWheelAngle.Listener mSteeringWheelListener = new SteeringWheelAngle.Listener() {
public void receive(Measurement measurement) {
mSteeringCount++;
final SteeringWheelAngle angle = (SteeringWheelAngle) measurement;
mSteeringWheelAngle = angle.getValue().doubleValue();
if(mDataUsed == 2)
mNewData = true;
}
};
private ServiceConnection mConnection = new ServiceConnection() {
// Called when the connection with the service is established
public void onServiceConnected(ComponentName className,
IBinder service) {
Log.i(TAG, "Bound to VehicleManager");
mVehicleManager = ((VehicleManager.VehicleBinder)service).getService();
try {
mVehicleManager.addListener(SteeringWheelAngle.class,
mSteeringWheelListener);
mVehicleManager.addListener(VehicleSpeed.class,
mSpeedListener);
mVehicleManager.addListener(FuelConsumed.class,
mFuelConsumedListener);
mVehicleManager.addListener(Odometer.class,
mFineOdometerListener);
} catch(VehicleServiceException e) {
Log.w(TAG, "Couldn't add listeners for measurements", e);
} catch(UnrecognizedMeasurementTypeException e) {
Log.w(TAG, "Couldn't add listeners for measurements", e);
}
}
// Called when the connection with the service disconnects unexpectedly
public void onServiceDisconnected(ComponentName className) {
Log.w(TAG, "VehicleService disconnected unexpectedly");
mVehicleManager = null;
}
};
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.i(TAG, "Gauge Driver created");
mColorCheckBox = (CheckBox) findViewById(R.id.checkBoxColor);
mColorCheckBox.setChecked(mColorToValue);
mColorSeekBar = (SeekBar) findViewById(R.id.seekBarColor);
mColorSeekBar.setMax(259);
mColorSeekBar.setEnabled(!mColorToValue);
mColorSeekBar.setProgress(mLastColor);
mColorSeekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
public void onProgressChanged(SeekBar seekbar, int progress, boolean fromUser) {
if(!mColorToValue){
writeStringToSerial( "<" + String.format("%03d", progress) + ">");
mLastColor = progress;
}
}
public void onStartTrackingTouch(SeekBar seekbar) {}
public void onStopTrackingTouch(SeekBar seekbar) {}
});
mStatusText = (TextView) findViewById(R.id.textViewStatus);
switch (mDataUsed){
case 0:
mStatusText.setText("Using Vehicle Speed Data");
break;
case 1:
mStatusText.setText("Using Vehicle Mileage Data");
break;
case 2:
mStatusText.setText("Using Steering Wheel Angle Data");
break;
default:
Log.d(TAG, "mDataUsed got screwed up somehow. Fixing in onCreate...");
mStatusText.setText("Using Vehicle Speed Data");
mDataUsed = 0;
}
mSendText = (TextView) findViewById(R.id.editTextManualData);
mDebugText = (TextView) findViewById(R.id.editTextDebug);
mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
IntentFilter filter = new IntentFilter();
filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
registerReceiver(mBroadcastReceiver, filter);
if (mReceiveTimer != null) //If the timer is running
{
onTimerToggle(null);
onTimerToggle(null); //Reset the timer so the slider updates are pointing at the right Activity.
}
mToggleButton = (ToggleButton) findViewById(R.id.toggleButtonTimer);
if (mReceiveTimer != null) { //If the timer is running
mToggleButton.setChecked(true);
} else {
mToggleButton.setChecked(false);
}
bindService(new Intent(this, VehicleManager.class),
mConnection, Context.BIND_AUTO_CREATE);
}
private void connectToDevice() {
if(mSerialPort == null) {
mSerialPort = new FTDriver(mUsbManager);
}
if(mSerialPort.isConnected()) {
mSerialPort.end();
}
mSerialPort.begin(9600);
if (!mSerialPort.isConnected())
{
Log.d(TAG, "mSerialPort.begin() failed.");
} else {
Log.d(TAG, "mSerialPort.begin() success!.");
if(mReceiveTimer == null) //Start the updates.
onTimerToggle(null);
}
}
private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
Log.d(TAG, "Device detached");
mSerialPort.end();
}
}
};
@Override
public void onResume() {
super.onResume();
connectToDevice();
}
private void UpdateStatus(String newMessage) {
final CharSequence outCS = newMessage;
runOnUiThread(new Runnable() {
public void run() {
mStatusText.setText(outCS);
}
});
}
private void UpdateDebug(final boolean clearFirst, String newMessage) {
final CharSequence outCS = newMessage;
runOnUiThread(new Runnable() {
public void run() {
if(clearFirst)
mDebugText.setText(outCS);
else
mDebugText.append(outCS);
}
});
}
private void ReceiveTimerMethod()
{
if(!mNewData)
return;
mNewData = false;
//Send data
double dValue = 0.0;
switch(mDataUsed) {
case 0: //Speed
dValue = mSpeed * 0.621371; //Converting from kph to mph.
UpdateStatus("Speed: " + dValue);
break;
case 1: //mpg
dValue = mMPG;
UpdateStatus("Mileage: " + dValue);
break;
case 2: //Steering wheel angle
dValue = mSteeringWheelAngle + 90.0;
//Make sure we're never sending a negative number here...
if (dValue < 0.0)
dValue = 0.0;
else if (dValue > 180.0)
dValue = 180.0;
dValue /= 1.81;
UpdateStatus("Steering wheel angle: " + dValue);
break;
default:
Log.d(TAG, "mDataUsed got screwed up. Fixing in ReceiveTimerMethod...");
mDataUsed = 0;
dValue = mSpeed;
runOnUiThread(new Runnable() {
public void run() {
mStatusText.setText("Using Vehicle Speed Data");
}
});
}
double dPercent = (dValue - mGaugeMin) / mGaugeRange;
if (dPercent > 1.0)
dPercent = 1.0;
else if (dPercent < 0.0)
dPercent = 0.0;
if(mColorToValue) {
int thisColor = 0;
switch (mDataUsed) {
//colors: 0-259. Red == 0, Yellow == 65, Green == 110, Blue == 170, Purple == 260.
case 0: //Speed: 0mph = green, 80mph = red.
thisColor = 110 - (int)(dPercent * 110.0);
break;
case 1: //Mileage: 50mpg = green, 0mpg = red.
thisColor = (int)(dPercent * 110.0);
break;
case 2: //Steering wheel angle: Sweep through the spectrum.
thisColor = (int)(dPercent * 259.0);
break;
default:
Log.d(TAG, "mDataUsed got messed up in ReceiveTimerMethod, in the percentage code!");
}
if (thisColor != mLastColor) {
mLastColor = thisColor;
String colorPacket = "<" + String.format("%03d", thisColor) + ">";
writeStringToSerial(colorPacket);
//UpdateDebug(true, colorPacket);
runOnUiThread(new Runnable() {
public void run() {
mColorSeekBar.setProgress(mLastColor);
}
});
}
}
int iPercent = (int)(100.0 * dPercent);
if(iPercent > 99)
{
iPercent = 99;
} else if (iPercent < 0)
{
iPercent = 0;
}
int value = (int)dValue;
if (value > 99)
value = 99; //We've only got two digits to work with.
String dataPacket = "(" + String.format("%02d", value) + "|" +
String.format("%02d", iPercent) + ")";
writeStringToSerial(dataPacket);
//UpdateDebug(false, dataPacket + "\n");
// mDebugCounter--;
// if (mDebugCounter < 1) {
// UpdateDebug(true, "Latest Fuel: " + mFuelTotal.Latest() + "\nFuel Updates: " + mFuelCount +
// "\nLatest Odometer: " + mOdoTotal.Latest() + "\nOdometer Updates: " + mOdoCount +
// "\nTotal MPG: " + ((mOdoTotal.Latest()/mFuelTotal.Latest())*2.35215));
// mDebugCounter = 3;
}
private void writeStringToSerial(String outString){
if(mSerialPort.isConnected()) {
char[] outMessage = outString.toCharArray();
byte outBuffer[] = new byte[128];
for(int i=0; i<outString.length(); i++)
{
outBuffer[i] = (byte)outMessage[i];
}
try {
mSerialPort.write(outBuffer, outString.length());
} catch (Exception e) {
Log.d(TAG, "mSerialPort.write() just threw an exception. Is the cable plugged in?");
}
}
}
public void onExit(View view){
if (mReceiveTimer != null){
mReceiveTimer.cancel();
}
if (mSerialPort != null){
mSerialPort.end();
}
if(mVehicleManager != null) {
Log.i(TAG, "Unbinding from vehicle service before exit");
unbindService(mConnection);
mVehicleManager = null;
}
finish();
System.exit(0);
}
public void onTimerToggle(View view) {
if(mReceiveTimer == null)
{
mReceiveTimer = new Timer();
mReceiveTimer.schedule(new TimerTask() {
@Override
public void run() {
ReceiveTimerMethod();
}
}, 0, mTimerPeriod);
Log.d(TAG, "Timer has been initialized.");
} else
{
mReceiveTimer.cancel();
mReceiveTimer.purge();
mReceiveTimer = null;
Log.d(TAG, "Timer has been canceled.");
}
}
public void onSpeedClick(View view) {
mDataUsed = 0;
mStatusText.setText("Using Vehicle Speed Data");
mGaugeMin = 0.0;
mGaugeRange = 120.0;
mNewData = true;
}
public void onMPGClick(View view) {
mDataUsed = 1;
mStatusText.setText("Using Vehicle Mileage Data");
mGaugeMin = 0.0;
mGaugeRange = 50.0;
mNewData = true;
}
public void onSteeringClick(View view) {
mDataUsed = 2;
mStatusText.setText("Using SteeringWheel Angle Data");
mGaugeMin = 0.0;
mGaugeRange = 100.0;
mNewData = true;
}
public void onColorCheckBoxClick(View view) {
mColorToValue = mColorCheckBox.isChecked();
mColorSeekBar.setEnabled(!mColorToValue);
}
public void onSend(View view) {
writeStringToSerial(mSendText.getText().toString());
}
} |
package com.techhounds.commands.auton;
import com.techhounds.RobotMap;
import com.techhounds.commands.angler.SetAnglerPosition;
import com.techhounds.commands.angler.SetStateDown;
import com.techhounds.commands.angler.SetStateUp;
import com.techhounds.commands.collector.SetCollectorPower;
import com.techhounds.commands.drive.DriveDistance;
import com.techhounds.commands.gyro.RotateToPreviousAngle;
import com.techhounds.commands.gyro.RotateUsingGyro;
import com.techhounds.commands.gyro.SaveCurrentAngle;
import com.techhounds.commands.shooter.Fire;
import com.techhounds.commands.shooter.SetShooterSpeed;
import edu.wpi.first.wpilibj.command.Command;
import edu.wpi.first.wpilibj.command.CommandGroup;
import edu.wpi.first.wpilibj.command.WaitCommand;
import edu.wpi.first.wpilibj.smartdashboard.SendableChooser;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
public class AutonChooser {
private static AutonChooser instance;
private AutonChooser() {
setupDashboard();
}
public static AutonChooser getInstance() {
return instance == null ? instance = new AutonChooser() : instance;
}
enum Defense {
LOW_BAR,
PORTCULLIS,
CHEVAL_DE_FRISE,
MOAT,
RAMPARTS,
ROCK_WALL,
ROUGH_TERRAIN,
REACH_DEFENSE,
DO_NOTHING
}
enum Goal {
LEFT,
MIDDLE,
RIGHT,
DO_NOTHING
}
private SendableChooser chooseStart;
private SendableChooser chooseDefense;
private SendableChooser chooseGoal;
private SendableChooser chooseShoot;
private SendableChooser choosePost;
private int getStart() {
return ((Number) chooseStart.getSelected()).intValue();
}
private Defense getDefense() {
return ((Defense) chooseDefense.getSelected());
}
private int getShoot() {
return ((Number) chooseShoot.getSelected()).intValue();
}
private Goal getGoal() {
return ((Goal) chooseGoal.getSelected());
}
private int getPost() {
return ((Number) choosePost.getSelected()).intValue();
}
public void setupDashboard() {
chooseStart = new SendableChooser();
chooseStart.addDefault("Low Bar (5)", new Integer(5));
chooseStart.addObject("Position 4", new Integer(4));
chooseStart.addObject("Position 3", new Integer(3));
chooseStart.addObject("Position 2", new Integer(2));
chooseStart.addObject("Secret Passage (1)", new Integer(1));
chooseDefense = new SendableChooser();
chooseDefense.addObject("A: Portcullis", Defense.PORTCULLIS);
chooseDefense.addObject("A: Cheval De Frise", Defense.CHEVAL_DE_FRISE);
chooseDefense.addObject("B: Moat", Defense.MOAT);
chooseDefense.addObject("B: Ramparts", Defense.RAMPARTS);
chooseDefense.addObject("D: Rock Wall", Defense.ROCK_WALL);
chooseDefense.addObject("D: Rough Terrain", Defense.ROUGH_TERRAIN);
chooseDefense.addObject("Low Bar", Defense.LOW_BAR);
chooseDefense.addObject("Reach Defense", Defense.REACH_DEFENSE);
chooseDefense.addDefault("Do Nothing", Defense.DO_NOTHING);
chooseGoal = new SendableChooser();
chooseGoal.addDefault("Left Goal", Goal.LEFT);
chooseGoal.addObject("Middle Goal", Goal.MIDDLE);
chooseGoal.addObject("Right Goal", Goal.RIGHT);
chooseGoal.addObject("Do Nothing", Goal.DO_NOTHING);
chooseShoot = new SendableChooser();
chooseShoot.addObject("High Goal", new Integer(0));
chooseShoot.addObject("Low Goal", new Integer(1));
chooseShoot.addDefault("Do Nothing", new Integer(2));
choosePost = new SendableChooser();
choosePost.addObject("Get into Position", new Integer(1));
choosePost.addObject("Do Nothing", new Integer(0));
SmartDashboard.putData("ChooseStart", chooseStart);
SmartDashboard.putData("ChooseDefense", chooseDefense);
SmartDashboard.putData("ChooseGoal", chooseGoal);
SmartDashboard.putData("ChooseShoot", chooseShoot);
SmartDashboard.putData("ChoosePost", choosePost);
}
public boolean isValid(){
int start = getStart();
Defense defense = getDefense();
Goal goal = getGoal();
int shoot = getShoot();
int post = getPost();
if(start == 5) {
if(defense == Defense.LOW_BAR) {
if(goal == Goal.LEFT) {
return true;
} else {
return false;
}
} else if(defense == Defense.REACH_DEFENSE || defense == Defense.DO_NOTHING) {
if(goal == Goal.DO_NOTHING && shoot == 2 && post == 0)
return true;
else
return false;
} else {
return false;
}
} else if(start == 4) {
if(defense == Defense.REACH_DEFENSE || defense == Defense.DO_NOTHING) {
if(goal == Goal.DO_NOTHING && shoot == 2 && post == 0)
return true;
else
return false;
} else if(defense != null && defense != Defense.LOW_BAR) {
if(goal == Goal.LEFT) {
return true;
} else if(goal == Goal.MIDDLE) {
if(shoot == 1) {
return false;
} else {
return true;
}
} else {
return false;
}
} else {
return false;
}
} else if(start == 3 || start == 2 || start == 1) {
if(defense == Defense.REACH_DEFENSE || defense == Defense.DO_NOTHING) {
if(goal == Goal.DO_NOTHING && shoot == 2 && post == 0)
return true;
else
return false;
} else if(defense != null && defense != Defense.LOW_BAR) {
if(goal == Goal.MIDDLE) {
if(shoot == 1) {
return false;
} else {
return true;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
}
public Command createAutonCommand() {
int start = getStart();
Defense defense = getDefense();
Goal goal = getGoal();
int shoot = getShoot();
int post = getPost();
if(!isValid()) {
System.out.print("-- INVALID AUTON --");
return new AutonCommand();
} else {
// TODO: If Invalid Auton, just reach the defense so we get points
return new DriveDistance(2);
}
}
private class AutonCommand extends CommandGroup {
public AutonCommand() {
int start = getStart();
Defense defense = getDefense();
Goal goal = getGoal();
int shoot = getShoot();
int post = getPost();
switch(defense) {//first sequence, crosses the designated defense
case LOW_BAR:
addSequential(new SetAnglerPosition(RobotMap.Collector.COLLECTING));
addSequential(new CrossDefense());
break;
case MOAT:
case RAMPARTS:
addSequential(new CrossDefense(.65, true));
break;
case ROCK_WALL:
case ROUGH_TERRAIN:
addSequential(new CrossDefense(.5, true));
break;
case PORTCULLIS:
addSequential(new CrossPortcullis());
break;
case CHEVAL_DE_FRISE:
addSequential(new CrossCDF());
break;
default: // case Defense.DO_NOTHING && Defense.REACH_DEFENSE
addSequential(new DriveDistance(60, .5));
return; // If only Reaching Defense and Do Nothing
}
// We have only made it here if not Reaching Defense or Do Nothing
//This group of if statements determines what to do after crossing a defense
if(goal == Goal.DO_NOTHING) {
addSequential(new WaitCommand(0));
} else if(start == 5 && goal == Goal.LEFT) {
addSequential(new DriveDistance(43));
addSequential(new RotateUsingGyro(60));
} else if(start == 4 && goal == Goal.LEFT) {
addSequential(new RotateUsingGyro(-49.29));
addSequential(new SaveCurrentAngle());
addSequential(new DriveDistance(66.46));
addSequential(new RotateToPreviousAngle(109.29));
} else if(start == 4 && goal == Goal.MIDDLE) {
addSequential(new RotateUsingGyro(90));
addSequential(new SaveCurrentAngle());
addSequential(new DriveDistance(88.94));
addSequential(new RotateToPreviousAngle(-90));
} else if(start == 3) {
addSequential(new RotateUsingGyro(15));
addSequential(new DriveDistance(12));
} else if(start == 2 && goal == Goal.MIDDLE) {
// You are basically close enough
} else if(start == 2 && goal == Goal.RIGHT) {
addSequential(new RotateUsingGyro(55.68));
addSequential(new SaveCurrentAngle());
addSequential(new DriveDistance(112.81));
addSequential(new RotateToPreviousAngle(115.68));
} else if(start == 1 && goal == Goal.MIDDLE) {
addSequential(new RotateUsingGyro(-90));
addSequential(new SaveCurrentAngle());
addSequential(new DriveDistance(66.82));
addSequential(new RotateToPreviousAngle(90));
} else if(start == 1 && goal == Goal.RIGHT) {
addSequential(new RotateUsingGyro(33.93));
addSequential(new SaveCurrentAngle());
addSequential(new DriveDistance(76.66));
addSequential(new RotateToPreviousAngle(-93.93));
}
//This group of if statements determines what to do after positioning toward the enemy castle
if(shoot == 0) {
addParallel(new VisionRotateToTarget());// Get ourselves ready to target
addParallel(new SetShooterSpeed(69));
addSequential(new WaitCommand(.3));
addSequential(new Fire());
addSequential(new WaitCommand(.2));
} else if(shoot == 1) {
addSequential(new VisionRotateToTarget());// Should be targeted before moving -so Sequential instead of Parallel
if(goal == Goal.LEFT) {
addSequential(new SaveCurrentAngle());
addSequential(new DriveDistance(140));
addSequential(new RotateToPreviousAngle(180));
} else if(goal == Goal.RIGHT) {
addSequential(new SaveCurrentAngle());
addSequential(new DriveDistance(100));
addSequential(new RotateToPreviousAngle(180));
} else {
addSequential(new WaitCommand(1));
}
if(goal == Goal.LEFT || goal == Goal.RIGHT) {
addSequential(new SetCollectorPower(-.8));
addSequential(new WaitCommand(.25));
addSequential(new SetCollectorPower());
addSequential(new DriveDistance(12));
}
} else {
addSequential(new WaitCommand(0));
}
}
}
public void updateSmartDashboard() {
SmartDashboard.putBoolean("Valid Auton", isValid());
}
} |
package com.vaadin.data.util;
import java.io.Serializable;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import com.vaadin.data.Container;
import com.vaadin.data.Container.Filterable;
import com.vaadin.data.Container.PropertySetChangeNotifier;
import com.vaadin.data.Container.SimpleFilterable;
import com.vaadin.data.Container.Sortable;
import com.vaadin.data.Item;
import com.vaadin.data.Property;
import com.vaadin.data.Property.ValueChangeEvent;
import com.vaadin.data.Property.ValueChangeListener;
import com.vaadin.data.Property.ValueChangeNotifier;
import com.vaadin.data.util.MethodProperty.MethodException;
import com.vaadin.data.util.filter.SimpleStringFilter;
import com.vaadin.data.util.filter.UnsupportedFilterException;
/**
* An abstract base class for in-memory containers for JavaBeans.
*
* <p>
* The properties of the container are determined automatically by introspecting
* the used JavaBean class and explicitly adding or removing properties is not
* supported. Only beans of the same type can be added to the container.
* </p>
*
* <p>
* Subclasses should implement any public methods adding items to the container,
* typically calling the protected methods {@link #addItem(Object, Object)},
* {@link #addItemAfter(Object, Object, Object)} and
* {@link #addItemAt(int, Object, Object)}.
* </p>
*
* @param <IDTYPE>
* The type of the item identifier
* @param <BEANTYPE>
* The type of the Bean
*
* @since 6.5
*/
public abstract class AbstractBeanContainer<IDTYPE, BEANTYPE> extends
AbstractInMemoryContainer<IDTYPE, String, BeanItem<BEANTYPE>> implements
Filterable, SimpleFilterable, Sortable, ValueChangeListener,
PropertySetChangeNotifier {
/**
* Resolver that maps beans to their (item) identifiers, removing the need
* to explicitly specify item identifiers when there is no need to customize
* this.
*
* Note that beans can also be added with an explicit id even if a resolver
* has been set.
*
* @param <IDTYPE>
* @param <BEANTYPE>
*
* @since 6.5
*/
public static interface BeanIdResolver<IDTYPE, BEANTYPE> extends
Serializable {
/**
* Return the item identifier for a bean.
*
* @param bean
* @return
*/
public IDTYPE getIdForBean(BEANTYPE bean);
}
/**
* A item identifier resolver that returns the value of a bean property.
*
* The bean must have a getter for the property, and the getter must return
* an object of type IDTYPE.
*/
protected class PropertyBasedBeanIdResolver implements
BeanIdResolver<IDTYPE, BEANTYPE> {
private final Object propertyId;
public PropertyBasedBeanIdResolver(Object propertyId) {
if (propertyId == null) {
throw new IllegalArgumentException(
"Property identifier must not be null");
}
this.propertyId = propertyId;
}
@SuppressWarnings("unchecked")
public IDTYPE getIdForBean(BEANTYPE bean)
throws IllegalArgumentException {
VaadinPropertyDescriptor<BEANTYPE> pd = model.get(propertyId);
if (null == pd) {
throw new IllegalStateException("Property " + propertyId
+ " not found");
}
try {
Property<IDTYPE> property = pd.createProperty(bean);
return property.getValue();
} catch (MethodException e) {
throw new IllegalArgumentException(e);
}
}
}
/**
* The resolver that finds the item ID for a bean, or null not to use
* automatic resolving.
*
* Methods that add a bean without specifying an ID must not be called if no
* resolver has been set.
*/
private BeanIdResolver<IDTYPE, BEANTYPE> beanIdResolver = null;
/**
* Maps all item ids in the container (including filtered) to their
* corresponding BeanItem.
*/
private final Map<IDTYPE, BeanItem<BEANTYPE>> itemIdToItem = new HashMap<IDTYPE, BeanItem<BEANTYPE>>();
/**
* The type of the beans in the container.
*/
private final Class<? super BEANTYPE> type;
/**
* A description of the properties found in beans of type {@link #type}.
* Determines the property ids that are present in the container.
*/
private LinkedHashMap<String, VaadinPropertyDescriptor<BEANTYPE>> model;
protected AbstractBeanContainer(Class<? super BEANTYPE> type) {
if (type == null) {
throw new IllegalArgumentException(
"The bean type passed to AbstractBeanContainer must not be null");
}
this.type = type;
model = BeanItem.getPropertyDescriptors((Class<BEANTYPE>) type);
}
/*
* (non-Javadoc)
*
* @see com.vaadin.data.Container#getType(java.lang.Object)
*/
public Class<?> getType(Object propertyId) {
return model.get(propertyId).getPropertyType();
}
/**
* Create a BeanItem for a bean using pre-parsed bean metadata (based on
* {@link #getBeanType()}).
*
* @param bean
* @return created {@link BeanItem} or null if bean is null
*/
protected BeanItem<BEANTYPE> createBeanItem(BEANTYPE bean) {
return bean == null ? null : new BeanItem<BEANTYPE>(bean, model);
}
/**
* Returns the type of beans this Container can contain.
*
* This comes from the bean type constructor parameter, and bean metadata
* (including container properties) is based on this.
*
* @return
*/
public Class<? super BEANTYPE> getBeanType() {
return type;
}
/*
* (non-Javadoc)
*
* @see com.vaadin.data.Container#getContainerPropertyIds()
*/
public Collection<String> getContainerPropertyIds() {
return model.keySet();
}
/*
* (non-Javadoc)
*
* @see com.vaadin.data.Container#removeAllItems()
*/
@Override
public boolean removeAllItems() {
int origSize = size();
internalRemoveAllItems();
// detach listeners from all Items
for (Item item : itemIdToItem.values()) {
removeAllValueChangeListeners(item);
}
itemIdToItem.clear();
// fire event only if the visible view changed, regardless of whether
// filtered out items were removed or not
if (origSize != 0) {
fireItemSetChange();
}
return true;
}
/*
* (non-Javadoc)
*
* @see com.vaadin.data.Container#getItem(java.lang.Object)
*/
@Override
public BeanItem<BEANTYPE> getItem(Object itemId) {
// TODO return only if visible?
return getUnfilteredItem(itemId);
}
@Override
protected BeanItem<BEANTYPE> getUnfilteredItem(Object itemId) {
return itemIdToItem.get(itemId);
}
/*
* (non-Javadoc)
*
* @see com.vaadin.data.Container#getItemIds()
*/
@Override
@SuppressWarnings("unchecked")
public Collection<IDTYPE> getItemIds() {
return (Collection<IDTYPE>) super.getItemIds();
}
/*
* (non-Javadoc)
*
* @see com.vaadin.data.Container#getContainerProperty(java.lang.Object,
* java.lang.Object)
*/
public Property getContainerProperty(Object itemId, Object propertyId) {
Item item = getItem(itemId);
if (item == null) {
return null;
}
return item.getItemProperty(propertyId);
}
/*
* (non-Javadoc)
*
* @see com.vaadin.data.Container#removeItem(java.lang.Object)
*/
@Override
public boolean removeItem(Object itemId) {
// TODO should also remove items that are filtered out
int origSize = size();
Item item = getItem(itemId);
int position = indexOfId(itemId);
if (internalRemoveItem(itemId)) {
// detach listeners from Item
removeAllValueChangeListeners(item);
// remove item
itemIdToItem.remove(itemId);
// fire event only if the visible view changed, regardless of
// whether filtered out items were removed or not
if (size() != origSize) {
fireItemRemoved(position, itemId);
}
return true;
} else {
return false;
}
}
/**
* Re-filter the container when one of the monitored properties changes.
*/
public void valueChange(ValueChangeEvent event) {
// if a property that is used in a filter is changed, refresh filtering
filterAll();
}
/*
* (non-Javadoc)
*
* @see
* com.vaadin.data.Container.Filterable#addContainerFilter(java.lang.Object,
* java.lang.String, boolean, boolean)
*/
public void addContainerFilter(Object propertyId, String filterString,
boolean ignoreCase, boolean onlyMatchPrefix) {
try {
addFilter(new SimpleStringFilter(propertyId, filterString,
ignoreCase, onlyMatchPrefix));
} catch (UnsupportedFilterException e) {
// the filter instance created here is always valid for in-memory
// containers
}
}
/*
* (non-Javadoc)
*
* @see com.vaadin.data.Container.Filterable#removeAllContainerFilters()
*/
public void removeAllContainerFilters() {
if (!getFilters().isEmpty()) {
for (Item item : itemIdToItem.values()) {
removeAllValueChangeListeners(item);
}
removeAllFilters();
}
}
/*
* (non-Javadoc)
*
* @see
* com.vaadin.data.Container.Filterable#removeContainerFilters(java.lang
* .Object)
*/
public void removeContainerFilters(Object propertyId) {
Collection<Filter> removedFilters = super.removeFilters(propertyId);
if (!removedFilters.isEmpty()) {
// stop listening to change events for the property
for (Item item : itemIdToItem.values()) {
removeValueChangeListener(item, propertyId);
}
}
}
public void addContainerFilter(Filter filter)
throws UnsupportedFilterException {
addFilter(filter);
}
public void removeContainerFilter(Filter filter) {
removeFilter(filter);
}
/**
* Make this container listen to the given property provided it notifies
* when its value changes.
*
* @param item
* The {@link Item} that contains the property
* @param propertyId
* The id of the property
*/
private void addValueChangeListener(Item item, Object propertyId) {
Property property = item.getItemProperty(propertyId);
if (property instanceof ValueChangeNotifier) {
// avoid multiple notifications for the same property if
// multiple filters are in use
ValueChangeNotifier notifier = (ValueChangeNotifier) property;
notifier.removeListener(this);
notifier.addListener(this);
}
}
/**
* Remove this container as a listener for the given property.
*
* @param item
* The {@link Item} that contains the property
* @param propertyId
* The id of the property
*/
private void removeValueChangeListener(Item item, Object propertyId) {
Property property = item.getItemProperty(propertyId);
if (property instanceof ValueChangeNotifier) {
((ValueChangeNotifier) property).removeListener(this);
}
}
/**
* Remove this contains as a listener for all the properties in the given
* {@link Item}.
*
* @param item
* The {@link Item} that contains the properties
*/
private void removeAllValueChangeListeners(Item item) {
for (Object propertyId : item.getItemPropertyIds()) {
removeValueChangeListener(item, propertyId);
}
}
/*
* (non-Javadoc)
*
* @see com.vaadin.data.Container.Sortable#getSortableContainerPropertyIds()
*/
public Collection<?> getSortableContainerPropertyIds() {
return getSortablePropertyIds();
}
/*
* (non-Javadoc)
*
* @see com.vaadin.data.Container.Sortable#sort(java.lang.Object[],
* boolean[])
*/
public void sort(Object[] propertyId, boolean[] ascending) {
sortContainer(propertyId, ascending);
}
@Override
public ItemSorter getItemSorter() {
return super.getItemSorter();
}
@Override
public void setItemSorter(ItemSorter itemSorter) {
super.setItemSorter(itemSorter);
}
@Override
protected void registerNewItem(int position, IDTYPE itemId,
BeanItem<BEANTYPE> item) {
itemIdToItem.put(itemId, item);
// add listeners to be able to update filtering on property
// changes
for (Filter filter : getFilters()) {
for (String propertyId : getContainerPropertyIds()) {
if (filter.appliesToProperty(propertyId)) {
// addValueChangeListener avoids adding duplicates
addValueChangeListener(item, propertyId);
}
}
}
}
/**
* Check that a bean can be added to the container (is of the correct type
* for the container).
*
* @param bean
* @return
*/
private boolean validateBean(BEANTYPE bean) {
return bean != null && getBeanType().isAssignableFrom(bean.getClass());
}
/**
* Adds the bean to the Container.
*
* Note: the behavior of this method changed in Vaadin 6.6 - now items are
* added at the very end of the unfiltered container and not after the last
* visible item if filtering is used.
*
* @see com.vaadin.data.Container#addItem(Object)
*/
protected BeanItem<BEANTYPE> addItem(IDTYPE itemId, BEANTYPE bean) {
if (!validateBean(bean)) {
return null;
}
return internalAddItemAtEnd(itemId, createBeanItem(bean), true);
}
/**
* Adds the bean after the given bean.
*
* @see com.vaadin.data.Container.Ordered#addItemAfter(Object, Object)
*/
protected BeanItem<BEANTYPE> addItemAfter(IDTYPE previousItemId,
IDTYPE newItemId, BEANTYPE bean) {
if (!validateBean(bean)) {
return null;
}
return internalAddItemAfter(previousItemId, newItemId,
createBeanItem(bean), true);
}
/**
* Adds a new bean at the given index.
*
* The bean is used both as the item contents and as the item identifier.
*
* @param index
* Index at which the bean should be added.
* @param newItemId
* The item id for the bean to add to the container.
* @param bean
* The bean to add to the container.
*
* @return Returns the new BeanItem or null if the operation fails.
*/
protected BeanItem<BEANTYPE> addItemAt(int index, IDTYPE newItemId,
BEANTYPE bean) {
if (!validateBean(bean)) {
return null;
}
return internalAddItemAt(index, newItemId, createBeanItem(bean), true);
}
protected BeanItem<BEANTYPE> addBean(BEANTYPE bean)
throws IllegalStateException, IllegalArgumentException {
if (bean == null) {
return null;
}
IDTYPE itemId = resolveBeanId(bean);
if (itemId == null) {
throw new IllegalArgumentException(
"Resolved identifier for a bean must not be null");
}
return addItem(itemId, bean);
}
protected BeanItem<BEANTYPE> addBeanAfter(IDTYPE previousItemId,
BEANTYPE bean) throws IllegalStateException,
IllegalArgumentException {
if (bean == null) {
return null;
}
IDTYPE itemId = resolveBeanId(bean);
if (itemId == null) {
throw new IllegalArgumentException(
"Resolved identifier for a bean must not be null");
}
return addItemAfter(previousItemId, itemId, bean);
}
protected BeanItem<BEANTYPE> addBeanAt(int index, BEANTYPE bean)
throws IllegalStateException, IllegalArgumentException {
if (bean == null) {
return null;
}
IDTYPE itemId = resolveBeanId(bean);
if (itemId == null) {
throw new IllegalArgumentException(
"Resolved identifier for a bean must not be null");
}
return addItemAt(index, itemId, bean);
}
protected void addAll(Collection<? extends BEANTYPE> collection)
throws IllegalStateException {
boolean modified = false;
for (BEANTYPE bean : collection) {
// TODO skipping invalid beans - should not allow them in javadoc?
if (bean == null
|| !getBeanType().isAssignableFrom(bean.getClass())) {
continue;
}
IDTYPE itemId = resolveBeanId(bean);
if (internalAddItemAtEnd(itemId, createBeanItem(bean), false) != null) {
modified = true;
}
}
if (modified) {
// Filter the contents when all items have been added
if (isFiltered()) {
filterAll();
} else {
fireItemSetChange();
}
}
}
protected IDTYPE resolveBeanId(BEANTYPE bean) {
if (beanIdResolver == null) {
throw new IllegalStateException(
"Bean item identifier resolver is required.");
}
return beanIdResolver.getIdForBean(bean);
}
/**
* Sets the resolver that finds the item id for a bean, or null not to use
* automatic resolving.
*
* Methods that add a bean without specifying an id must not be called if no
* resolver has been set.
*
* Note that methods taking an explicit id can be used whether a resolver
* has been defined or not.
*
* @param beanIdResolver
* to use or null to disable automatic id resolution
*/
protected void setBeanIdResolver(
BeanIdResolver<IDTYPE, BEANTYPE> beanIdResolver) {
this.beanIdResolver = beanIdResolver;
}
/**
* Returns the resolver that finds the item ID for a bean.
*
* @return resolver used or null if automatic item id resolving is disabled
*/
public BeanIdResolver<IDTYPE, BEANTYPE> getBeanIdResolver() {
return beanIdResolver;
}
/**
* Create an item identifier resolver using a named bean property.
*
* @param propertyId
* property identifier, which must map to a getter in BEANTYPE
* @return created resolver
*/
protected BeanIdResolver<IDTYPE, BEANTYPE> createBeanPropertyResolver(
Object propertyId) {
return new PropertyBasedBeanIdResolver(propertyId);
}
@Override
public void addListener(Container.PropertySetChangeListener listener) {
super.addListener(listener);
}
@Override
public void removeListener(Container.PropertySetChangeListener listener) {
super.removeListener(listener);
}
@Override
public boolean addContainerProperty(Object propertyId, Class<?> type,
Object defaultValue) throws UnsupportedOperationException {
throw new UnsupportedOperationException(
"Use addNestedContainerProperty(String) to add container properties to a "
+ getClass().getSimpleName());
}
/**
* Adds a property for the container and all its items.
*
* Primarily for internal use, may change in future versions.
*
* @param propertyId
* @param propertyDescriptor
* @return true if the property was added
*/
protected final boolean addContainerProperty(String propertyId,
VaadinPropertyDescriptor<BEANTYPE> propertyDescriptor) {
if (null == propertyId || null == propertyDescriptor) {
return false;
}
// Fails if the Property is already present
if (model.containsKey(propertyId)) {
return false;
}
model.put(propertyId, propertyDescriptor);
for (BeanItem<BEANTYPE> item : itemIdToItem.values()) {
item.addItemProperty(propertyId,
propertyDescriptor.createProperty(item.getBean()));
}
// Sends a change event
fireContainerPropertySetChange();
return true;
}
/**
* Adds a nested container property for the container, e.g.
* "manager.address.street".
*
* All intermediate getters must exist and must return non-null values when
* the property value is accessed.
*
* @see NestedMethodProperty
*
* @param propertyId
* @return true if the property was added
*/
public boolean addNestedContainerProperty(String propertyId) {
return addContainerProperty(propertyId, new NestedPropertyDescriptor(
propertyId, type));
}
/**
* Adds a nested container properties for all sub-properties of a named
* property to the container. The named property itself is removed from the
* model as its subproperties are added.
*
* All intermediate getters must exist and must return non-null values when
* the property value is accessed.
*
* @see NestedMethodProperty
* @see #addNestedContainerProperty(String)
*
* @param propertyId
*/
@SuppressWarnings("unchecked")
public void addNestedContainerBean(String propertyId) {
Class<?> propertyType = getType(propertyId);
LinkedHashMap<String, VaadinPropertyDescriptor<Object>> pds = BeanItem
.getPropertyDescriptors((Class<Object>) propertyType);
for (String subPropertyId : pds.keySet()) {
String qualifiedPropertyId = propertyId + "." + subPropertyId;
NestedPropertyDescriptor<BEANTYPE> pd = new NestedPropertyDescriptor<BEANTYPE>(
qualifiedPropertyId, (Class<BEANTYPE>) type);
model.put(qualifiedPropertyId, pd);
model.remove(propertyId);
for (BeanItem<BEANTYPE> item : itemIdToItem.values()) {
item.addItemProperty(propertyId,
pd.createProperty(item.getBean()));
item.removeItemProperty(propertyId);
}
}
// Sends a change event
fireContainerPropertySetChange();
}
@Override
public boolean removeContainerProperty(Object propertyId)
throws UnsupportedOperationException {
// Fails if the Property is not present
if (!model.containsKey(propertyId)) {
return false;
}
// Removes the Property to Property list and types
model.remove(propertyId);
// If remove the Property from all Items
for (final Iterator<IDTYPE> i = getAllItemIds().iterator(); i.hasNext();) {
getUnfilteredItem(i.next()).removeItemProperty(propertyId);
}
// Sends a change event
fireContainerPropertySetChange();
return true;
}
} |
package ifc.sheet;
import com.sun.star.sheet.XScenario;
import com.sun.star.table.CellRangeAddress;
import com.sun.star.uno.Any;
import com.sun.star.uno.XInterface;
import lib.MultiMethodTest;
import lib.Status;
import util.ValueComparer;
public class _XScenario extends MultiMethodTest {
public XScenario oObj = null;
CellRangeAddress address = null;
String comment = null;
boolean skipTest = false;
public void before() {
// testing a scenario containing the whole sheet does not make sense.
// test is skipped until this interface is implemented somewhere else
skipTest = true;
}
public void _addRanges() {
if (skipTest) {
tRes.tested("addRanges()",Status.skipped(true));
return;
}
oObj.addRanges(new CellRangeAddress[] {address});
tRes.tested("addRanges()", true);
}
public void _apply() {
requiredMethod("addRanges()");
if (skipTest) {
tRes.tested("apply()",Status.skipped(true));
return;
}
oObj.apply();
tRes.tested("apply()", true);
}
public void _getIsScenario() {
requiredMethod("apply()");
if (skipTest) {
tRes.tested("getIsScenario()",Status.skipped(true));
return;
}
boolean getIs = oObj.getIsScenario();
tRes.tested("getIsScenario()", getIs);
}
public void _getScenarioComment() {
if (skipTest) {
tRes.tested("getScenarioComment()",Status.skipped(true));
return;
}
comment = oObj.getScenarioComment();
tRes.tested("getScenarioComment()", true);
}
public void _setScenarioComment() {
requiredMethod("getScenarioComment()");
if (skipTest) {
tRes.tested("setScenarioComment()",Status.skipped(true));
return;
}
boolean res = false;
oObj.setScenarioComment("MyComment");
String c = oObj.getScenarioComment();
res = c.equals("MyComment");
oObj.setScenarioComment(comment);
tRes.tested("setScenarioComment()", res);
}
} |
package raptor.connector.ics;
import java.util.StringTokenizer;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import raptor.Raptor;
import raptor.chat.ChatType;
import raptor.chat.Bugger.BuggerStatus;
import raptor.chess.AtomicGame;
import raptor.chess.BughouseGame;
import raptor.chess.ClassicGame;
import raptor.chess.CrazyhouseGame;
import raptor.chess.Game;
import raptor.chess.GameConstants;
import raptor.chess.GameFactory;
import raptor.chess.LosersGame;
import raptor.chess.Move;
import raptor.chess.SetupGame;
import raptor.chess.SuicideGame;
import raptor.chess.Variant;
import raptor.chess.pgn.PgnHeader;
import raptor.chess.pgn.PgnUtils;
import raptor.chess.pgn.RemainingClockTime;
import raptor.chess.util.GameUtils;
import raptor.chess.util.ZobristUtils;
import raptor.connector.Connector;
import raptor.connector.ics.game.message.G1Message;
import raptor.connector.ics.game.message.MovesMessage;
import raptor.connector.ics.game.message.Style12Message;
import raptor.swt.chess.ChessBoardController;
import raptor.swt.chess.ChessBoardUtils;
import raptor.swt.chess.controller.BughouseSuggestController;
import raptor.swt.chess.controller.ExamineController;
import raptor.swt.chess.controller.ObserveController;
import raptor.swt.chess.controller.PlayingController;
import raptor.swt.chess.controller.SetupController;
import raptor.util.RaptorStringTokenizer;
public class IcsUtils implements GameConstants {
public static final String ATOMIC_IDENTIFIER = "atomic";
public static final String BLITZ_IDENTIFIER = "blitz";
public static final String BUGHOUSE_IDENTIFIER = "bughouse";
public static final String CHANNEL_STRIP_CHARS = "()~!@?
public static final String CRAZYHOUSE_IDENTIFIER = "crazyhouse";
public static final String LEGAL_CHARACTERS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890 "
+ "!@
public static final String LIGHTNING_IDENTIFIER = "lightning";
private static final Log LOG = LogFactory.getLog(IcsUtils.class);
public static final String LOSERS_IDENTIFIER = "losers";
public static final String STANDARD_IDENTIFIER = "standard";
public static final String STRIP_CHARS = "()~!@?#$%^&*_+|}{'\";/?<>.,:[]1234567890";
public static final String SUICIDE_IDENTIFIER = "suicide";
public static final String UNTIMED_IDENTIFIER = "untimed";
public static final String VALID_PERSON_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
public static final String WILD_IDENTIFIER = "wild";
/**
* Returns true if a move was added, false if no move was added (This can
* occur on a refresh or a game end.).
*/
public static boolean addCurrentMove(Game game, Style12Message message) {
boolean result = false;
if (!message.isWhitesMoveAfterMoveIsMade
&& game.getColorToMove() != WHITE
|| message.isWhitesMoveAfterMoveIsMade
&& game.getColorToMove() == WHITE) {
// At the end of a game multiple <12> messages are sent.
// The are also sent when a refresh is sent.
game.setHeader(PgnHeader.WhiteRemainingMillis, ""
+ message.whiteRemainingTimeMillis);
game.setHeader(PgnHeader.BlackRemainingMillis, ""
+ message.blackRemainingTimeMillis);
if (message.timeTakenForLastMoveMillis != 0) {
game.getMoveList().get(game.getMoveList().getSize() - 1)
.addAnnotation(
new RemainingClockTime(
message.timeTakenForLastMoveMillis));
}
} else {
if (message.san.equals("none")) {
Raptor
.getInstance()
.onError(
"Received a none for san in a style 12 event. This should have contained a move.");
} else {
Move move = game.makeSanMove(message.san);
move.addAnnotation(new RemainingClockTime(
message.timeTakenForLastMoveMillis));
}
game.setHeader(PgnHeader.WhiteRemainingMillis, ""
+ message.whiteRemainingTimeMillis);
game.setHeader(PgnHeader.BlackRemainingMillis, ""
+ message.blackRemainingTimeMillis);
if (message.isWhitesMoveAfterMoveIsMade) {
String lag = StringUtils.defaultString(game
.getHeader(PgnHeader.BlackLagMillis), "0");
game.setHeader(PgnHeader.BlackLagMillis, ""
+ (Long.parseLong(lag) + message.lagInMillis));
} else {
String lag = StringUtils.defaultString(game
.getHeader(PgnHeader.WhiteLagMillis), "0");
game.setHeader(PgnHeader.WhiteLagMillis, ""
+ (Long.parseLong(lag) + message.lagInMillis));
}
result = true;
}
if (message.isClockTicking) {
game.addState(Game.IS_CLOCK_TICKING_STATE);
} else {
game.clearState(Game.IS_CLOCK_TICKING_STATE);
}
return result;
}
/**
* Returns true if the game was adjusted for takebacks. False otherwise.
*/
public static boolean adjustToTakebacks(Game game, Style12Message message,
Connector connector) {
boolean result = false;
int currentHalfMove = (message.fullMoveNumber - 1) * 2
+ (message.isWhitesMoveAfterMoveIsMade ? 0 : 1);
if (LOG.isDebugEnabled()) {
LOG.debug("adjustToTakebacks calculatedHalfMove " + currentHalfMove
+ " 12FulLMoveNumber " + message.fullMoveNumber
+ " 12isWhitesMoveAfter "
+ message.isWhitesMoveAfterMoveIsMade + " gameHalfMove "
+ game.getHalfMoveCount());
}
if (currentHalfMove != game.getHalfMoveCount() + 1) {
if (game.getHalfMoveCount() < currentHalfMove) {
if (LOG.isDebugEnabled()) {
LOG
.debug("Didnt have all the moves needed for rollback. Resetting game and sending moves request.");
}
resetGame(game, message);
connector.sendMessage("moves " + message.gameId, true,
ChatType.MOVES);
result = true;
} else {
while (game.getHalfMoveCount() > currentHalfMove) {
if (LOG.isDebugEnabled()) {
LOG.debug("Rolled back a move.");
}
game.rollback();
}
result = true;
}
}
if (message.isClockTicking) {
game.addState(Game.IS_CLOCK_TICKING_STATE);
} else {
game.clearState(Game.IS_CLOCK_TICKING_STATE);
}
return result;
}
public static ChessBoardController buildController(Game game,
Connector connector) {
return buildController(game, connector, false);
}
public static ChessBoardController buildController(Game game,
Connector connector, boolean isBughouseOtherBoard) {
ChessBoardController controller = null;
if (game.isInState(Game.OBSERVING_STATE)
|| game.isInState(Game.OBSERVING_EXAMINED_STATE)) {
if (isBughouseOtherBoard) {
if (((BughouseGame) game).getOtherBoard().isInState(
Game.PLAYING_STATE)) {
Game otherGame = ((BughouseGame) game).getOtherBoard();
boolean isPartnerWhite = !StringUtils.equals(otherGame
.getHeader(PgnHeader.White), connector
.getUserName());
controller = new BughouseSuggestController(game, connector,
isPartnerWhite);
} else {
controller = new ObserveController(game, connector);
}
} else {
controller = new ObserveController(game, connector);
}
} else if (game.isInState(Game.SETUP_STATE)) {
controller = new SetupController(game, connector);
} else if (game.isInState(Game.EXAMINING_STATE)) {
controller = new ExamineController(game, connector);
} else if (game.isInState(Game.PLAYING_STATE)) {
controller = new PlayingController(game, connector);
} else {
LOG.error("Could not find controller type for game state. "
+ "Ignoring game. state= " + game.getState());
}
return controller;
}
/**
* Cleans up the message by ensuring only \n is used as a line terminator.
* \r\n and \r may be used depending on the operating system.
*/
public static String cleanupMessage(String message) {
return StringUtils.remove(message, '\r');
}
/**
* Clears out all the games position state.
*/
public static void clearGamePosition(Game game) {
game.clear();
}
public static Game createGame(G1Message g1) {
Game result = null;
Variant variant = IcsUtils.identifierToGameType(g1.gameTypeDescription);
switch (variant) {
case classic:
result = new ClassicGame();
break;
case wild:
result = new ClassicGame();
result.setHeader(PgnHeader.Variant, Variant.wild.name());
case suicide:
result = new SuicideGame();
break;
case losers:
result = new LosersGame();
break;
case atomic:
result = new AtomicGame();
break;
case crazyhouse:
result = new CrazyhouseGame();
break;
case bughouse:
result = new BughouseGame();
break;
default:
LOG.error("Uhandled game type " + g1.gameTypeDescription);
throw new IllegalStateException("Unsupported game type" + variant);
}
result.setId(g1.gameId);
result.addState(Game.UPDATING_SAN_STATE);
result.addState(Game.UPDATING_ECO_HEADERS_STATE);
result.setHeader(PgnHeader.Date, PgnUtils.longToPgnDate(System
.currentTimeMillis()));
result.setHeader(PgnHeader.Round, "?");
result.setHeader(PgnHeader.Site, "freechess.org");
result.setHeader(PgnHeader.TimeControl, PgnUtils
.timeIncMillisToTimeControl(g1.initialWhiteTimeMillis,
g1.initialWhiteIncMillis));
result.setHeader(PgnHeader.BlackRemainingMillis, ""
+ g1.initialBlackTimeMillis);
result.setHeader(PgnHeader.WhiteRemainingMillis, ""
+ g1.initialWhiteTimeMillis);
result.setHeader(PgnHeader.WhiteClock, PgnUtils
.timeToClock(g1.initialWhiteTimeMillis));
result.setHeader(PgnHeader.BlackClock, PgnUtils
.timeToClock(g1.initialBlackTimeMillis));
result.setHeader(PgnHeader.BlackElo, g1.blackRating);
result.setHeader(PgnHeader.WhiteElo, g1.whiteRating);
result.setHeader(PgnHeader.Event, g1.initialWhiteTimeMillis / 60000
+ " " + g1.initialWhiteIncMillis / 1000 + " "
+ (!g1.isRated ? "unrated" : "rated") + " "
+ (g1.isPrivate ? "private " : "") + g1.gameTypeDescription);
return result;
}
public static Game createGame(Style12Message message, String entireMessage) {
if (message.relation == Style12Message.EXAMINING_GAME_RELATION) {
boolean isSetup = entireMessage.contains("Entering setup mode.\n");
Game game = isSetup ? new SetupGame() : new ClassicGame();
game.setId(message.gameId);
game.addState(Game.UPDATING_SAN_STATE);
game.addState(Game.UPDATING_ECO_HEADERS_STATE);
game.setHeader(PgnHeader.Date, PgnUtils.longToPgnDate(System
.currentTimeMillis()));
game.setHeader(PgnHeader.Round, "?");
game.setHeader(PgnHeader.Site, "freechess.org");
game.setHeader(PgnHeader.TimeControl, PgnUtils
.timeIncMillisToTimeControl(0, 0));
game.setHeader(PgnHeader.BlackRemainingMillis, "" + 0);
game.setHeader(PgnHeader.WhiteRemainingMillis, "" + 0);
game.setHeader(PgnHeader.WhiteClock, PgnUtils.timeToClock(0));
game.setHeader(PgnHeader.BlackClock, PgnUtils.timeToClock(0));
game.setHeader(PgnHeader.BlackElo, "");
game.setHeader(PgnHeader.WhiteElo, "");
game.setHeader(PgnHeader.Event, isSetup ? "Setting Up Position"
: "Examining Game");
updateNonPositionFields(game, message);
updatePosition(game, message);
verifyLegal(game);
return game;
} else {
LOG.error("Cant create an examined game for relation "
+ message.relation);
throw new IllegalStateException(
"Cant created a examined or setup game from a game with relation "
+ message.relation);
}
}
public static void filterOutbound(StringBuilder message) {
for (int i = 0; i < message.length(); i++) {
char currentChar = message.charAt(i);
if (LEGAL_CHARACTERS.indexOf(currentChar) == -1) {
if (currentChar > 256) {
int charAsInt = currentChar;
String stringVersion = Integer.toString(charAsInt, 16);
String replacement = "&#x" + stringVersion + ";";
message.replace(i, i + 1, replacement);
i += replacement.length() - 1;
} else {
message.deleteCharAt(i);
i
}
}
}
}
public static BuggerStatus getBuggserStatus(String status) {
if (status.equals(":")) {
return BuggerStatus.Closed;
} else if (status.equals("^")) {
return BuggerStatus.Playing;
} else if (status.equals(".")) {
return BuggerStatus.Idle;
} else if (status.equals("~")) {
return BuggerStatus.Simul;
} else if (status.equals("
return BuggerStatus.Examining;
} else if (status.equals("&")) {
return BuggerStatus.InTourney;
} else {
return BuggerStatus.Available;
}
}
/**
* Returns the game type constant for the specified identifier.
*
*/
public static Variant identifierToGameType(String identifier) {
Variant result = null;
if (identifier.indexOf(SUICIDE_IDENTIFIER) != -1) {
result = Variant.suicide;
} else if (identifier.indexOf(BUGHOUSE_IDENTIFIER) != -1) {
result = Variant.bughouse;
} else if (identifier.indexOf(CRAZYHOUSE_IDENTIFIER) != -1) {
result = Variant.crazyhouse;
} else if (identifier.indexOf(STANDARD_IDENTIFIER) != -1) {
result = Variant.classic;
} else if (identifier.indexOf(WILD_IDENTIFIER) != -1) {
result = Variant.wild;
} else if (identifier.indexOf(LIGHTNING_IDENTIFIER) != -1) {
result = Variant.classic;
} else if (identifier.indexOf(BLITZ_IDENTIFIER) != -1) {
result = Variant.classic;
} else if (identifier.indexOf(ATOMIC_IDENTIFIER) != -1) {
result = Variant.atomic;
} else if (identifier.indexOf(LOSERS_IDENTIFIER) != -1) {
result = Variant.losers;
} else if (identifier.indexOf(UNTIMED_IDENTIFIER) != -1) {
result = Variant.classic;
} else {
throw new IllegalArgumentException("Unknown identifier "
+ identifier
+ " encountered. Please notify someone on the raptor team "
+ "so they can implement this new game type.");
}
return result;
}
/**
* Removes the ICS channel wrapping around a specified channel word
* returning only the channel number.
*
* Returns -1 if the specified word is not a channel.
*/
public static boolean isLikelyChannel(String word) {
boolean result = false;
if (word != null) {
RaptorStringTokenizer tok = new RaptorStringTokenizer(word,
CHANNEL_STRIP_CHARS, true);
if (tok.hasMoreTokens()) {
String current = tok.nextToken();
try {
int channel = Integer.parseInt(current);
return channel >= 0 && channel <= 255;
} catch (NumberFormatException nfe) {
if (tok.hasMoreTokens()) {
try {
current = tok.nextToken();
int channel = Integer.parseInt(current);
return channel >= 0 && channel <= 255;
} catch (NumberFormatException nfe2) {
}
}
}
}
}
return result;
}
public static boolean isLikelyGameId(String word) {
boolean result = false;
if (word != null) {
try {
int gameId = Integer.parseInt(stripWord(word));
return gameId > 0 && gameId <= 5000;
} catch (NumberFormatException nfe) {
return false;
}
}
return result;
}
/**
* Returns true if the specified word is probably a persons name.
*/
public static boolean isLikelyPerson(String word) {
String strippedWord = stripWord(word);
if (word != null && strippedWord.length() > 2) {
boolean result = true;
for (int i = 0; result && i < strippedWord.length(); i++) {
result = VALID_PERSON_CHARS.indexOf(word.charAt(i)) != -1;
}
return result;
} else {
return false;
}
}
/**
* Maciejg format, named after him because of his finger notes. Unicode
* chars are represented as α β γ δ ε ζ
* unicode equivalent \u03B1,\U03B2,...
*/
public static String maciejgFormatToUnicode(String inputString) {
StringBuilder builder = new StringBuilder(inputString);
int unicodePrefix = 0;
while ((unicodePrefix = builder.indexOf("&#x", unicodePrefix)) != -1) {
int endIndex = builder.indexOf(";", unicodePrefix);
if (endIndex != -1 && endIndex - unicodePrefix <= 8) {
String unicodeHex = builder.substring(unicodePrefix + 3,
endIndex).toUpperCase();
try {
int intValue = Integer.parseInt(unicodeHex, 16);
String replacement = new String(
new char[] { (char) intValue });
builder.replace(unicodePrefix, endIndex + 1, replacement);
} catch (NumberFormatException nfe) {
unicodePrefix = endIndex;
}
}
}
return builder.toString();
}
/**
* Removes all line breaks and excessive spaces from the specified message.
*
* @param msg
* THe message to remove line breaks from.
* @return The message without any line breaks.
*/
public static String removeLineBreaks(String msg) {
StringBuilder result = new StringBuilder(msg.length());
RaptorStringTokenizer tok = new RaptorStringTokenizer(msg, "\n\\ ",
true);
if (tok.hasMoreTokens()) {
result.append(tok.nextToken());
}
while (tok.hasMoreTokens()) {
result.append(" " + tok.nextToken());
}
return result.toString();
}
public static void resetGame(Game game, Style12Message message) {
IcsUtils.clearGamePosition(game);
IcsUtils.updateNonPositionFields(game, message);
IcsUtils.updatePosition(game, message);
verifyLegal(game);
}
public static String stripChannel(String word) {
String result = null;
if (word != null) {
RaptorStringTokenizer tok = new RaptorStringTokenizer(word,
CHANNEL_STRIP_CHARS, true);
if (tok.hasMoreTokens()) {
String current = tok.nextToken();
try {
int channel = Integer.parseInt(current);
if (channel >= 0 && channel <= 255) {
return "" + channel;
}
} catch (NumberFormatException nfe) {
if (tok.hasMoreTokens()) {
try {
current = tok.nextToken();
int channel = Integer.parseInt(current);
if (channel >= 0 && channel <= 255) {
return "" + channel;
}
} catch (NumberFormatException nfe2) {
}
}
}
}
}
return result;
}
public static String stripGameId(String gameId) {
return gameId;
}
public static String stripTitles(String playerName) {
StringTokenizer stringtokenizer = new StringTokenizer(playerName,
"()~!@
if (stringtokenizer.hasMoreTokens()) {
return stringtokenizer.nextToken();
} else {
return playerName;
}
}
/**
* Returns the word with all characters in: ()~!@?#$%^&*_+|}{'\";/?<>.,
* :[]1234567890\t\r\n removed.
*/
public static String stripWord(String word) {
if (word != null) {
RaptorStringTokenizer stringtokenizer = new RaptorStringTokenizer(
word, STRIP_CHARS, true);
if (stringtokenizer.hasMoreTokens()) {
return stringtokenizer.nextToken();
} else {
return word;
}
}
return null;
}
/**
* Converts a time in: (0:00.000) mmm:ss.MMM format into a long value
* representing milliseconds.
*
* @param timeString
* The time string.
* @return The result.
*/
public static final long timeToLong(String timeString) {
RaptorStringTokenizer tok = new RaptorStringTokenizer(timeString,
"(:.)", true);
long minutes = Integer.parseInt(tok.nextToken());
long seconds = Integer.parseInt(tok.nextToken());
long millis = Integer.parseInt(tok.nextToken());
return minutes * 1000 * 60 + seconds * 1000 + millis;
}
/**
* Updates the moves that are missing in the game to the ones in the move
* message.
*/
public static void updateGamesMoves(Game game, MovesMessage message) {
int halfMoveCountGameStartedOn = game.getHalfMoveCount()
- game.getMoveList().getSize();
if (halfMoveCountGameStartedOn != 0) {
Game gameClone = GameFactory.createStartingPosition(game
.getVariant());
gameClone.addState(Game.UPDATING_ECO_HEADERS_STATE);
for (int i = 0; i < halfMoveCountGameStartedOn; i++) {
try {
if (gameClone.isInState(Game.DROPPABLE_STATE)) {
gameClone.setDropCount(WHITE, PAWN, 1);
gameClone.setDropCount(WHITE, QUEEN, 1);
gameClone.setDropCount(WHITE, ROOK, 1);
gameClone.setDropCount(WHITE, KNIGHT, 1);
gameClone.setDropCount(WHITE, BISHOP, 1);
gameClone.setDropCount(BLACK, PAWN, 1);
gameClone.setDropCount(BLACK, QUEEN, 1);
gameClone.setDropCount(BLACK, ROOK, 1);
gameClone.setDropCount(BLACK, KNIGHT, 1);
gameClone.setDropCount(BLACK, BISHOP, 1);
}
Move move = gameClone.makeSanMove(message.moves[i]);
move.addAnnotation(new RemainingClockTime(
message.timePerMove[i]));
} catch (IllegalArgumentException iae) {
LOG.error("Could not parse san", iae);
Raptor.getInstance().onError(
"Error update game with moves", iae);
}
}
Move[] moves = gameClone.getMoveList().asArray();
game.getMoveList().prepend(moves);
game.setInitialEpSquare(gameClone.getInitialEpSquare());
if (StringUtils.isBlank(game.getHeader(PgnHeader.ECO))
&& StringUtils.isNotBlank(gameClone
.getHeader(PgnHeader.ECO))) {
game.setHeader(PgnHeader.ECO, gameClone
.getHeader(PgnHeader.ECO));
}
if (StringUtils.isBlank(game.getHeader(PgnHeader.Opening))
&& StringUtils.isNotBlank(gameClone
.getHeader(PgnHeader.Opening))) {
game.setHeader(PgnHeader.Opening, gameClone
.getHeader(PgnHeader.Opening));
}
}
}
/**
* Handles updating everything but the position related fields in the game.
* i.e. the bitboards,pieces, etc.
*/
public static void updateNonPositionFields(Game game, Style12Message message) {
switch (message.relation) {
case Style12Message.EXAMINING_GAME_RELATION:
game.addState(Game.EXAMINING_STATE);
break;
case Style12Message.ISOLATED_POSITION_RELATION:
throw new IllegalArgumentException(
"Isolated positions are not currently implemented. "
+ game.getId() + " " + message);
case Style12Message.OBSERVING_EXAMINED_GAME_RELATION:
game.addState(Game.OBSERVING_EXAMINED_STATE);
break;
case Style12Message.OBSERVING_GAME_RELATION:
game.addState(Game.OBSERVING_STATE);
break;
case Style12Message.PLAYING_MY_MOVE_RELATION:
case Style12Message.PLAYING_OPPONENTS_MOVE_RELATION:
game.addState(Game.PLAYING_STATE);
break;
}
if (message.isClockTicking) {
game.addState(Game.IS_CLOCK_TICKING_STATE);
} else {
game.clearState(Game.IS_CLOCK_TICKING_STATE);
}
game.addState(Game.ACTIVE_STATE);
game
.setHeader(PgnHeader.Black, IcsUtils
.stripTitles(message.blackName));
game
.setHeader(PgnHeader.White, IcsUtils
.stripTitles(message.whiteName));
game.setHeader(PgnHeader.WhiteRemainingMillis, ""
+ message.whiteRemainingTimeMillis);
game.setHeader(PgnHeader.BlackRemainingMillis, ""
+ message.blackRemainingTimeMillis);
game
.setColorToMove(message.isWhitesMoveAfterMoveIsMade ? WHITE
: BLACK);
game.setCastling(WHITE, message.canWhiteCastleKSide
&& message.canWhiteCastleQSide ? CASTLE_BOTH
: message.canWhiteCastleKSide ? CASTLE_SHORT
: message.canWhiteCastleQSide ? CASTLE_LONG
: CASTLE_NONE);
game.setCastling(BLACK, message.canBlackCastleKSide
&& message.canBlackCastleQSide ? CASTLE_BOTH
: message.canBlackCastleKSide ? CASTLE_SHORT
: message.canBlackCastleQSide ? CASTLE_LONG
: CASTLE_NONE);
if (message.doublePawnPushFile == -1) {
game.setEpSquare(EMPTY_SQUARE);
game.setInitialEpSquare(EMPTY_SQUARE);
} else {
int doublePawnPushSquare = GameUtils.getSquare(
message.isWhitesMoveAfterMoveIsMade ? 4 : 5,
message.doublePawnPushFile);
game.setEpSquare(doublePawnPushSquare);
game.setInitialEpSquare(doublePawnPushSquare);
}
game.setFiftyMoveCount(message.numberOfMovesSinceLastIrreversible);
int fullMoveCount = message.fullMoveNumber;
game
.setHalfMoveCount(game.getColorToMove() == BLACK ? fullMoveCount * 2 - 1
: fullMoveCount * 2 - 2);
game.incrementRepCount();
}
/**
* Should be invoked after the castling,EP,and to move data has been set.
*/
public static void updatePosition(Game game, Style12Message style12) {
for (int i = 0; i < style12.position.length; i++) {
for (int j = 0; j < style12.position[i].length; j++) {
if (style12.position[i][j] != EMPTY) {
int square = GameUtils.getSquare(i, j);
int pieceColor = ChessBoardUtils
.isWhitePiece(style12.position[i][j]) ? WHITE
: BLACK;
int piece = ChessBoardUtils
.pieceFromColoredPiece(style12.position[i][j]);
long squareBB = GameUtils.getBitboard(square);
game.setPieceCount(pieceColor, piece, game.getPieceCount(
pieceColor, piece) + 1);
game.getBoard()[square] = piece;
game.setColorBB(pieceColor, game.getColorBB(pieceColor)
| squareBB);
game.setOccupiedBB(game.getOccupiedBB() | squareBB);
game.setPieceBB(pieceColor, piece, game.getPieceBB(
pieceColor, piece)
| squareBB);
}
}
}
game.setEmptyBB(~game.getOccupiedBB());
game.setNotColorToMoveBB(~game.getColorBB(game.getColorToMove()));
game.setZobristPositionHash(ZobristUtils.zobristHashPositionOnly(game));
game.setZobristGameHash(game.getZobristPositionHash()
^ ZobristUtils.zobrist(game.getColorToMove(), game
.getEpSquare(), game.getCastling(WHITE), game
.getCastling(BLACK)));
if (game.isInState(Game.SETUP_STATE)) {
game.setPieceCount(WHITE, PAWN, 1);
game.setPieceCount(WHITE, KNIGHT, 1);
game.setPieceCount(WHITE, BISHOP, 1);
game.setPieceCount(WHITE, ROOK, 1);
game.setPieceCount(WHITE, QUEEN, 1);
game.setPieceCount(WHITE, KING, 1);
game.setPieceCount(BLACK, PAWN, 1);
game.setPieceCount(BLACK, KNIGHT, 1);
game.setPieceCount(BLACK, BISHOP, 1);
game.setPieceCount(BLACK, ROOK, 1);
game.setPieceCount(BLACK, QUEEN, 1);
game.setPieceCount(BLACK, KING, 1);
}
}
public static void verifyLegal(Game game) {
if (!game.isLegalPosition()) {
throw new IllegalStateException("Position is not legal: "
+ game.toString());
}
}
} |
package j2s;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.text.TextSelection;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.FontData;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.ISelectionListener;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.ViewPart;
import org.eclipse.ui.texteditor.ITextEditor;
public class J2SView extends ViewPart {
Label label;
Button button;
Composite parent;
String selectedText = null;
String selectedLink = "";
public J2SView() {
}
public void createPartControl(Composite parent) {
this.parent = parent;
parent.setLayout(new RowLayout(SWT.VERTICAL));
label = new Label(parent, SWT.WRAP);
FontData[] fD = label.getFont().getFontData();
fD[0].setHeight(16);
label.setFont(new Font(null, fD));
button = new Button(parent, SWT.PUSH);
button.setText("Generate Query");
button.addSelectionListener(buttonListener);
getSite().getWorkbenchWindow().getSelectionService().addSelectionListener(selectionListener);
}
private SelectionListener buttonListener = new SelectionListener() {
@Override
public void widgetSelected(SelectionEvent arg0) {
label.setForeground(new Color(Display.getCurrent(), 255, 0, 0));
String filename = System.getProperty("user.home") + "/Downloads/methodSelection.txt";
File file = new File(filename);
file.setReadable(true);
file.setWritable(true);
PrintWriter writer = null;
try {
writer = new PrintWriter(file);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
writer.print(selectedText);
writer.close();
label.setText("Query generated, awaiting results...");
parent.layout(true, true);
GenerateSwiftQueryString tester = new GenerateSwiftQueryString();
ArrayList<String> searchKeywords = tester.executeFrequencyAnalysis(filename);
System.out.println("PRINTING KEYWORDS: " + searchKeywords.toString());
SearchAndRank sar = null;
try {
sar = new SearchAndRank(searchKeywords);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ArrayList<MetaData> rankedResults = sar.sortedFinalRanking;
for (int i = 0; i < rankedResults.size(); i++) {
System.out.println(rankedResults.get(i).getID());
System.out.println(rankedResults.get(i).printFields());
System.out.println(rankedResults.get(i).getCosValueFinal());
System.out.println(rankedResults.get(i).getNormLinScore());
System.out.println(rankedResults.get(i).getFinalRankingScore());
}
label.setText("Results: ");
for (int i = 0; i < 2; i++) {
MetaData result = rankedResults.get(i);
if (result == null) {
continue;
} else {
newActionLink(parent, result.getQuestionTitle()
+ "\nhttp:
}
}
button.setVisible(false);
parent.layout(true, true);
}
@Override
public void widgetDefaultSelected(SelectionEvent arg0) {
// TODO Auto-generated method stub
}
};
/**
* Creates and returns a new Link, which when selected, will run the
* specified action.
*
* @param parent
* The parent composite in which to create the new link.
* @param text
* The text to display in the link.
* @return The new link.
*/
public Button newActionLink(Composite parent, String text) {
Button button1 = new Button(parent, SWT.RADIO);
FontData[] fD = button1.getFont().getFontData();
fD[0].setHeight(16);
button1.setFont(new Font(null, fD));
button1.setSelection(false);
button1.setText(text);
button1.setBackground(parent.getBackground());
button1.addSelectionListener(linkListener);
return button1;
}
private SelectionListener linkListener = new SelectionListener() {
@Override
public void widgetSelected(SelectionEvent arg0) {
Button test = (Button) arg0.getSource();
System.out.println(test.getText().split("\n")[1]);
StringSelection selection = new StringSelection(test.getText().split("\n")[1]);
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(selection, selection);
label.setText("URL copied to clipboard");
// button.setVisible(true);
parent.layout(true, true);
}
@Override
public void widgetDefaultSelected(SelectionEvent arg0) {
// TODO Auto-generated method stub
}
};
public static void main(String[] args) {
String filename = System.getProperty("user.home") + "/Downloads/methodSelection.txt";
// String filename =
// "C:\\Users\\Antuan\\Downloads\\methodSelection.txt";
GenerateSwiftQueryString tester = new GenerateSwiftQueryString();
ArrayList<String> searchKeywords = tester.executeFrequencyAnalysis(filename);
System.out.println("PRINTING KEYWORDS: " + searchKeywords.toString());
SearchAndRank sar = null;
try {
sar = new SearchAndRank(searchKeywords);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ArrayList<MetaData> rankedResults = sar.sortedFinalRanking;
for (int i = 0; i < rankedResults.size(); i++) {
System.out.println(rankedResults.get(i).getID());
System.out.println(rankedResults.get(i).printFields());
System.out.println(rankedResults.get(i).getCosValueFinal());
System.out.println(rankedResults.get(i).getNormLinScore());
System.out.println(rankedResults.get(i).getFinalRankingScore());
}
System.out.println("Number 1 ranked answer body is: ");
System.out.println(rankedResults.get(0).getAnswerBody().toString());
System.out.println("Number 2 ranked answer body is: ");
System.out.println(rankedResults.get(1).getAnswerBody().toString());
}
private ISelectionListener selectionListener = new ISelectionListener() {
public void selectionChanged(IWorkbenchPart sourcepart, ISelection selection) {
if (sourcepart != J2SView.this) {
showSelection(sourcepart, selection);
}
}
};
public void showSelection(IWorkbenchPart sourcepart, ISelection selection) {
setContentDescription(sourcepart.getTitle() + " (" + selection.getClass().getName() + ")");
if (selection instanceof TextSelection) {
label.setForeground(new Color(Display.getCurrent(), 0, 0, 0));
ITextSelection ts = (ITextSelection) selection;
selectedText = ts.getText();
String[] lines = selectedText.split("\r\n|\r|\n");
if (selectedText.equals("") || selectedText == null) {
label.setText("Select entire method from Java file");
} else {
int startIndex = -1;
int endIndex = -1;
if (selectedText.contains("public")) {
startIndex = selectedText.indexOf("public");
endIndex = selectedText.indexOf(")", startIndex);
} else if (selectedText.contains("private")) {
startIndex = selectedText.indexOf("private");
endIndex = selectedText.indexOf(")", startIndex);
}
if (startIndex != -1 && endIndex != -1) {
String methodDeclaration = selectedText.substring(startIndex, endIndex + 1);
label.setText("Selected " + lines.length + " lines from method: \n\n" + methodDeclaration);
} else {
label.setText("Selected a valid method from the Java file.");
}
}
parent.layout(true, true);
}
}
public String getCurrentSelectedText() {
final IEditorPart editor = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor();
if (!(editor instanceof ITextEditor))
return null;
ITextEditor ite = (ITextEditor) editor;
ITextSelection its = (ITextSelection) ite.getSelectionProvider().getSelection();
return its.getText();
}
public void setFocus() {
// set focus to my widget. For a label, this doesn't
// make much sense, but for more complex sets of widgets
// you would decide which one gets the focus.
}
public void dispose() {
// important: We need do unregister our listener when the view is
// disposed
getSite().getWorkbenchWindow().getSelectionService().removeSelectionListener(selectionListener);
super.dispose();
}
} |
/**
* File: Board.java
* Purpose: A Chess Board implementation using the 0x88 board representation.
*/
package model;
import static lookup.Pieces.*;
import static lookup.Masks.*;
import static lookup.Coordinates.*;
import static lookup.PieceTables.*;
import java.util.ArrayList;
public class Board {
private byte[] squares = null;
private byte turnColour = 0;
private Move previousMove = null;
private int whiteKingPosition = 0;
private int blackKingPosition = 0;
private ArrayList<Move> validMoves = new ArrayList<Move>();
private ArrayList<Byte> whitePiecesCaptured = new ArrayList<Byte>();
private ArrayList<Byte> blackPiecesCaptured = new ArrayList<Byte>();
private int score = 0;
private int amountOfMoves = 0;
/**
* Initialise and create the board to contain chess pieces arranged in an order such that the resulting positions represent
* a valid chess starting position.
*/
public Board() {
this.squares = new byte[]{ ROOK, KNIGHT, BISHOP, QUEEN, KING, BISHOP, KNIGHT, ROOK, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY,
PAWN, PAWN, PAWN, PAWN, PAWN, PAWN, PAWN, PAWN, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY,
EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY,
EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY,
EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY,
EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY,
BPAWN, BPAWN, BPAWN, BPAWN, BPAWN, BPAWN, BPAWN, BPAWN, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY,
BROOK, BKNIGHT, BBISHOP, BQUEEN, BKING, BBISHOP, BKNIGHT, BROOK, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY };
this.turnColour = WHITE;
this.previousMove = null;
this.whiteKingPosition = E1;
this.blackKingPosition = E8;
this.validMoves = generateValidMoves();
this.whitePiecesCaptured = new ArrayList<Byte>();
this.blackPiecesCaptured = new ArrayList<Byte>();
this.score = 0;
this.amountOfMoves = 0;
}
/**
* Construct a new chess board which is a copy of a supplied board.
*
* @param board - The chess board to copy.
*/
public Board( Board board ) {
this.squares = board.getSquares();
this.turnColour = board.getTurnColour();
this.previousMove = board.getPreviousMove();
this.whiteKingPosition = board.getWhiteKingPosition();
this.blackKingPosition = board.getBlackKingPosition();
this.validMoves = board.getValidMoves();
this.whitePiecesCaptured = board.getWhitePiecesCaptured();
this.blackPiecesCaptured = board.getBlackPiecesCaptured();
this.score = board.getScore();
this.amountOfMoves = board.getAmountOfMoves();
}
/**
* Is the square mapped to by the given index empty?
*
* @param position The square index.
*
* @return True if there are no pieces on the square, false otherwise.
*/
private boolean squareEmpty( final int POSITION ) {
if ( pieceAt( POSITION ) == EMPTY ){
return true;
}else{
return false;
}
}
/**
* Get the piece located on the square mapped to by the given index.
*
* @param position The square index.
*
* @return A byte representation of the piece located at 'position'.
*/
private byte pieceAt(final int POSITION ) {
if ( ( POSITION & 0x88 ) == VALID ) {
return ( this.squares[ POSITION ] );
}
return ( EMPTY );
}
/**
* What colour is the piece on the square mapped to by the given index?
*
* @param position The square index.
*
* @return The colour, as a byte, of the piece.
*/
public byte pieceColourAt( final int POSITION ) {
return ( (byte)( pieceAt( POSITION ) & COLOUR_MASK ) );
}
/**
* What is the type of the given piece?
*
* @param piece The piece to check.
*
* @return A byte representing the piece type.
*/
public static byte pieceType( final byte PIECE ) {
return ( (byte)( PIECE & PIECE_MASK ) );
}
/**
* What is the colour of the given piece?
*
* @param piece The piece to check.
*
* @return A byte representing the piece colour.
*/
public static byte pieceColour( final byte PIECE ) {
return ( (byte)( PIECE & COLOUR_MASK ) );
}
/**
* What is the type of the piece located at the given square index?
*
* @param position The square index.
*
* @return A byte representing the piece type.
*/
public byte pieceTypeAt( final int POSITION ) {
return ( (byte)( pieceAt( POSITION ) & PIECE_MASK ) );
}
/**
* Is the given square index within the playable game area?
*
* @param destination The square index to check.
*
* @return True if the destination square index is on the playable chess board, false otherwise.
*/
private boolean isValidDestination(final int DESTINATION ) {
if ( ( ( DESTINATION & 0x88 ) == VALID ) &&
( squareEmpty( DESTINATION ) || ( pieceColourAt( DESTINATION ) != this.turnColour ) ) ) {
return true;
}else {
return false;
}
}
/**
* Is the piece located at the given square index white?
*
* @param position The square index.
*
* @return True if the piece is white, false otherwise.
*/
private boolean isWhitePiece(final int POSITION ) {
if ( pieceColourAt( POSITION ) == WHITE ){
return true;
}else{
return false;
}
}
/**
* Can the given move be played on the chess board?
*
* @param move The move to check the validity of.
*
* @return True if the move is valid, false otherwise.
*/
public boolean isValidMove( Move move ) {
assert( move != null ):"Move is null";
if ( this.validMoves.contains( move ) == true ){
return true;
}else{
return false;
}
}
/**
* Set the bit that represents whether or not a piece has moved.
*
* @param position The square index at which to set the bit.
*/
private void setMovementBit(final int POSITION ) {
this.squares[ POSITION ] |= MOVED;
}
/**
* Has a given piece made at least one move?
*
* @param piece The piece to check.
*
* @return True if the piece has moved, false otherwise.
*/
private static boolean hasPieceMoved( final byte PIECE ) {
if ( ( PIECE & MOVED_MASK ) == MOVED ){
return true;
}else{
return false;
}
}
/**
* Does the current board state represent a checkmate situation?
*
* @return True if checkmate, false otherwise.
*/
public boolean isCheckmate() {
if ( this.validMoves.size() == 0 && kingInCheck() ){
return true;
}else{
return false;
}
}
/**
* Does the current board state represent a stalemate situation?
*
* @return True if stalemate, false otherwise.
*/
public boolean isStalemate() {
if ( this.validMoves.size() == 0 && !kingInCheck() ){
return true;
}else{
return false;
}
}
/**
* Is is the white players turn to move?
*
* @return True if it is the white players turn to move, false otherwise.
*/
private boolean isWhiteTurn() {
if ( this.turnColour == WHITE ){
return true;
}else{
return false;
}
}
/**
* Set the position of the current players king to a new square.
*
* @param position The new square index.
*/
private void setKingPosition( final int POSITION ) {
assert( POSITION >= 0 ):"Position invalid";
if ( isWhiteTurn() ) {
this.whiteKingPosition = POSITION;
}
else {
this.blackKingPosition = POSITION;
}
}
/**
* Return the colour of the current players opponent.
*
* @return A byte representation of the opponents colour.
*/
private byte opponentColour() {
if ( isWhiteTurn() ){
return BLACK;
}else{
return WHITE;
}
}
/**
* Does the given move perform a king or queenside castle?
*
* @param move The move to check.
*
* @return True if the move performs a castling, false otherwise.
*/
private boolean isCastle( Move move ) {
return ( isKingMove( move ) && Math.abs( move.to() - move.from() ) == 2 );
}
/**
* Perform the castling move contained in 'move'.
*
* @param move - The castling move to perform.
*/
private void performCastle( Move move ) {
assert( move != null ):"Move is null";
if ( move.to() > move.from() ) {
performCastleKingSide( getKingPosition() );
}
else {
performCastleQueenSide( getKingPosition() );
}
if ( isWhiteTurn() ) {
score += 30;
}
else {
score -= 30;
}
setKingPosition( move.to() );
}
/**
* Perform a kingside castling for the king located at 'kingPosition'.
*
* @param kingPosition - The position of the king to castle.
*/
private void performCastleKingSide( final int KING_POSITION ) {
this.squares[ KING_POSITION + 1 ] = this.squares[ KING_POSITION + 3 ];
this.squares[ KING_POSITION + 3 ] = EMPTY;
this.squares[ KING_POSITION + 2 ] = this.squares[ KING_POSITION ];
this.squares[ KING_POSITION ] = EMPTY;
}
/**
* Perform a queenside castling for the king located at 'kingPosition'.
*
* @param kingPosition - The position of the king to castle.
*/
private void performCastleQueenSide( final int KING_POSITION ) {
this.squares[ KING_POSITION - 1 ] = this.squares[ KING_POSITION - 4 ];
this.squares[ KING_POSITION - 4 ] = EMPTY;
this.squares[ KING_POSITION - 2 ] = this.squares[ KING_POSITION ];
this.squares[ KING_POSITION ] = EMPTY;
}
/**
* Is the given move an en passent move?
*
* @param move - The move to check.
*
* @return True if the move performs en passent, false otherwise.
*/
private boolean isEnPassant( Move move ) {
return ( ( Math.abs( move.to() - move.from() ) == 17 || Math.abs( move.to() - move.from() ) == 15 ) && squareEmpty( move.to() ) && isPawnMove( move ) );
}
/**
* Is a pawn being moved?
*
* @param move - The move to check.
*
* @return True if a pawn is being moved.
*/
private boolean isPawnMove( Move move ) {
assert( move != null ):"null move";
if ( pieceTypeAt( move.from() ) == PAWN ) {
return true;
}
else {
return false;
}
}
/**
* Is a rook being moved?
*
* @param move - The move to check.
*
* @return True if a rook is being moved.
*/
private boolean isRookMove( Move move ) {
if ( pieceTypeAt( move.from() ) == ROOK ) {
return true;
}
else {
return false;
}
}
/**
* Is a king being moved?
*
* @param move - The move to check.
*
* @return True if a king is being moved.
*/
private boolean isKingMove( Move move ) {
assert( move != null ):"null move";
if ( pieceTypeAt( move.from() ) == KING ) {
return true;
}
else {
return false;
}
}
/**
* Does the move result in a pawn promotion?
*
* @param move - The move to check.
*/
private boolean isPawnPromotion( Move move ) {
assert( move != null ):"null move";
if ( isPawnMove( move ) && ( ( move.to() >= A1 && move.to() <= H1 ) || ( move.to() >= A8 && move.to() <= H8 ) ) ) {
return true;
}
else {
return false;
}
}
/**
* Promote the pawn located on the given square.
*
* @param pawnPosition - The square index of the pawn to promote.
*/
private void promotePawn( final int PAWN_POSITION ) {
this.squares[ PAWN_POSITION ] = isWhiteTurn() ? QUEEN : BQUEEN;
}
/**
* Perform the supplied move on the board.
*
* @param move - The move to make.
*/
public void makeMove( Move move ) {
assert( move != null ):"null move";
setMovementBit( move.from() );
if ( isPawnMove( move ) ) {
movePawn ( move );
}
else if ( isKingMove( move ) ) {
// separate this block of code (isKingMove) from this function. Warning: It may generate an error on the 'roque' moviment.
assert( move != null ):"null move";
setMovementBit( move.from() );
if ( isCastle( move ) ) {
performCastle( move );
setKingPosition( move.to() );
this.turnColour = opponentColour();
this.previousMove = move;
this.validMoves = generateValidMoves();
return;
}
setKingPosition( move.to() );
}
else if ( isRookMove( move ) ) {
setMovementBit( move.from() );
}
updateScore( move.to() );
if ( !squareEmpty( move.to() ) ) {
if ( isWhiteTurn() ) {
this.blackPiecesCaptured.add( this.squares[ move.to() ] );
}
else {
this.whitePiecesCaptured.add( this.squares[ move.to() ] );
}
}
else {
//do nothing
}
// updates the squares status after the movement
this.squares[ move.to() ] = this.squares[ move.from() ];
this.squares[ move.from() ] = EMPTY;
this.turnColour = opponentColour();
this.previousMove = move;
this.validMoves = generateValidMoves();
this.amountOfMoves++;
}
/**
* Perform the moves for a Pawn piece.
*
* @param move - The move to make.
*/
private void movePawn ( Move move ){
setMovementBit( move.from() );
if ( isEnPassant( move ) ) {
if ( isWhiteTurn() ) {
updateScore( move.to() - 16 );
this.squares[ move.to() - 16 ] = EMPTY;
this.squares[ move.to() ] = this.squares[ move.from() ];
this.squares[ move.from() ] = EMPTY;
this.blackPiecesCaptured.add( PAWN );
}
else {
updateScore( move.to() + 16 );
this.squares[ move.to() + 16 ] = EMPTY;
this.squares[ move.to() ] = this.squares[ move.from() ];
this.squares[ move.from() ] = EMPTY;
this.whitePiecesCaptured.add( PAWN );
}
this.turnColour = opponentColour();
this.previousMove = move;
this.validMoves = generateValidMoves();
return;
}
else if ( isPawnPromotion( move ) ) {
promotePawn( move.from() );
if ( isWhiteTurn() ) {
score += 700;
}
else {
score -= 700;
}
}
}
/**
* What is the value of the piece located on the given square index?
*
* @param position The index of the square the piece is on.
*
* @return A integer value of the piece worth.
*/
private int pieceValueAt(final int POSITION ) {
// returns the value of the piece according to the requested position
switch ( pieceTypeAt( POSITION ) ) {
case PAWN: {
return ( 100 );
}
case KNIGHT: {
return ( 325 );
}
case BISHOP: {
return ( 330 );
}
case ROOK: {
return ( 500 );
}
case QUEEN: {
return ( 900 );
}
case KING: {
return ( 20000 );
}
default: {
//do nothing
}
}
return 0;
}
/**
* Update the zero sum material balance score.
*
* @param position The index of the square at which a piece was captured.
*/
private void updateScore( final int POSITION ) {
if ( this.turnColour == WHITE ) {
score = score + pieceValueAt( POSITION );
} else {
score = score - pieceValueAt( POSITION );
}
}
private boolean canMoveTo( final int POSITION, int destination ) {
byte p = this.squares[ POSITION ];
byte t = this.squares[ destination ];
if ( pieceType( p ) == KING ) {
setKingPosition( destination );
}
else {
//do nothing
}
this.squares[ POSITION ] = EMPTY;
this.squares[ destination ] = p;
boolean canMove = !kingInCheck();
if ( pieceType( p ) == KING ) {
setKingPosition( POSITION );
}
else {
//do nothing
}
this.squares[ POSITION ] = p;
this.squares[ destination ] = t;
return ( canMove );
}
/**
* Is the current players king in check?
*
* @return True if the king is in check, false otherwise.
*/
public boolean kingInCheck() {
return ( squareAttacked( getKingPosition() ) );
}
/**
* Is the square indexed by 'position' under attack from any opponent pieces?
*
* @param position The index of the square to check.
*
* @return True if at least one piece is attacking the square, false otherwise.
*/
private boolean squareAttacked( final int POSITION ) {
int[] directions = new int[]{ 15, 17, -15, -17 };
// searches on diagonal positions for enemy pieces that may attack
for ( int direction : directions ) {
for ( int i = 1; isValidDestination( POSITION + i*direction ); i++ ) {
if ( enemyPieceAt( POSITION + i*direction ) ) {
if ( pieceTypeAt( POSITION + i*direction ) == QUEEN || pieceTypeAt( POSITION + i*direction ) == BISHOP ) {
return ( true );
}
else if ( pieceTypeAt( POSITION + i*direction ) == PAWN && i == 1 ) {
if ( this.turnColour == WHITE ) {
return ( direction == 15 || direction == 17 );
}
else {
//do nothing
}
return ( direction == -15 || direction == -17 );
}
else {
//do nothing
}
break;
}
else {
//do nothing
}
}
}
// searches on horizontal and vertical lines for possible enemy attacks
for ( int direction : new int[]{ 1, -1, 16, -16 } ) {
for ( int i = 1; isValidDestination( POSITION + i*direction ); i++ ) {
if ( enemyPieceAt( POSITION + i*direction ) ) {
if ( pieceTypeAt( POSITION + i*direction ) == ROOK || pieceTypeAt( POSITION + i*direction ) == QUEEN ) {
return ( true );
}
break;
}
else {
//do nothing
}
}
}
// searches on 'L' for a possible Knight attack
directions = new int[]{ 18, 33, 31, 14, -18, -33, -31, -14 };
for ( int direction : directions ) {
if ( isValidDestination( POSITION + direction ) && enemyPieceAt( POSITION + direction ) && pieceTypeAt( POSITION + direction ) == KNIGHT ) {
return ( true );
}
else {
//do nothing
}
}
return ( false );
}
/**
* Obtain a list of all valid moves that can be played on the current board position.
*
* @return An ArrayList of all valid moves that can be played.
*/
public ArrayList<Move> getValidMoves() {
ArrayList<Move> validMoves = new ArrayList<Move>();
validMoves = this.validMoves;
assert( validMoves != null ): "Move Valid is null";
return ( validMoves );
}
private ArrayList<Move> generateValidMoves() {
ArrayList<Move> validMoves = new ArrayList<Move>();
for ( int rank = 0; rank < 8; rank++ ) {
for ( int file = rank * 16 + 7; file >= rank * 16; file
if ( !squareEmpty( file ) && pieceColourAt( file ) == this.turnColour ) {
validMoves.addAll( generateValidMoves( pieceTypeAt( file ), file ) );
}
else {
//do nothing
}
}
}
return ( validMoves );
}
/**
* Generate all valid moves for the piece of type 'pieceType' located on square 'position'.
*
* @param pieceType The type of the piece to generate moves for.
* @param position The index of the current square position of the piece.
*
* @return An ArrayList of all valid moves that the piece can make.
*/
public ArrayList<Move> generateValidMoves( final byte PIECE_TYPE, final int POSITION ) {
ArrayList<Move> validMoves = new ArrayList<Move>();
ArrayList<Integer> destinations = generateDestinations( PIECE_TYPE, POSITION );
for ( int destination : destinations ) {
if ( isValidDestination( destination ) && canMoveTo( POSITION, destination ) ) {
validMoves.add( new Move( POSITION, destination ) );
}
else {
//do nothing
}
}
assert( validMoves != null ): "Move Valid is null";
return ( validMoves );
}
/**
* Generate all destinations for the piece of type 'pieceType' located on square 'position'.
*
* @param pieceType The type of the piece to generate moves for.
* @param position The index of the current square position of the piece.
*
* @return An ArrayList of all destinations that the piece can move to.
*/
private ArrayList<Integer> generateDestinations( final byte PIECE_TYPE, final int POSITION ) {
//This switch return an arrayList of all destinations that the piece can move to.
switch ( PIECE_TYPE ) {
case PAWN: {
return ( generatePawnDestinations( POSITION ) );
}
case KNIGHT: {
return ( generateKnightDestinations( POSITION ) );
}
case BISHOP: {
return ( generateBishopDestinations( POSITION ) );
}
case ROOK: {
return ( generateRookDestinations( POSITION ) );
}
case QUEEN: {
return ( generateQueenDestinations( POSITION ) );
}
case KING: {
return ( generateKingDestinations( POSITION ) );
}
default: {
//do nothing
}
}
return ( new ArrayList<Integer>() );
}
/**
* Generate the destinations for a pawn located at 'position'.
*
* @param position The index of the square the pawn is located.
*
* @return An ArrayList of all destinations that the pawn can move to.
*/
private ArrayList<Integer> generatePawnDestinations( final int POSITION ) {
if ( isWhitePiece( POSITION ) ) {
return ( generateWhitePawnDestinations( POSITION ) );
}
else {
//do nothing
}
return ( generateBlackPawnDestinations( POSITION ) );
}
/**
* Generate the destinations for a white pawn located at 'position'.
*
* @param position The index of the square the white pawn is located.
*
* @return An ArrayList of all destinations that the white pawn can move to.
*/
public ArrayList<Integer> generateWhitePawnDestinations( final int POSITION ) {
ArrayList<Integer> destinations = new ArrayList<Integer>();
if ( !hasPieceMoved( pieceAt( POSITION ) ) && squareEmpty( POSITION + 16 ) && squareEmpty( POSITION + 32 ) ) {
destinations.add( POSITION + 32 );
}
if ( !squareEmpty( POSITION + 15 ) || whiteCanEnPassantLeft( POSITION ) ) {
destinations.add( POSITION + 15 );
}
if ( !squareEmpty( POSITION + 17 ) || whiteCanEnPassantRight( POSITION ) ) {
destinations.add( POSITION + 17 );
}
if ( squareEmpty( POSITION + 16 ) ) {
destinations.add( POSITION + 16 );
}
assert( destinations != null ): "Destinations of white pawn is null";
return ( destinations );
}
/**
* Can the white pawn located at 'position' perform en passent to the left?
*
* @param position The index of the square the white pawn is located.
*
* @return True if the pawn can en passent left, false otherwise.
*/
private boolean whiteCanEnPassantLeft( final int POSITION ) {
assert( POSITION > 0 ):"invalid position";
if ( this.previousMove != null && pieceTypeAt( POSITION - 1 ) == PAWN
&& this.previousMove.from() == ( POSITION + 31 ) && this.previousMove.to() == ( POSITION - 1 )){
return true;
}
else {
return false;
}
}
/**
* Can the white pawn located at 'position' perform en passent to the right?
*
* @param position The index of the square the white pawn is located.
*
* @return True if the pawn can en passent right, false otherwise.
*/
private boolean whiteCanEnPassantRight( final int POSITION ) {
if ( this.previousMove != null && pieceTypeAt( POSITION + 1 ) == PAWN
&& this.previousMove.from() == ( POSITION + 33 ) && this.previousMove.to() == ( POSITION + 1 ) ){
return true;
}
else {
return false;
}
}
/**
* Generate the destinations for a black pawn located at 'position'.
*
* @param position The index of the square the black pawn is located.
*
* @return An ArrayList of all destinations that the black pawn can move to.
*/
public ArrayList<Integer> generateBlackPawnDestinations( final int POSITION ) {
ArrayList<Integer> destinations = new ArrayList<Integer>();
if ( !hasPieceMoved( pieceAt( POSITION ) ) && squareEmpty( POSITION - 16 ) && squareEmpty( POSITION - 32 ) ) {
destinations.add( POSITION - 32 );
}
else {
//do nothing
}
if ( !squareEmpty( POSITION - 15 ) || blackCanEnPassantLeft( POSITION ) ) {
destinations.add( POSITION - 15 );
}
else {
//do nothing
}
if ( !squareEmpty( POSITION - 17 ) || blackCanEnPassantRight( POSITION ) ) {
destinations.add( POSITION - 17 );
}
else {
//do nothing
}
if ( squareEmpty( POSITION - 16 ) ) {
destinations.add( POSITION - 16 );
}
else {
//do nothing
}
return ( destinations );
}
/**
* Can the black pawn located at 'position' perform en passent to the left?
*
* @param position The index of the square the black pawn is located.
*
* @return True if the pawn can en passent left, false otherwise.
*/
private boolean blackCanEnPassantLeft( final int POSITION ) {
if ( this.previousMove != null && pieceTypeAt( POSITION + 1 ) == PAWN
&& this.previousMove.from() == ( POSITION - 31 ) && this.previousMove.to() == ( POSITION + 1 ) ){
return true;
}
else {
return false;
}
}
/**
* Can the black pawn located at 'position' perform en passent to the right?
*
* @param position The index of the square the black pawn is located.
*
* @return True if the pawn can en passent right, false otherwise.
*/
private boolean blackCanEnPassantRight( final int POSITION ) {
if ( this.previousMove != null && pieceTypeAt( POSITION - 1 ) == PAWN
&& this.previousMove.from() == ( POSITION - 33 ) && this.previousMove.to() == ( POSITION -1 ) ){
return true;
}
else {
return false;
}
}
/**
* Generate the destinations for a king located at 'position'.
*
* @param position The index of the square the king is located on.
*
* @return An ArrayList of all destinations that the king can move to.
*/
public ArrayList<Integer> generateKingDestinations( final int POSITION ) {
ArrayList<Integer> destinations = new ArrayList<Integer>();
int[] kingPositions = { 15, 16, 17, 1, -1, -17, -16, -15 };
if ( canCastleKingSide( POSITION ) ) {
destinations.add( POSITION + 2 );
}
else {
//do nothing
}
if ( canCastleQueenSide( POSITION ) ) {
destinations.add( POSITION - 2 );
}
else {
//do nothing
}
for ( int i : kingPositions) {
if ( !nextToOpponentKing( POSITION + i ) ) {
destinations.add( POSITION + i );
}
else {
//do nothing
}
}
return ( destinations );
}
/**
* Can the king located at 'position' perform a king side castling move?
*
* @return True if the king can castle, false otherwise.
*/
private boolean canCastleKingSide( final int POSITION ) {
return ( !hasPieceMoved( pieceAt( POSITION ) ) && !kingInCheck() && pieceTypeAt( POSITION + 3 ) == ROOK && !hasPieceMoved( pieceAt( POSITION + 3 ) )
&& squareEmpty( POSITION + 1 ) && !squareAttacked( POSITION + 1 )
&& squareEmpty( POSITION + 2 ) && !squareAttacked( POSITION + 2 ) );
}
/**
* Can the king located at 'position' perform a queen side castling move?
*
* @return True if the king can castle, false otherwise.
*/
private boolean canCastleQueenSide( final int POSITION ) {
return ( !hasPieceMoved( pieceAt( POSITION ) ) && !kingInCheck() && pieceTypeAt( POSITION + 3 ) == ROOK && !hasPieceMoved( pieceAt( POSITION - 4 ) )
&& squareEmpty( POSITION - 1 ) && !squareAttacked( POSITION - 1 )
&& squareEmpty( POSITION - 2 ) && !squareAttacked( POSITION - 2 )
&& squareEmpty( POSITION - 3 ) && !squareAttacked( POSITION - 3 ) );
}
/**
* Is the king located at 'position' adjacent to an opponents king?
*
* @param position The location of the king to check.
*/
private boolean nextToOpponentKing( final int POSITION ) {
int[] offsets = new int[]{ 15, 16, 17, -1, 1, -15, -16, -17 };
for ( int i : offsets ) {
if ( ( POSITION + i ) == getOpposingKingPosition() ) {
return ( true );
}
}
return ( false );
}
/**
* Generate the destinations for a knight located at 'position'.
*
* @param position The index of the square the knight is located on.
*
* @return An ArrayList of all destinations that the knight can move to.
*/
public ArrayList<Integer> generateKnightDestinations( final int POSITION ) {
ArrayList<Integer> destinations = new ArrayList<Integer>();
int[] knightDestinations = { 18, 33, 31, 14, -18, -33, -31, -14 };
for ( int d : knightDestinations) {
destinations.add( POSITION + d );
}
return ( destinations );
}
/**
* Generate the destinations for a bishop located at 'position'.
*
* @param position The index of the square the bishop is located on.
*
* @return An ArrayList of all destinations that the bishop can move to.
*/
public ArrayList<Integer> generateBishopDestinations( int position ) {
return ( generateUpDownDestinations( position, new int[]{ 15, 17, -15, -17 } ) );
}
/**
* Generate the destinations for a rook located at 'position'.
*
* @param position The index of the square the rook is located on.
*
* @return An ArrayList of all destinations that the rook can move to.
*/
public ArrayList<Integer> generateRookDestinations( final int POSITION ) {
return ( generateUpDownDestinations( POSITION, new int[]{ 1, -1, 16, -16 } ) );
}
/**
* Generate the destinations for a queen located at 'position'.
*
* @param position The index of the square the queen is located on.
*
* @return An ArrayList of all destinations that the queen can move to.
*/
public ArrayList<Integer> generateQueenDestinations( final int POSITION ) {
return ( generateUpDownDestinations( POSITION, new int[]{ 1, -1, 16, -16, 15, 17, -15, -17 } ) );
}
/**
* Is there an enemy piece located at the given square index?
*
* @param position The square index to check.
*
* @return True if an opponents piece is located at that position, false otherwise.
*/
public boolean enemyPieceAt( final int POSITION ) {
if ( !squareEmpty( POSITION ) && pieceColourAt( POSITION ) != this.turnColour ) {
return true;
}
else {
return false;
}
}
/**
* Multipurpose method that can generate destinations for sliding pieces.
*
* @param position The square index of the locations of the piece.
* @param directions The directions in which the piece should be moving.
*
* @return An ArrayList of all destinations that the piece can move to.
*/
private ArrayList<Integer> generateUpDownDestinations( final int POSITION, int[] directions ) {
assert( directions.length > 0): "no directions found";
ArrayList<Integer> destinations = new ArrayList<Integer>();
for ( int direction : directions ) {
for ( int i = 1; isValidDestination( POSITION + i*direction ); i++ ) {
if ( enemyPieceAt( POSITION + i*direction ) ) {
destinations.add( POSITION + i*direction );
break;
}
else {
//do nothing
}
destinations.add( POSITION + i*direction );
}
}
return ( destinations );
}
/**
* Evaluate the material balance on the board.
*
* @return The zero sum material score.
*/
public int evaluateMaterial() {
if ( isWhiteTurn() == true ) {
return this.score;
}
else {
return -this.score;
}
}
/**
* Evaluate the positional score of each piece on the board.
*
* @return The material score for the current player.
*/
public int evaluatePiecePositions() {
int score = 0;
for ( int rank = 0; rank < 8; rank++ ) {
for ( int file = rank * 16 + 7; file >= rank * 16; file
if ( !squareEmpty( file ) && pieceColourAt( file ) == this.turnColour ) {
if ( isWhiteTurn() ) {
score += piecePositionScore( pieceTypeAt( file ), file );
}
else {
score -= piecePositionScore( pieceTypeAt( file ), file );
}
}
else {
//do nothing
}
}
}
if ( isWhiteTurn() == true ) {
return score;
} else {
return -score;
}
}
/**
* Give a score to a piece based on its position on the board.
*
* @return A score representing how good/bad the position of the piece is.
*/
public int piecePositionScore( final byte PIECE_TYPE, final int POS ) {
switch ( PIECE_TYPE ) {
case PAWN: {
return pawnPositionScore(POS);
}
case KNIGHT: {
return KNIGHT_POSITION_TABLE[ POS ];
}
case BISHOP: {
return bishopPositionScore(POS);
}
case ROOK: {
return rookPositionScore(POS);
}
case QUEEN: {
return queenPositionScore(POS);
}
case KING: {
return kingPositionScore(POS);
}
default: {
// do nothing
}
}
return 0;
}
private int pawnPositionScore (final int POS){
if (isWhiteTurn() == true){
return WPAWN_POSITION_TABLE[ POS ] ;
}else{
return BPAWN_POSITION_TABLE[ POS ];
}
}
private int bishopPositionScore (final int POS){
if (isWhiteTurn() == true){
return WBISHOP_POSITION_TABLE[ POS ] ;
}else{
return BBISHOP_POSITION_TABLE[ POS ] ;
}
}
private int rookPositionScore (final int POS){
if (isWhiteTurn() == true){
return WROOK_POSITION_TABLE[ POS ] ;
}else{
return BROOK_POSITION_TABLE[ POS ] ;
}
}
private int queenPositionScore (final int POS){
if (this.amountOfMoves < 15){
return OPENING_QUEEN_POSITION_TABLE[ POS ] ;
}else{
return QUEEN_POSITION_TABLE[ POS ] ;
}
}
private int kingPositionScore (final int POS){
if (isWhiteTurn() == true){
return WKING_POSITION_TABLE[ POS ] ;
}else{
return BKING_POSITION_TABLE[ POS ] ;
}
}
/**
* Evaluate the development of knights and bishops.
*
* @return A score representing how good the piece development of the current player is.
*/
public int evaluatePieceDevelopment() {
int score = 0;
int[] minorPiecePositions = new int[]{ 1, 2, 5, 6 };
int turn = isWhiteTurn() ? 0 : 112;
for ( int pos : minorPiecePositions ) {
if ( !squareEmpty( pos + turn ) && !hasPieceMoved( pieceAt( pos + turn ) ) ) {
if ( isWhiteTurn() ) {
score -= 50;
}
else {
score += 50;
}
}
}
if ( isWhiteTurn() == true ) {
return score;
} else {
return -score;
}
}
/**
* Returns a list of all white pieces captured by the black player.
*
* @return A list of all white pieces captured.
*/
private ArrayList<Byte> getWhitePiecesCaptured() {
return ( new ArrayList<Byte>( this.whitePiecesCaptured ) );
}
/**
* Returns a list of all black pieces captured by the white player.
*
* @return A list of all black pieces captured.
*/
private ArrayList<Byte> getBlackPiecesCaptured() {
return ( new ArrayList<Byte>( this.blackPiecesCaptured ) );
}
/**
* Return the zero sum material score of the board.
*
* @return The zero sum material score.
*/
private int getScore() {
return ( this.score );
}
/**
* Return the byte array of chess board squares.
*
* @return The array of chess board squares as bytes.
*/
public byte[] getSquares() {
return ( this.squares.clone() );
}
/**
* What is the colour of the player to move?
*
* @return A byte representing the colour of the player whos turn it is currently.
*/
public byte getTurnColour() {
return ( this.turnColour );
}
/**
* How many moves have been made since board creation?
*
* @return The number of moves made since the board was created.
*/
public int getAmountOfMoves() {
return this.amountOfMoves;
}
/**
* Get the last move made on the board.
*
* @return The last move that was made on the board.
*/
private Move getPreviousMove() {
return ( this.previousMove );
}
/**
* Which square is the white king located on?
*
* @return The square index of the white king position.
*/
public int getWhiteKingPosition() {
return ( this.whiteKingPosition );
}
/**
* Which square is the black king located on?
*
* @return The square index of the black king position.
*/
public int getBlackKingPosition() {
return ( this.blackKingPosition );
}
/**
* Which square is the current players king on?
*
* @return The square index of the current players king.
*/
public int getKingPosition() {
if ( isWhiteTurn() == true){
return this.whiteKingPosition;
}else{
return this.blackKingPosition;
}
}
/**
* Which square is the opponent of the current players king on?
*
* @return The square index of opponent of the current players king.
*/
private int getOpposingKingPosition() {
if (isWhiteTurn() == true){
return this.blackKingPosition;
}else{
return this.whiteKingPosition;
}
}
} |
package model;
import dataSet.*;//`ll be changed
import view.UI.FileSaveUI;
import view.UI.Position;//`ll be changed
import java.io.File;
import java.util.List;
import java.util.ArrayList;
public class Model implements ModelInterface{
private FileManager fm;
private Document left;
private Document right;
private Document oleft;
private Document oright;
private Algorithm algo;
private ArrayList<String> compResultLeft;
private ArrayList<String> compResultRight;
public Model(){
this.fm = new FileManager(null,null);
this.left = null;
this.right = null;
this.oleft = null;
this.oright = null;
this.algo = null;
this.compResultLeft = null;
this.compResultRight = null;
}
public Model(File fl, File fr){
this.fm = new FileManager(fl,fr);
if(this.fm.getPathLeft() != null){
this.left = new Document(this.fm.getBufLeft());
}
else {
this.left = null;
}
if(this.fm.getPathRight() != null){
this.right = new Document(this.fm.getBufRight());
}
else {
this.right = null;
}
this.algo = null;
this.compResultLeft = null;
this.compResultRight = null;
}
private ArrayList<String> parseData(String data){
if(data == null){
return null;
}
StringBuilder buf = new StringBuilder(data);
ArrayList<String> listData = new ArrayList<String>();
int tmpIdx = 0;
int newlineIdx = 0;
if(data.length() > 0){
while((newlineIdx = buf.indexOf("\n",tmpIdx)) > 0){
listData.add(buf.substring(tmpIdx, newlineIdx));
tmpIdx = newlineIdx + 1;
}
if(tmpIdx < buf.length()){
listData.add(buf.substring(tmpIdx, buf.length()));
}
}
return listData;
}
private String concatData(List<String> data){
if(data == null){
return "";
}
String buf = new String("");
for(int i = 0; i < data.size();i++){
buf += data.get(i) +( (i != data.size() - 1) ? ("\n") : ("") );
}
return buf;
}
@Override
public Item load(File f, int lr){
if(f == null){
return null;
}
if(lr == Position.LEFT){
return this.loadLeft(f);
}
else if(lr == Position.RIGHT){
return this.loadRight(f);
}
else {
//error
return null;
}
}
// load sub-methods
private Item loadLeft(File f){
FileOpen rtn = new Item();
if(f != null && f.isFile()){
if(this.fm.loadLeft(f)){
this.left = new Document(this.fm.getBufLeft());
if(this.isCompared()){
this.algo = null;
}
rtn.setFileName(f.getName());
rtn.setTextData(this.concatData(this.left.getLines()));
return (Item) rtn;
}
}
return null;
}
private Item loadRight(File f){
FileOpen rtn = new Item();
if(f != null && f.isFile()){
if(this.fm.loadRight(f)){
this.right = new Document(this.fm.getBufRight());
if(this.isCompared()){
this.algo = null;
}
rtn.setFileName(f.getName());
rtn.setTextData(this.concatData(this.right.getLines()));
return (Item) rtn;
}
}
return null;
}
@Override
public Item load(String path, int lr){
File f = new File(path);
return this.load(f, lr);
}
public Item save(int lr){
if(lr == Position.LEFT || lr == Position.ALL){
while(!this.saveLeft());
}
if(lr == Position.RIGHT || lr == Position.ALL){
while(!this.saveRight());
}
return null;
}
@Override
public Item save(String data, int lr){
return this.save(this.parseData(data), lr);
}
@Override
public Item save(List<String> data, int lr){
FileEditSave rtn = new Item();
if(data == null){
return null;
}
if(lr == Position.LEFT || lr == Position.ALL){
// if(this.fm.getPathLeft() == null){
// return null;
this.left = new Document(data, true);
}
if(lr == Position.RIGHT || lr == Position.ALL){
// if(this.fm.getPathRight() == null){
// return null;
this.right = new Document(data, true);
}
if(lr == Position.LEFT || lr == Position.ALL){
while(!this.saveLeft());
rtn.setFileName(fm.getNameLeft());
return (Item)rtn;
}
if(lr == Position.RIGHT || lr == Position.ALL){
while(!this.saveRight());
rtn.setFileName(fm.getNameRight());
return (Item)rtn;
}
return null;
}
// save sub-methods
private boolean saveLeft(){
return this.fm.saveLeft(this.left.getLines());
}
private boolean saveRight(){
return this.fm.saveRight(this.right.getLines());
}
public Item edit(String data, int lr){
return this.edit(this.parseData(data), lr);
}
public Item edit(List<String> data, int lr){
String name = "";
boolean isEdited = false;
FileEditSave rtn = new Item();
if(lr == Position.LEFT){
name = this.fm.getNameLeft();
if(isEdited = this.editLeft(data)){
name = "*" + name;
}
}
else if(lr == Position.RIGHT){
name = this.fm.getNameRight();
if(isEdited = this.editRight(data)){
name = "*" + name;
}
}
if(isEdited && this.isCompared()){
this.algo = null;
}
rtn.setFileName(name);
return (Item) rtn;
}
private boolean editLeft(List<String> data){
boolean isEdited = false;
if(!this.left.isEdited() && this.oleft == null){
this.oleft = new Document(this.left.getLines());
}
if(data.size() == this.oleft.length()){
for(int i = 0; i < data.size(); i++){
if(!data.get(i).equals(this.oleft.getLine(i))){
isEdited = true;
this.left.setLine(i,data.get(i));
}
}
}
else {
isEdited = true;
this.left = new Document(data);
}
return isEdited;
}
private boolean editRight(List<String> data){
boolean isEdited = false;
if(!this.right.isEdited() && this.oright == null){
this.oright = new Document(this.right.getLines());
}
if(data.size() == this.right.length()){
for(int i = 0; i < data.size(); i++){
if(!data.get(i).equals(this.oright.getLine(i))){
isEdited = true;
this.right.setLine(i,data.get(i));
}
}
}
else {
isEdited = true;
this.right = new Document(data);
}
return isEdited;
}
@Override
public Item compare(){
MergeCompare rtn = new Item();
if(!this.isCompared()){
this.algo = new Algorithm(this.left.getLines(), this.right.getLines());
}
String[][] ListData = {
this.getResultLeft().toArray(new String[this.getResultLeft().size() + 1]),
this.getResultRight().toArray(new String[this.getResultRight().size() + 1])
};
rtn.setListViewItem(ListData);
rtn.setListActiveOrder(this.algo.isFirstAreSame());
return (Item) rtn;
}
// @Override
// public Item getCompareResult(int lr){
// if(this.isCompared()){
// if(lr == Position.LEFT){
// return new Item(this.getResultLeft());
// else if(lr == Position.RIGHT){
// return new Item(this.getResultRight());
// else if(lr == Position.ALL){
// return new Item(this.getResultLeft(), this.getResultRight());
// else {
// return null;
private ArrayList<String> getResultLeft(){
if(!this.isCompared()){
return new ArrayList<String>();
}
if(this.compResultLeft != null){
return this.compResultLeft;
}
//StringBuilder data = new StringBuilder(concatData(this.left.getLines()));
ArrayList<String> result = new ArrayList<String>();
StringBuilder buf = new StringBuilder();
ArrayList<IdxPair> diff = this.algo.getResultLeft();
ArrayList<Integer> same = this.algo.getLcsIdxLeft();
int cntDiff = 0, cntSame = 0;
for(int i = 0; i < this.left.length();){
int chki = i;
if(!this.algo.isIdentical() && i == diff.get(cntDiff).begin && i != diff.get(cntDiff).end){
buf.append(this.concatData(this.left.getLines().subList(diff.get(cntDiff).begin, diff.get(cntDiff).end)));
if(diff.get(cntDiff).distance < this.algo.getResultRight().get(cntDiff).distance){
for(int j = 0; j < this.algo.getResultRight().get(cntDiff).distance - diff.get(cntDiff).distance; j++){
buf.append("\n");
}
}
result.add(buf.toString());
i += diff.get(cntDiff).distance;
if(cntDiff < diff.size() - 1){
cntDiff++;
}
}
if(this.algo.lenLcs() > 0 && i == same.get(cntSame)){
buf.append(this.left.getLines().get(same.get(cntSame)));
if(i + 1 < this.left.length() || (!this.algo.isIdentical() && i + 1 < diff.get(cntDiff).begin)){
buf.append("\n");
if(cntSame < same.size()){
cntSame++;
}
i++;
}
else {
result.add(buf.toString());
i++;
}
}
if(i == chki){ // unexpected condition
return new ArrayList<String>();
}
}
return result;
}
private ArrayList<String> getResultRight(){
if(!this.isCompared()){
return new ArrayList<String>();
}
if(this.compResultRight != null){
return this.compResultRight;
}
//StringBuilder data = new StringBuilder(concatData(this.left.getLines()));
ArrayList<String> result = new ArrayList<String>();
StringBuilder buf = new StringBuilder();
ArrayList<IdxPair> diff = this.algo.getResultRight();
ArrayList<Integer> same = this.algo.getLcsIdxRight();
int cntDiff = 0, cntSame = 0;
for(int i = 0; i < this.right.length();){
int chki = i;
if(!this.algo.isIdentical() && i == diff.get(cntDiff).begin && i != diff.get(cntDiff).end){
buf.append(this.concatData(this.right.getLines().subList(diff.get(cntDiff).begin, diff.get(cntDiff).end)));
if(diff.get(cntDiff).distance < this.algo.getResultLeft().get(cntDiff).distance){
for(int j = 0; j < this.algo.getResultLeft().get(cntDiff).distance - diff.get(cntDiff).distance; j++){
buf.append("\n");
}
}
result.add(buf.toString());
i += diff.get(cntDiff).distance;
if(cntDiff < diff.size() - 1){
cntDiff++;
}
}
if(this.algo.lenLcs() > 0 && i == same.get(cntSame)){
buf.append(this.right.getLines().get(same.get(cntSame)));
if(i + 1 < this.right.length() || (!this.algo.isIdentical() && i + 1 < diff.get(cntDiff).begin)){
buf.append("\n");
if(cntSame < same.size()){
cntSame++;
}
i++;
}
else {
result.add(buf.toString());
i++;
}
}
if(i == chki){ // unexpected condition
return new ArrayList<String>();
}
}
return result;
}
public boolean isCompared(){
return this.algo != null;
}
@Override
public Item merge(List<Integer> idxList, int lr){
if(this.isCompared()){
if(!this.algo.isIdentical()){
if(lr == Position.LEFT){
for(int i = 0; i < idxList.size();i++){
this.copyToRight(idxList.get(i).intValue());
}
}
else if(lr == Position.RIGHT){
for(int i = 0; i < idxList.size();i++){
this.copyToLeft(idxList.get(i).intValue());
}
}
else {
return null;
}
// if(this.isCompared()){
// this.algo = null;
// return this.compare();
this.algo = null;
return this.compare();
}
return null;
}
else {
return null;
}
}
@Override
public Item merge(int idx, int lr){
if(this.isCompared()){
if(!this.algo.isIdentical()){
if(lr == Position.LEFT){
this.copyToRight(idx);
}
else if(lr == Position.RIGHT){
this.copyToLeft(idx);
}
else {
return null;
}
// if(this.isCompared()){
// this.algo = null;
// return this.compare();
this.algo = null;
return this.compare();
}
return null;
}
else {
return null;
}
}
// @Override
// public Item merge(int lr){
// if(this.isCompared()){
// if(this.algo.isIdentical()){
// return new Item();
// return new Item();
// else {
// return null;
private void copyToRight(int idx){
ArrayList<String> compResult = this.getResultLeft();
ArrayList<String> dataToCp = this.parseData(compResult.get(idx));
int diffIdx = (idx - (this.algo.isFirstAreSame() ? 1 : 0) )/ 2;
this.right.deleteLine(this.algo.getResultRight().get(diffIdx).begin, this.algo.getResultRight().get(diffIdx).end);
this.right.insertLine(this.algo.getResultRight().get(diffIdx).begin, dataToCp);
}
private void copyToLeft(int idx){
ArrayList<String> compResult = this.getResultRight();
ArrayList<String> dataToCp = this.parseData(compResult.get(idx));
int diffIdx = (idx - (this.algo.isFirstAreSame() ? 1 : 0) )/ 2;
this.left.deleteLine(this.algo.getResultLeft().get(diffIdx).begin, this.algo.getResultLeft().get(diffIdx).end);
this.left.insertLine(this.algo.getResultLeft().get(diffIdx).begin, dataToCp);
}
} |
package robot;
import config.Config;
import config.DynamicConfigurable;
import exceptions.ActionneurException;
import exceptions.UnableToMoveException;
import utils.Log;
import utils.Vec2RO;
public abstract class Robot implements DynamicConfigurable
{
public abstract long getTempsDepuisDebutMatch();
protected Cinematique cinematique;
protected volatile boolean symetrie;
protected boolean deploye = false;
protected Log log;
protected boolean filetBaisse = false;
protected boolean filetPlein = false;
protected abstract void bloque(String nom, Object... param) throws InterruptedException, ActionneurException;
public abstract void avance(double distance, Speed speed) throws UnableToMoveException, InterruptedException;
public abstract void avanceVersCentre(Speed speed, Vec2RO centre, double rayon) throws UnableToMoveException, InterruptedException;
public abstract void followTrajectory(Speed vitesse) throws InterruptedException, UnableToMoveException;
public Robot(Log log)
{
this.log = log;
cinematique = new Cinematique();
}
public int codeForPFCache()
{
return cinematique.codeForPFCache();
}
public final void copy(RobotChrono rc)
{
cinematique.copy(rc.cinematique);
rc.date = getTempsDepuisDebutMatch();
}
@Override
public synchronized void updateConfig(Config config)
{
symetrie = config.getSymmetry();
}
@Override
public String toString()
{
return cinematique.toString();
}
public void setCinematique(Cinematique cinematique)
{
cinematique.copy(this.cinematique);
}
public void baisseFilet() throws InterruptedException, ActionneurException
{
filetBaisse = true;
bloque("baisseFilet");
}
public void bougeFiletMiChemin() throws InterruptedException, ActionneurException
{
filetBaisse = true;
bloque("bougeFiletMiChemin");
}
public void leveFilet() throws InterruptedException, ActionneurException
{
bloque("leveFilet");
filetBaisse = false;
}
public void verrouilleFilet() throws InterruptedException
{
try {
bloque("verrouilleFilet");
} catch (ActionneurException e) {
log.critical(e);
// impossible
}
filetBaisse = false;
}
public boolean isFiletBaisse()
{
return filetBaisse;
}
public void ouvreFilet() throws InterruptedException
{
try {
bloque("ouvreFilet");
} catch (ActionneurException e) {
log.critical(e);
// impossible
}
filetPlein = false;
}
public void fermeFilet() throws InterruptedException
{
try {
bloque("fermeFilet");
} catch (ActionneurException e) {
log.critical(e);
// impossible
}
// filetPlein = false; // TODO
}
public void ejecteBalles() throws InterruptedException, ActionneurException
{
bloque("ejecteBalles", !symetrie);
filetPlein = false;
}
public void ejecteBallesAutreCote() throws InterruptedException, ActionneurException
{
bloque("ejecteBalles", symetrie);
filetPlein = false;
}
public void rearme() throws InterruptedException, ActionneurException
{
bloque("rearme", !symetrie);
}
public void rearmeAutreCote() throws InterruptedException, ActionneurException
{
bloque("rearme", symetrie);
}
public void traverseBascule() throws InterruptedException, ActionneurException
{
bloque("traverseBascule");
}
public void funnyAction() throws InterruptedException
{
try {
bloque("funnyAction");
} catch (ActionneurException e) {
log.critical(e);
// impossible
}
}
public void filetVuVide()
{
filetPlein = false;
}
public void filetVuPlein()
{
filetPlein = true;
}
public boolean isFiletPlein()
{
return filetPlein;
}
} |
package server;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Iterator;
import javax.crypto.Cipher;
import rmi.CertusServer;
import database.DatabaseConnector;
import dto.*;
import enumeration.*;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
DatabaseConnector db = new DatabaseConnector();
UserDto u = db.selectUserById(1);
System.out.println(u.toString());
Validator v = db.checkIfUsernamePasswordMatch("user@certus.org", "password");
System.out.println(v.getStatus());
// Retrive Elections
/*ElectionDto electionDto = db.selectElection(1);
System.out.println(electionDto.toString());
for (ElectionDto e : db.selectElections(ElectionStatus.NEW)) {
System.out.println(e.toString());
}
// Retrieve Candidates
CandidateDto candidateDto = db.selectCandidate(1);
System.out.println(candidateDto.toString());
for (CandidateDto c : db.selectCandidatesOfElection(1)) {
System.out.println(c.toString());
}*/
try {
CertusServer serv=new CertusServer();
PublicKey pk=(PublicKey)serv.getTallierPublicKey().getObject();
System.out.println(pk.toString());
Cipher enc = Cipher.getInstance("RSA");
// Note 1: "ECB" in line above is bogus. Doesn't actually encrypt
// more than one block.
// Note 2: Encoding function above is OAEP.
enc.init(Cipher.ENCRYPT_MODE, pk);
String m1 = "Attack at dawn";
byte[] b1 = m1.getBytes();
byte[] c = enc.doFinal(b1);
SecurityValidator sec=new SecurityValidator();
PrivateKey sk=sec.getPrivateKey();
System.out.println(sk.toString());
String hex=sec.byteArraytoHex(c);
String pt=sec.decrypt(hex);
byte[] plain=sec.hexStringtoByteArray(pt);
String message=new String(plain);
System.out.println(message);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} |
package snake;
import java.io.IOException;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
/**
* @author Aaron
*
*/
public class Sound {
private Clip clip;
private String fileName;
public Sound(String fileName) {
this.fileName = fileName;
System.out.println("loaded");
loadSound();
}
/**
* This method plays the sound
*/
public void play(){
if(clip.isRunning()){
clip.stop();
}
clip.setFramePosition(0);
clip.start();
}
/**
* This method loops the sound
*/
public void loop(){
if(clip.isRunning()){
clip.stop();
}
clip.setFramePosition(0);
clip.loop(Clip.LOOP_CONTINUOUSLY);
}
/**
* This method stops the sound
*/
public void stop(){
clip.stop();
}
/**
* This method loads the sound into memory
*/
private void loadSound(){
try {
AudioInputStream audio = AudioSystem.getAudioInputStream(this.getClass().getResource(fileName));
clip = AudioSystem.getClip();
clip.open(audio);
} catch(UnsupportedAudioFileException e){
e.printStackTrace();
} catch(LineUnavailableException e){
e.printStackTrace();
} catch(IOException e){
e.printStackTrace();
}
}
} |
package ui;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
public class RGBPanel extends JPanel {
private BufferedImage image;
public RGBPanel(){
super();
setPreferredSize(new Dimension(600, 400));
image = new BufferedImage(100, 100, BufferedImage.TYPE_3BYTE_BGR);
}
public void setImage(BufferedImage img){
this.image = img;
invalidate();
repaint();
}
@Override
public void paintComponent(Graphics g){
super.paintComponent(g);
g.drawImage(image, 0, 0, null);
}
} |
public class Door
{
public static final String START = "AA";
public static final String EXIT = "ZZ";
public Door (Coordinate position, boolean horizontalRepresentation)
{
_location = position;
_horizontal = horizontalRepresentation;
}
private Coordinate _location;
private boolean _horizontal;
} |
public class Tile
{
} |
import java.util.*;
import java.io.*;
public class Util
{
public static final Vector<Tile> loadData (String inputFile)
{
/*
* Open the data file and read it in.
*/
BufferedReader reader = null;
Vector<Tile> data = new Vector<Tile>();
try
{
reader = new BufferedReader(new FileReader(inputFile));
String line = null;
while ((line = reader.readLine()) != null)
{
long id = -1;
if (line.startsWith(TileData.TILE_ID))
{
Tile t = null;
int index = line.indexOf(':');
String value = line.substring(TileData.TILE_ID.length(), index);
while ((line = reader.readLine()) != null)
{
if (line.length() > 0)
{
}
}
data.add(t);
}
}
}
catch (Throwable ex)
{
ex.printStackTrace();
}
finally
{
try
{
reader.close();
}
catch (Throwable ex)
{
}
}
return data;
}
private Util ()
{
}
} |
package com.amos.project4.models;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
* Simple POJO Class to represent a client data entry
*
* @author Jupiter BAKAKEU
*
*/
@Entity
@Table(name = "\"Kundendaten\"")
public class Client implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "\"ID\"")
private Integer ID;
@Column(name = "\"Nachname\"")
private String name;
@Column(name = "\"Vorname\"")
private String firstname;
@Temporal(TemporalType.DATE)
@Column(name = "\"Geburtstag\"")
private Date birthdate;
@Column(name = "\"Mail\"")
private String mail;
@Column(name = "\"Wohnort\"")
private String place;
public Client() {
super();
}
public Client(String name, String firstname, Date birthdate, String mail,
String place) {
super();
this.name = name;
this.firstname = firstname;
this.birthdate = birthdate;
this.mail = mail;
this.place = place;
}
public Integer getID() {
return ID;
}
public void setID(Integer iD) {
ID = iD;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public Date getBirthdate() {
return birthdate;
}
public void setBirthdate(Date birthdate) {
this.birthdate = birthdate;
}
public String getMail() {
return mail;
}
public void setMail(String mail) {
this.mail = mail;
}
public String getPlace() {
return place;
}
public void setPlace(String place) {
this.place = place;
}
} |
package edu.vu.isis.ammo.api;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.ReceiverCallNotAllowedException;
import android.content.ServiceConnection;
import android.net.Uri;
import android.os.IBinder;
import android.os.Parcel;
import android.os.ParcelFormatException;
import android.os.Parcelable;
import android.os.RemoteException;
import edu.vu.isis.ammo.api.type.Action;
import edu.vu.isis.ammo.api.type.BroadIntent;
import edu.vu.isis.ammo.api.type.ChannelFilter;
import edu.vu.isis.ammo.api.type.DeliveryScope;
import edu.vu.isis.ammo.api.type.Form;
import edu.vu.isis.ammo.api.type.Limit;
import edu.vu.isis.ammo.api.type.Notice;
import edu.vu.isis.ammo.api.type.Notice.Via;
import edu.vu.isis.ammo.api.type.Oid;
import edu.vu.isis.ammo.api.type.Order;
import edu.vu.isis.ammo.api.type.Payload;
import edu.vu.isis.ammo.api.type.Provider;
import edu.vu.isis.ammo.api.type.Quantifier;
import edu.vu.isis.ammo.api.type.Query;
import edu.vu.isis.ammo.api.type.Selection;
import edu.vu.isis.ammo.api.type.SerialMoment;
import edu.vu.isis.ammo.api.type.TimeInterval;
import edu.vu.isis.ammo.api.type.TimeStamp;
import edu.vu.isis.ammo.api.type.TimeTrigger;
import edu.vu.isis.ammo.api.type.Topic;
/**
* see docs/dev-guide/developer-guide.pdf The request has many options. Option
* usage:
*/
public class AmmoRequest implements IAmmoRequest, Parcelable {
private static final Logger logger = LoggerFactory.getLogger("api.request");
private static final Logger plogger = LoggerFactory.getLogger("api.parcel");
/**
* Typically logging by clients is suppressed.
*/
private static final boolean CLIENT_LOGGING = false;
// PUBLIC PROPERTIES
final public Action action;
final public String uuid; // the request globally unique identifier
final public String uid; // the application object unique identifier
/**
* the data store which holds the object.
*/
final public Provider provider;
/**
* the data is to be sent as a broadcast intent.
*/
final public BroadIntent intent;
/**
* the serialized content data.
*/
final public Payload payload;
final public SerialMoment moment;
/**
* the general uid and data type. This is a prefix match pattern.
*/
final public Topic topic;
final public Topic subtopic;
final public Quantifier quantifier;
final public Integer downsample;
/**
* indicates the volatility of the value. It amounts to deciding the allowed
* sources of the content. It can be considered a measure of number of
* sources.
*/
final public Integer durability;
/**
* the preferred delivery order for the content. This is used to select
* between objects of differing types.
*/
final public Integer priority;
/**
* the preferred delivery order for the content. Unlike priority, this is
* used when there are multiple versions of the same item.
*/
final public Order order;
/**
* states from which time 'missed' data should be retrieved. This is
* typically used only on the retrieve or interest actions.
*/
final public TimeTrigger start;
/**
* specifies the time until the subscription is dropped.
*/
final public TimeTrigger expire;
/**
* obtain no more than the specified number of items.
*/
final public Limit limit;
/**
* how far the request is allowed to travel. It can be considered a measure
* of distance travelled.
*/
final public DeliveryScope scope;
/**
* constrains the message rate to lower the load on the network. The
* parameter is the maximum number of bits per second.
*/
final public Integer throttle;
/**
* filter out (or in) the unnecessary fields.
*/
final public String[] project;
/**
* reduce the quantity of items returned.
*/
final public Selection select;
/**
* used as a check against priority. This does not affect request delivery,
* but it will impact status.
*/
final public Integer worth;
/**
* provides delivery notices concerning the progress of requests which meet
* the subscription type/uid.
*/
final public Notice notice;
final public ChannelFilter channelFilter;
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
if (this.action != null)
sb.append(this.action.toString()).append(" Request ");
if (this.uuid != null)
sb.append(this.uuid).append(" ");
if (this.uid != null)
sb.append(this.uid).append(" ");
if (this.topic != null)
sb.append(this.topic).append(' ');
return sb.toString();
}
public String toShow() {
StringBuilder sb = new StringBuilder();
if (this.action != null)
sb.append(this.action.toString()).append(" Request ");
if (this.uuid != null)
sb.append('[').append(this.uuid).append("]");
if (this.uid != null)
sb.append(":[").append(this.uid).append("] ");
if (this.topic != null)
sb.append('@').append(this.topic);
if (this.subtopic != null)
sb.append('&').append(this.subtopic);
if (this.quantifier != null)
sb.append('&').append(this.quantifier);
sb.append(' ');
return sb.toString();
}
// Parcelable Support
public static final Parcelable.Creator<AmmoRequest> CREATOR = new Parcelable.Creator<AmmoRequest>() {
@Override
public AmmoRequest createFromParcel(Parcel source) {
try {
return new AmmoRequest(source);
} catch (IncompleteRequest ex) {
return null;
} catch (Throwable ex) {
final int capacity = source.dataCapacity();
// final int size = (capacity < 50) ? capacity : 50;
// final byte[] data = new byte[size];
// source.unmarshall(data, 0, size);
final byte[] data = source.marshall();
plogger.error("PARCEL UNMARSHALLING PROBLEM: size {} data {}",
new Object[] {
capacity, data
}, ex);
return null;
}
}
@Override
public AmmoRequest[] newArray(int size) {
return new AmmoRequest[size];
}
};
/**
* The this.provider.writeToParcel(dest, flags) form is not used rather
* Class.writeToParcel(this.provider, dest, flags) so that when the null
* will will be handled correctly.
*/
private final byte VERSION = (byte) 0x05;
/**
* The first few fields are required and are positional. The remainder are
* optional, their presence is indicated by their nominal values.
*/
@Override
public void writeToParcel(Parcel dest, int flags) {
plogger.debug("version: {}", VERSION);
dest.writeByte(VERSION);
plogger.debug("request: [{}:{}]", this.uuid, this.uid);
dest.writeValue(this.uuid);
dest.writeValue(this.uid);
if (CLIENT_LOGGING)
plogger.debug("action: {}", this.action);
Action.writeToParcel(dest, this.action);
// PROVIDER
if (CLIENT_LOGGING)
plogger.debug("provider: {}", this.provider);
Nominal.PROVIDER.writeToParcel(dest, flags);
Provider.writeToParcel(this.provider, dest, flags);
// PAYLOAD
if (CLIENT_LOGGING)
plogger.debug("payload: {}", this.payload);
Nominal.PAYLOAD.writeToParcel(dest, flags);
Payload.writeToParcel(this.payload, dest, flags);
// INTENT
//if (CLIENT_LOGGING)
// plogger.debug("intent: {}", this.intent);
//Nominal.INTENT.writeToParcel(dest, flags);
//Payload.writeToParcel(this.intent, dest, flags);
// SERIAL MOMENT
if (CLIENT_LOGGING)
plogger.debug("moment: {}", this.moment);
Nominal.MOMENT.writeToParcel(dest, flags);
SerialMoment.writeToParcel(this.moment, dest, flags);
// TOPIC
if (CLIENT_LOGGING)
plogger.debug("topic: [{}]+[{}]", this.topic, this.subtopic);
Nominal.TOPIC.writeToParcel(dest, flags);
Topic.writeToParcel(this.topic, dest, flags);
Nominal.SUBTOPIC.writeToParcel(dest, flags);
Topic.writeToParcel(this.subtopic, dest, flags);
// QUANTIFIER
if (CLIENT_LOGGING)
plogger.debug("quantifier: {}", this.quantifier);
Nominal.QUANTIFIER.writeToParcel(dest, flags);
Quantifier.writeToParcel(this.quantifier, dest, flags);
// DOWNSAMPLE
if (CLIENT_LOGGING)
plogger.debug("downsample: {}", this.downsample);
Nominal.DOWNSAMPLE.writeToParcel(dest, flags);
dest.writeValue(this.downsample);
// DURABILITY
if (CLIENT_LOGGING)
plogger.debug("durability: {}", this.durability);
Nominal.DURABLILITY.writeToParcel(dest, flags);
dest.writeValue(this.durability);
// PRIORITY
if (CLIENT_LOGGING)
plogger.debug("priority: {}", this.priority);
Nominal.PRIORITY.writeToParcel(dest, flags);
dest.writeValue(this.priority);
// ORDER
if (CLIENT_LOGGING)
plogger.debug("order: {}", this.order);
Nominal.ORDER.writeToParcel(dest, flags);
Order.writeToParcel(this.order, dest, flags);
// START
if (CLIENT_LOGGING)
plogger.debug("start: {}", this.start);
Nominal.START.writeToParcel(dest, flags);
TimeTrigger.writeToParcel(this.start, dest, flags);
// EXPIRE
if (CLIENT_LOGGING)
plogger.debug("expire: {}", this.expire);
Nominal.EXPIRE.writeToParcel(dest, flags);
TimeTrigger.writeToParcel(this.expire, dest, flags);
// LIMIT
if (CLIENT_LOGGING)
plogger.debug("limit: {}", this.limit);
Nominal.LIMIT.writeToParcel(dest, flags);
Limit.writeToParcel(this.limit, dest, flags);
// DELIVERY SCOPE
if (CLIENT_LOGGING)
plogger.debug("scope: {}", this.scope);
Nominal.DELIVERY_SCOPE.writeToParcel(dest, flags);
DeliveryScope.writeToParcel(this.scope, dest, flags);
// THROTTLE
if (CLIENT_LOGGING)
plogger.debug("throttle: {}", this.throttle);
Nominal.THROTTLE.writeToParcel(dest, flags);
dest.writeValue(this.throttle);
// WORTH
if (CLIENT_LOGGING)
plogger.debug("worth: {}", this.worth);
Nominal.WORTH.writeToParcel(dest, flags);
dest.writeValue(this.worth);
// NOTICE
if (CLIENT_LOGGING)
plogger.debug("notice: {}", this.notice);
Nominal.NOTICE.writeToParcel(dest, flags);
Notice.writeToParcel(this.notice, dest, flags);
// SELECTION
if (CLIENT_LOGGING)
plogger.debug("selection: {}", this.select);
Nominal.SELECTION.writeToParcel(dest, flags);
Selection.writeToParcel(this.select, dest, flags);
// PROJECTION
if (CLIENT_LOGGING)
plogger.debug("projection: {}", this.project);
Nominal.PROJECTION.writeToParcel(dest, flags);
dest.writeStringArray(this.project);
// CHANNEL FILTER
if (CLIENT_LOGGING)
plogger.debug("channelFilter: [{}]", this.channelFilter);
Nominal.CHANNEL_FILTER.writeToParcel(dest, flags);
ChannelFilter.writeToParcel(this.channelFilter, dest, flags);
}
/**
* When the request is placed into a parcel the fields have nominal
* identifiers.
*/
private enum Nominal {
PROVIDER(2),
PAYLOAD(3),
MOMENT(4),
TOPIC(5),
SUBTOPIC(6),
QUANTIFIER(7),
DOWNSAMPLE(8),
DURABLILITY(9),
PRIORITY(10),
ORDER(11),
START(12),
EXPIRE(13),
LIMIT(14),
DELIVERY_SCOPE(15),
THROTTLE(16),
WORTH(17),
NOTICE(18),
SELECTION(19),
PROJECTION(20),
CHANNEL_FILTER(21),
INTENT(22);
public final int code;
private Nominal(int code) {
this.code = code;
}
public void writeToParcel(Parcel dest, int flags) {
// TODO Auto-generated method stub
}
public static final Map<Integer, Nominal> lookup = new HashMap<Integer, Nominal>();
static {
for (Nominal nominal : EnumSet.allOf(Nominal.class)) {
lookup.put(nominal.code, nominal);
}
}
}
private Nominal getNominalFromParcel(Parcel in) {
final int nominalRaw = in.readInt();
return Nominal.lookup.get(new Integer(nominalRaw));
}
/**
* @param in
* @throws IncompleteRequest
*/
private AmmoRequest(Parcel in) throws IncompleteRequest {
final byte version;
try {
version = in.readByte();
if (version < VERSION) {
plogger.info("AMMO REQUEST VERSION MISMATCH, received {}, expected {}",
version, VERSION);
} else if (version > VERSION) {
plogger.warn("AMMO REQUEST VERSION MISMATCH, received {}, expected {}",
version, VERSION);
throw new ParcelFormatException("AMMO REQUEST VERSION MISMATCH");
} else {
plogger.trace("AMMO REQUEST VERSION MATCH: {}", version);
}
} catch (Exception ex) {
plogger.error("unmarshall on version", ex);
throw new IncompleteRequest(ex);
}
if (version < (byte) 6) {
try {
this.uuid = (String) in.readValue(String.class.getClassLoader());
this.uid = (version < (byte) 3) ? this.uuid : (String) in.readValue(String.class
.getClassLoader());
plogger.trace("uuid: [{}:{}]", this.uuid, this.uid);
} catch (Exception ex) {
plogger.error("decoding uid: {}", ex);
throw new IncompleteRequest(ex);
}
try {
this.action = Action.getInstance(in);
plogger.trace("action: {}", this.action);
} catch (Exception ex) {
plogger.error("decoding action: {}", ex);
throw new IncompleteRequest(ex);
}
try {
this.provider = Provider.readFromParcel(in);
plogger.trace("provider: {}", this.provider);
} catch (Exception ex) {
plogger.error("decoding provider: {}", ex);
throw new IncompleteRequest(ex);
}
try {
this.payload = Payload.readFromParcel(in);
plogger.trace("payload: {}", this.payload);
} catch (Exception ex) {
plogger.error("decoding payload: {}", ex);
throw new IncompleteRequest(ex);
}
try {
this.moment = (version < (byte) 4) ? SerialMoment.DEFAULT : SerialMoment
.readFromParcel(in);
plogger.trace("moment: {}", this.moment);
} catch (Exception ex) {
plogger.error("decoding moment: {}", ex);
throw new IncompleteRequest(ex);
}
try {
this.topic = Topic.readFromParcel(in);
plogger.trace("topic: {}", this.topic);
} catch (Exception ex) {
plogger.error("decoding topic: {}", ex);
throw new IncompleteRequest(ex);
}
if (version < (byte) 3) {
// unused read slack bytes
this.subtopic = new Topic("");
this.quantifier = new Quantifier(Quantifier.Type.BULLETIN);
} else {
try {
this.subtopic = Topic.readFromParcel(in);
plogger.trace("subtopic: {}", this.subtopic);
} catch (Exception ex) {
plogger.error("decoding subtopic: {}", ex);
throw new IncompleteRequest(ex);
}
try {
this.quantifier = Quantifier.readFromParcel(in);
plogger.trace("quantifier: {}", this.quantifier);
} catch (Exception ex) {
plogger.error("decoding quantifier: {}", ex);
throw new IncompleteRequest(ex);
}
}
try {
this.downsample = (Integer) in.readValue(Integer.class.getClassLoader());
plogger.trace("downsample: {}", this.downsample);
} catch (Exception ex) {
plogger.error("decoding downsample: {}", ex);
throw new IncompleteRequest(ex);
}
try {
this.durability = (Integer) in.readValue(Integer.class.getClassLoader());
plogger.trace("durability: {}", this.durability);
} catch (Exception ex) {
plogger.error("decoding durability: {}", ex);
throw new IncompleteRequest(ex);
}
try {
this.priority = (Integer) in.readValue(Integer.class.getClassLoader());
plogger.trace("priority: {}", this.priority);
} catch (Exception ex) {
plogger.error("decoding priority: {}", ex);
throw new IncompleteRequest(ex);
}
try {
this.order = Order.readFromParcel(in);
plogger.trace("order: {}", this.order);
} catch (Exception ex) {
plogger.error("decoding order: {}", ex);
throw new IncompleteRequest(ex);
}
try {
this.start = TimeTrigger.readFromParcel(in);
plogger.trace("start: {}", this.start);
} catch (Exception ex) {
plogger.error("unmarshall start {}", ex);
throw new IncompleteRequest(ex);
}
try {
this.expire = TimeTrigger.readFromParcel(in);
plogger.trace("expire: {}", this.expire);
} catch (Exception ex) {
plogger.error("decoding expire: {}", ex);
throw new IncompleteRequest(ex);
}
try {
this.limit = (version < (byte) 2) ? new Limit(100) : Limit.readFromParcel(in);
plogger.trace("limit: {}", this.limit);
} catch (Exception ex) {
plogger.error("decoding limit: {}", ex);
throw new IncompleteRequest(ex);
}
try {
this.scope = DeliveryScope.readFromParcel(in);
plogger.trace("scope: {}", this.scope);
} catch (Exception ex) {
plogger.error("decoding scope: {}", ex);
throw new IncompleteRequest(ex);
}
try {
this.throttle = (Integer) in.readValue(Integer.class.getClassLoader());
plogger.trace("throttle: {}", this.throttle);
} catch (Exception ex) {
plogger.error("unmarshall throttle {}", ex);
throw new IncompleteRequest(ex);
}
try {
this.worth = (Integer) in.readValue(Integer.class.getClassLoader());
plogger.trace("worth: {}", this.worth);
} catch (Exception ex) {
plogger.error("decoding worth: {}", ex);
throw new IncompleteRequest(ex);
}
try {
this.notice = (version < 4) ? new Notice() : Notice.readFromParcel(in);
plogger.trace("notice: {}", this.notice);
} catch (Exception ex) {
plogger.error("decoding notice: {}", ex);
throw new IncompleteRequest(ex);
}
try {
this.select = Selection.readFromParcel(in);
plogger.trace("select: {}", this.select);
} catch (Exception ex) {
plogger.error("decoding select: {}", ex);
throw new IncompleteRequest(ex);
}
try {
this.project = in.createStringArray();
plogger.trace("projection: {}", this.project);
} catch (Exception ex) {
plogger.error("decoding projection: {}", ex);
throw new IncompleteRequest(ex);
}
try {
this.channelFilter = (version < (byte) 5) ? null : ChannelFilter.readFromParcel(in);
plogger.trace("channelFilter: {}", this.channelFilter);
} catch (Exception ex) {
plogger.error("decoding channelFilter: {}", ex);
throw new IncompleteRequest(ex);
}
this.intent = null;
return;
}
try {
this.uuid = ((String) in.readValue(String.class.getClassLoader()));
this.uid = (String) in.readValue(String.class.getClassLoader());
plogger.trace("uuid: [{}:{}]", this.uuid, this.uid);
} catch (Exception ex) {
plogger.error("decoding uid: {}", ex);
throw new IncompleteRequest(ex);
}
try {
this.action = Action.getInstance(in);
plogger.trace("action: {}", this.action);
} catch (Exception ex) {
plogger.error("decoding action: {}", ex);
throw new IncompleteRequest(ex);
}
final Builder builder = newBuilder(null);
builder.limit = new Limit(100);
builder.moment = SerialMoment.DEFAULT;
for (Nominal nominal = getNominalFromParcel(in); nominal != null; nominal = getNominalFromParcel(in)) {
switch (nominal) {
case PROVIDER:
try {
builder.provider = Provider.readFromParcel(in);
plogger.trace("provider: {}", builder.provider);
} catch (Exception ex) {
plogger.error("decoding provider: {}", ex);
throw new IncompleteRequest(ex);
}
break;
case PAYLOAD:
try {
builder.payload = Payload.readFromParcel(in);
plogger.trace("payload: {}", builder.payload);
} catch (Exception ex) {
plogger.error("decoding payload: {}", ex);
throw new IncompleteRequest(ex);
}
break;
case MOMENT:
try {
builder.moment = SerialMoment.readFromParcel(in);
plogger.trace("moment: {}", builder.moment);
} catch (Exception ex) {
plogger.error("decoding moment: {}", ex);
throw new IncompleteRequest(ex);
}
break;
case TOPIC:
try {
builder.topic = Topic.readFromParcel(in);
plogger.trace("topic: {}", builder.topic);
} catch (Exception ex) {
plogger.error("decoding topic: {}", ex);
throw new IncompleteRequest(ex);
}
case SUBTOPIC:
try {
builder.subtopic = Topic.readFromParcel(in);
plogger.trace("subtopic: {}", builder.subtopic);
} catch (Exception ex) {
plogger.error("decoding subtopic: {}", ex);
throw new IncompleteRequest(ex);
}
break;
case QUANTIFIER:
try {
builder.quantifier = Quantifier.readFromParcel(in);
plogger.trace("quantifier: {}", builder.quantifier);
} catch (Exception ex) {
plogger.error("decoding quantifier: {}", ex);
throw new IncompleteRequest(ex);
}
break;
case DOWNSAMPLE:
try {
builder.downsample = (Integer) in.readValue(Integer.class.getClassLoader());
plogger.trace("downsample: {}", builder.downsample);
} catch (Exception ex) {
plogger.error("decoding downsample: {}", ex);
throw new IncompleteRequest(ex);
}
break;
case DURABLILITY:
try {
builder.durability = (Integer) in.readValue(Integer.class.getClassLoader());
plogger.trace("durability: {}", builder.durability);
} catch (Exception ex) {
plogger.error("decoding durability: {}", ex);
throw new IncompleteRequest(ex);
}
break;
case PRIORITY:
try {
builder.priority = (Integer) in.readValue(Integer.class.getClassLoader());
plogger.trace("priority: {}", builder.priority);
} catch (Exception ex) {
plogger.error("decoding priority: {}", ex);
throw new IncompleteRequest(ex);
}
break;
case ORDER:
try {
builder.order = Order.readFromParcel(in);
plogger.trace("order: {}", builder.order);
} catch (Exception ex) {
plogger.error("decoding order: {}", ex);
throw new IncompleteRequest(ex);
}
break;
case START:
try {
builder.start = TimeTrigger.readFromParcel(in);
plogger.trace("start: {}", builder.start);
} catch (Exception ex) {
plogger.error("unmarshall start {}", ex);
throw new IncompleteRequest(ex);
}
break;
case EXPIRE:
try {
builder.expire = TimeTrigger.readFromParcel(in);
plogger.trace("expire: {}", builder.expire);
} catch (Exception ex) {
plogger.error("decoding expire: {}", ex);
throw new IncompleteRequest(ex);
}
break;
case LIMIT:
try {
builder.limit = Limit.readFromParcel(in);
plogger.trace("limit: {}", builder.limit);
} catch (Exception ex) {
plogger.error("decoding limit: {}", ex);
throw new IncompleteRequest(ex);
}
break;
case DELIVERY_SCOPE:
try {
builder.scope = DeliveryScope.readFromParcel(in);
plogger.trace("scope: {}", builder.scope);
} catch (Exception ex) {
plogger.error("decoding scope: {}", ex);
throw new IncompleteRequest(ex);
}
break;
case THROTTLE:
try {
builder.throttle = (Integer) in.readValue(Integer.class.getClassLoader());
plogger.trace("throttle: {}", builder.throttle);
} catch (Exception ex) {
plogger.error("unmarshall throttle {}", ex);
throw new IncompleteRequest(ex);
}
break;
case WORTH:
try {
builder.worth = (Integer) in.readValue(Integer.class.getClassLoader());
plogger.trace("worth: {}", builder.worth);
} catch (Exception ex) {
plogger.error("decoding worth: {}", ex);
throw new IncompleteRequest(ex);
}
break;
case NOTICE:
try {
builder.notice = Notice.readFromParcel(in);
plogger.trace("notice: {}", builder.notice);
} catch (Exception ex) {
plogger.error("decoding notice: {}", ex);
throw new IncompleteRequest(ex);
}
break;
case SELECTION:
try {
builder.select = Selection.readFromParcel(in);
plogger.trace("select: {}", builder.select);
} catch (Exception ex) {
plogger.error("decoding select: {}", ex);
throw new IncompleteRequest(ex);
}
break;
case PROJECTION:
try {
builder.project = in.createStringArray();
plogger.trace("projection: {}", builder.project);
} catch (Exception ex) {
plogger.error("decoding projection: {}", ex);
throw new IncompleteRequest(ex);
}
break;
case CHANNEL_FILTER:
try {
builder.channelFilter = ChannelFilter.readFromParcel(in);
plogger.trace("channelFilter: {}", builder.channelFilter);
} catch (Exception ex) {
plogger.error("decoding channelFilter: {}", ex);
throw new IncompleteRequest(ex);
}
break;
case INTENT:
builder.intent = BroadIntent.readFromParcel(in);
break;
default:
}
}
this.provider = builder.provider;
this.intent = builder.intent;
this.payload = builder.payload;
this.moment = builder.moment;
this.topic = builder.topic;
this.subtopic = builder.subtopic;
this.quantifier = builder.quantifier;
this.channelFilter = builder.channelFilter;
this.downsample = builder.downsample;
this.durability = builder.durability;
this.priority = builder.priority;
this.order = builder.order;
this.start = builder.start;
this.expire = builder.expire;
this.limit = builder.limit;
this.scope = builder.scope;
this.throttle = builder.throttle;
this.project = builder.project;
this.select = builder.select;
this.worth = builder.worth;
this.notice = builder.notice;
}
@Override
public int describeContents() {
return 0;
}
// IAmmoRequest Support
private AmmoRequest(Action action, Builder builder) {
this.action = action;
this.uid = builder.uid;
this.provider = builder.provider;
this.intent = builder.intent;
this.payload = builder.payload;
this.moment = builder.moment;
this.topic = builder.topic;
this.subtopic = builder.subtopic;
this.quantifier = builder.quantifier;
this.channelFilter = builder.channelFilter;
this.downsample = builder.downsample;
this.durability = builder.durability;
this.priority = builder.priority;
this.order = builder.order;
this.start = builder.start;
this.expire = builder.expire;
this.limit = builder.limit;
this.scope = builder.scope;
this.throttle = builder.throttle;
this.project = builder.project;
this.select = builder.select;
this.worth = builder.worth;
this.notice = builder.notice;
this.uuid = UUID.randomUUID().toString();
}
/**
* Replace the request with req.
*/
@Override
public IAmmoRequest replace(IAmmoRequest req) {
// TODO Auto-generated method stub
return null;
}
/**
* Replace the named request with ?
*/
@Override
public IAmmoRequest replace(String uuid) {
return null;
}
/**
* The principle factory method for obtaining a request builder.
*
* @param context
* @return
*/
public static Builder newBuilder(Context context) {
return new AmmoRequest.Builder(context).reset();
}
/**
* This method is deprecated.
* The resolver is no longer needed.
*
* @param context
* @param resolver
* @return
*/
public static Builder newBuilder(Context context, BroadcastReceiver resolver) {
return new AmmoRequest.Builder(context).reset();
}
/**
* This method (and its accompanying constructor
*
* @param context
* @param serviceBinder
* @return
*/
public static Builder newBuilder(Context context, IBinder serviceBinder) {
return new AmmoRequest.Builder(context, serviceBinder).reset();
}
// CONTROL
@Override
public void metricTimespan(Integer val) {
// TODO Auto-generated method stub
}
@Override
public void resetMetrics(Integer val) {
// TODO Auto-generated method stub
}
// STATISTICS
@Override
public TimeStamp lastMessage() {
// TODO Auto-generated method stub
return null;
}
/**
* The builder makes requests to the Distributor via AIDL methods.
*/
private static final Intent MAKE_DISTRIBUTOR_REQUEST = new Intent(
"edu.vu.isis.ammo.api.MAKE_REQUEST");
public static class Builder implements IAmmoRequest.Builder {
private enum ConnectionMode {
/**
* For some reason the service is not running.
*/
UNAVAILABLE,
/**
* A connection has been requested but not yet granted.
*/
BINDING,
/**
* Asynchronous request to obtain a connection over which
* synchronous requests are made.
*/
BOUND,
/** Asynchronous request without a response */
UNBOUND,
/** No connection */
NONE;
}
private final AtomicReference<ConnectionMode> mode;
private final AtomicReference<IDistributorService> distributor;
private final Context context;
private final BlockingQueue<AmmoRequest> pendingRequestQueue;
final private ServiceConnection conn = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
logger.info("service connected [{}] outstanding requests",
Builder.this.pendingRequestQueue.size());
final IDistributorService distributor = IDistributorService.Stub
.asInterface(service);
try {
for (final AmmoRequest request : Builder.this.pendingRequestQueue) {
final String ident = distributor.makeRequest(request);
logger.info("service bound : {} {}", request, ident);
}
} catch (RemoteException ex) {
logger.error("no connection on recently bound connection", ex);
return;
}
Builder.this.distributor.set(distributor);
Builder.this.mode.set(ConnectionMode.BOUND);
}
@Override
public void onServiceDisconnected(ComponentName name) {
logger.trace("service {} disconnected", name.flattenToShortString());
Builder.this.mode.set(ConnectionMode.UNBOUND);
Builder.this.distributor.set(null);
}
};
/**
* The builder acquires a connection to the service. The status of the
* connection is managed. If the connection is not ready but there is a
* reasonable expectation that it will be made then requests are placed
* in a queue. The queue will be drained when the connection is
* established. This works with the makeRequest() and
* onServiceConnected() methods.
*
* @param context
*/
private Builder(Context context) {
this.mode = new AtomicReference<ConnectionMode>(ConnectionMode.UNBOUND);
this.distributor = new AtomicReference<IDistributorService>(null);
this.context = context;
this.pendingRequestQueue = new LinkedBlockingQueue<AmmoRequest>();
try {
final boolean isBound = this.context.bindService(MAKE_DISTRIBUTOR_REQUEST, this.conn,
Context.BIND_AUTO_CREATE);
logger.trace("is the service bound? {}", isBound);
this.mode.compareAndSet(ConnectionMode.UNBOUND,
(isBound ? ConnectionMode.BINDING : ConnectionMode.UNAVAILABLE));
} catch (ReceiverCallNotAllowedException ex) {
logger.error("the service cannot be bound");
}
}
/**
* This constructor is for direct connections to the service (not IPC).
* Primarily for testing.
*
* @param context
* @param serviceBinder
*/
private Builder(Context context, IBinder serviceBinder) {
this.context = context;
this.pendingRequestQueue = null;
this.mode = new AtomicReference<ConnectionMode>(ConnectionMode.BOUND);
this.distributor = new AtomicReference<IDistributorService>(
IDistributorService.Stub.asInterface(serviceBinder));
}
private String uid;
private Provider provider;
public BroadIntent intent;
private Payload payload;
private SerialMoment moment;
private Topic topic;
private Topic subtopic;
private Quantifier quantifier;
private ChannelFilter channelFilter;
private Integer downsample;
private Integer durability;
private Integer priority;
private Order order;
private TimeTrigger start;
private TimeTrigger expire;
private Limit limit;
private DeliveryScope scope;
private Integer throttle;
private String[] project;
private Selection select;
private Integer worth;
private Notice notice;
// ACTIONS
/**
* Generally the BIND approach should be used as it has the best
* performance. Sometimes this is not possible and the
* getService()/COMMAND method must be used (in the case of
* BroadcastReceiver). There are cases where the PEEK method may be used
* (BroadcastReceiver) but it is not particularly reliable so the
* fall-back to COMMAND is necessary. It may also be the case that the
* service has not yet started and the binder has not yet been obtained.
* In that interim case the COMMAND mode should be used.
*/
private IAmmoRequest makeRequest(final AmmoRequest request) throws RemoteException {
logger.info("make service request {} {}", this.mode, request);
switch (this.mode.get()) {
case BOUND:
final String ident = this.distributor.get().makeRequest(request);
logger.info("service bound : {} {}", request, ident);
break;
case UNBOUND:
final Intent parcelIntent = MAKE_DISTRIBUTOR_REQUEST.cloneFilter();
try {
this.pendingRequestQueue.put(request);
} catch (InterruptedException ex) {
logger.debug("make request interrupted ", ex);
}
final ComponentName componentName = this.context.startService(parcelIntent);
if (componentName != null) {
logger.debug("service binding : {}", componentName.getClassName());
} else {
logger.error("service binding : {}", parcelIntent);
}
break;
case NONE:
case BINDING:
case UNAVAILABLE:
default:
break;
}
return request;
}
@Override
public IAmmoRequest base() {
return new AmmoRequest(Action.NONE, this);
}
@Override
public IAmmoRequest post() throws RemoteException {
return this.makeRequest(new AmmoRequest(Action.POSTAL, this));
}
@Override
public IAmmoRequest unpost() throws RemoteException {
return this.makeRequest(new AmmoRequest(Action.UNPOSTAL, this));
}
@Override
public IAmmoRequest retrieve() throws RemoteException {
return this.makeRequest(new AmmoRequest(Action.RETRIEVAL, this));
}
@Override
public IAmmoRequest unretrieve() throws RemoteException {
return this.makeRequest(new AmmoRequest(Action.UNRETRIEVAL, this));
}
@Override
public IAmmoRequest subscribe() throws RemoteException {
return this.makeRequest(new AmmoRequest(Action.SUBSCRIBE, this));
}
@Override
public IAmmoRequest unsubscribe() throws RemoteException {
return this.makeRequest(new AmmoRequest(Action.UNSUBSCRIBE, this));
}
@Override
public IAmmoRequest duplicate() throws RemoteException {
// TODO Auto-generated method stub
return null;
}
@Override
public IAmmoRequest getInstance(String uuid) throws RemoteException {
// TODO Auto-generated method stub
return null;
}
@Override
public void releaseInstance() {
try {
if (this.conn == null)
return;
this.context.unbindService(this.conn);
} catch (IllegalArgumentException ex) {
logger.warn("the service is not bound or registered", ex);
}
}
// SET PROPERTIES
@Override
public Builder reset() {
this.downsample(DOWNSAMPLE_DEFAULT);
this.durability(DURABILITY_DEFAULT);
this.order(ORDER_DEFAULT);
this.payload(PAYLOAD_DEFAULT);
this.moment(SerialMoment.DEFAULT);
this.priority(PRIORITY_DEFAULT);
this.provider(PROVIDER_DEFAULT);
this.scope(SCOPE_DEFAULT);
this.start(START_DEFAULT);
this.throttle(THROTTLE_DEFAULT);
this.topic(Topic.DEFAULT);
this.subtopic(Topic.DEFAULT);
this.quantifier(QUANTIFIER_DEFAULT);
this.uid(UID_DEFAULT);
this.expire(EXPIRE_DEFAULT);
this.project(PROJECT_DEFAULT);
this.select(SELECT_DEFAULT);
this.filter(FILTER_DEFAULT);
this.worth(WORTH_DEFAULT);
return this;
}
public Builder downsample(String max) {
if (max == null)
return this;
this.downsample = Integer.parseInt(max);
return this;
}
@Override
public Builder downsample(Integer maxSize) {
this.downsample = maxSize;
return this;
}
public Builder durability(String val) {
if (val == null)
return this;
this.durability = Integer.parseInt(val);
return this;
}
@Override
public Builder durability(Integer val) {
this.durability = val;
return this;
}
public Builder order(String val) {
if (val == null)
return this;
return this.order(new Order(val));
}
@Override
public Builder order(Order val) {
this.order = val;
return this;
}
@Override
public Builder payload(String val) {
if (val == null)
return this;
this.payload = new Payload(val);
return this;
}
@Override
public Builder payload(byte[] val) {
if (val == null)
return this;
this.payload = new Payload(val);
return this;
}
@Override
public Builder payload(ContentValues val) {
if (val == null)
return this;
this.payload = new Payload(val);
return this;
}
@Override
public Builder payload(AmmoValues val) {
if (val == null)
return this;
return this.payload(val.asContentValues());
}
@Override
public Builder moment(String val) {
if (val == null) {
return this.moment(SerialMoment.DEFAULT);
}
return this.moment(new SerialMoment(val));
}
@Override
public Builder moment(SerialMoment val) {
this.moment = val;
return this;
}
public Builder priority(String val) {
if (val == null)
return this;
return this.priority(Integer.parseInt(val));
}
@Override
public Builder priority(Integer val) {
this.priority = val;
return this;
}
public Builder provider(String val) {
if (val == null) {
return this.provider(Provider.DEFAULT);
}
return this.provider(Uri.parse(val));
}
@Override
public Builder provider(Uri val) {
this.provider = new Provider(val);
return this;
}
public Builder scope(String val) {
if (val == null) {
return this.scope(DeliveryScope.DEFAULT);
}
return this.scope(new DeliveryScope(val));
}
@Override
public Builder scope(DeliveryScope val) {
this.scope = val;
return this;
}
public Builder throttle(String val) {
if (val == null)
return this;
this.throttle = Integer.parseInt(val);
return this;
}
@Override
public Builder throttle(Integer val) {
this.throttle = val;
return this;
}
@Override
public Builder topic(String val) {
this.topic = new Topic(val);
return this;
}
@Override
public Builder topic(Oid val) {
this.topic = new Topic(val);
return this;
}
@Override
public Builder subtopic(String val) {
this.subtopic = new Topic(val);
return this;
}
@Override
public Builder subtopic(Oid val) {
this.subtopic = new Topic(val);
return this;
}
@Override
public Builder quantifier(String type) {
this.quantifier(type);
return this;
}
@Override
public Builder quantifier(Quantifier.Type type) {
this.quantifier = new Quantifier(type);
return this;
}
@Override
public Builder topic(String topic, String subtopic, String quantifier) {
this.topic(topic);
this.subtopic(subtopic);
this.quantifier(quantifier);
return this;
}
@Override
public Builder topic(Oid topic, Oid subtopic, Quantifier.Type quantifier) {
this.topic(topic);
this.subtopic(subtopic);
this.quantifier(quantifier);
return this;
}
public Builder topicFromProvider() {
if (this.provider == null) {
logger.error("you must first set the provider");
return this;
}
final String topic = this.context
.getContentResolver()
.getType(this.provider.asUri());
this.topic(topic);
return this;
}
@Override
public Builder useChannel(String val) {
if (val == null) {
this.channelFilter = null;
return this;
}
this.channelFilter = new ChannelFilter(val);
return this;
}
@Override
public Builder uid(String val) {
this.uid = val;
return this;
}
public Builder start(String val) {
if (val == null)
return this;
return this.start(new TimeStamp(val));
}
@Override
public Builder start(TimeStamp val) {
this.start = new TimeTrigger(val);
return this;
}
@Override
public Builder start(TimeInterval val) {
this.start = new TimeTrigger(val);
return this;
}
public Builder expire(String val) {
if (val == null)
return this;
return this.expire(new TimeStamp(val));
}
@Override
public Builder expire(TimeInterval val) {
this.expire = new TimeTrigger(val);
return this;
}
@Override
public Builder expire(TimeStamp val) {
this.expire = new TimeTrigger(val);
return this;
}
public Builder limit(String val) {
this.limit = new Limit(val);
return null;
}
@Override
public Builder limit(int val) {
this.limit = new Limit(Limit.Type.NEWEST, val);
return this;
}
@Override
public Builder limit(Limit val) {
this.limit = val;
return this;
}
public Builder project(String val) {
if (val == null)
return this;
if (val.length() < 1)
return this;
this.project(val.substring(1).split(val.substring(0, 1)));
return this;
}
@Override
public Builder project(String[] val) {
this.project = val;
return this;
}
public Builder select(String val) {
if (val == null)
return this;
this.select = new Selection(val);
return this;
}
@Override
public Builder select(Query val) {
this.select = new Selection(val);
return this;
}
@Override
public Builder select(Form val) {
this.select = new Selection(val);
return this;
}
@Override
public Builder filter(String val) {
// this.filter = new Filter(val);
return this;
}
public Builder worth(String val) {
if (val == null)
return this;
this.worth = Integer.parseInt(val);
return null;
}
@Override
public Builder worth(Integer val) {
this.worth = val;
return this;
}
/**
* To clear the notices use notice(Notice.RESET).
*/
public Builder notice(Notice.Threshold threshold, Via.Type type) {
if (this.notice == null)
this.notice = Notice.newInstance();
this.notice.setItem(threshold, type);
plogger.trace("notice=[{}]", this.notice);
return this;
}
/**
* It replaces the current notice object with the argument. The notice
* set can be cleared by using this method with the Notice.RESET object.
*/
@Override
public Builder notice(Notice val) {
this.notice = val;
return this;
}
}
@Override
public void cancel() {
// TODO Auto-generated method stub
}
} |
package bugfree.example;
import static org.assertj.core.api.BDDAssertions.then;
import org.junit.Test;
/**
* This is an example whose goal is to show that writing the simplest code first
* and them add code only driven by additional requirements helps avoid trivial
* but dangerous bugs.
*
* @author ste
*/
public class BugFreeSimplestFirst {
@Test
public void setValidationKeyValid_sets_validation_key_by_user() {
ActivationKeyDAO dao = new ActivationKeyDAO();
// set validation key for a user
for (String username: new String[] {"user-one", "user-two", "user-three"}) {
for (boolean value: new boolean[] {true, false, false, true}) {
dao.setValidationKeyValidity(username, value);
then(dao.isValidationKeyValid(username)).isEqualTo(value);
}
}
}
@Test
public void validation_key_is_invalid_if_the_user_does_not_exist() {
ActivationKeyDAO dao = new ActivationKeyDAO();
// no validations so far...
for (String username: new String[] {"user-one", "user-two", "user-three"}) {
then(dao.isValidationKeyValid(username)).isFalse();
}
// adding some validation
dao.setValidationKeyValidity("anotheruser1", true);
dao.setValidationKeyValidity("anotheruser2", false);
for (String username: new String[] {"user-one", "user-two", "user-three"}) {
then(dao.isValidationKeyValid(username)).isFalse();
}
}
@Test
public void setValidationKeyValidity_invalid_arguments() {
ActivationKeyDAO dao = new ActivationKeyDAO();
try {
for (String BLANK: new String[] {null, "", " ", "\t "}) {
dao.setValidationKeyValidity(BLANK, true);
fail("missing argument validity check");
}
}
}
} |
package com.cedarsoftware.ncube;
import org.junit.Test;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Calendar;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
public class TestCellInfo
{
@Test
public void testFormatForEditing() {
assertEquals("4.56", CellInfo.formatForEditing(4.56));
assertEquals("0.0", CellInfo.formatForEditing(0.0));
assertEquals("4.0", CellInfo.formatForEditing(new Float(4)));
assertEquals("4.0", CellInfo.formatForEditing(new Double(4)));
assertEquals("4.56", CellInfo.formatForEditing(new BigDecimal("4.56000")));
assertEquals("4.56", CellInfo.formatForEditing(new BigDecimal("4.56")));
}
@Test
public void testFormatForDisplay() {
assertEquals("4.56", CellInfo.formatForEditing(4.560));
assertEquals("4.5", CellInfo.formatForEditing(4.5));
assertEquals("4.56", CellInfo.formatForEditing(new BigDecimal("4.5600")));
assertEquals("4", CellInfo.formatForEditing(new BigDecimal("4.00")));
assertEquals("4", CellInfo.formatForEditing(new BigDecimal("4")));
}
@Test
public void testRecreate() {
assertNull(new CellInfo(null).recreate());
performRecreateAssertion(new StringUrlCmd("http:
performRecreateAssertion(new Double(4.56));
performRecreateAssertion(new Float(4.56));
performRecreateAssertion(new Short((short)4));
performRecreateAssertion(new Long(4));
performRecreateAssertion(new Integer(4));
performRecreateAssertion(new Byte((byte)4));
performRecreateAssertion(new BigDecimal("4.56"));
performRecreateAssertion(new BigInteger("900"));
performRecreateAssertion(Boolean.TRUE);
performRecreateAssertion(new GroovyExpression("0", null));
performRecreateAssertion(new GroovyMethod("0", null));
performRecreateAssertion(new GroovyTemplate(null, "http:
performRecreateAssertion(new BinaryUrlCmd("http:
performArrayRecreateAssertion(new byte[]{0, 4, 5, 6});
performRecreateAssertion("foo");
// Have to special create this because milliseconds are not saved
Calendar c = Calendar.getInstance();
c.set(Calendar.MILLISECOND, 0);
performRecreateAssertion(c.getTime());
}
public void performRecreateAssertion(Object o) {
assertEquals(o, new CellInfo(o).recreate());
}
public void performArrayRecreateAssertion(byte[] o) {
assertArrayEquals(o, (byte[])new CellInfo(o).recreate());
}
} |
// This file is part of the Fuel Java SDK.
// 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,
// of the Software, and to permit persons to whom the Software
// is furnished to do so, subject to the following conditions:
// included in all copies or substantial portions of the Software.
// 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 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 com.exacttarget.fuelsdk;
import java.util.ArrayList;
import java.util.List;
import org.junit.BeforeClass;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import static org.junit.Assert.*;
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class ETFolderTest {
private static ETClient client = null;
@BeforeClass
public static void setUpBeforeClass()
throws ETSdkException
{
client = new ETClient();
}
@Test
public void _01_TestRetrieveAll()
throws ETSdkException
{
ETResponse<ETFolder> response = client.retrieve(ETFolder.class);
for (ETFolder folder : response.getObjects()) {
// ensure all properties were retrieved
assertNotNull(folder.getId());
assertNotNull(folder.getKey());
assertNotNull(folder.getName());
assertNotNull(folder.getDescription());
assertNotNull(folder.getCreatedDate());
assertNotNull(folder.getModifiedDate());
assertNotNull(folder.getContentType());
// parentFolder can be null if there's no parent
assertNotNull(folder.getIsActive());
assertNotNull(folder.getIsEditable());
assertNotNull(folder.getAllowChildren());
}
}
@Test
public void _02_TestRetrieveAllPropertiesSubset()
throws ETSdkException
{
ETResponse<ETFolder> response = client.retrieve(ETFolder.class,
"key",
"name",
"description");
for (ETFolder folder : response.getObjects()) {
// ensure only the specified properties were retrieved
assertNull(folder.getId());
assertNotNull(folder.getKey());
assertNotNull(folder.getName());
assertNotNull(folder.getDescription());
assertNull(folder.getCreatedDate());
assertNull(folder.getModifiedDate());
assertNull(folder.getContentType());
assertNull(folder.getParentFolderKey());
assertNull(folder.getIsActive());
assertNull(folder.getIsEditable());
assertNull(folder.getAllowChildren());
}
}
@Test
public void _03_TestRetrieveFiltered()
throws ETSdkException
{
// retrieve the Data Extension folder, which
// has customer key of dataextension_default
ETResponse<ETFolder> response = client.retrieve(ETFolder.class,
"key='dataextension_default'");
// ensure we only received 1
assertEquals(1, response.getObjects().size());
ETFolder folder = response.getObjects().get(0);
// ensure it's the Data Extensions folder
// and that all properties were retrieved
assertNotNull(folder.getId());
assertEquals("dataextension_default", folder.getKey());
assertEquals("Data Extensions", folder.getName());
assertEquals("", folder.getDescription());
assertNotNull(folder.getCreatedDate());
assertNotNull(folder.getModifiedDate());
assertEquals("dataextension", folder.getContentType());
assertNull(folder.getParentFolderKey());
assertTrue(folder.getIsActive());
assertFalse(folder.getIsEditable());
assertTrue(folder.getAllowChildren());
}
@Test
public void _04_TestRetrieveFilteredPropertiesSubset()
throws ETSdkException
{
ETResponse<ETFolder> response = client.retrieve(ETFolder.class,
"key='dataextension_default'",
"key",
"name",
"description");
// ensure we only received 1
assertEquals(1, response.getObjects().size());
ETFolder folder = response.getObjects().get(0);
// ensure it's the Data Extensions folder
// and that only the specified properties
// were retrieved
assertNull(folder.getId());
assertEquals("dataextension_default", folder.getKey());
assertEquals("Data Extensions", folder.getName());
assertEquals("", folder.getDescription());
assertNull(folder.getCreatedDate());
assertNull(folder.getModifiedDate());
assertNull(folder.getContentType());
assertNull(folder.getParentFolderKey());
assertNull(folder.getIsActive());
assertNull(folder.getIsEditable());
assertNull(folder.getAllowChildren());
}
private static String id = null;
@Test
public void _05_TestCreateSingle()
throws ETSdkException
{
ETFolder folder = new ETFolder();
folder.setKey("test1");
folder.setName("test1");
folder.setDescription("test1");
folder.setContentType("dataextension");
folder.setParentFolderKey("dataextension_default");
ETResponse<ETFolder> response = client.create(folder);
assertNotNull(response.getRequestId());
assertEquals("OK", response.getResponseCode());
assertEquals("OK", response.getResponseMessage());
assertNull(response.getPage());
assertNull(response.getPageSize());
assertNull(response.getTotalCount());
assertFalse(response.hasMoreResults());
assertEquals(1, response.getResults().size());
ETResult<ETFolder> result = response.getResults().get(0);
assertEquals("OK", result.getResponseCode());
assertEquals("Folder created successfully.", result.getResponseMessage());
assertNotNull(result.getObjectId());
// save the ID for use in the next test
id = result.getObjectId();
}
private static ETFolder createdFolder = null;
@Test
public void _06_TestRetrieveCreatedSingle()
throws ETSdkException
{
ETResponse<ETFolder> response = client.retrieve(ETFolder.class, "id=" + id);
// ensure we only received 1
assertEquals(1, response.getObjects().size());
createdFolder = response.getObjects().get(0);
// ensure it's the folder we just created
assertEquals(id, createdFolder.getId());
assertEquals("test1", createdFolder.getKey());
assertEquals("test1", createdFolder.getName());
assertEquals("test1", createdFolder.getDescription());
assertNotNull(createdFolder.getCreatedDate());
assertNotNull(createdFolder.getModifiedDate());
assertEquals("dataextension", createdFolder.getContentType());
assertEquals("dataextension_default", createdFolder.getParentFolderKey());
assertTrue(createdFolder.getIsActive());
assertFalse(createdFolder.getIsEditable());
assertFalse(createdFolder.getAllowChildren());
}
@Test
public void _07_TestUpdateSingle()
throws ETSdkException
{
createdFolder.setName("TEST1");
ETResponse<ETFolder> response = client.update(createdFolder);
assertNotNull(response.getRequestId());
assertEquals("OK", response.getResponseCode());
assertEquals("OK", response.getResponseMessage());
assertNull(response.getPage());
assertNull(response.getPageSize());
assertNull(response.getTotalCount());
assertFalse(response.hasMoreResults());
assertEquals(1, response.getResults().size());
ETResult<ETFolder> result = response.getResults().get(0);
assertEquals("OK", result.getResponseCode());
assertEquals("Folder updated successfully.", result.getResponseMessage());
}
@Test
public void _08_TestRetrieveUpdatedSingle()
throws ETSdkException
{
ETResponse<ETFolder> response = client.retrieve(ETFolder.class, "id=" + id);
// ensure we only received 1
assertEquals(1, response.getObjects().size());
ETFolder folder = response.getObjects().get(0);
assertEquals(id, folder.getId());
assertEquals("test1", folder.getKey());
assertEquals("TEST1", folder.getName());
assertEquals("test1", folder.getDescription());
assertNotNull(folder.getCreatedDate());
assertNotNull(folder.getModifiedDate());
assertEquals("dataextension", folder.getContentType());
assertEquals("dataextension_default", folder.getParentFolderKey());
assertTrue(folder.getIsActive());
assertFalse(folder.getIsEditable());
assertFalse(folder.getAllowChildren());
}
@Test
public void _09_TestDeleteSingle()
throws ETSdkException
{
ETFolder folder = new ETFolder();
folder.setKey("test1");
ETResponse<ETFolder> response = client.delete(folder);
assertNotNull(response.getRequestId());
assertEquals("OK", response.getResponseCode());
assertEquals("OK", response.getResponseMessage());
assertNull(response.getPage());
assertNull(response.getPageSize());
assertNull(response.getTotalCount());
assertFalse(response.hasMoreResults());
assertEquals(1, response.getResults().size());
ETResult<ETFolder> result = response.getResults().get(0);
assertEquals("OK", result.getResponseCode());
assertEquals("Folder deleted successfully.", result.getResponseMessage());
}
private static String id1 = null;
private static String id2 = null;
@Test
public void _10_TestCreateMultiple()
throws ETSdkException
{
ETFolder folder1 = new ETFolder();
folder1.setKey("test1");
folder1.setName("test1");
folder1.setDescription("test1");
folder1.setContentType("dataextension");
folder1.setParentFolderKey("dataextension_default");
ETFolder folder2 = new ETFolder();
folder2.setKey("test2");
folder2.setName("test2");
folder2.setDescription("test2");
folder2.setContentType("dataextension");
folder2.setParentFolderKey("dataextension_default");
List<ETFolder> folders = new ArrayList<ETFolder>();
folders.add(folder1);
folders.add(folder2);
ETResponse<ETFolder> response = client.create(folders);
assertNotNull(response.getRequestId());
assertEquals("OK", response.getResponseCode());
assertEquals("OK", response.getResponseMessage());
assertNull(response.getPage());
assertNull(response.getPageSize());
assertNull(response.getTotalCount());
assertFalse(response.hasMoreResults());
assertEquals(2, response.getResults().size());
ETResult<ETFolder> result1 = response.getResults().get(0);
assertEquals("OK", result1.getResponseCode());
assertEquals("Folder created successfully.", result1.getResponseMessage());
assertNotNull(result1.getObjectId());
// save the ID for use in the next test
id1 = result1.getObjectId();
ETResult<ETFolder> result2 = response.getResults().get(0);
assertEquals("OK", result2.getResponseCode());
assertEquals("Folder created successfully.", result2.getResponseMessage());
assertNotNull(result2.getObjectId());
// save the ID for use in the next test
id2 = result2.getObjectId();
}
@Test
public void _11_TestRetrieveCreatedMultiple()
throws ETSdkException
{
// XXX implement when we can pass the filter id = <id1> and id = <id2>
}
@Test
public void _12_TestUpdateMultiple()
throws ETSdkException
{
// XXX implement when we implement _11_TestRetrieveCreatedMultiple
}
@Test
public void _13_TestRetrieveUpdatedMultiple()
throws ETSdkException
{
// XXX implement when we implement _12_TestUpdateMultiple
}
@Test
public void _14_TestDeleteMultiple()
throws ETSdkException
{
ETFolder folder1 = new ETFolder();
folder1.setKey("test1");
ETFolder folder2 = new ETFolder();
folder2.setKey("test2");
List<ETFolder> folders = new ArrayList<ETFolder>();
folders.add(folder1);
folders.add(folder2);
ETResponse<ETFolder> response = client.delete(folders);
assertNotNull(response.getRequestId());
assertEquals("OK", response.getResponseCode());
assertEquals("OK", response.getResponseMessage());
assertNull(response.getPage());
assertNull(response.getPageSize());
assertNull(response.getTotalCount());
assertFalse(response.hasMoreResults());
assertEquals(2, response.getResults().size());
ETResult<ETFolder> result1 = response.getResults().get(0);
assertEquals("OK", result1.getResponseCode());
assertEquals("Folder deleted successfully.", result1.getResponseMessage());
ETResult<ETFolder> result2 = response.getResults().get(0);
assertEquals("OK", result2.getResponseCode());
assertEquals("Folder deleted successfully.", result2.getResponseMessage());
}
} |
package com.tinkerpop.pipes;
import com.tinkerpop.blueprints.pgm.Graph;
import com.tinkerpop.blueprints.pgm.Vertex;
import com.tinkerpop.blueprints.pgm.impls.tg.TinkerEdge;
import com.tinkerpop.blueprints.pgm.impls.tg.TinkerGraphFactory;
import com.tinkerpop.blueprints.pgm.impls.tg.TinkerVertex;
import com.tinkerpop.pipes.pgm.EdgeVertexPipe;
import com.tinkerpop.pipes.pgm.PropertyPipe;
import com.tinkerpop.pipes.pgm.VertexEdgePipe;
import com.tinkerpop.pipes.merge.*;
import java.util.Arrays;
import java.util.List;
import java.util.Iterator;
public class PathSequenceTest extends BaseTest {
private Pipe<Vertex, Vertex> outE_inV(Iterator source) {
Pipe pipe1 = new VertexEdgePipe(VertexEdgePipe.Step.OUT_EDGES);
Pipe pipe2 = new EdgeVertexPipe(EdgeVertexPipe.Step.IN_VERTEX);
Pipe<Vertex, Vertex> pipeline = new Pipeline<Vertex, Vertex>(Arrays.asList(pipe1, pipe2));
pipeline.setStarts(source);
return pipeline;
}
private Pipe<Vertex, Vertex> inE_outV(Iterator source) {
Pipe pipe1 = new VertexEdgePipe(VertexEdgePipe.Step.IN_EDGES);
Pipe pipe2 = new EdgeVertexPipe(EdgeVertexPipe.Step.OUT_VERTEX);
Pipe<Vertex, Vertex> pipeline = new Pipeline<Vertex, Vertex>(Arrays.asList(pipe1, pipe2));
pipeline.setStarts(source);
return pipeline;
}
private Pipe<Vertex, Object> outE_inV_Property(Vertex vertex, String property) {
Pipe pipe1 = new VertexEdgePipe(VertexEdgePipe.Step.OUT_EDGES);
Pipe pipe2 = new EdgeVertexPipe(EdgeVertexPipe.Step.IN_VERTEX);
Pipe pipe3 = new PropertyPipe<Vertex, String>(property);
Pipe<Vertex, Object> pipeline = new Pipeline<Vertex, Object>(Arrays.asList(pipe1, pipe2, pipe3));
pipeline.setStarts(Arrays.asList(vertex).iterator());
return pipeline;
}
public void testPathSequencing() {
Graph graph = TinkerGraphFactory.createTinkerGraph();
Vertex marko = graph.getVertex("1");
PathSequence paths = new PathSequence(outE_inV_Property(marko, "name"));
for (List path : paths) {
String name = (String) path.get(path.size() - 1);
assertEquals(path.get(0), marko);
assertEquals(path.get(1).getClass(), TinkerEdge.class);
assertEquals(path.get(2).getClass(), TinkerVertex.class);
assertEquals(path.get(3).getClass(), String.class);
if (name.equals("vadas")) {
assertEquals(path.get(1), graph.getEdge(7));
assertEquals(path.get(2), graph.getVertex(2));
assertEquals(path.get(3), "vadas");
} else if (name.equals("lop")) {
assertEquals(path.get(1), graph.getEdge(9));
assertEquals(path.get(2), graph.getVertex(3));
assertEquals(path.get(3), "lop");
} else if (name.equals("josh")) {
assertEquals(path.get(1), graph.getEdge(8));
assertEquals(path.get(2), graph.getVertex(4));
assertEquals(path.get(3), "josh");
} else {
assertFalse(true);
}
//System.out.println(path);
}
}
public void testExhaustiveMergePath() {
Graph graph = TinkerGraphFactory.createTinkerGraph();
Vertex marko = graph.getVertex("1");
Pipe<Vertex, Object> namePipe = outE_inV_Property(marko, "name");
Pipe<Vertex, Object> agePipe = outE_inV_Property(marko, "age");
ExhaustiveMergePipe<Object> mergePipe = new ExhaustiveMergePipe<Object>();
mergePipe.setStarts(Arrays.asList(namePipe.iterator(), agePipe.iterator()).iterator());
PathSequence paths = new PathSequence(mergePipe);
Iterator<String> expected = Arrays.asList(
"[v[1], e[7][1-knows->2], v[2], vadas]",
"[v[1], e[9][1-created->3], v[3], lop]",
"[v[1], e[8][1-knows->4], v[4], josh]",
"[v[1], e[7][1-knows->2], v[2], 27]",
"[v[1], e[9][1-created->3], v[3], null]",
"[v[1], e[8][1-knows->4], v[4], 32]").iterator();
for (List path : paths) {
assertEquals(path.toString(), expected.next());
//System.out.println(path);
}
}
public void testRobinMergePath() {
Graph graph = TinkerGraphFactory.createTinkerGraph();
Vertex marko = graph.getVertex("1");
Pipe<Vertex, Object> namePipe = outE_inV_Property(marko, "name");
Pipe<Vertex, Object> agePipe = outE_inV_Property(marko, "age");
RobinMergePipe<Object> mergePipe = new RobinMergePipe<Object>();
mergePipe.setStarts(Arrays.asList(namePipe.iterator(), agePipe.iterator()).iterator());
PathSequence paths = new PathSequence(mergePipe);
Iterator<String> expected = Arrays.asList(
"[v[1], e[7][1-knows->2], v[2], vadas]",
"[v[1], e[7][1-knows->2], v[2], 27]",
"[v[1], e[9][1-created->3], v[3], lop]",
"[v[1], e[9][1-created->3], v[3], null]",
"[v[1], e[8][1-knows->4], v[4], josh]",
"[v[1], e[8][1-knows->4], v[4], 32]").iterator();
for (List path : paths) {
assertEquals(path.toString(), expected.next());
//System.out.println(path);
}
}
public void testRobinMergeExtendedPath() {
Graph graph = TinkerGraphFactory.createTinkerGraph();
Vertex marko = graph.getVertex("1");
Vertex vadas = graph.getVertex("2");
Pipe<Vertex, Vertex> source1 = outE_inV(Arrays.asList(marko).iterator());
Pipe<Vertex, Vertex> source2 = inE_outV(Arrays.asList(vadas).iterator());
RobinMergePipe<Vertex> mergePipe = new RobinMergePipe<Vertex>();
mergePipe.setStarts(Arrays.asList(source1.iterator(), source2.iterator()).iterator());
PathSequence paths = new PathSequence(outE_inV(mergePipe.iterator()));
Iterator<String> expected = Arrays.asList(
"[v[2], e[7][1-knows->2], v[1], e[7][1-knows->2], v[2]]",
"[v[2], e[7][1-knows->2], v[1], e[9][1-created->3], v[3]]",
"[v[2], e[7][1-knows->2], v[1], e[8][1-knows->4], v[4]]",
"[v[1], e[8][1-knows->4], v[4], e[10][4-created->5], v[5]]",
"[v[1], e[8][1-knows->4], v[4], e[11][4-created->3], v[3]]").iterator();
for (List path : paths) {
assertEquals(path.toString(), expected.next());
//System.out.println(path);
}
}
} |
package datastructures;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
/**
* @author Pavel Nichita
*
*/
public class DFJointProjectionTest {
private SetUpClass setUpObject;
/**
* Set up.
*/
@Before
public void setUp() {
this.setUpObject = new SetUpClass();
}
/**
* Test method for {@link datastructures.FDSet#projectionOnAttributeJoint(datastructures.AttributeSet)}.
* Projecting {AB -> C, C -> A} on {B, C},
* result: {}.
*/
@Test
public void testProjectionOnAttributeJointDFJoint10OnBC() {
FDSet dfJoint = this.setUpObject.dfJoint10();
AttributeSet attrJoint = this.setUpObject.attrJntBC();
FDSet expected = new FDSet();
assertEquals(expected, dfJoint.projectionOnAttributeJoint(attrJoint));
}
/**
* Test method for {@link datastructures.FDSet#projectionOnAttributeJoint(datastructures.AttributeSet)}.
* Projecting {AB -> C, C -> A} on {A, C},
* result: {C -> A}.
*/
@Test
public void testProjectionDFJointTenToAttributeJointAC() {
FDSet dfJoint = this.setUpObject.dfJoint10();
AttributeSet attrJoint = this.setUpObject.attrJntAC();
FDSet expected = this.setUpObject.dfJoint11();
assertEquals(expected, dfJoint.projectionOnAttributeJoint(attrJoint));
}
/**
* Test method for {@link datastructures.FDSet#projectionOnAttributeJoint(datastructures.AttributeSet)}.
* Projecting {A -> B, CD -> A, BD -> C, DE -> C} on {A, B},
* result: {A -> B}.
*/
@Test
public void testProjectionDFJointTwelveToAttributeJointAB() {
FDSet dfJoint = this.setUpObject.dfJoint12();
AttributeSet attrJoint = this.setUpObject.attrJntAB();
FDSet expected = this.setUpObject.dfJoint13();
assertEquals(expected, dfJoint.projectionOnAttributeJoint(attrJoint));
}
/**
* Test method for {@link datastructures.FDSet#projectionOnAttributeJoint(datastructures.AttributeSet)}.
* Projecting {A -> B, CD -> A, BD -> C, DE -> C} on {A, C, D, E},
* result: {CD -> A, DE -> C, AD -> C}.
*/
@Test
public void testProjectionDFJointTwelveToAttributeJointACDE() {
FDSet dfJoint = this.setUpObject.dfJoint12();
AttributeSet attrJoint = this.setUpObject.attrJntACDE();
FDSet expected = this.setUpObject.dfJoint14();
assertEquals(expected, dfJoint.projectionOnAttributeJoint(attrJoint));
}
/**
* Test method for {@link datastructures.FDSet#projectionOnAttributeJoint(datastructures.AttributeSet)}.
* Projecting {CD -> A, AD -> C, DE -> C} on {A, C, D},
* result: {CD -> A, AD -> C}.
*/
@Test
public void testProjectionDFJointFourteenToAttributeJointACD() {
FDSet dfJoint = this.setUpObject.dfJoint14();
AttributeSet attrJoint = this.setUpObject.attrJntACD();
FDSet expected = this.setUpObject.dfJoint15();
assertEquals(expected, dfJoint.projectionOnAttributeJoint(attrJoint));
}
/**
* Test method for {@link datastructures.FDSet#projectionOnAttributeJoint(datastructures.AttributeSet)}.
* Projecting {CD -> A, AD -> C, DE -> C} on {C, D, E},
* result: {DE -> C}.
*/
@Test
public void testProjectionDFJointFourteenToAttributeJointCDE() {
FDSet dfJoint = this.setUpObject.dfJoint14();
AttributeSet attrJoint = this.setUpObject.attrJntCDE();
FDSet expected = this.setUpObject.dfJoint16();
assertEquals(expected, dfJoint.projectionOnAttributeJoint(attrJoint));
}
/**
* Test method for {@link datastructures.FDSet#projectionOnAttributeJoint(datastructures.AttributeSet)}.
* Projecting {BCD -> E, E -> C} on {C, E},
* result: {E -> C}.
*/
@Test
public void testProjectionDFJointSeventeenToAttributeJointCE() {
FDSet dfJoint = this.setUpObject.dfJoint17();
AttributeSet attrJoint = this.setUpObject.attrJntCE();
FDSet expected = this.setUpObject.dfJoint18();
assertEquals(expected, dfJoint.projectionOnAttributeJoint(attrJoint));
}
/**
* Test method for {@link datastructures.FDSet#projectionOnAttributeJoint(datastructures.AttributeSet)}.
* Projecting {BCD -> E, E -> C} on {B, D, E},
* result: {}.
*/
@Test
public void testProjectionDFJointSeventeenToAttributeJointBDE() {
FDSet dfJoint = this.setUpObject.dfJoint17();
AttributeSet attrJoint = this.setUpObject.attrJntBDE();
FDSet expected = new FDSet();
assertEquals(expected, dfJoint.projectionOnAttributeJoint(attrJoint));
}
/**
* Test method for {@link datastructures.FDSet#projectionOnAttributeJoint(datastructures.AttributeSet)}.
* Projecting {AB -> C, C -> B} on {B, C},
* result: {C -> B}.
*/
@Test
public void testProjectionDFJointNineteenToAttributeJointBC() {
FDSet dfJoint = this.setUpObject.dfJoint19();
AttributeSet attrJoint = this.setUpObject.attrJntBC();
FDSet expected = this.setUpObject.dfJoint20();
assertEquals(expected, dfJoint.projectionOnAttributeJoint(attrJoint));
}
/**
* Test method for {@link datastructures.FDSet#projectionOnAttributeJoint(datastructures.AttributeSet)}.
* Projecting {AB -> C, C -> B} on {A, C},
* result: {}.
*/
@Test
public void testProjectionDFJointNineteenToAttributeJointAC() {
FDSet dfJoint = this.setUpObject.dfJoint19();
AttributeSet attrJoint = this.setUpObject.attrJntAC();
FDSet expected = new FDSet();
assertEquals(expected, dfJoint.projectionOnAttributeJoint(attrJoint));
}
/**
* Test method for {@link datastructures.FDSet#projectionOnAttributeJoint(datastructures.AttributeSet)}.
* Projecting {A -> BC, B -> C, A -> B, AB -> C} on {A, C},
* result: {A -> C}.
*/
@Test
public void testProjectionDFJointFourToAttributeJointAC() {
FDSet dfJoint = this.setUpObject.dfJoint04();
AttributeSet attrJoint = this.setUpObject.attrJntAC();
FDSet expected = this.setUpObject.dfJoint21();
assertEquals(expected, dfJoint.projectionOnAttributeJoint(attrJoint));
}
/**
* Test method for {@link datastructures.FDSet#projectionOnAttributeJoint(datastructures.AttributeSet)}.
* Projecting {A -> BC, B -> C, A -> B, AB -> C} on {A, B},
* result: {A -> B}.
*/
@Test
public void testProjectionDFJointFourToAttributeJointAB() {
FDSet dfJoint = this.setUpObject.dfJoint04();
AttributeSet attrJoint = this.setUpObject.attrJntAB();
FDSet expected = this.setUpObject.dfJoint13();
assertEquals(expected, dfJoint.projectionOnAttributeJoint(attrJoint));
}
/**
* Test method for {@link datastructures.FDSet#projectionOnAttributeJoint(datastructures.AttributeSet)}.
* Projecting {A -> BC, B -> C, A -> B, AB -> C} on {B, C},
* result: {B -> C}.
*/
@Test
public void testProjectionDFJointFourToAttributeJointBC() {
FDSet dfJoint = this.setUpObject.dfJoint04();
AttributeSet attrJoint = this.setUpObject.attrJntBC();
FDSet expected = this.setUpObject.dfJoint22();
assertEquals(expected, dfJoint.projectionOnAttributeJoint(attrJoint));
}
/**
* Test method for {@link datastructures.FDSet#projectionOnAttributeJoint(datastructures.AttributeSet)}.
* Projecting {C -> A, CD -> E, A -> B} on {A, C},
* result: {C -> A}.
*/
@Test
public void testProjectionDFJoint35AToAttributeJointAC() {
FDSet dfJoint = this.setUpObject.dpJoint35A();
AttributeSet attrJoint = this.setUpObject.attrJntAC();
FDSet expected = this.setUpObject.dfJointCtoA();
assertEquals(expected, dfJoint.projectionOnAttributeJoint(attrJoint));
}
/**
* Test method for {@link datastructures.FDSet#projectionOnAttributeJoint(datastructures.AttributeSet)}.
* Projecting {A -> B, B -> C, C -> D} on {A, D},
* result: {A -> D}.
*/
@Test
public void testProjectionDFJoint07AToAttributeJointAD() {
FDSet dfJoint = this.setUpObject.dfJoint07();
AttributeSet attrJoint = this.setUpObject.attrJntAD();
FDSet expected = this.setUpObject.dfJoint29();
assertEquals(expected, dfJoint.projectionOnAttributeJoint(attrJoint));
}
/**
* Test method for {@link datastructures.FDSet#projectionOnAttributeJoint(datastructures.AttributeSet)}.
* Projecting {A -> B, B -> C, C -> D} on {A, B, C},
* result: {A -> B, B -> C}.
*/
@Test
public void testProjectionDFJoint07AToAttributeJointABC() {
FDSet dfJoint = this.setUpObject.dfJoint07();
AttributeSet attrJoint = this.setUpObject.attrJntABC();
FDSet expected = this.setUpObject.dfJoint05();
assertEquals(expected, dfJoint.projectionOnAttributeJoint(attrJoint));
}
/**
* Test method for {@link datastructures.FDSet#projectionOnAttributeJoint(datastructures.AttributeSet)}.
* Projecting {A -> BE, B -> C, EC -> D} on {A, D},
* result: {A -> D}.
*/
@Test
public void testProjectionDFJoint100AToAttributeJointAD() {
FDSet dfJoint = this.setUpObject.dfJoint100();
AttributeSet attrJoint = this.setUpObject.attrJntAD();
FDSet expected = this.setUpObject.dfJoint29();
assertEquals(expected, dfJoint.projectionOnAttributeJoint(attrJoint));
}
/**
* Test method for {@link datastructures.FDSet#projectionOnAttributeJoint(datastructures.AttributeSet)}.
* Projecting {A -> BC, BC -> A, BCD -> E, E -> C} on {A, D, E},
* result: {AD -> E}.
*/
@Test
public void testProjectionDFJoint01AToAttributeJointADE() {
FDSet dfJoint = this.setUpObject.dfJoint01();
AttributeSet attrJoint = this.setUpObject.attrJntADE();
FDSet expected = this.setUpObject.dfJointADtoe();
assertEquals(expected, dfJoint.projectionOnAttributeJoint(attrJoint));
}
} |
package guitests.guihandles;
import guitests.GuiRobot;
import javafx.collections.ObservableList;
import javafx.scene.input.KeyCode;
import javafx.stage.Stage;
/**
* A handle to the Command Box in the GUI.
*/
public class CommandBoxHandle extends GuiHandle {
private static final String COMMAND_INPUT_FIELD_ID = "#commandTextField";
public CommandBoxHandle(GuiRobot guiRobot, Stage primaryStage, String stageTitle) {
super(guiRobot, primaryStage, stageTitle);
}
/**
* Clicks on the TextField.
*/
public void clickOnTextField() {
guiRobot.clickOn(COMMAND_INPUT_FIELD_ID);
}
public void type(KeyCode... keyCodes) {
guiRobot.type(keyCodes);
}
public void enterCommand(String command) {
setTextField(COMMAND_INPUT_FIELD_ID, command);
}
public String getCommandInput() {
return getTextFieldText(COMMAND_INPUT_FIELD_ID);
}
/**
* Enters the given command in the Command Box and presses enter.
*/
public void runCommand(String command) {
enterCommand(command);
pressEnter();
guiRobot.sleep(200); //Give time for the command to take effect
}
public HelpWindowHandle runHelpCommand() {
enterCommand("help");
pressEnter();
return new HelpWindowHandle(guiRobot, primaryStage);
}
public ObservableList<String> getStyleClass() {
return getNode(COMMAND_INPUT_FIELD_ID).getStyleClass();
}
} |
package de.gurkenlabs.litiengine.sound;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import de.gurkenlabs.litiengine.Game;
import de.gurkenlabs.litiengine.IGameLoop;
import de.gurkenlabs.litiengine.IUpdateable;
import de.gurkenlabs.litiengine.entities.IEntity;
public final class SoundEngine implements ISoundEngine, IUpdateable {
private static final int DEFAULT_MAX_DISTANCE = 250;
private Point2D listenerLocation;
private float maxDist;
private SoundSource music;
private final List<SoundSource> sounds;
public SoundEngine() {
this.sounds = new CopyOnWriteArrayList<>();
this.maxDist = DEFAULT_MAX_DISTANCE;
}
@Override
public float getMaxDistance() {
return this.maxDist;
}
@Override
public void playMusic(final Sound sound) {
if (sound == null) {
return;
}
if (this.music != null) {
this.music.dispose();
}
this.music = new SoundSource(sound);
this.music.play(true, Game.getConfiguration().SOUND.getMusicVolume());
}
@Override
public void playSound(final IEntity entity, final Sound sound) {
if (sound == null) {
return;
}
final SoundSource source = new SoundSource(sound, this.listenerLocation, entity);
source.play();
this.sounds.add(source);
}
@Override
public void playSound(final Point2D location, final Sound sound) {
if (sound == null) {
return;
}
final SoundSource source = new SoundSource(sound, this.listenerLocation);
source.play();
this.sounds.add(source);
}
@Override
public void playSound(final Sound sound) {
if (sound == null) {
return;
}
final SoundSource source = new SoundSource(sound);
source.play();
this.sounds.add(source);
}
@Override
public void setMaxDistance(final float radius) {
this.maxDist = radius;
}
@Override
public void start() {
Game.getLoop().attach(this);
this.listenerLocation = Game.getScreenManager().getCamera().getFocus();
}
@Override
public void stopMusic() {
this.music.dispose();
this.music = null;
}
@Override
public void terminate() {
Game.getLoop().detach(this);
SoundSource.terminate();
}
@Override
public void update(final IGameLoop loop) {
this.listenerLocation = Game.getScreenManager().getCamera().getFocus();
final List<SoundSource> remove = new ArrayList<>();
for (final SoundSource s : this.sounds) {
if (s != null && !s.isPlaying()) {
s.dispose();
remove.add(s);
}
}
this.sounds.removeAll(remove);
for (final SoundSource s : this.sounds) {
s.updateControls(this.listenerLocation);
}
// music is looped by default
if (this.music != null && !this.music.isPlaying()) {
this.playMusic(this.music.getSound());
}
}
} |
package me.ysobj.sqlparser.parser;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsNot.not;
import static org.hamcrest.core.IsNull.nullValue;
import static org.junit.Assert.assertThat;
import org.junit.Test;
import me.ysobj.sqlparser.tokenizer.Tokenizer;
public class ParserTest {
@Test
public void testTokenParser() {
Parser parser = new KeywordParser("select");
assertThat(parser.parse(new Tokenizer("select")), not(nullValue()));
assertThat(parser.parse(new Tokenizer("update")), is(nullValue()));
}
@Test
public void testChoiseParser() {
Parser p1 = new KeywordParser("select");
Parser p2 = new KeywordParser("update");
Parser p3 = new KeywordParser("delete");
Parser parser = new ChoiseParser(p1, p2, p3);
assertThat(parser.parse(new Tokenizer("select")), not(nullValue()));
assertThat(parser.parse(new Tokenizer("update")), not(nullValue()));
assertThat(parser.parse(new Tokenizer("delete")), not(nullValue()));
assertThat(parser.parse(new Tokenizer("insert")), is(nullValue()));
}
@Test
public void testSeaquenceParser() {
Parser p1 = new KeywordParser("select");
Parser p2 = new KeywordParser("update");
Parser p3 = new KeywordParser("delete");
Parser parser = new SequenceParser(p1, p2, p3);
assertThat(parser.parse(new Tokenizer("select update delete")), not(nullValue()));
assertThat(parser.parse(new Tokenizer("select delete update")), is(nullValue()));
}
@Test
public void testCombination() {
// (A|B)CD
Parser ab = new ChoiseParser(new KeywordParser("A"), new KeywordParser("B"));
Parser parser = new SequenceParser(ab, new KeywordParser("C"), new KeywordParser("D"));
assertThat(parser.parse(new Tokenizer("A C D")), not(nullValue()));
assertThat(parser.parse(new Tokenizer("B C D")), not(nullValue()));
assertThat(parser.parse(new Tokenizer("A B C D")), is(nullValue()));
assertThat(parser.parse(new Tokenizer("C D")), is(nullValue()));
}
} |
package openmods.geometry;
import com.google.common.collect.Lists;
import java.util.Optional;
import javax.vecmath.Vector3f;
import net.minecraft.util.EnumFacing;
import org.junit.Assert;
import org.junit.Test;
public class FaceClassifierTest {
private static void test(FaceClassifier classifier, EnumFacing result, float x, float y, float z) {
Vector3f v = new Vector3f(x, y, z);
v.normalize();
Assert.assertEquals(Optional.of(result), classifier.classify(v));
}
private static void test(FaceClassifier classifier, float x, float y, float z) {
Vector3f v = new Vector3f(x, y, z);
v.normalize();
Assert.assertEquals(Optional.empty(), classifier.classify(v));
}
@Test
public void testSingleDirection() {
final FaceClassifier cut = new FaceClassifier(Lists.newArrayList(EnumFacing.NORTH));
test(cut, EnumFacing.NORTH, 0, 0, -1);
test(cut, EnumFacing.NORTH, 0, -1, -1);
test(cut, EnumFacing.NORTH, 0, +1, -1);
test(cut, EnumFacing.NORTH, -1, 0, -1);
test(cut, EnumFacing.NORTH, +1, 0, -1);
test(cut, EnumFacing.NORTH, +1, +1, -1);
test(cut, EnumFacing.NORTH, +1, -1, -1);
test(cut, EnumFacing.NORTH, -1, +1, -1);
test(cut, EnumFacing.NORTH, -1, -1, -1);
test(cut, EnumFacing.NORTH, 0, 0, Math.nextUp(-1));
// test(cut, EnumFacing.NORTH, 0, 0, Math.nextDown(-1)); // since Java 1.8
test(cut, EnumFacing.NORTH, 0, 0, Float.intBitsToFloat(Float.floatToRawIntBits(-1) + 1));
test(cut, EnumFacing.NORTH, 0, 5, -1);
test(cut, 0, 0, +1);
test(cut, EnumFacing.NORTH, 0, -1, -Float.MIN_VALUE);
test(cut, 0, -1, 0);
test(cut, 0, -1, +Float.MIN_VALUE);
test(cut, EnumFacing.NORTH, 0, +1, -Float.MIN_VALUE);
test(cut, 0, +1, 0);
test(cut, 0, +1, +Float.MIN_VALUE);
test(cut, -1, 0, 0);
test(cut, +1, 0, 0);
}
@Test
public void testNeigboringDirections() {
final FaceClassifier cut = new FaceClassifier(Lists.newArrayList(EnumFacing.NORTH, EnumFacing.WEST));
test(cut, EnumFacing.NORTH, 0, 0, -1);
test(cut, EnumFacing.WEST, -1, 0, 0);
test(cut, EnumFacing.NORTH, -2, 0, -1);
test(cut, EnumFacing.NORTH, 2, 0, -1);
test(cut, EnumFacing.NORTH, -1, 0, -1);
test(cut, EnumFacing.NORTH, -1, 0.5f, -1);
test(cut, 0, 0, +1);
test(cut, +1, 0, 0);
test(cut, 0, +1, 0);
test(cut, 0, -1, 0);
}
@Test
public void testNeigboringDirectionsSwitchedOrder() {
final FaceClassifier cut = new FaceClassifier(Lists.newArrayList(EnumFacing.WEST, EnumFacing.NORTH));
test(cut, EnumFacing.NORTH, 0, 0, -1);
test(cut, EnumFacing.WEST, -1, 0, 0);
test(cut, EnumFacing.WEST, -2, 0, -1);
test(cut, EnumFacing.NORTH, 2, 0, -1);
test(cut, EnumFacing.WEST, -1, 0, -1);
test(cut, EnumFacing.WEST, -1, 0.5f, -1);
test(cut, 0, 0, +1);
test(cut, +1, 0, 0);
test(cut, 0, +1, 0);
test(cut, 0, -1, 0);
}
@Test
public void testOppositeDirections() {
final FaceClassifier cut = new FaceClassifier(Lists.newArrayList(EnumFacing.NORTH, EnumFacing.SOUTH));
test(cut, EnumFacing.NORTH, 0, 0, -1);
test(cut, EnumFacing.SOUTH, 0, 0, +1);
test(cut, +1, 0, 0);
test(cut, -1, 0, 0);
test(cut, 0, +1, 0);
test(cut, 0, -1, 0);
}
} |
package org.takes.rq;
import com.google.common.base.Joiner;
import java.io.IOException;
import java.util.Collections;
import org.hamcrest.MatcherAssert;
import org.hamcrest.Matchers;
import org.junit.Test;
/**
* Test case for {@link RqWithDefaultHeader}.
* @author Andrey Eliseev (aeg.exper0@gmail.com)
* @version $Id$
* @since 0.31
*/
public final class RqWithDefaultHeaderTest {
/**
* Carriage return constant.
*/
private static final String CRLF = "\r\n";
/**
* RqWithDefaultHeader can provide default header value.
* @throws IOException If some problem inside
*/
@Test
public void providesDefaultHeader() throws IOException {
final String req = "GET /";
MatcherAssert.assertThat(
new RqPrint(
new RqWithDefaultHeader(
new RqFake(Collections.singletonList(req), "body"),
"X-Default-Header1",
"X-Default-Value1"
)
).print(),
Matchers.startsWith(
Joiner.on(RqWithDefaultHeaderTest.CRLF).join(
req,
"X-Default-Header1: X-Default-Value"
)
)
);
}
/**
* RqWithDefaultHeader can override default value.
* @throws IOException If some problem inside
*/
@Test
public void allowsOverrideDefaultHeader() throws IOException {
final String req = "POST /";
final String header = "X-Default-Header2";
MatcherAssert.assertThat(
new RqPrint(
new RqWithDefaultHeader(
new RqWithHeader(
new RqFake(Collections.singletonList(req), "body2"),
header,
"Non-Default-Value2"
),
header,
"X-Default-Value"
)
).print(),
Matchers.startsWith(
Joiner.on(RqWithDefaultHeaderTest.CRLF).join(
req,
"X-Default-Header2: Non-Default-Value"
)
)
);
}
} |
package seedu.address.logic;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static seedu.address.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import static seedu.address.commons.core.Messages.MESSAGE_INVALID_TASK_DISPLAYED_INDEX;
import static seedu.address.commons.core.Messages.MESSAGE_UNKNOWN_COMMAND;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import com.google.common.eventbus.Subscribe;
import seedu.address.commons.core.EventsCenter;
import seedu.address.commons.events.model.TaskListChangedEvent;
import seedu.address.commons.events.ui.JumpToListRequestEvent;
import seedu.address.commons.events.ui.ShowHelpRequestEvent;
import seedu.address.logic.commands.AddCommand;
import seedu.address.logic.commands.ClearCommand;
import seedu.address.logic.commands.Command;
import seedu.address.logic.commands.CommandResult;
import seedu.address.logic.commands.DeleteCommand;
import seedu.address.logic.commands.ExitCommand;
import seedu.address.logic.commands.FindCommand;
import seedu.address.logic.commands.HelpCommand;
import seedu.address.logic.commands.ListCommand;
import seedu.address.logic.commands.SelectCommand;
import seedu.address.logic.commands.exceptions.CommandException;
import seedu.address.logic.parser.ParserUtil;
import seedu.address.model.Model;
import seedu.address.model.ModelManager;
import seedu.address.model.ReadOnlyTaskList;
import seedu.address.model.TaskList;
import seedu.address.model.tag.Tag;
import seedu.address.model.tag.UniqueTagList;
import seedu.address.model.task.Deadline;
import seedu.address.model.task.Name;
import seedu.address.model.task.ReadOnlyTask;
import seedu.address.model.task.StartEndDateTime;
import seedu.address.model.task.Task;
import seedu.address.storage.StorageManager;
public class LogicManagerTest {
@Rule
public TemporaryFolder saveFolder = new TemporaryFolder();
private Model model;
private Logic logic;
//These are for checking the correctness of the events raised
private ReadOnlyTaskList latestSavedTaskList;
private boolean helpShown;
private int targetedJumpIndex;
@Subscribe
private void handleLocalModelChangedEvent(TaskListChangedEvent abce) {
latestSavedTaskList = new TaskList(abce.data);
}
@Subscribe
private void handleShowHelpRequestEvent(ShowHelpRequestEvent she) {
helpShown = true;
}
@Subscribe
private void handleJumpToListRequestEvent(JumpToListRequestEvent je) {
targetedJumpIndex = je.targetIndex;
}
@Before
public void setUp() {
model = new ModelManager();
String tempTaskListFile = saveFolder.getRoot().getPath() + "TempTaskList.xml";
String tempPreferencesFile = saveFolder.getRoot().getPath() + "TempPreferences.json";
logic = new LogicManager(model, new StorageManager(tempTaskListFile, tempPreferencesFile));
EventsCenter.getInstance().registerHandler(this);
latestSavedTaskList = new TaskList(model.getTaskList()); // last saved assumed to be up to date
helpShown = false;
targetedJumpIndex = -1; // non yet
}
@After
public void tearDown() {
EventsCenter.clearSubscribers();
}
@Test
public void execute_invalid() {
String invalidCommand = " ";
assertCommandFailure(invalidCommand, String.format(MESSAGE_INVALID_COMMAND_FORMAT, HelpCommand.MESSAGE_USAGE));
}
/**
* Executes the command, confirms that a CommandException is not thrown and that the result message is correct.
* Also confirms that both the 'task list' and the 'last shown list' are as specified.
* @see #assertCommandBehavior(boolean, String, String, ReadOnlyTaskList, List)
*/
private void assertCommandSuccess(String inputCommand, String expectedMessage,
ReadOnlyTaskList expectedTaskList,
List<? extends ReadOnlyTask> expectedShownList) {
assertCommandBehavior(false, inputCommand, expectedMessage, expectedTaskList, expectedShownList);
}
/**
* Executes the command, confirms that a CommandException is thrown and that the result message is correct.
* Both the 'task list' and the 'last shown list' are verified to be unchanged.
* @see #assertCommandBehavior(boolean, String, String, ReadOnlyTaskList, List)
*/
private void assertCommandFailure(String inputCommand, String expectedMessage) {
TaskList expectedTaskList = new TaskList(model.getTaskList());
List<ReadOnlyTask> expectedShownList = new ArrayList<>(model.getFilteredTaskList());
assertCommandBehavior(true, inputCommand, expectedMessage, expectedTaskList, expectedShownList);
}
/**
* Executes the command, confirms that the result message is correct
* and that a CommandException is thrown if expected
* and also confirms that the following three parts of the LogicManager object's state are as expected:<br>
* - the internal task list data are same as those in the {@code expectedTaskList} <br>
* - the backing list shown by UI matches the {@code shownList} <br>
* - {@code expectedAddressBook} was saved to the storage file. <br>
*/
private void assertCommandBehavior(boolean isCommandExceptionExpected, String inputCommand, String expectedMessage,
ReadOnlyTaskList expectedTaskList,
List<? extends ReadOnlyTask> expectedShownList) {
try {
CommandResult result = logic.execute(inputCommand);
assertFalse("CommandException expected but was not thrown.", isCommandExceptionExpected);
assertEquals(expectedMessage, result.feedbackToUser);
} catch (CommandException e) {
assertTrue("CommandException not expected but was thrown.", isCommandExceptionExpected);
assertEquals(expectedMessage, e.getMessage());
}
//Confirm the ui display elements should contain the right data
assertEquals(expectedShownList, model.getFilteredTaskList());
//Confirm the state of data (saved and in-memory) is as expected
assertEquals(expectedTaskList, model.getTaskList());
assertEquals(expectedTaskList, latestSavedTaskList);
}
@Test
public void execute_unknownCommandWord() {
String unknownCommand = "uicfhmowqewca";
assertCommandFailure(unknownCommand, MESSAGE_UNKNOWN_COMMAND);
}
@Test
public void execute_help() {
assertCommandSuccess("help", HelpCommand.SHOWING_HELP_MESSAGE, new TaskList(), Collections.emptyList());
assertTrue(helpShown);
}
@Test
public void execute_exit() {
assertCommandSuccess("exit", ExitCommand.MESSAGE_EXIT_ACKNOWLEDGEMENT,
new TaskList(), Collections.emptyList());
}
@Test
public void execute_clear() throws Exception {
TestDataHelper helper = new TestDataHelper();
model.addTask(helper.generateTask(1));
model.addTask(helper.generateTask(2));
model.addTask(helper.generateTask(3));
assertCommandSuccess("clear", ClearCommand.MESSAGE_SUCCESS, new TaskList(), Collections.emptyList());
}
@Test
public void execute_add_invalidArgsFormat() {
// TODO no way to have invalid arguments currently
// ArgumentTokenizer to understand, along with execute_add_invalidArgsFormat in LogicManagerTest why should fail
//String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddCommand.MESSAGE_USAGE);
//assertCommandFailure("add wrong args wrong args", expectedMessage);
//assertCommandFailure("add Valid Name 12345 e/valid@email.butNoPhonePrefix a/valid,address", expectedMessage);
//assertCommandFailure("add Valid Name p/12345 valid@email.butNoPrefix a/valid, address", expectedMessage);
// assertCommandFailure("add Valid Name p/12345 e/valid@email.butNoAddressPrefix valid,
// address", expectedMessage);
}
@Test
public void execute_add_invalidTaskData() {
assertCommandFailure("add []\\[;] p/12345 e/valid@e.mail a/valid, address",
Name.MESSAGE_NAME_CONSTRAINTS);
// TODO floating tasks don't have much to check at the moment
//assertCommandFailure("add Valid Name p/not_numbers e/valid@e.mail a/valid, address",
// Phone.MESSAGE_PHONE_CONSTRAINTS);
//assertCommandFailure("add Valid Name p/12345 e/notAnEmail a/valid, address",
// Email.MESSAGE_EMAIL_CONSTRAINTS);
assertCommandFailure("add Valid Name p/12345 e/valid@e.mail a/valid, address t/invalid_-[.tag",
Tag.MESSAGE_TAG_CONSTRAINTS); //TODO only fails because of _-[
}
@Test
public void execute_add_successful() throws Exception {
// setup expectations
TestDataHelper helper = new TestDataHelper();
Task toBeAdded = helper.accept();
TaskList expectedAB = new TaskList();
expectedAB.addTask(toBeAdded);
// execute command and verify result
assertCommandSuccess(helper.generateAddCommand(toBeAdded),
String.format(AddCommand.MESSAGE_SUCCESS, toBeAdded),
expectedAB,
expectedAB.getTaskList());
}
@Test
public void execute_addDuplicate_notAllowed() throws Exception {
// setup expectations
TestDataHelper helper = new TestDataHelper();
Task toBeAdded = helper.accept();
// setup starting state
model.addTask(toBeAdded); // task already in internal task list
// execute command and verify result
assertCommandFailure(helper.generateAddCommand(toBeAdded), AddCommand.MESSAGE_DUPLICATE_TASK);
}
@Test
public void execute_list_showsAllTasks() throws Exception {
// prepare expectations
TestDataHelper helper = new TestDataHelper();
TaskList expectedAB = helper.generateTaskList(2);
List<? extends ReadOnlyTask> expectedList = expectedAB.getTaskList();
// prepare address book state
helper.addToModel(model, 2);
assertCommandSuccess("list",
ListCommand.MESSAGE_SUCCESS,
expectedAB,
expectedList);
}
/**
* Confirms the 'invalid argument index number behaviour' for the given command
* targeting a single task in the shown list, using visible index.
* @param commandWord to test assuming it targets a single task in the last shown list
* based on visible index.
*/
private void assertIncorrectIndexFormatBehaviorForCommand(String commandWord, String expectedMessage)
throws Exception {
assertCommandFailure(commandWord , expectedMessage); //index missing
assertCommandFailure(commandWord + " +1", expectedMessage); //index should be unsigned
assertCommandFailure(commandWord + " -1", expectedMessage); //index should be unsigned
assertCommandFailure(commandWord + " 0", expectedMessage); //index cannot be 0
assertCommandFailure(commandWord + " not_a_number", expectedMessage);
}
/**
* Confirms the 'invalid argument index number behaviour' for the given command
* targeting a single task in the shown list, using visible index.
* @param commandWord to test assuming it targets a single task in the last shown list
* based on visible index.
*/
private void assertIndexNotFoundBehaviorForCommand(String commandWord) throws Exception {
String expectedMessage = MESSAGE_INVALID_TASK_DISPLAYED_INDEX;
TestDataHelper helper = new TestDataHelper();
List<Task> tasks = helper.generateTasks(2);
// set AB state to 2 tasks
model.resetData(new TaskList());
for (Task task : tasks) {
model.addTask(task);
}
assertCommandFailure(commandWord + " 3", expectedMessage);
}
@Test
public void execute_selectInvalidArgsFormat_errorMessageShown() throws Exception {
String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, SelectCommand.MESSAGE_USAGE);
assertIncorrectIndexFormatBehaviorForCommand("select", expectedMessage);
}
@Test
public void execute_selectIndexNotFound_errorMessageShown() throws Exception {
assertIndexNotFoundBehaviorForCommand("select");
}
@Test
public void execute_select_jumpsToCorrectTask() throws Exception {
TestDataHelper helper = new TestDataHelper();
List<Task> threeTasks = helper.generateTasks(3);
TaskList expectedAB = helper.generateTaskList(threeTasks);
helper.addToModel(model, threeTasks);
assertCommandSuccess("select 2",
String.format(SelectCommand.MESSAGE_SELECT_PERSON_SUCCESS, 2), // TODO
expectedAB,
expectedAB.getTaskList());
assertEquals(1, targetedJumpIndex);
assertEquals(model.getFilteredTaskList().get(1), threeTasks.get(1));
}
@Test
public void execute_deleteInvalidArgsFormat_errorMessageShown() throws Exception {
String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, DeleteCommand.MESSAGE_USAGE);
assertIncorrectIndexFormatBehaviorForCommand("delete", expectedMessage);
}
@Test
public void execute_deleteIndexNotFound_errorMessageShown() throws Exception {
assertIndexNotFoundBehaviorForCommand("delete");
}
@Test
public void execute_delete_removesCorrectTask() throws Exception {
TestDataHelper helper = new TestDataHelper();
List<Task> threeTasks = helper.generateTasks(3);
TaskList expectedAB = helper.generateTaskList(threeTasks);
expectedAB.removeTask(threeTasks.get(1));
helper.addToModel(model, threeTasks);
assertCommandSuccess("delete 2",
String.format(DeleteCommand.MESSAGE_DELETE_TASK_SUCCESS, threeTasks.get(1)),
expectedAB,
expectedAB.getTaskList());
}
@Test
public void execute_find_invalidArgsFormat() {
String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, FindCommand.MESSAGE_USAGE);
assertCommandFailure("find ", expectedMessage);
}
@Test
public void execute_find_onlyMatchesFullWordsInNames() throws Exception {
TestDataHelper helper = new TestDataHelper();
Task taskTarget1 = helper.generateTaskWithName("bla bla KEY bla");
Task taskTarget2 = helper.generateTaskWithName("bla KEY bla bceofeia");
Task task1 = helper.generateTaskWithName("KE Y");
Task task2 = helper.generateTaskWithName("KEYKEYKEY sduauo");
List<Task> fourTasks = helper.generateTasks(task1, taskTarget1, task2, taskTarget2);
TaskList expectedAB = helper.generateTaskList(fourTasks);
List<Task> expectedList = helper.generateTasks(taskTarget1, taskTarget2);
helper.addToModel(model, fourTasks);
assertCommandSuccess("find KEY",
Command.getMessageForPersonListShownSummary(expectedList.size()), // TODO
expectedAB,
expectedList);
}
@Test
public void execute_find_isNotCaseSensitive() throws Exception {
TestDataHelper helper = new TestDataHelper();
Task task1 = helper.generateTaskWithName("bla bla KEY bla");
Task task2 = helper.generateTaskWithName("bla KEY bla bceofeia");
Task task3 = helper.generateTaskWithName("key key");
Task task4 = helper.generateTaskWithName("KEy sduauo");
List<Task> fourTasks = helper.generateTasks(task3, task1, task4, task2);
TaskList expectedAB = helper.generateTaskList(fourTasks);
List<Task> expectedList = fourTasks;
helper.addToModel(model, fourTasks);
assertCommandSuccess("find KEY",
Command.getMessageForPersonListShownSummary(expectedList.size()),
expectedAB,
expectedList);
}
@Test
public void execute_find_matchesIfAnyKeywordPresent() throws Exception {
TestDataHelper helper = new TestDataHelper();
Task taskTarget1 = helper.generateTaskWithName("bla bla KEY bla");
Task taskTarget2 = helper.generateTaskWithName("bla rAnDoM bla bceofeia");
Task taskTarget3 = helper.generateTaskWithName("key key");
Task task1 = helper.generateTaskWithName("sduauo");
List<Task> fourTasks = helper.generateTasks(taskTarget1, task1, taskTarget2, taskTarget3);
TaskList expectedAB = helper.generateTaskList(fourTasks);
List<Task> expectedList = helper.generateTasks(taskTarget1, taskTarget2, taskTarget3);
helper.addToModel(model, fourTasks);
assertCommandSuccess("find key rAnDoM",
Command.getMessageForPersonListShownSummary(expectedList.size()),
expectedAB,
expectedList);
}
/**
* A utility class to generate test data.
*/
class TestDataHelper {
//@@author A0140023E
// TODO should this be done in another way?
// Starting Test Date Time is set to one day after today so that we would not generate dates in the past
// otherwise a PastDateTimeException might be generated
private ZonedDateTime startTestDateTime = ZonedDateTime.now().plusDays(1);
Task accept() throws Exception {
Name name = new Name("Accept Changes");
Tag tag1 = new Tag("tag1");
Tag tag2 = new Tag("longertag2");
UniqueTagList tags = new UniqueTagList(tag1, tag2);
// TODO improve maybe not to use just Optionals
return new Task(name, Optional.empty(), Optional.empty(), tags);
}
/**
* Generates a valid task using the given seed.
* Running this function with the same parameter values guarantees the returned task will have the same state.
* Each unique seed will generate a unique task object.
*
* @param seed used to generate the task data field values
*/
Task generateTask(int seed) throws Exception {
// note to change
return new Task(
new Name("Task" + seed),
Optional.of(new Deadline(startTestDateTime.plusDays(seed))),
Optional.of(new StartEndDateTime(startTestDateTime.plusDays(seed + 1),
startTestDateTime.plusDays(seed + 2))),
new UniqueTagList(new Tag("tag" + Math.abs(seed)), new Tag("tag" + Math.abs(seed + 1)))
);
}
/** Generates the correct add command based on the task given */
String generateAddCommand(Task task) {
StringBuffer cmd = new StringBuffer();
cmd.append("add ");
cmd.append(task.getName().toString());
if (task.getDeadline().isPresent()) {
cmd.append(" by ");
// TODO double check
cmd.append(task.getDeadline().get().getValue().format(ParserUtil.DATE_TIME_FORMAT));
}
if (task.getStartEndDateTime().isPresent()) {
// TODO double check
StartEndDateTime startEndDateTime = task.getStartEndDateTime().get();
cmd.append(" from ");
cmd.append(startEndDateTime.getStartDateTime().format(ParserUtil.DATE_TIME_FORMAT));
cmd.append(" to ");
cmd.append(startEndDateTime.getEndDateTime().format(ParserUtil.DATE_TIME_FORMAT));
}
UniqueTagList tags = task.getTags();
for (Tag t: tags) {
cmd.append(" t/").append(t.tagName);
}
return cmd.toString();
}
//@@author
/**
* Generates a TaskList with auto-generated tasks.
*/
TaskList generateTaskList(int numGenerated) throws Exception {
TaskList taskList = new TaskList();
addToTaskList(taskList, numGenerated);
return taskList;
}
/**
* Generates a TaskList based on the list of Tasks given.
*/
TaskList generateTaskList(List<Task> tasks) throws Exception {
TaskList taskList = new TaskList();
addToTaskList(taskList, tasks);
return taskList;
}
/**
* Adds auto-generated Task objects to the given TaskList
* @param taskList The TaskList to which the tasks will be added
*/
void addToTaskList(TaskList taskList, int numGenerated) throws Exception {
addToTaskList(taskList, generateTasks(numGenerated));
}
/**
* Adds the given list of Tasks to the given TaskList
*/
void addToTaskList(TaskList taskList, List<Task> tasksToAdd) throws Exception {
for (Task task: tasksToAdd) {
taskList.addTask(task);
}
}
/**
* Adds auto-generated Task objects to the given model
* @param model The model to which the Tasks will be added
*/
void addToModel(Model model, int numGenerated) throws Exception {
addToModel(model, generateTasks(numGenerated));
}
/**
* Adds the given list of Tasks to the given model
*/
void addToModel(Model model, List<Task> tasksToAdd) throws Exception {
for (Task task: tasksToAdd) {
model.addTask(task);
}
}
/**
* Generates a list of Tasks based on the flags.
*/
List<Task> generateTasks(int numGenerated) throws Exception {
List<Task> tasks = new ArrayList<>(); // TODO TaskList not a good name for AddressBook replacement
for (int i = 1; i <= numGenerated; i++) {
tasks.add(generateTask(i));
}
return tasks;
}
List<Task> generateTasks(Task... taskss) {
return Arrays.asList(taskss);
}
//@@author A0140023E
/**
* Generates a Task object with given name. Other fields will have some dummy values.
*/
Task generateTaskWithName(String name) throws Exception {
// Note that we are generating tasks with a StartEndDateTime as that would be more complex
// than a task with Deadline or a Task with no Deadline and StartEndDateTime, thus more likely to fail
return new Task(
new Name(name),
Optional.empty(),
Optional.of(new StartEndDateTime(startTestDateTime.plusDays(3), startTestDateTime.plusDays(6))),
new UniqueTagList(new Tag("tag"))
);
}
}
} |
package dr.app.tools;
import dr.app.beast.BeastVersion;
import dr.app.util.Arguments;
import dr.evolution.io.*;
import dr.evolution.tree.*;
import dr.evolution.util.Taxon;
import dr.util.Version;
import java.io.*;
import java.util.*;
/**
* @author Philippe Lemey
* @author Marc Suchard
*/
public class TaxaMarkovJumpHistoryAnalyzer {
private final static Version version = new BeastVersion();
// Messages to stderr, output to stdout
private static PrintStream progressStream = System.err;
public static final String HISTORY = "history";
public static final String BURNIN = "burnin";
private TaxaMarkovJumpHistoryAnalyzer(String inputFileName,
String outputFileName,
String[] taxaToProcess,
String endState, // if no end state is provided, we will need to go to the root.
String stateAnnotationName,
double mrsd,
int burnin
) throws IOException {
List<Tree> trees = new ArrayList<>();
readTrees(trees, inputFileName, burnin);
List<Taxon> taxa = getTaxaToProcess(trees.get(0), taxaToProcess);
historyStrings = new String[totalUsedTrees*taxa.size()];
this.mrsd = mrsd;
this.stateAnnotationName = stateAnnotationName;
processTrees(trees, taxa, endState, burnin);
writeOutputFile(outputFileName);
}
private void readTrees(List<Tree> trees, String inputFileName, int burnin) throws IOException {
progressStream.println("Reading trees (bar assumes 10,000 trees)...");
progressStream.println("0 25 50 75 100");
progressStream.println("|
long stepSize = 10000 / 60;
FileReader fileReader = new FileReader(inputFileName);
TreeImporter importer = new NexusImporter(fileReader, false);
try {
totalTrees = 0;
while (importer.hasTree()) {
Tree tree = importer.importNextTree();
if (trees == null) {
trees = new ArrayList<>();
}
trees.add(tree);
if (totalTrees > 0 && totalTrees % stepSize == 0) {
progressStream.print("*");
progressStream.flush();
}
totalTrees++;
if (totalTrees > burnin){
totalUsedTrees++;
}
}
} catch (Importer.ImportException e) {
System.err.println("Error Parsing Input Tree: " + e.getMessage());
return;
}
fileReader.close();
progressStream.println();
progressStream.println();
if (totalTrees < 1) {
System.err.println("No trees");
return;
}
if (totalUsedTrees < 1) {
System.err.println("No trees past burnin (="+burnin+")");
return;
}
progressStream.println("Total trees read: " + totalTrees);
progressStream.println("Total trees used: " + totalUsedTrees);
}
private List<Taxon> getTaxaToProcess(Tree tree, String[] taxaToProcess) {
List<Taxon> taxa = new ArrayList<>();
if (taxaToProcess != null) {
for (String name : taxaToProcess) {
int taxonId = tree.getTaxonIndex(name);
if (taxonId == -1) {
throw new RuntimeException("Unable to find taxon '" + name + "'.");
}
taxa.add(tree.getTaxon(taxonId));
}
}
return taxa;
}
private void processTrees(List<Tree> trees, List<Taxon> taxa, String endState, int burnin) {
if (burnin < 0){
burnin = 0;
}
for (int i = burnin; i <trees.size(); ++i) {
Tree tree = trees.get(i);
processOneTree(tree, taxa, endState, i-burnin);
}
}
private void processOneTree(Tree tree, List<Taxon> taxa, String endState, int treeNumber) {
int counter = 0;
for (Taxon taxon : taxa) {
// System.out.println(counter);
// System.out.println(taxon.getId());
processOneTreeForOneTaxon(tree, taxon, endState, treeNumber, treeNumber+(totalUsedTrees*counter));
counter++;
}
}
private void processOneTreeForOneTaxon(Tree tree, Taxon taxon, String endState, int treeNumber, int lineNumber) {
for (int i = 0; i < tree.getExternalNodeCount(); ++i) {
NodeRef tip = tree.getExternalNode(i);
if (tree.getNodeTaxon(tip) == taxon) {
sb.append(taxon.getId()+",");
sb.append((treeNumber+1)+",");
processOneTip(tree, tip, endState, lineNumber);
}
}
}
private void processOneTip(Tree tree, NodeRef tip, String endState, int lineNumber) {
String currentState = (String)tree.getNodeAttribute(tip,stateAnnotationName);
if (currentState==null){
System.err.println("no "+stateAnnotationName+" annotation for tip");
System.exit(-1);
}
sb.append(currentState+",");
double nodeTime = tree.getNodeHeight(tip);
if (mrsd < Double.MAX_VALUE){
nodeTime = mrsd - nodeTime;
}
sb.append(nodeTime);
while (tip != tree.getRoot()){
Object[] jumps = readCJH(tip, tree);
if (jumps != null){
for (int i = jumps.length-1; i>=0; i
Object[] jump = (Object[])jumps[i];
if (!currentState.equalsIgnoreCase((String)jump[2])){
System.err.println(jump[1]+"\t"+jump[2]);
System.err.println("mismatch between states in Markov Jump History");
System.exit(-1);
}
sb.append(",");
currentState = ((String)jump[1]);
sb.append(currentState+",");
double jumpTime = (Double)jump[0];
if (mrsd < Double.MAX_VALUE){
jumpTime = mrsd - jumpTime;
}
sb.append(jumpTime);
}
}
tip = tree.getParent(tip);
if ((endState!=null) && (currentState.equalsIgnoreCase(endState))){
break;
}
}
// System.out.println(sb.toString());
historyStrings[lineNumber] = sb.toString();
sb.setLength(0);
}
private static Object[] readCJH(NodeRef node, Tree treeTime){
if(treeTime.getNodeAttribute(node, HISTORY)!=null){
Object[] cjh = (Object[])treeTime.getNodeAttribute(node, HISTORY);
return cjh;
} else {
return null;
}
}
private void writeOutputFile(String outputFileName) {
PrintStream ps = null;
if (outputFileName == null) {
ps = progressStream;
} else {
try {
ps = new PrintStream(new File(outputFileName));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
ps.println("#each trajectory starts with the tip name, the tree number its state, its height, and then the subsequent states adopted and their transition times up to either the root state or a pre-defined state");
for (String historyString : historyStrings) {
ps.println(historyString);
}
if (ps != null) {
ps.close();
}
}
int totalTrees = 0;
int totalUsedTrees = 0;
StringBuffer sb = new StringBuffer();
String[] historyStrings;
double mrsd;
String stateAnnotationName;
public static void printTitle() {
progressStream.println();
centreLine("TaxonMarkovJumpHistory " + version.getVersionString() + ", " + version.getDateString(), 60);
centreLine("tool to get a Markov Jump History for a Taxon", 60);
centreLine("by", 60);
centreLine("Philippe Lemey and Marc Suchard", 60);
progressStream.println();
progressStream.println();
}
public static void centreLine(String line, int pageWidth) {
int n = pageWidth - line.length();
int n1 = n / 2;
for (int i = 0; i < n1; i++) {
progressStream.print(" ");
}
progressStream.println(line);
}
public static void printUsage(Arguments arguments) {
arguments.printUsage("TaxonMarkovJumpHistory", "<input-file-name> [<output-file-name>]");
progressStream.println();
progressStream.println(" Example: taxonMarkovJumpHistory -taxaToProcess taxon1,taxon2 input.trees output.trees");
progressStream.println();
}
//Main method
public static void main(String[] args) throws IOException {
String inputFileName = null;
String outputFileName = null;
String[] taxaToProcess = null;
String endState = null;
String stateAnnotationName = "location";
double mrsd = Double.MAX_VALUE;
int burnin = -1;
printTitle();
Arguments arguments = new Arguments(
new Arguments.Option[]{
new Arguments.IntegerOption(BURNIN, "the number of states to be considered as 'burn-in' [default = 0]"),
new Arguments.StringOption("taxaToProcess", "list","a list of taxon names to process MJHs"),
new Arguments.StringOption("endState", "end_state","a state at which the MJH processing stops"),
new Arguments.StringOption("stateAnnotation", "state_annotation_name","The annotation name for the discrete state string"),
new Arguments.RealOption("mrsd", "The most recent sampling time to convert heights to times [default=MAX_VALUE]"),
new Arguments.Option("help", "option to print this message"),
});
try {
arguments.parseArguments(args);
} catch (Arguments.ArgumentException ae) {
progressStream.println(ae);
printUsage(arguments);
System.exit(1);
}
if (arguments.hasOption("help")) {
printUsage(arguments);
System.exit(0);
}
if (arguments.hasOption("taxaToProcess")) {
taxaToProcess = Branch2dRateToGrid.parseVariableLengthStringArray(arguments.getStringOption("taxaToProcess"));
}
if (arguments.hasOption("endState")) {
endState = arguments.getStringOption("endState");
}
if (arguments.hasOption("stateAnnotation")) {
stateAnnotationName = arguments.getStringOption("stateAnnotation");
}
if (arguments.hasOption("mrsd")) {
mrsd = arguments.getRealOption("mrsd");
}
if (arguments.hasOption(BURNIN)) {
burnin = arguments.getIntegerOption(BURNIN);
System.err.println("Ignoring a burnin of " + burnin + " trees.");
}
final String[] args2 = arguments.getLeftoverArguments();
switch (args2.length) {
case 2:
outputFileName = args2[1];
// fall to
case 1:
inputFileName = args2[0];
break;
default: {
System.err.println("Unknown option: " + args2[2]);
System.err.println();
printUsage(arguments);
System.exit(1);
}
}
new TaxaMarkovJumpHistoryAnalyzer(inputFileName, outputFileName, taxaToProcess, endState, stateAnnotationName, mrsd, burnin);
System.exit(0);
}
} |
package dr.inference.operators.hmc;
import dr.inference.hmc.GradientWrtParameterProvider;
import dr.inference.model.Likelihood;
import dr.inference.model.Parameter;
import dr.inference.operators.CoercionMode;
import dr.inference.operators.GeneralOperator;
import dr.inference.operators.GibbsOperator;
import dr.math.MathUtils;
import dr.util.Transform;
import java.util.Arrays;
/**
* @author Marc A. Suchard
* @author Zhenyu Zhang
*/
public class NoUTurnOperator extends HamiltonianMonteCarloOperator implements GeneralOperator, GibbsOperator {
private final int dim = gradientProvider.getDimension();
private class Options { //TODO: these values might be adjusted for dual averaging.
private double kappa = 0.75;
private double t0 = 10.0;
private double gamma = 0.05;
private double delta = 0.2;
private double deltaMax = 1000.0;
private double muFactor = 10.0;
private int findMax = 100;
private int maxDepth = 100;
private int adaptLength = 1000;
}
// TODO Magic numbers; pass as options
private final Options options = new Options();
public NoUTurnOperator(CoercionMode mode, double weight, GradientWrtParameterProvider gradientProvider,
Parameter parameter, Transform transform, double stepSize, int nSteps, double drawVariance) {
super(mode, weight, gradientProvider, parameter, transform, stepSize, nSteps, drawVariance);
}
private class StepSize {
final double initialStepSize;
double stepSize;
double logStepSize;
double averageLogStepSize;
double h;
double mu;
private StepSize(double initialStepSize) {
this.initialStepSize = initialStepSize;
this.stepSize = initialStepSize;
this.logStepSize = Math.log(stepSize);
this.averageLogStepSize = 0;
this.h = 0;
this.mu = Math.log(options.muFactor * initialStepSize);
}
private void update(long m, double alpha, double nAlpha, Options options) {
if (m <= options.adaptLength) {
h = (1 - 1 / (m + options.t0)) * h + 1 / (m + options.t0) * (options.delta - (alpha / nAlpha));
logStepSize = mu - Math.sqrt(m) / options.gamma * h;
averageLogStepSize = Math.pow(m, -options.kappa) * logStepSize +
(1 - Math.pow(m, -options.kappa)) * averageLogStepSize;
stepSize = Math.exp(logStepSize);
}
// stepSize = 0.05; //todo: use to hand tune the stepsize.
//stepSize = tempStepsize * (MathUtils.nextDouble()*0.2 + 0.9);//todo: randomize the stepsize each iteration.
//System.err.println("m is " + m + " stepsize is " + stepSize);
}
}
private StepSize stepSizeInformation;
@Override
public String getOperatorName() {
return "No-UTurn-Sampler operator";
}
@Override
public double doOperation(Likelihood likelihood) {
final double[] initialPosition = leapFrogEngine.getInitialPosition();
final double initialLogLikelihood = gradientProvider.getLikelihood().getLogLikelihood();
if (stepSizeInformation == null) {
final double initialStepSize = findReasonableStepSize(initialPosition);
stepSizeInformation = new StepSize(initialStepSize);
final double testLogLikelihood = gradientProvider.getLikelihood().getLogLikelihood();
assert (testLogLikelihood == initialLogLikelihood);
}
double[] position = takeOneStep(getCount() + 1, initialPosition);
leapFrogEngine.setParameter(position);
return 0.0;
}
private double[] takeOneStep(long m, double[] initialPosition) {
double[] endPosition = Arrays.copyOf(initialPosition, initialPosition.length);
final double[] initialMomentum = drawInitialMomentum(drawDistribution, dim);
final double initialJointDensity = getJointProbability(gradientProvider, initialMomentum);
double logSliceU = Math.log(MathUtils.nextDouble()) + initialJointDensity;
TreeState root = new TreeState(initialPosition, initialMomentum, 1, true);
int j = 0;
while (root.flagContinue) {
double[] tmp = updateRoot(root, j, logSliceU, initialJointDensity);
if (tmp != null) {
endPosition = tmp;
}
j++;
if (j > options.maxDepth) {
throw new RuntimeException("Reach maximum tree depth"); // TODO Handle more gracefully
}
}
stepSizeInformation.update(m, root.alpha, root.nAlpha, options);
return endPosition;
}
private double[] updateRoot(TreeState root, int j, double logSliceU, double initialJointDensity) {
double[] endPosition = null;
final double uniform1 = MathUtils.nextDouble();
int direction = (uniform1 < 0.5) ? -1 : 1;
TreeState node = buildTree(root.getPosition(direction), root.getMomentum(direction), direction,
logSliceU, j, stepSizeInformation.stepSize, initialJointDensity);
root.setPosition(direction, node.getPosition(direction));
root.setMomentum(direction, node.getMomentum(direction));
if (node.flagContinue) {
final double uniform = MathUtils.nextDouble();
final double p = (double) node.numNodes / (double)root.numNodes;
if (uniform < p) {
endPosition = node.getPosition(0);
}
}
// Recursion
root.numNodes += node.numNodes;
root.flagContinue = computeStopCriterion(node.flagContinue, root);
// Dual-averaging
root.alpha += node.alpha;
root.nAlpha += node.nAlpha;
return endPosition;
}
private TreeState buildTree(double[] position, double[] momentum, int direction,
double logSliceU, int j, double stepSize, double initialJointDensity) {
if (j == 0) {
return buildBaseCase(position, momentum, direction, logSliceU, stepSize, initialJointDensity);
} else {
return buildRecursiveCase(position, momentum, direction, logSliceU, j, stepSize, initialJointDensity);
}
}
private TreeState buildBaseCase(double[] inPosition, double[] inMomentum, int direction,
double logSliceU, double stepSize, double initialJointDensity) {
// Make deep copy of position and momentum
double[] position = Arrays.copyOf(inPosition, inPosition.length);
double[] momentum = Arrays.copyOf(inMomentum, inMomentum.length);
leapFrogEngine.setParameter(position);
// "one frog jump!"
leapFrogEngine.updateMomentum(position, momentum, gradientProvider.getGradientLogDensity(), direction * stepSize / 2);
leapFrogEngine.updatePosition(position, momentum, direction * stepSize, 1.0);
leapFrogEngine.updateMomentum(position, momentum, gradientProvider.getGradientLogDensity(), direction * stepSize / 2);
double logJointProbAfter = getJointProbability(gradientProvider, momentum);
final int numNodes = (logSliceU <= logJointProbAfter ? 1 : 0);
final boolean flagContinue = (logSliceU < options.deltaMax + logJointProbAfter);
// Values for dual-averaging
final double alpha = Math.min(1.0, Math.exp(logJointProbAfter - initialJointDensity));
final int nAlpha = 1;
leapFrogEngine.setParameter(inPosition);
return new TreeState(position, momentum, numNodes, flagContinue, alpha, nAlpha);
}
private TreeState buildRecursiveCase(double[] inPosition, double[] inMomentum, int direction,
double logSliceU, int j, double stepSize, double initialJointDensity) {
TreeState node = buildTree(inPosition, inMomentum, direction, logSliceU,
j - 1, // Recursion
stepSize, initialJointDensity);
if (node.flagContinue) {
TreeState child = buildTree(node.getPosition(direction), node.getMomentum(direction), direction,
logSliceU, j - 1, stepSizeInformation.stepSize, initialJointDensity);
node.setPosition(direction, child.getPosition(direction));
node.setMomentum(direction, child.getMomentum(direction));
double uniform = MathUtils.nextDouble();
if (child.numNodes > 0
&& uniform < ((double) child.numNodes / (double) (node.numNodes + child.numNodes))) {
node.setPosition(0, child.getPosition(0));
}
node.numNodes += child.numNodes;
node.flagContinue = computeStopCriterion(child.flagContinue, node);
node.alpha += child.alpha;
node.nAlpha += child.nAlpha;
}
return node;
}
private double findReasonableStepSize(double[] position) {
double stepSize = 1;
double[] momentum = drawInitialMomentum(drawDistribution, dim);
int count = 1;
double[] initialPosition = Arrays.copyOf(position, dim);
double probBefore = getJointProbability(gradientProvider, momentum);
leapFrogEngine.updateMomentum(position, momentum, gradientProvider.getGradientLogDensity(), stepSize / 2);
leapFrogEngine.updatePosition(position, momentum, stepSize, 1.0);
leapFrogEngine.updateMomentum(position, momentum, gradientProvider.getGradientLogDensity(), stepSize / 2);
double probAfter = getJointProbability(gradientProvider, momentum);
double a = ((probAfter - probBefore) > Math.log(0.5) ? 1 : -1);
double probRatio = Math.exp(probAfter - probBefore);
while (Math.pow(probRatio, a) > Math.pow(2, -a)) {
probBefore = probAfter;
//"one frog jump!"
leapFrogEngine.updateMomentum(position, momentum, gradientProvider.getGradientLogDensity(), stepSize / 2);
leapFrogEngine.updatePosition(position, momentum, stepSize, 1.0); //zy: after "updateposition"
leapFrogEngine.updateMomentum(position, momentum, gradientProvider.getGradientLogDensity(), stepSize / 2);
probAfter = getJointProbability(gradientProvider, momentum);
probRatio = Math.exp(probAfter - probBefore);
stepSize = Math.pow(2, a) * stepSize;
count++;
if (count > options.findMax) {
throw new RuntimeException("Cannot find a reasonable stepsize in " + options.findMax + " iterations");
}
}
leapFrogEngine.setParameter(initialPosition);
return stepSize;
}
private static boolean computeStopCriterion(boolean flagContinue, TreeState state) {
return computeStopCriterion(flagContinue,
state.getPosition(1), state.getPosition(-1),
state.getMomentum(1), state.getMomentum(-1));
}
private static boolean computeStopCriterion(boolean flagContinue,
double[] positionPlus, double[] positionMinus,
double[] momentumPlus, double[] momentumMinus) {
double[] positionDifference = subtractArray(positionPlus, positionMinus);
return flagContinue &&
getDotProduct(positionDifference, momentumMinus) >= 0 &&
getDotProduct(positionDifference, momentumPlus) >= 0;
}
private static double getDotProduct(double[] x, double[] y) {
assert (x.length == y.length);
final int dim = x.length;
double total = 0.0;
for (int i = 0; i < dim; i++) {
total += x[i] * y[i];
}
return total;
}
private static double[] subtractArray(double[] a, double[] b) {
assert (a.length == b.length);
final int dim = a.length;
double result[] = new double[dim];
for (int i = 0; i < dim; i++) {
result[i] = a[i] - b[i];
}
return result;
}
private double getJointProbability(GradientWrtParameterProvider gradientProvider, double[] momentum) {
assert (gradientProvider != null);
assert (momentum != null);
return gradientProvider.getLikelihood().getLogLikelihood() - getScaledDotProduct(momentum, 1.0)
- leapFrogEngine.getParameterLogJacobian();
}
private class TreeState {
private TreeState(double[] position, double[] moment,
int numNodes, boolean flagContinue) {
this(position, moment, numNodes, flagContinue, 0.0, 0);
}
private TreeState(double[] position, double[] moment,
int numNodes, boolean flagContinue,
double alpha, int nAlpha) {
this.position = new double[3][];
this.momentum = new double[3][];
for (int i = 0; i < 3; ++i) {
this.position[i] = position;
this.momentum[i] = moment;
}
// Recursion variables
this.numNodes = numNodes;
this.flagContinue = flagContinue;
// Dual-averaging variables
this.alpha = alpha;
this.nAlpha = nAlpha;
}
private double[] getPosition(int direction) {
return position[getIndex(direction)];
}
private double[] getMomentum(int direction) {
return momentum[getIndex(direction)];
}
private void setPosition(int direction, double[] position) {
this.position[getIndex(direction)] = position;
}
private void setMomentum(int direction, double[] momentum) {
this.momentum[getIndex(direction)] = momentum;
}
private int getIndex(int direction) { // valid directions: -1, 0, +1
assert (direction >= -1 && direction <= 1);
return direction + 1;
}
final private double[][] position;
final private double[][] momentum;
private int numNodes;
private boolean flagContinue;
private double alpha;
private int nAlpha;
}
} |
package dr.inferencexml.hmc;
import dr.inference.distribution.DistributionLikelihood;
import dr.inference.distribution.MultivariateDistributionLikelihood;
import dr.inference.hmc.CompoundDerivative;
import dr.inference.hmc.CompoundGradient;
import dr.inference.hmc.GradientWrtParameterProvider;
import dr.inference.model.*;
import dr.xml.*;
import java.util.ArrayList;
import java.util.List;
/**
* @author Max Tolkoff
*/
public class CompoundGradientParser extends AbstractXMLObjectParser {
public final static String SUM_DERIVATIVE = "appendedPotentialDerivative";
public static final String SUM_DERIVATIVE2 = "compoundGradient";
@Override
public String getParserName() {
return SUM_DERIVATIVE;
}
@Override
public String[] getParserNames() {
return new String[]{SUM_DERIVATIVE, SUM_DERIVATIVE2};
}
@Override
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
List<GradientWrtParameterProvider> gradList = new ArrayList<GradientWrtParameterProvider>();
List<Likelihood> likelihoodList = new ArrayList<Likelihood>(); // TODO Remove?
for (int i = 0; i < xo.getChildCount(); ++i) {
Object obj = xo.getChild(i);
GradientWrtParameterProvider grad;
Likelihood likelihood;
if (obj instanceof DistributionLikelihood) {
DistributionLikelihood dl = (DistributionLikelihood) obj;
if (!(dl.getDistribution() instanceof GradientProvider)) {
throw new XMLParseException("Not a gradient provider");
}
throw new RuntimeException("Not yet implemented");
} else if (obj instanceof MultivariateDistributionLikelihood) {
final MultivariateDistributionLikelihood mdl = (MultivariateDistributionLikelihood) obj;
if (!(mdl.getDistribution() instanceof GradientProvider)) {
throw new XMLParseException("Not a gradient provider");
}
final GradientProvider provider = (GradientProvider) mdl.getDistribution();
final Parameter parameter = mdl.getDataParameter();
likelihood = mdl;
grad = new GradientWrtParameterProvider.ParameterWrapper(provider, parameter, mdl);
} else if (obj instanceof GradientWrtParameterProvider) {
grad = (GradientWrtParameterProvider) obj;
likelihood = grad.getLikelihood();
} else {
throw new XMLParseException("Not a Gaussian process");
}
gradList.add(grad);
likelihoodList.add(likelihood);
}
return new CompoundDerivative(gradList);
}
@Override
public XMLSyntaxRule[] getSyntaxRules() {
return rules;
}
private final XMLSyntaxRule[] rules = {
new ElementRule(GradientWrtParameterProvider.class, 1, Integer.MAX_VALUE),
};
@Override
public String getParserDescription() {
return null;
}
@Override
public Class getReturnType() {
return CompoundDerivative.class;
}
} |
package org.voltdb.licensetool;
import java.io.File;
import java.util.Calendar;
public interface LicenseApi {
public boolean initializeFromFile(File license);
public boolean isTrial();
public int maxHostcount();
public Calendar expires();
public boolean verify();
public boolean isWanReplicationAllowed();
public boolean isCommandLoggingAllowed();
} |
package org.aikodi.chameleon.oo.type;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import org.aikodi.chameleon.core.Config;
import org.aikodi.chameleon.core.declaration.Declaration;
import org.aikodi.chameleon.core.element.Element;
import org.aikodi.chameleon.core.lookup.DeclarationSelector;
import org.aikodi.chameleon.core.lookup.LookupException;
import org.aikodi.chameleon.core.lookup.SelectionResult;
import org.aikodi.chameleon.core.property.ChameleonProperty;
import org.aikodi.chameleon.exception.ChameleonProgrammerException;
import org.aikodi.chameleon.oo.language.ObjectOrientedLanguage;
import org.aikodi.chameleon.oo.member.Member;
import org.aikodi.chameleon.oo.type.generics.TypeParameter;
import org.aikodi.chameleon.util.Lists;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableList.Builder;
/**
*
* All non-static declarations of a lazy class body have their origin set to the corresponding
* declaration in the base type.
*
* @author Marko van Dooren
*/
public class LazyClassBody extends ClassBody {
public LazyClassBody(ClassBody original) {
setClassBody(original);
setOrigin(original);
}
private ClassBody _original;
public ClassBody original() {
return _original;
}
protected void setClassBody(ClassBody original) {
_original = original;
}
/**
* Return the declarations with the given name. The declarations are loaded lazily from the base type.
*/
@Override
protected List<Declaration> declarations(String selectionName) throws LookupException {
if(_initializedElements) {
return super.declarations(selectionName);
} else {
List<Declaration> result = cachedDeclarations(selectionName);
if(result == null) {
List<Declaration> declarationsFromBaseType = original().declarations(selectionName);
result = fetchMembers(selectionName, declarationsFromBaseType);
}
return result;
}
}
public List<Declaration> fetchMembers(String selectionName, List<Declaration> declarationsFromBaseType)
throws LookupException {
Builder<Declaration> builder = ImmutableList.builder();
List<Declaration> result = ImmutableList.of();
if(declarationsFromBaseType != null) {
// If the cache was empty, and the aliased body contains matches
// we clone the matches and store them in the cache.
// Use lazy initialization for the type parameters. We want to reuse the collection
// for different elements in declarationsFromBaseType, but we don't want to compute
// it unnecessarily when we don't need it, or compute it more than once if we do need it.
ObjectOrientedLanguage language = language(ObjectOrientedLanguage.class);
for(Declaration declarationFromBaseType: declarationsFromBaseType) {
Element parent = declarationFromBaseType.parent();
// Replace the references to the formal type parameters of base class with
// references to the actual type arguments of the derived type that is the parent of
// this lazy class body.
Declaration clone = null;
if(parent instanceof TypeElementStub) {
clone = caseElementFromStub(selectionName, declarationFromBaseType, (TypeElementStub) parent);
} else {
if(! declarationFromBaseType.isTrue(language.CLASS)) {
clone = clone(declarationFromBaseType);
super.add((TypeElement) clone); //FIX ME there should be a separate stub for type elements.
clone.setOrigin(declarationFromBaseType);
} else {
clone = declarationFromBaseType;
}
}
builder.add(clone);
}
result = builder.build();
storeCache(selectionName, result);
}
return result;
}
private Declaration caseElementFromStub(String selectionName, Declaration declarationFromBaseType, TypeElementStub stub) throws LookupException {
Declaration clone = null;
// 1. Clone the declaration
Declaration declClone = clone(declarationFromBaseType);
// 2. Substitute the type parameters with those of the surrounding DerivedType.
ObjectOrientedLanguage language = language(ObjectOrientedLanguage.class);
List<TypeParameter> typeParameters = original().nearestAncestor(Type.class).parameters(TypeParameter.class);
declClone.setUniParent(stub);
Iterator<TypeParameter> parameterIter = typeParameters.iterator();
while(parameterIter.hasNext()) {
TypeParameter par = parameterIter.next();
// Creating a new type reference with the same name will ensure that the name is
// resolved in the current context, and thus point to the corresponding type
// parameter in the surrounding DerivedType.
TypeReference tref = language.createTypeReference(par.name());
tref.setUniParent(this);
language.replace(tref, par, declClone, Declaration.class);
}
// 3. Find out who generated the stub
TypeElement generator = stub.generator();
// 4. Search for the clone of the generator and store it in newGenerator.
TypeElement newGenerator = null;
for(TypeElement element:super.elements()) {
if(element.origin().sameAs(generator)) {
newGenerator = element;
break;
}
}
// 5. If the generator had not yet been cloned before, we do it now.
if(newGenerator == null) {
newGenerator = clone(generator);
newGenerator.setOrigin(generator);
super.add(newGenerator);
}
// 6. Ask which members are introduced by the new (cloned) generator.
List<? extends Member> introducedByNewGenerator = newGenerator.getIntroducedMembers();
// 7. Search for the one with the same signature as the clone of the declaration (which is in the same context).
for(Member m: introducedByNewGenerator) {
if(m.name().equals(selectionName) && m.sameSignatureAs(declClone)) {
clone = m;
break;
}
}
if(clone == null) {
//DEBUG CODE
for(Member m: introducedByNewGenerator) {
if(m.sameSignatureAs(declClone)) {
clone = m;
break;
}
}
throw new ChameleonProgrammerException();
}
return clone;
}
@Override
public void add(TypeElement element) {
throw new ChameleonProgrammerException("Trying to add an element to a lazy class body.");
}
@Override
public void remove(TypeElement element) {
throw new ChameleonProgrammerException("Trying to remove an element from a lazy class body.");
}
private boolean _initializedElements = false;
@Override
public void flushLocalCache() {
super.flushLocalCache();
_initializedElements = false;
}
@Override
public synchronized List<TypeElement> elements() {
if(! _initializedElements) {
_statics = Lists.create();
List<TypeElement> alreadyCloned = super.elements();
for(TypeElement element: original().elements()) {
ChameleonProperty clazz = language(ObjectOrientedLanguage.class).CLASS;
TypeElement clonedElement=null;
for(TypeElement already: alreadyCloned) {
if(already.origin().equals(element)) { //EQUALS
clonedElement = already;
break;
}
}
if(clonedElement == null) {
if(! element.isTrue(clazz)) {
clonedElement = clone(element);
super.add(clonedElement);
} else {
_statics.add(element);
}
} else {
super.add(clonedElement);
}
}
_initializedElements = true;
}
List<TypeElement> result = super.elements();
result.addAll(_statics);
return result;
}
private List<TypeElement> _statics;
@Override
public <D extends Member> List<? extends SelectionResult> members(DeclarationSelector<D> selector) throws LookupException {
if(selector.usesSelectionName()) {
List<? extends Declaration> list = null;
if(Config.cacheDeclarations()) {
list = declarations(selector.selectionName(this));
} else {
list = members();
}
if(list == null) {
list = Collections.EMPTY_LIST;
}
return selector.selection(Collections.unmodifiableList(list));
} else {
return selector.selection(declarations());
}
}
@Override
public <D extends Member> List<D> members(Class<D> kind) throws LookupException {
List<D> originals = original().members(kind);
List<D> result = Lists.create();
for(D original:originals) {
List<Declaration> clones = declarations(original.name());
for(Declaration clone:clones) {
if(kind.isInstance(clone)) {
result.add((D) clone);
}
}
}
return result;
}
@Override
public LazyClassBody cloneSelf() {
return new LazyClassBody(original());
}
} |
package gov.nih.nci.calab.ui.core;
import gov.nih.nci.calab.dto.characterization.CharacterizationBean;
import gov.nih.nci.calab.dto.common.LabFileBean;
import gov.nih.nci.calab.dto.common.UserBean;
import gov.nih.nci.calab.dto.function.FunctionBean;
import gov.nih.nci.calab.dto.inventory.AliquotBean;
import gov.nih.nci.calab.dto.inventory.ContainerBean;
import gov.nih.nci.calab.dto.inventory.ContainerInfoBean;
import gov.nih.nci.calab.dto.inventory.SampleBean;
import gov.nih.nci.calab.dto.workflow.AssayBean;
import gov.nih.nci.calab.dto.workflow.RunBean;
import gov.nih.nci.calab.exception.InvalidSessionException;
import gov.nih.nci.calab.service.common.LookupService;
import gov.nih.nci.calab.service.search.SearchNanoparticleService;
import gov.nih.nci.calab.service.security.UserService;
import gov.nih.nci.calab.service.submit.SubmitNanoparticleService;
import gov.nih.nci.calab.service.util.CaNanoLabComparators;
import gov.nih.nci.calab.service.util.CaNanoLabConstants;
import gov.nih.nci.calab.service.util.StringUtils;
import gov.nih.nci.calab.service.workflow.ExecuteWorkflowService;
import gov.nih.nci.common.util.StringHelper;
import gov.nih.nci.security.exceptions.CSException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedSet;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.struts.util.LabelValueBean;
/**
* This class sets up session level or servlet context level variables to be
* used in various actions during the setup of query forms.
*
* @author pansu
*
*/
public class InitSessionSetup {
private static LookupService lookupService;
private static UserService userService;
private InitSessionSetup() throws Exception {
lookupService = new LookupService();
userService = new UserService(CaNanoLabConstants.CSM_APP_NAME);
}
public static InitSessionSetup getInstance() throws Exception {
return new InitSessionSetup();
}
public void setCurrentRun(HttpServletRequest request) throws Exception {
HttpSession session = request.getSession();
String runId = (String) request.getParameter("runId");
if (runId == null && session.getAttribute("currentRun") == null) {
throw new InvalidSessionException(
"The session containing a run doesn't exists.");
} else if (runId == null && session.getAttribute("currentRun") != null) {
RunBean currentRun = (RunBean) session.getAttribute("currentRun");
runId = currentRun.getId();
}
if (session.getAttribute("currentRun") == null
|| session.getAttribute("newRunCreated") != null) {
ExecuteWorkflowService executeWorkflowService = new ExecuteWorkflowService();
RunBean runBean = executeWorkflowService.getCurrentRun(runId);
session.setAttribute("currentRun", runBean);
}
session.removeAttribute("newRunCreated");
}
public void clearRunSession(HttpSession session) {
session.removeAttribute("currentRun");
}
public void setAllUsers(HttpSession session) throws Exception {
if ((session.getAttribute("newUserCreated") != null)
|| (session.getServletContext().getAttribute("allUsers") == null)) {
List allUsers = userService.getAllUsers();
session.getServletContext().setAttribute("allUsers", allUsers);
}
session.removeAttribute("newUserCreated");
}
public void setSampleSourceUnmaskedAliquots(HttpSession session)
throws Exception {
// set map between sample source and samples that have unmasked aliquots
if (session.getAttribute("sampleSourceSamplesWithUnmaskedAliquots") == null
|| session.getAttribute("newAliquotCreated") != null) {
Map<String, SortedSet<SampleBean>> sampleSourceSamples = lookupService
.getSampleSourceSamplesWithUnmaskedAliquots();
session.setAttribute("sampleSourceSamplesWithUnmaskedAliquots",
sampleSourceSamples);
List<String> sources = new ArrayList<String>(sampleSourceSamples
.keySet());
session.setAttribute("allSampleSourcesWithUnmaskedAliquots",
sources);
}
setAllSampleUnmaskedAliquots(session);
session.removeAttribute("newAliquotCreated");
}
public void clearSampleSourcesWithUnmaskedAliquotsSession(
HttpSession session) {
session.removeAttribute("allSampleSourcesWithUnmaskedAliquots");
}
public void setAllSampleUnmaskedAliquots(HttpSession session)
throws Exception {
// set map between samples and unmasked aliquots
if (session.getAttribute("allUnmaskedSampleAliquots") == null
|| session.getAttribute("newAliquotCreated") != null) {
Map<String, SortedSet<AliquotBean>> sampleAliquots = lookupService
.getUnmaskedSampleAliquots();
List<String> sampleNames = new ArrayList<String>(sampleAliquots
.keySet());
Collections.sort(sampleNames,
new CaNanoLabComparators.SortableNameComparator());
session.setAttribute("allUnmaskedSampleAliquots", sampleAliquots);
session.setAttribute("allSampleNamesWithAliquots", sampleNames);
}
session.removeAttribute("newAliquotCreated");
}
public void clearSampleUnmaskedAliquotsSession(HttpSession session) {
session.removeAttribute("allUnmaskedSampleAliquots");
session.removeAttribute("allSampleNamesWithAliquots");
}
public void setAllAssayTypeAssays(HttpSession session) throws Exception {
if (session.getServletContext().getAttribute("allAssayTypes") == null) {
List assayTypes = lookupService.getAllAssayTypes();
session.getServletContext().setAttribute("allAssayTypes",
assayTypes);
}
if (session.getServletContext().getAttribute("allAssayTypeAssays") == null) {
Map<String, SortedSet<AssayBean>> assayTypeAssays = lookupService
.getAllAssayTypeAssays();
List<String> assayTypes = new ArrayList<String>(assayTypeAssays
.keySet());
session.getServletContext().setAttribute("allAssayTypeAssays",
assayTypeAssays);
session.getServletContext().setAttribute("allAvailableAssayTypes",
assayTypes);
}
}
public void setAllSampleSources(HttpSession session) throws Exception {
if (session.getAttribute("allSampleSources") == null
|| session.getAttribute("newSampleCreated") != null) {
List sampleSources = lookupService.getAllSampleSources();
session.setAttribute("allSampleSources", sampleSources);
}
// clear the new sample created flag
session.removeAttribute("newSampleCreated");
}
public void clearSampleSourcesSession(HttpSession session) {
session.removeAttribute("allSampleSources");
}
public void setAllSampleContainerTypes(HttpSession session)
throws Exception {
if (session.getAttribute("allSampleContainerTypes") == null
|| session.getAttribute("newSampleCreated") != null) {
List containerTypes = lookupService.getAllSampleContainerTypes();
session.setAttribute("allSampleContainerTypes", containerTypes);
}
// clear the new sample created flag
session.removeAttribute("newSampleCreated");
}
public void clearSampleContainerTypesSession(HttpSession session) {
session.removeAttribute("allSampleContainerTypes");
}
public void setAllSampleTypes(ServletContext appContext) throws Exception {
if (appContext.getAttribute("allSampleTypes") == null) {
List sampleTypes = lookupService.getAllSampleTypes();
appContext.setAttribute("allSampleTypes", sampleTypes);
}
}
public void clearSampleTypesSession(HttpSession session) {
session.removeAttribute("allSampleTypes");
}
public void setAllSampleSOPs(HttpSession session) throws Exception {
if (session.getServletContext().getAttribute("allSampleSOPs") == null) {
List sampleSOPs = lookupService.getAllSampleSOPs();
session.getServletContext().setAttribute("allSampleSOPs",
sampleSOPs);
}
}
public void setAllSampleContainerInfo(HttpSession session) throws Exception {
if (session.getAttribute("sampleContainerInfo") == null
|| session.getAttribute("newSampleCreated") != null) {
ContainerInfoBean containerInfo = lookupService
.getSampleContainerInfo();
session.setAttribute("sampleContainerInfo", containerInfo);
// exclude Other in the lists for search samples drop-down
List<String> rooms = new ArrayList<String>(containerInfo
.getStorageRooms());
rooms.remove(CaNanoLabConstants.OTHER);
List<String> freezers = new ArrayList<String>(containerInfo
.getStorageFreezers());
freezers.remove(CaNanoLabConstants.OTHER);
List<String> shelves = new ArrayList<String>(containerInfo
.getStorageShelves());
shelves.remove(CaNanoLabConstants.OTHER);
List<String> boxes = new ArrayList<String>(containerInfo
.getStorageBoxes());
boxes.remove(CaNanoLabConstants.OTHER);
ContainerInfoBean containerInfoExcludeOther = new ContainerInfoBean(
containerInfo.getQuantityUnits(), containerInfo
.getConcentrationUnits(), containerInfo
.getVolumeUnits(), containerInfo.getStorageLabs(),
rooms, freezers, shelves, boxes);
session.setAttribute("sampleContainerInfoExcludeOther",
containerInfoExcludeOther);
}
// clear the new sample created flag
session.removeAttribute("newSampleCreated");
}
public void setCurrentUser(HttpSession session) throws Exception {
// get user and date information
String creator = "";
if (session.getAttribute("user") != null) {
UserBean user = (UserBean) session.getAttribute("user");
creator = user.getLoginName();
}
String creationDate = StringUtils.convertDateToString(new Date(),
CaNanoLabConstants.DATE_FORMAT);
session.setAttribute("creator", creator);
session.setAttribute("creationDate", creationDate);
}
public void setAllAliquotContainerTypes(HttpSession session)
throws Exception {
if (session.getAttribute("allAliquotContainerTypes") == null
|| session.getAttribute("newAliquotCreated") != null) {
List containerTypes = lookupService.getAllAliquotContainerTypes();
session.setAttribute("allAliquotContainerTypes", containerTypes);
}
session.removeAttribute("newAliquotCreated");
}
public void clearAliquotContainerTypesSession(HttpSession session) {
session.removeAttribute("allAliquotContainerTypes");
}
public void setAllAliquotContainerInfo(HttpSession session)
throws Exception {
if (session.getAttribute("aliquotContainerInfo") == null
|| session.getAttribute("newAliquotCreated") != null) {
ContainerInfoBean containerInfo = lookupService
.getAliquotContainerInfo();
session.setAttribute("aliquotContainerInfo", containerInfo);
// exclude Other in the lists for search aliquots drop-down
List<String> rooms = new ArrayList<String>(containerInfo
.getStorageRooms());
rooms.remove(CaNanoLabConstants.OTHER);
List<String> freezers = new ArrayList<String>(containerInfo
.getStorageFreezers());
freezers.remove(CaNanoLabConstants.OTHER);
List<String> shelves = new ArrayList<String>(containerInfo
.getStorageShelves());
shelves.remove(CaNanoLabConstants.OTHER);
List<String> boxes = new ArrayList<String>(containerInfo
.getStorageBoxes());
boxes.remove(CaNanoLabConstants.OTHER);
ContainerInfoBean containerInfoExcludeOther = new ContainerInfoBean(
containerInfo.getQuantityUnits(), containerInfo
.getConcentrationUnits(), containerInfo
.getVolumeUnits(), containerInfo.getStorageLabs(),
rooms, freezers, shelves, boxes);
session.setAttribute("aliquotContainerInfoExcludeOther",
containerInfoExcludeOther);
}
session.removeAttribute("newAliquotCreated");
}
public void setAllAliquotCreateMethods(HttpSession session)
throws Exception {
if (session.getServletContext().getAttribute("aliquotCreateMethods") == null) {
List methods = lookupService.getAliquotCreateMethods();
session.getServletContext().setAttribute("aliquotCreateMethods",
methods);
}
}
public void setAllSampleContainers(HttpSession session) throws Exception {
if (session.getAttribute("allSampleContainers") == null
|| session.getAttribute("newSampleCreated") != null) {
Map<String, SortedSet<ContainerBean>> sampleContainers = lookupService
.getAllSampleContainers();
List<String> sampleNames = new ArrayList<String>(sampleContainers
.keySet());
Collections.sort(sampleNames,
new CaNanoLabComparators.SortableNameComparator());
session.setAttribute("allSampleContainers", sampleContainers);
session.setAttribute("allSampleNames", sampleNames);
}
session.removeAttribute("newSampleCreated");
}
public void clearSampleContainersSession(HttpSession session) {
session.removeAttribute("allSampleContainers");
session.removeAttribute("allSampleNames");
}
public void setAllSourceSampleIds(HttpSession session) throws Exception {
if (session.getAttribute("allSourceSampleIds") == null
|| session.getAttribute("newSampleCreated") != null) {
List sourceSampleIds = lookupService.getAllSourceSampleIds();
session.setAttribute("allSourceSampleIds", sourceSampleIds);
}
// clear the new sample created flag
session.removeAttribute("newSampleCreated");
}
public void clearSourceSampleIdsSession(HttpSession session) {
session.removeAttribute("allSourceSampleIds");
}
public void clearWorkflowSession(HttpSession session) {
clearRunSession(session);
clearSampleSourcesWithUnmaskedAliquotsSession(session);
clearSampleUnmaskedAliquotsSession(session);
session.removeAttribute("httpFileUploadSessionData");
}
public void clearSearchSession(HttpSession session) {
clearSampleTypesSession(session);
clearSampleContainerTypesSession(session);
clearAliquotContainerTypesSession(session);
clearSourceSampleIdsSession(session);
clearSampleSourcesSession(session);
session.removeAttribute("aliquots");
session.removeAttribute("sampleContainers");
}
public void clearInventorySession(HttpSession session) {
clearSampleTypesSession(session);
clearSampleContainersSession(session);
clearSampleContainerTypesSession(session);
clearSampleUnmaskedAliquotsSession(session);
clearAliquotContainerTypesSession(session);
session.removeAttribute("createSampleForm");
session.removeAttribute("createAliquotForm");
session.removeAttribute("aliquotMatrix");
}
public static LookupService getLookupService() {
return lookupService;
}
public static UserService getUserService() {
return userService;
}
public boolean canUserExecuteClass(HttpSession session, Class classObj)
throws CSException {
UserBean user = (UserBean) session.getAttribute("user");
// assume the part of the package name containing the function domain
// is the same as the protection element defined in CSM
String[] nameStrs = classObj.getName().split("\\.");
String domain = nameStrs[nameStrs.length - 2];
return userService.checkExecutePermission(user, domain);
}
public void setParticleTypeParticles(HttpSession session) throws Exception {
if (session.getAttribute("particleTypeParticles") == null
|| session.getAttribute("newSampleCreated") != null
|| session.getAttribute("newParticleCreated") != null) {
Map<String, SortedSet<String>> particleTypeParticles = lookupService
.getAllParticleTypeParticles();
List<String> particleTypes = new ArrayList<String>(
particleTypeParticles.keySet());
Collections.sort(particleTypes);
session.setAttribute("allParticleTypeParticles",
particleTypeParticles);
session.setAttribute("allParticleTypes", particleTypes);
}
session.removeAttribute("newParticleCreated");
}
public void setAllVisibilityGroups(HttpSession session) throws Exception {
if (session.getAttribute("allVisibilityGroups") == null
|| session.getAttribute("newSampleCreated") != null) {
List<String> groupNames = userService.getAllVisibilityGroups();
session.setAttribute("allVisibilityGroups", groupNames);
}
}
public void setAllDendrimerCores(HttpSession session) throws Exception {
if (session.getServletContext().getAttribute("allDendrimerCores") == null) {
String[] dendrimerCores = lookupService.getAllDendrimerCores();
session.getServletContext().setAttribute("allDendrimerCores",
dendrimerCores);
}
}
public void setAllDendrimerSurfaceGroupNames(HttpSession session)
throws Exception {
if (session.getServletContext().getAttribute(
"allDendrimerSurfaceGroupNames") == null
|| session.getAttribute("newCharacterizationCreated") != null) {
String[] surfaceGroupNames = lookupService
.getAllDendrimerSurfaceGroupNames();
session.getServletContext().setAttribute(
"allDendrimerSurfaceGroupNames", surfaceGroupNames);
}
}
public void setAllDendrimerBranches(HttpSession session) throws Exception {
if (session.getServletContext().getAttribute("allDendrimerBranches") == null
|| session.getAttribute("newCharacterizationCreated") != null) {
String[] branches = lookupService.getAllDendrimerBranches();
session.getServletContext().setAttribute("allDendrimerBranches",
branches);
}
}
public void setAllDendrimerGenerations(HttpSession session)
throws Exception {
if (session.getServletContext().getAttribute("allDendrimerGenerations") == null
|| session.getAttribute("newCharacterizationCreated") != null) {
String[] generations = lookupService.getAllDendrimerGenerations();
session.getServletContext().setAttribute("allDendrimerGenerations",
generations);
}
}
public void addSessionAttributeElement(HttpSession session,
String attributeName, String newElement) throws Exception {
String[] attributeValues = (String[]) session.getServletContext()
.getAttribute(attributeName);
if (!StringHelper.contains(attributeValues, newElement, true)) {
session.getServletContext().setAttribute(attributeName,
StringHelper.add(attributeValues, newElement));
}
}
public void setAllMetalCompositions(HttpSession session) throws Exception {
if (session.getServletContext().getAttribute("allMetalCompositions") == null) {
String[] compositions = lookupService.getAllMetalCompositions();
session.getServletContext().setAttribute("allMetalCompositions",
compositions);
}
}
public void setAllPolymerInitiators(HttpSession session) throws Exception {
if ((session.getServletContext().getAttribute("allPolymerInitiators") == null)
|| (session.getAttribute("newCharacterizationCreated") != null)) {
String[] initiators = lookupService.getAllPolymerInitiators();
session.getServletContext().setAttribute("allPolymerInitiators",
initiators);
}
}
public void setAllParticleFunctionTypes(HttpSession session)
throws Exception {
if (session.getServletContext()
.getAttribute("allParticleFunctionTypes") == null) {
String[] functions = lookupService.getAllParticleFunctions();
session.getServletContext().setAttribute(
"allParticleFunctionTypes", functions);
}
}
public void setAllParticleSources(HttpSession session) throws Exception {
if (session.getServletContext().getAttribute("allParticleSources") == null) {
List<String> sources = lookupService.getAllParticleSources();
session.getServletContext().setAttribute("allParticleSources",
sources);
}
}
public void setAllParticleCharacterizationTypes(HttpSession session)
throws Exception {
if (session.getServletContext()
.getAttribute("allCharacterizationTypes") == null) {
String[] charTypes = lookupService.getAllCharacterizationTypes();
session.getServletContext().setAttribute(
"allCharacterizationTypes", charTypes);
}
}
public void setSideParticleMenu(HttpServletRequest request,
String particleName, String particleType) throws Exception {
HttpSession session = request.getSession();
SearchNanoparticleService service = new SearchNanoparticleService();
if (session.getAttribute("charTypeChars") == null
|| session.getAttribute("newCharacterizationCreated") != null
|| session.getAttribute("newParticleCreated") != null) {
List<CharacterizationBean> charBeans = service
.getCharacterizationInfo(particleName, particleType);
Map<String, List<CharacterizationBean>> existingCharTypeChars = new HashMap<String, List<CharacterizationBean>>();
if (!charBeans.isEmpty()) {
Map<String, String[]> charTypeChars = lookupService
.getCharacterizationTypeCharacterizations();
for (String charType : charTypeChars.keySet()) {
List<CharacterizationBean> newCharBeans = new ArrayList<CharacterizationBean>();
List<String> charList = Arrays.asList(charTypeChars
.get(charType));
for (CharacterizationBean charBean : charBeans) {
if (charList.contains(charBean.getName())) {
newCharBeans.add(charBean);
}
}
if (!newCharBeans.isEmpty()) {
existingCharTypeChars.put(charType, newCharBeans);
}
}
}
session.setAttribute("charTypeChars", existingCharTypeChars);
}
if (session.getAttribute("funcTypeFuncs") == null
|| session.getAttribute("newFunctionCreated") != null
|| session.getAttribute("newParticleCreated") != null) {
Map<String, List<FunctionBean>> funcTypeFuncs = service
.getFunctionInfo(particleName, particleType);
session.setAttribute("funcTypeFuncs", funcTypeFuncs);
}
UserBean user = (UserBean) session.getAttribute("user");
if (session.getAttribute("particleReports") == null
|| session.getAttribute("newReportCreated") != null
|| session.getAttribute("newParticleCreated") != null) {
List<LabFileBean> reportBeans = service.getReportInfo(particleName,
particleType, CaNanoLabConstants.REPORT, user);
session.setAttribute("particleReports", reportBeans);
}
if (session.getAttribute("particleAssociatedFiles") == null
|| session.getAttribute("newReportCreated") != null
|| session.getAttribute("newParticleCreated") != null) {
List<LabFileBean> associatedBeans = service.getReportInfo(
particleName, particleType,
CaNanoLabConstants.ASSOCIATED_FILE, user);
session.setAttribute("particleAssociatedFiles", associatedBeans);
}
// not part of the side menu, but need to up
if (session.getAttribute("newParticleCreated") != null) {
setParticleTypeParticles(session);
}
session.removeAttribute("newCharacterizationCreated");
session.removeAttribute("newFunctionCreated");
session.removeAttribute("newParticleCreated");
session.removeAttribute("newReportCreated");
session.removeAttribute("detailPage");
setStaticDropdowns(session);
}
public void setCharacterizationTypeCharacterizations(HttpSession session)
throws Exception {
if (session.getServletContext().getAttribute(
"allCharacterizationTypeCharacterizations") == null) {
Map<String, String[]> charTypeChars = lookupService
.getCharacterizationTypeCharacterizations();
session.getServletContext().setAttribute(
"allCharacterizationTypeCharacterizations", charTypeChars);
}
}
public void setAllInstrumentTypes(HttpSession session) throws Exception {
if (session.getServletContext().getAttribute("allInstrumentTypes") == null) {
List<LabelValueBean> instrumentTypes = lookupService
.getAllInstrumentTypeAbbrs();
session.getServletContext().setAttribute("allInstrumentTypes",
instrumentTypes);
}
}
public void setAllInstrumentTypeManufacturers(HttpSession session)
throws Exception {
if (session.getServletContext().getAttribute(
"allInstrumentTypeManufacturers") == null) {
Map<String, SortedSet<String>> instrumentManufacturers = lookupService
.getAllInstrumentManufacturers();
session.getServletContext().setAttribute(
"allInstrumentTypeManufacturers", instrumentManufacturers);
}
}
public void setAllSizeDistributionGraphTypes(HttpSession session)
throws Exception {
if (session.getServletContext().getAttribute(
"allSizeDistributionGraphTypes") == null) {
String[] graphTypes = lookupService.getSizeDistributionGraphTypes();
session.getServletContext().setAttribute(
"allSizeDistributionGraphTypes", graphTypes);
}
}
public void setAllMolecularWeightDistributionGraphTypes(HttpSession session)
throws Exception {
if (session.getServletContext().getAttribute(
"allMolecularWeightDistributionGraphTypes") == null) {
String[] graphTypes = lookupService
.getMolecularWeightDistributionGraphTypes();
session.getServletContext().setAttribute(
"allMolecularWeightDistributionGraphTypes", graphTypes);
}
}
public void setAllMorphologyDistributionGraphTypes(HttpSession session)
throws Exception {
if (session.getServletContext().getAttribute(
"allMorphologyDistributionGraphTypes") == null) {
String[] graphTypes = lookupService
.getMorphologyDistributionGraphTypes();
session.getServletContext().setAttribute(
"allMorphologyDistributionGraphTypes", graphTypes);
}
}
public void setAllShapeDistributionGraphTypes(HttpSession session)
throws Exception {
if (session.getServletContext().getAttribute(
"allShapeDistributionGraphTypes") == null) {
String[] graphTypes = lookupService
.getShapeDistributionGraphTypes();
session.getServletContext().setAttribute(
"allShapeDistributionGraphTypes", graphTypes);
}
}
public void setAllStabilityDistributionGraphTypes(HttpSession session)
throws Exception {
if (session.getServletContext().getAttribute(
"allStabilityDistributionGraphTypes") == null) {
String[] graphTypes = lookupService
.getStabilityDistributionGraphTypes();
session.getServletContext().setAttribute(
"allStabilityDistributionGraphTypes", graphTypes);
}
}
public void setAllPurityDistributionGraphTypes(HttpSession session)
throws Exception {
if (session.getServletContext().getAttribute(
"allPurityDistributionGraphTypes") == null) {
String[] graphTypes = lookupService
.getPurityDistributionGraphTypes();
session.getServletContext().setAttribute(
"allPurityDistributionGraphTypes", graphTypes);
}
}
public void setAllSolubilityDistributionGraphTypes(HttpSession session)
throws Exception {
if (session.getServletContext().getAttribute(
"allSolubilityDistributionGraphTypes") == null) {
String[] graphTypes = lookupService
.getSolubilityDistributionGraphTypes();
session.getServletContext().setAttribute(
"allSolubilityDistributionGraphTypes", graphTypes);
}
}
public void setAllMorphologyTypes(HttpSession session) throws Exception {
if (session.getServletContext().getAttribute("allMorphologyTypes") == null) {
String[] morphologyTypes = lookupService.getAllMorphologyTypes();
session.getServletContext().setAttribute("allMorphologyTypes",
morphologyTypes);
}
}
public void setAllShapeTypes(HttpSession session) throws Exception {
if (session.getServletContext().getAttribute("allShapeTypes") == null) {
String[] shapeTypes = lookupService.getAllShapeTypes();
session.getServletContext().setAttribute("allShapeTypes",
shapeTypes);
}
}
public void setAllStressorTypes(HttpSession session) throws Exception {
if (session.getServletContext().getAttribute("allStessorTypes") == null) {
String[] stressorTypes = lookupService.getAllStressorTypes();
session.getServletContext().setAttribute("allStressorTypes",
stressorTypes);
}
}
public void setStaticDropdowns(HttpSession session) {
// set static boolean yes or no and characterization source choices
session.setAttribute("booleanChoices",
CaNanoLabConstants.BOOLEAN_CHOICES);
session.setAttribute("characterizationSources",
CaNanoLabConstants.CHARACTERIZATION_SOURCES);
session.setAttribute("allCarbonNanotubeWallTypes",
CaNanoLabConstants.CARBON_NANOTUBE_WALLTYPES);
if (session.getAttribute("allReportTypes") == null) {
String[] allReportTypes = lookupService.getAllReportTypes();
session.setAttribute("allReportTypes", allReportTypes);
}
session.setAttribute("allFunctionLinkageTypes",
CaNanoLabConstants.FUNCTION_LINKAGE_TYPES);
session.setAttribute("allFunctionAgentTypes",
CaNanoLabConstants.FUNCTION_AGENT_TYPES);
}
public void setAllRunFiles(HttpSession session, String particleName)
throws Exception {
if (session.getAttribute("allRunFiles") == null
|| session.getAttribute("newParticleCreated") != null
|| session.getAttribute("newFileLoaded") != null) {
SubmitNanoparticleService service = new SubmitNanoparticleService();
List<LabFileBean> runFileBeans = service
.getAllRunFiles(particleName);
session.setAttribute("allRunFiles", runFileBeans);
}
session.removeAttribute("newParticleCreated");
session.removeAttribute("newFileLoaded");
}
public void setAllAreaMeasureUnits(HttpSession session) throws Exception {
if (session.getServletContext().getAttribute("allAreaMeasureUnits") == null) {
String[] areaUnits = lookupService.getAllAreaMeasureUnits();
session.getServletContext().setAttribute("allAreaMeasureUnits",
areaUnits);
}
}
public void setAllChargeMeasureUnits(HttpSession session) throws Exception {
if (session.getServletContext().getAttribute("allChargeMeasureUnits") == null) {
String[] chargeUnits = lookupService.getAllChargeMeasureUnits();
session.getServletContext().setAttribute("allChargeMeasureUnits",
chargeUnits);
}
}
public void setAllControlTypes(HttpSession session) throws Exception {
if (session.getServletContext().getAttribute("allControlTypes") == null) {
String[] controlTypes = lookupService.getAllControlTypes();
session.getServletContext().setAttribute("allControlTypes",
controlTypes);
}
}
public void setAllConditionTypes(HttpSession session) throws Exception {
if (session.getServletContext().getAttribute("allConditionTypes") == null) {
String[] conditionTypes = lookupService.getAllConditionTypes();
session.getServletContext().setAttribute("allConditionTypes",
conditionTypes);
}
}
public void setAllConditionUnits(HttpSession session) throws Exception {
if (session.getServletContext().getAttribute("allConditionTypeUnits") == null) {
Map<String, String[]> conditionTypeUnits = lookupService
.getAllConditionUnits();
session.getServletContext().setAttribute("allConditionTypeUnits",
conditionTypeUnits);
}
}
public void setAllAgentTypes(HttpSession session) throws Exception {
if (session.getServletContext().getAttribute("allAgentTypes") == null) {
Map<String, String[]> agentTypes = lookupService.getAllAgentTypes();
session.getServletContext().setAttribute("allAgentTypes",
agentTypes);
}
}
public void setAllAgentTargetTypes(HttpSession session) throws Exception {
if (session.getServletContext().getAttribute("allAgentTargetTypes") == null) {
Map<String, String[]> agentTargetTypes = lookupService
.getAllAgentTargetTypes();
session.getServletContext().setAttribute("allAgentTargetTypes",
agentTargetTypes);
}
}
public void setAllTimeUnits(HttpSession session) throws Exception {
if (session.getServletContext().getAttribute("allTimeUnits") == null) {
String[] timeUnits = lookupService.getAllTimeUnits();
session.getServletContext().setAttribute("allTimeUnits", timeUnits);
}
}
public void setAllConcentrationUnits(HttpSession session) throws Exception {
if (session.getServletContext().getAttribute("allConcentrationUnits") == null) {
String[] concentrationUnits = lookupService
.getAllConcentrationUnits();
session.getServletContext().setAttribute("allConcentrationUnits",
concentrationUnits);
}
}
public void setAllCellLines(HttpSession session) throws Exception {
if (session.getServletContext().getAttribute("allCellLines") == null) {
String[] cellLines = lookupService.getAllCellLines();
session.getServletContext().setAttribute("allCellLines", cellLines);
}
}
public void setAllActivationMethods(HttpSession session) throws Exception {
if (session.getServletContext().getAttribute("allActivationMethods") == null) {
String[] activationMethods = lookupService
.getAllActivationMethods();
session.getServletContext().setAttribute("allActivationMethods",
activationMethods);
}
}
public void setAllSpecies(HttpSession session) throws Exception {
if (session.getServletContext().getAttribute("allSpecies") == null) {
List<LabelValueBean> species = lookupService.getAllSpecies();
session.getServletContext().setAttribute("allSpecies", species);
}
}
public void setApplicationOwner(HttpSession session) {
if (session.getServletContext().getAttribute("applicationOwner") == null) {
session.getServletContext().setAttribute("applicationOwner",
CaNanoLabConstants.APP_OWNER);
}
}
// public void addCellLine(HttpSession session, String option) throws
// Exception {
// String[] cellLines = (String[])
// session.getServletContext().getAttribute("allCellLines");
// if (!StringHelper.contains(cellLines, option, true)) {
// session.getServletContext().setAttribute("allCellLines",
// StringHelper.add(cellLines, option));
/**
* Create default CSM groups for default visible groups and admin
*
*/
public void createDefaultCSMGroups() throws Exception {
for (String groupName : CaNanoLabConstants.VISIBLE_GROUPS) {
userService.createAGroup(groupName);
}
userService.createAGroup(CaNanoLabConstants.CSM_ADMIN);
}
} |
package org.bouncycastle.jce.provider;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.security.InvalidKeyException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Signature;
import java.security.SignatureException;
import java.security.interfaces.DSAKey;
import java.security.spec.AlgorithmParameterSpec;
import org.bouncycastle.asn1.ASN1EncodableVector;
import org.bouncycastle.asn1.ASN1InputStream;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.DERInteger;
import org.bouncycastle.asn1.DEROutputStream;
import org.bouncycastle.asn1.DERSequence;
import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers;
import org.bouncycastle.asn1.x509.X509ObjectIdentifiers;
import org.bouncycastle.crypto.CipherParameters;
import org.bouncycastle.crypto.DSA;
import org.bouncycastle.crypto.Digest;
import org.bouncycastle.crypto.digests.SHA1Digest;
import org.bouncycastle.crypto.digests.SHA224Digest;
import org.bouncycastle.crypto.digests.SHA256Digest;
import org.bouncycastle.crypto.digests.SHA384Digest;
import org.bouncycastle.crypto.digests.SHA512Digest;
import org.bouncycastle.crypto.params.ParametersWithRandom;
import org.bouncycastle.crypto.signers.DSASigner;
import org.bouncycastle.crypto.signers.ECDSASigner;
import org.bouncycastle.crypto.signers.ECNRSigner;
import org.bouncycastle.jce.interfaces.ECKey;
import org.bouncycastle.jce.interfaces.ECPublicKey;
import org.bouncycastle.jce.interfaces.GOST3410Key;
public class JDKDSASigner
extends Signature implements PKCSObjectIdentifiers, X509ObjectIdentifiers
{
private Digest digest;
private DSA signer;
private SecureRandom random;
protected JDKDSASigner(
String name,
Digest digest,
DSA signer)
{
super(name);
this.digest = digest;
this.signer = signer;
}
protected void engineInitVerify(
PublicKey publicKey)
throws InvalidKeyException
{
CipherParameters param = null;
if (publicKey instanceof ECPublicKey)
{
param = ECUtil.generatePublicKeyParameter(publicKey);
}
else if (publicKey instanceof GOST3410Key)
{
param = GOST3410Util.generatePublicKeyParameter(publicKey);
}
else if (publicKey instanceof DSAKey)
{
param = DSAUtil.generatePublicKeyParameter(publicKey);
}
else
{
try
{
byte[] bytes = publicKey.getEncoded();
publicKey = JDKKeyFactory.createPublicKeyFromDERStream(
new ByteArrayInputStream(bytes));
if (publicKey instanceof ECPublicKey)
{
param = ECUtil.generatePublicKeyParameter(publicKey);
}
else if (publicKey instanceof DSAKey)
{
param = DSAUtil.generatePublicKeyParameter(publicKey);
}
else
{
throw new InvalidKeyException("can't recognise key type in DSA based signer");
}
}
catch (Exception e)
{
throw new InvalidKeyException("can't recognise key type in DSA based signer");
}
}
digest.reset();
signer.init(false, param);
}
protected void engineInitSign(
PrivateKey privateKey,
SecureRandom random)
throws InvalidKeyException
{
this.random = random;
engineInitSign(privateKey);
}
protected void engineInitSign(
PrivateKey privateKey)
throws InvalidKeyException
{
CipherParameters param = null;
if (privateKey instanceof ECKey)
{
param = ECUtil.generatePrivateKeyParameter(privateKey);
}
else if (privateKey instanceof GOST3410Key)
{
param = GOST3410Util.generatePrivateKeyParameter(privateKey);
}
else
{
param = DSAUtil.generatePrivateKeyParameter(privateKey);
}
digest.reset();
if (random != null)
{
signer.init(true, new ParametersWithRandom(param, random));
}
else
{
signer.init(true, param);
}
}
protected void engineUpdate(
byte b)
throws SignatureException
{
digest.update(b);
}
protected void engineUpdate(
byte[] b,
int off,
int len)
throws SignatureException
{
digest.update(b, off, len);
}
protected byte[] engineSign()
throws SignatureException
{
byte[] hash = new byte[digest.getDigestSize()];
digest.doFinal(hash, 0);
try
{
BigInteger[] sig = signer.generateSignature(hash);
return derEncode(sig[0], sig[1]);
}
catch (Exception e)
{
throw new SignatureException(e.toString());
}
}
protected boolean engineVerify(
byte[] sigBytes)
throws SignatureException
{
byte[] hash = new byte[digest.getDigestSize()];
digest.doFinal(hash, 0);
BigInteger[] sig;
try
{
sig = derDecode(sigBytes);
}
catch (Exception e)
{
throw new SignatureException("error decoding signature bytes.");
}
return signer.verifySignature(hash, sig[0], sig[1]);
}
protected void engineSetParameter(
AlgorithmParameterSpec params)
{
throw new UnsupportedOperationException("engineSetParameter unsupported");
}
/**
* @deprecated replaced with <a href = "#engineSetParameter(java.security.spec.AlgorithmParameterSpec)">
*/
protected void engineSetParameter(
String param,
Object value)
{
throw new UnsupportedOperationException("engineSetParameter unsupported");
}
/**
* @deprecated
*/
protected Object engineGetParameter(
String param)
{
throw new UnsupportedOperationException("engineSetParameter unsupported");
}
private byte[] derEncode(
BigInteger r,
BigInteger s)
throws IOException
{
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
DEROutputStream dOut = new DEROutputStream(bOut);
ASN1EncodableVector v = new ASN1EncodableVector();
v.add(new DERInteger(r));
v.add(new DERInteger(s));
dOut.writeObject(new DERSequence(v));
return bOut.toByteArray();
}
private BigInteger[] derDecode(
byte[] encoding)
throws IOException
{
ByteArrayInputStream bIn = new ByteArrayInputStream(encoding);
ASN1InputStream aIn = new ASN1InputStream(bIn);
ASN1Sequence s = (ASN1Sequence)aIn.readObject();
BigInteger[] sig = new BigInteger[2];
sig[0] = ((DERInteger)s.getObjectAt(0)).getValue();
sig[1] = ((DERInteger)s.getObjectAt(1)).getValue();
return sig;
}
static public class stdDSA
extends JDKDSASigner
{
public stdDSA()
{
super("SHA1withDSA", new SHA1Digest(), new DSASigner());
}
}
static public class ecDSA
extends JDKDSASigner
{
public ecDSA()
{
super("SHA1withECDSA", new SHA1Digest(), new ECDSASigner());
}
}
static public class ecDSA224
extends JDKDSASigner
{
public ecDSA224()
{
super("SHA224withECDSA", new SHA224Digest(), new ECDSASigner());
}
}
static public class ecDSA256
extends JDKDSASigner
{
public ecDSA256()
{
super("SHA256withECDSA", new SHA256Digest(), new ECDSASigner());
}
}
static public class ecDSA384
extends JDKDSASigner
{
public ecDSA384()
{
super("SHA384withECDSA", new SHA384Digest(), new ECDSASigner());
}
}
static public class ecDSA512
extends JDKDSASigner
{
public ecDSA512()
{
super("SHA512withECDSA", new SHA512Digest(), new ECDSASigner());
}
}
static public class ecNR
extends JDKDSASigner
{
public ecNR()
{
super("SHA1withECNR", new SHA1Digest(), new ECNRSigner());
}
}
static public class ecNR224
extends JDKDSASigner
{
public ecNR224()
{
super("SHA224withECNR", new SHA224Digest(), new ECNRSigner());
}
}
static public class ecNR256
extends JDKDSASigner
{
public ecNR256()
{
super("SHA256withECNR", new SHA256Digest(), new ECNRSigner());
}
}
static public class ecNR384
extends JDKDSASigner
{
public ecNR384()
{
super("SHA384withECNR", new SHA384Digest(), new ECNRSigner());
}
}
static public class ecNR512
extends JDKDSASigner
{
public ecNR512()
{
super("SHA512withECNR", new SHA512Digest(), new ECNRSigner());
}
}
} |
package org.camsrobotics.frc2016.auto;
/**
* Autonomous mode magic
*
* @author Wesley
*
*/
public class AutoExecutor {
private AutoMode m_auto;
private Thread m_thread = null;
/**
* Constructs the AutoExecutor with the given mode
*
* @param mode The mode to be executed
*/
public AutoExecutor(AutoMode mode) {
m_auto = mode;
}
/**
* Let's go!
*/
public void start() {
if(m_thread == null) {
m_thread = new Thread(new Runnable() {
@Override
public void run() {
m_auto.run();
}
});
m_thread.start();
}
}
/**
* Stops the Autonomous mode
*/
public void stop() {
if(m_auto != null) {
m_auto.stop();
}
m_thread = null;
}
} |
package org.concord.datagraph.engine;
/**
* DataGraphable
* This class is an object that takes data from a
* data store and draws this data in a graph (it's a Graphable)
* as a countinuous set of points that can be connected or not
* (connected by default).
* It is itself a DataStore with 2 channels (x,y), so it can easily
* be added to a data table.
*
* Date created: June 18, 2004
*
* @author Scott Cytacki<p>
* @author Ingrid Moncada<p>
*
*/
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Shape;
import java.awt.Stroke;
import java.awt.geom.AffineTransform;
import java.awt.geom.GeneralPath;
import java.awt.geom.Point2D;
import java.util.Vector;
import javax.swing.event.ChangeEvent;
import org.concord.data.stream.ProducerDataStore;
import org.concord.framework.data.stream.DataChannelDescription;
import org.concord.framework.data.stream.DataProducer;
import org.concord.framework.data.stream.DataStore;
import org.concord.framework.data.stream.DataStoreEvent;
import org.concord.framework.data.stream.DataStoreListener;
import org.concord.framework.data.stream.AutoIncrementDataStore;
import org.concord.framework.data.stream.WritableDataStore;
import org.concord.graph.engine.CoordinateSystem;
import org.concord.graph.engine.DefaultGraphable;
import org.concord.graph.engine.Graphable;
import org.concord.graph.engine.MathUtil;
public class DataGraphable extends DefaultGraphable
implements DataStoreListener, DataStore
{
protected DataStore dataStore;
//By default, it graphs the dt (x axis) and the first channel (y axis)
protected int channelX = -1;
protected int channelY = 0;
protected Color lineColor = Color.black;
protected float lineWidth = 2;
protected Stroke stroke;
protected GeneralPath path;
/**
* This is the path used to draw all the markers on the
* graph.
*/
protected GeneralPath markerListPath;
/**
* This is shape of each marker. The path is transformed
* to the correct position and then added to the markerListPath.
*/
protected GeneralPath markerPath = null;
/**
* This variable determines if the markers should be filled
*/
protected boolean fillMarkers = false;
/**
* This is the color of the markers if it is null then
* they will be a little darker than the line color
*/
protected Color markerColor = null;
protected Vector dataStoreListeners;
protected boolean connectPoints = true;
protected static int crossSize = 3;
public final static GeneralPath CROSS_MARKER_PATH = new GeneralPath();
static {
CROSS_MARKER_PATH.moveTo(-crossSize, -crossSize);
CROSS_MARKER_PATH.lineTo(crossSize, crossSize);
CROSS_MARKER_PATH.moveTo(-crossSize, crossSize);
CROSS_MARKER_PATH.lineTo(crossSize, -crossSize);
}
private int lastValueCalculated = -1;
protected boolean locked = false;
/*
* validPrevPoint indicates that last point "processed"
* was a valid point. This is used to figure out if points
* should be connected. If there is an invalid point then there
* will be a break in the line drawn.
*/
private boolean validPrevPoint = false;
protected boolean needUpdate = true;
// This is used to indicate when a full recalculation is
// needed. It should only be modified in synchronized regions
// this replaces the needUpdateDataReceived boolean. This is basically
// the inverse.
protected boolean needRecalculate = true;
protected boolean autoRepaintData = true;
private float minXValue;
private float maxXValue;
private float minYValue;
private float maxYValue;
private boolean validMinMax;
// If this is true then we have internally created a ProducerDataStore
// this would be done if someone adds a dataProducer to us.
// This is useful for state saving
private boolean internalProducerDataStore = false;
private Point2D tmpDataPoint = new Point2D.Double();
private boolean useVirtualChannels = false;
/**
* Default constructor.
*/
public DataGraphable()
{
path = new GeneralPath();
markerListPath = new GeneralPath();
dataStoreListeners = new Vector();
updateStroke();
minXValue = Float.MAX_VALUE;
maxXValue = -Float.MAX_VALUE;
minYValue = Float.MAX_VALUE;
maxYValue = -Float.MAX_VALUE;
validMinMax = false;
}
public void connect(DataProducer dataProducer)
{
if(internalProducerDataStore) {
ProducerDataStore pDataStore = (ProducerDataStore) dataStore;
if (pDataStore.getDataProducer() == null)
pDataStore.setDataProducer(dataProducer);
}
}
public void disconnect(DataProducer dataProducer)
{
if(internalProducerDataStore) {
ProducerDataStore pDataStore = (ProducerDataStore) dataStore;
if (pDataStore.getDataProducer() == dataProducer)
pDataStore.setDataProducer(null);
}
}
/**
* Sets the data producer of this graphable.
* By default it will graph dt vs channel 0
* If the data will be shared by more components, this method is not recommended.
* Create a ProducerDataStore with the data prodeucer and share the data store with other
* components. Use setDataStore() instead
*/
public void setDataProducer(DataProducer dataProducer)
{
setDataProducer(dataProducer, -1, 0);
}
/**
* If the data will be shared by more components, this method is not recommended.
* Create a ProducerDataStore with the data prodeucer and share the data store with other
* components. Use setDataStore() instead
* @param dataProducer
* @param channelXAxis
* @param channelYAxis
*/
public void setDataProducer(DataProducer dataProducer, int channelXAxis, int channelYAxis)
{
// Create a default data store for this data producer
ProducerDataStore pDataStore = new ProducerDataStore(dataProducer);
// This sets the internal producer data store to false
setDataStore(pDataStore);
// We just created an internal datastore so we need to remember it
internalProducerDataStore = true;
setChannelX(channelXAxis);
setChannelY(channelYAxis);
}
/**
* Sets the data store that this graphable will be using
* to get its data
* By default it will graph dt vs channel 0
* @param dataStore
*/
public void setDataStore(DataStore dataStore)
{
if (this.dataStore != null){
this.dataStore.removeDataStoreListener(this);
}
this.dataStore = dataStore;
// Assume someone set this from the outside with their own dataStore
internalProducerDataStore = false;
forceRecalculate();
if (this.dataStore != null){
this.dataStore.addDataStoreListener(this);
}
}
/**
* Sets the data store that this graphable will be using
* to get its data
* It will graph channelXAxis vs channelYAxis
* @param dataStore
*/
public void setDataStore(DataStore dataStore, int channelXAxis, int channelYAxis)
{
setDataStore(dataStore);
setChannelX(channelXAxis);
setChannelY(channelYAxis);
}
/*
* Resets the data received
*/
public void reset()
{
if(locked) return;
dataStore.clearValues();
forceRecalculate();
minXValue = Float.MAX_VALUE;
maxXValue = -Float.MAX_VALUE;
minYValue = Float.MAX_VALUE;
maxYValue = -Float.MAX_VALUE;
validMinMax = false;
notifyChange();
}
/*
* Sets the color of the path drawn on the graph
*/
public void setColor(int r, int g, int b)
{
setColor(new Color(r,g,b));
}
/*
* Sets the color of the path drawn on the graph
*/
public void setColor(Color c)
{
lineColor = c;
notifyChange();
}
public Color getColor()
{
return lineColor;
}
/*
* Sets the line width of the path drawn on the graph
*/
public void setLineWidth(float width)
{
lineWidth = width;
updateStroke();
}
protected void updateStroke()
{
stroke = new BasicStroke(lineWidth, BasicStroke.CAP_SQUARE, BasicStroke.JOIN_ROUND);
}
/**
* Draws this object on Graphics g
**/
public void draw(Graphics2D g)
{
//long b = System.currentTimeMillis();
if (needUpdate){
update();
}
Shape oldClip = g.getClip();
Color oldColor = g.getColor();
Stroke oldStroke = g.getStroke();
graphArea.clipGraphics(g);
g.setColor(lineColor);
g.setStroke(stroke);
if (connectPoints){
g.draw(path);
}
if (markerPath != null){
if(markerColor != null) {
g.setColor(markerColor);
} else {
g.setColor(lineColor.darker());
}
if(fillMarkers) {
g.fill(markerListPath);
} else {
g.draw(markerListPath);
}
}
extendedDraw(g);
g.setColor(oldColor);
g.setStroke(oldStroke);
g.setClip(oldClip);
//long a = System.currentTimeMillis();
//System.out.println(a-b);
}
/**
* This is added so the DataGraphable class can be extended
* to have addition markers around the data. For example the
* DataGraphableRegresssion class uses this to put regression lines
* @param g
*/
protected void extendedDraw(Graphics2D g)
{
}
public float handleValue(Object objVal)
{
if (objVal instanceof Float){
Float xFloat = (Float)objVal;
// Note: the floatValue could be a NaN here but that
// will get taken care of automatically later.
return xFloat.floatValue();
}
// Try to parse string. If unsuccessful, don't do anything and
// it will return NaN below.
if (objVal instanceof String){
try {
float xFloat = Float.parseFloat((String) objVal);
return xFloat;
} catch (java.lang.NumberFormatException e){
}
}
//Handling non null objects different than Floats
if (objVal != null && !(objVal instanceof Float)){
System.err.println("Warning! The value is not a Float object: "+objVal);
}
// objVal is either null or something other than a float
return Float.NaN;
}
public Point2D getRowPoint(int rowIndex, CoordinateSystem coord,
Point2D pathPoint)
{
float px, py;
Object objVal;
objVal = dataStore.getValueAt(rowIndex, getDataStoreChannelX());
px = handleValue(objVal);
objVal = dataStore.getValueAt(rowIndex, getDataStoreChannelY());
py = handleValue(objVal);
if(Float.isNaN(px) || Float.isNaN(py)) {
//We have found an invalid point. If there was a valid undrawn point
//before this one, then we need to draw it.
//There can only be an undrawn point if we are connecting points and not
//drawing crosses
// This could be caused if the data store was being updated at the same
// as we are looking at it. This should make this point the last point
// in the data store.
return null;
}
//Always keep the min and max value available
if (px < minXValue){
minXValue = px;
}
if (px > maxXValue){
maxXValue = px;
}
if (py < minYValue){
minYValue = py;
}
if (py > maxYValue){
maxYValue = py;
}
// record the fact that the min and maxes are now valid
// we could check this variable first but it is fast to just
// set it each time
validMinMax = true;
tmpDataPoint.setLocation(px, py);
coord.transformToDisplay(tmpDataPoint, pathPoint);
return pathPoint;
}
/**
* Handler of the changes in the graph area
*/
public void stateChanged(ChangeEvent e)
{
forceRecalculate();
notifyChange();
}
protected void resetPaths()
{
path.reset();
markerListPath.reset();
}
public void update()
{
float ppx, ppy;
int initialI;
//undrawnPoint stores the last point that was "processed"
//which was valid but it wasn't drawn. If crosses are
//being drawn or if points aren't connected then all points are drawn as they
//are processed. Points are not drawn when they are processed,
//if they might be the first point of a line segment.
//When the undrawnPoint is recorded the path is movedTo to this undrawn spot
Point2D undrawnPoint = null;
Point2D currentPathPoint;
if (dataStore == null) return;
Point2D.Double pathPointHolder = new Point2D.Double();
Point2D pathPoint = null;
CoordinateSystem coord = getGraphArea().getCoordinateSystem();
// if new data was not received or no values have been
// calculated then all the points need to be recalculated
synchronized(this) {
if (needRecalculate || lastValueCalculated < 0) {
lastValueCalculated = -1;
needRecalculate = false;
}
initialI = lastValueCalculated + 1;
// We set this to false here so that if someone sets it to
// true while we are updating then we will be sure to update
// again.
needUpdate = false;
}
// This is a bit a hack to handle cases that aren't handled correctly
// if the points are added atomically. Then there should never be
// and invalid points. So this code shouldn't be run, however
// some data stores don't add points atomically so this case might
// happen sometimes.
if(initialI != 0 && !validPrevPoint) {
System.err.println("last drawn point was invalid");
// verify that the previous point really is invalid
// it can happen that is it invlaid for a little while while
// it is being added to the DataStore.
// if there was an atomic DataStore store add row this wouldn't
// be a problem.
Point2D invalidPoint = getRowPoint(initialI-1, coord, pathPointHolder);
if(invalidPoint != null) {
// it wasn't really invalid
initialI
if(initialI != 0) {
validPrevPoint = true;
}
}
}
if(initialI == 0) {
resetPaths();
// the previous point is invalid because there is no
// previous point
validPrevPoint = false;
minXValue = Float.MAX_VALUE;
maxXValue = -Float.MAX_VALUE;
minYValue = Float.MAX_VALUE;
maxYValue = -Float.MAX_VALUE;
validMinMax = false;
}
int i;
int totalNumSamples = dataStore.getTotalNumSamples();
float thresholdPointTheSame = (float)(lineWidth/2 - 0.01);
if(connectPoints){
float lastPathX = Float.NaN;
float lastPathY = Float.NaN;
currentPathPoint = path.getCurrentPoint();
if(currentPathPoint != null) {
lastPathX = (float)currentPathPoint.getX();
lastPathY = (float)currentPathPoint.getY();
}
for(i=initialI; i < totalNumSamples; i++){
pathPoint = getRowPoint(i, coord, pathPointHolder);
if(pathPoint == null) {
//We have found an invalid point. If there was a valid undrawn point
//before this one, then we need to draw it.
//There can only be an undrawn point if we are connecting points and not
//drawing crosses
if (undrawnPoint != null){
drawPoint(undrawnPoint);
undrawnPoint = null;
}
// This could be caused if the data store was being updated at the same
// as we are looking at it. This should make this point the last point
// in the data store.
validPrevPoint = false;
continue;
}
ppx = (float)pathPoint.getX();
ppy = (float)pathPoint.getY();
if (MathUtil.equalsFloat(ppx, lastPathX, thresholdPointTheSame) &&
MathUtil.equalsFloat(ppy, lastPathY, thresholdPointTheSame)){
continue;
}
if (validPrevPoint){
path.lineTo(ppx, ppy);
undrawnPoint = null;
}
else{
path.moveTo(ppx, ppy);
if (undrawnPoint != null){
//if this statement is reach then there is an error in this
//algorythm
throw new RuntimeException("Assert: We have an undrawn point that will be forgotten");
}
//We aren't going to draw this point so we need to
//remember it so we can draw it later.
undrawnPoint = path.getCurrentPoint();
}
lastPathX = ppx;
lastPathY = ppy;
// If we made it here then the current point (soon to be the prev point)
// is a valid point, so set the flag
// technically we only care about this if we are connecting points
// but it seemed easier to understand if this is done out here
validPrevPoint = true;
drawPointMarker(ppx, ppy, i);
}
} else {
for(i=initialI; i < totalNumSamples; i++){
pathPoint = getRowPoint(i, coord, pathPointHolder);
if(pathPoint == null) {
//We have found an invalid point. If there was a valid undrawn point
//before this one, then we need to draw it.
//There can only be an undrawn point if we are connecting points and not
//drawing crosses
if (undrawnPoint != null){
drawPoint(undrawnPoint);
undrawnPoint = null;
}
// This could be caused if the data store was being updated at the same
// as we are looking at it. This should make this point the last point
// in the data store.
validPrevPoint = false;
continue;
}
ppx = (float)pathPoint.getX();
ppy = (float)pathPoint.getY();
currentPathPoint = path.getCurrentPoint();
float dy = 1;//TODO dy is 1 because of MAC OS X
if (currentPathPoint != null &&
MathUtil.equalsDouble(ppx, currentPathPoint.getX(), thresholdPointTheSame) &&
MathUtil.equalsDouble(ppy, currentPathPoint.getY() - dy, thresholdPointTheSame)){
//System.out.println("Not adding this point:"+ppx+","+ppy+" "+lastPathPoint);
continue;
}
drawPoint(ppx, ppy);
drawPointMarker(ppx, ppy, i);
// If we made it here then the current point (soon to be the prev point)
// is a valid point, so set the flag
// technically we only care about this if we are connecting points
// but it seemed easier to understand if this is done out here
validPrevPoint = true;
}
}
// This is to handle a threading issue
// the lastValueCalculated could be set by forceRecalcutate
// to -1. Then this statement is reached where we want to set it to i-1
synchronized(this) {
if(needRecalculate) {
// This means the forceRecalculate method was called while we were
// updating the paths. That means we need to update the paths again
// a check for this could be put in the inner loop so we didn't waste time
} else {
// we we don't need to recalculate then we can remember the last point we
// did calculate and start from there next time.
lastValueCalculated = i-1;
}
}
//There is a point that hasn't been drawn yet
//we will draw it here, however this might cause a display glitch.
//If several points
//are sent and the second to the last is an invalid point then this
//will draw the last point, but in the next "update" a valid point could
//be added. In this case there will be an extra point drawn. In this case
//there should just be a line. This could be fixed by removing the extra point
//on the next draw.
if (undrawnPoint != null){
drawPoint(undrawnPoint);
undrawnPoint = null;
}
//System.out.println("size:"+yValues.size());
}
/**
* @param ppx
* @param ppy
*/
protected void drawPoint(float ppx, float ppy)
{
// If we are not connecting points and there is a marker
// then we don't need to draw these one pixel points
// It is not clear when these points are drawn
// in generall they won't be seen because the line will be
// be on top of them. I believe they are to handle
// the case when there is a discontinutity before and
// after the current point. In that case this needs
// be used.
if(!isConnectPoints() || markerPath != null) return;
//Make a vertical "dot" of 1 pixel
path.moveTo(ppx, ppy);
path.lineTo(ppx, ppy + 1);//TODO Is 1 because of MAC OS X
}
/**
* @param ppx
* @param ppy
*/
private void drawPoint(Point2D p)
{
//Make a vertical "dot" of 1 pixel
drawPoint((float)p.getX(), (float)p.getY());
}
protected void drawPointMarker(float ppx, float ppy, int sample)
{
if(markerPath != null){
GeneralPath newMarker = (GeneralPath)markerPath.clone();
java.awt.Rectangle bounds = newMarker.getBounds();
float needDX = (ppx - (bounds.x + bounds.width/2));
float needDY = (ppy - (bounds.y + bounds.height/2));
newMarker.transform(AffineTransform.getTranslateInstance(needDX, needDY));
markerListPath.append(newMarker, false);
}
}
/**
* Returns a copy of itself
*/
public Graphable getCopy()
{
DataGraphable g = new DataGraphable();
g.setColor(lineColor);
g.setLineWidth(lineWidth);
g.setDataStore(dataStore);
//FIXME Add values to the vector... is that enough?
//for(int i=0; i<yValues.size(); i++){
// g.yValues.add(yValues.elementAt(i));
return g;
}
/**
* Set this to true if you want the channel numbers presented
* to the outside to always start at 0.
* This is to abstract the case where the datastore has a dt.
* In that case the dt (usually x) channel of the datastore is -1
*
* So if useVirtualChannels is true then channel 0 will really
* be -1 of the datastore if it has a dt or 0 if it doesn't.
* The other channels will be shifted too.
*
* This is useful when a single datagraphable can have different
* datastores plugged into it. Some of which have dts and some
* don't.
*/
public void setUseVirtualChannels(boolean flag)
{
useVirtualChannels = flag;
}
public boolean useVirtualChannels()
{
return useVirtualChannels;
}
/**
* @return Returns the channelX.
*/
public int getChannelX()
{
return channelX;
}
/**
* @param channelX The channelX to set.
*/
public void setChannelX(int channelX)
{
if (channelX < -1){
channelX = -1;
}
this.channelX = channelX;
}
protected boolean channelsNeedAdjusting()
{
// If this graphable is not using virtual channels then adjusting is
// not needed. There might still be some virtualChannels being used by the
// dataStore itself.
if(!useVirtualChannels) {
return false;
}
// Need to check if the data store is using virtual channels itself
// if it is, then we don't need to adjust them twice.
DataStore dStore = getDataStore();
if((dStore instanceof ProducerDataStore) &&
((ProducerDataStore)dStore).useVirtualChannels()) {
return false;
}
// If we have a dt channel then the channels need to be adjusted.
return hasDtChannel();
}
protected int getDataStoreChannelX()
{
if(channelsNeedAdjusting()){
return channelX - 1;
}
return channelX;
}
/**
* @return Returns the channelY.
*/
public int getChannelY()
{
return channelY;
}
/**
* @param channelY The channelY to set.
*/
public void setChannelY(int channelY)
{
if (channelY < -1){
channelY = -1;
}
this.channelY = channelY;
}
protected int getDataStoreChannelY()
{
if(channelsNeedAdjusting()){
return channelY - 1;
}
return channelY;
}
/**
* @return Returns the connectPoints.
*/
public boolean isConnectPoints()
{
return connectPoints;
}
/**
* @param connectPoints The connectPoints to set.
*/
public void setConnectPoints(boolean connectPoints)
{
if (this.connectPoints == connectPoints) return;
this.connectPoints = connectPoints;
forceRecalculate();
notifyChange();
}
/* //Debugging purposes
public void setData(Vector xValues, Vector yValues)
{
this.xValues = xValues;
this.yValues = yValues;
needUpdate = true;
needUpdateDataReceived = false;
}
*/
/**
* @return Returns the autoRepaintData.
*/
public boolean isAutoRepaintData()
{
return autoRepaintData;
}
/**
* @param autoRepaintData The autoRepaintData to set.
*/
public void setAutoRepaintData(boolean autoRepaintData)
{
this.autoRepaintData = autoRepaintData;
}
/**
* @see org.concord.graph.engine.DefaultGraphable#notifyChange()
*/
protected void notifyChange()
{
if (autoRepaintData){
super.notifyChange();
}
}
/**
* @see org.concord.graph.engine.DefaultGraphable#notifyChange()
*/
public void repaint()
{
if (needUpdate){
super.notifyChange();
}
}
/**
* This method is used to set the style of marker.
* If it is null then no marker is drawn. A marker
* is a shape drawn at each data point on the graph.
*
* @param userPath
*/
public void setMarkerPath(GeneralPath userPath){
markerPath = userPath;
// this should probably all be put into the
// the setMarkerPath method.
forceRecalculate();
notifyChange();
}
/**
* Set this to true if you want the markers to be filled in
* @param fillMarkers
*/
public void setFillMarkers(boolean fillMarkers)
{
this.fillMarkers = fillMarkers;
}
public boolean isFillMarkers()
{
return fillMarkers;
}
public void setMarkerColor(Color markerColor)
{
this.markerColor = markerColor;
}
public Color getMarkerColor()
{
return markerColor;
}
/**
* @return Returns the showCrossPoint.
*/
public boolean isShowCrossPoint()
{
return markerPath == CROSS_MARKER_PATH;
}
/**
* @param showCrossPoint The showCrossPoint to set.
*/
public void setShowCrossPoint(boolean showCrossPoint)
{
if (showCrossPoint) {
// if we are already showing the same marker path then
// we don't need to update it
if(markerPath == CROSS_MARKER_PATH) return;
setMarkerPath(CROSS_MARKER_PATH);
} else {
setMarkerPath(null);
}
}
/**
* This returns the data producer of this graphable.
*
* @return Returns the data producer.
*/
public DataProducer getDataProducer()
{
if(internalProducerDataStore) {
ProducerDataStore pDataStore = (ProducerDataStore)dataStore;
return pDataStore.getDataProducer();
}
return null;
}
/**
* This will return a data producer related to this graphable.
* If setDataProducer was called then that prodcuer will be returned.
* If setDataStore was called with a ProducerDataStore, then the
* producer of that datastore will be returned.
*
* @return
*/
public DataProducer findDataProducer()
{
// This class internally creates a producer data store when
// the setDataProducer method is called. So we just need
// to check for those types of dataStores
if(dataStore instanceof ProducerDataStore) {
return ((ProducerDataStore)dataStore).getDataProducer();
}
return null;
}
public float getMinXValue()
{
if(!validMinMax) {
return Float.NaN;
}
return minXValue;
}
public float getMaxXValue()
{
if(!validMinMax) {
return Float.NaN;
}
return maxXValue;
}
public float getMinYValue()
{
if(!validMinMax) {
return Float.NaN;
}
return minYValue;
}
public float getMaxYValue()
{
if(!validMinMax) {
return Float.NaN;
}
return maxYValue;
}
/* (non-Javadoc)
* @see org.concord.framework.data.stream.DataStoreListener#dataAdded(org.concord.framework.data.stream.DataStoreEvent)
*/
public void dataAdded(DataStoreEvent evt)
{
needUpdate = true;
notifyChange();
}
protected synchronized void forceRecalculate()
{
needUpdate = true;
needRecalculate = true;
// You can't count on this value staying -1
// because the update function might be in the middle
// of running. At the end of the update function this value
// is changed.
lastValueCalculated = -1;
}
/* (non-Javadoc)
* @see org.concord.framework.data.stream.DataStoreListener#dataRemoved(org.concord.framework.data.stream.DataStoreEvent)
*/
public void dataRemoved(DataStoreEvent evt)
{
forceRecalculate();
notifyChange();
}
/**
* @see org.concord.framework.data.stream.DataStoreListener#dataChanged(org.concord.framework.data.stream.DataStoreEvent)
*/
public void dataChanged(DataStoreEvent evt)
{
forceRecalculate();
notifyChange();
}
protected boolean hasDtChannel()
{
DataStore dStore = getDataStore();
if((!(dStore instanceof AutoIncrementDataStore))) {
return false;
}
return ((AutoIncrementDataStore)dStore).isAutoIncrementing();
}
/**
* @see org.concord.framework.data.stream.DataStoreListener#dataChannelDescChanged(org.concord.framework.data.stream.DataStoreEvent)
*/
public void dataChannelDescChanged(DataStoreEvent evt)
{
notifyChange();
}
/**
* Even if setDataStore has not been call this might return
* a non null value. If setDataProducer was called then an
* internal ProducerDataStore was created, and that would be
* returned here.
*
* @return Returns the dataStore.
*/
public DataStore getDataStore()
{
return dataStore;
}
/**
* @see org.concord.framework.data.stream.DataStore#getTotalNumSamples()
*/
public int getTotalNumSamples()
{
if (dataStore == null) return 0;
return dataStore.getTotalNumSamples();
}
/**
* @see org.concord.framework.data.stream.DataStore#getTotalNumChannels()
*/
public int getTotalNumChannels()
{
return 2;
}
/**
* @see org.concord.framework.data.stream.DataStore#getValueAt(int, int)
*/
public Object getValueAt(int numSample, int numChannel)
{
if (numChannel == 0){
return dataStore.getValueAt(numSample, getDataStoreChannelX());
}
else if (numChannel == 1){
return dataStore.getValueAt(numSample, getDataStoreChannelY());
}
return null;
}
/**
* Only works with a Writable Data Store!
* @param numSample
* @param numChannel
* @param value
*/
public void setValueAt(int numSample, int numChannel, Object value)
{
//Only works with a Writable Data Store!
if (!(dataStore instanceof WritableDataStore)) {
throw new UnsupportedOperationException("The Data Store "+dataStore+" is not Writable!");
}
if (numChannel == 0){
((WritableDataStore)dataStore).setValueAt(numSample, getDataStoreChannelX(), value);
}
else if (numChannel == 1){
((WritableDataStore)dataStore).setValueAt(numSample, getDataStoreChannelY(), value);
}
}
/**
* Only works with a Writable Data Store!
* @param numSample
*/
public void removeSampleAt(int numSample)
{
//Only works with a Writable Data Store!
if (!(dataStore instanceof WritableDataStore)) {
throw new UnsupportedOperationException("The Data Store "+dataStore+" is not Writable!");
}
((WritableDataStore)dataStore).removeSampleAt(numSample);
}
/**
* Only works with a Writable Data Store!
* @param numSample
*/
public void insertSampleAt(int numSample)
{
//Only works with a Writable Data Store!
if (!(dataStore instanceof WritableDataStore)) {
throw new UnsupportedOperationException("The Data Store "+dataStore+" is not Writable!");
}
((WritableDataStore)dataStore).insertSampleAt(numSample);
}
public void addPoint(double x, double y)
{
//Only works with a Writable Data Store!
if (!(dataStore instanceof WritableDataStore)) {
throw new UnsupportedOperationException("The Data Store "+dataStore+" is not Writable!");
}
int newPointIndex = getTotalNumSamples();
setValueAt(newPointIndex, 0, new Float(x));
setValueAt(newPointIndex, 1, new Float(y));
}
/**
* @see org.concord.framework.data.stream.DataStore#addDataStoreListener(org.concord.framework.data.stream.DataStoreListener)
*/
public void addDataStoreListener(DataStoreListener l)
{
if (dataStore == null) return;
dataStore.addDataStoreListener(l);
}
/**
* @see org.concord.framework.data.stream.DataStore#removeDataStoreListener(org.concord.framework.data.stream.DataStoreListener)
*/
public void removeDataStoreListener(DataStoreListener l)
{
if (dataStore == null) return;
dataStore.removeDataStoreListener(l);
}
/**
* Channel 0 is the x channel of the graphable and
* Channel 1 is the y channel of the graphable
*
* @see org.concord.framework.data.stream.DataStore#getDataChannelDescription(int)
*/
public DataChannelDescription getDataChannelDescription(int numChannel)
{
if (dataStore == null) return null;
if (numChannel == 0){
return dataStore.getDataChannelDescription(getDataStoreChannelX());
}
else if (numChannel == 1){
return dataStore.getDataChannelDescription(getDataStoreChannelY());
}
throw new ArrayIndexOutOfBoundsException("requested channel: " + numChannel +
" is not valid for DataGraphable");
}
/**
* @see org.concord.framework.data.stream.DataStore#clearValues()
*/
public void clearValues()
{
reset();
}
/**
* @param p
* @return
*/
public int getIndexValueAtDisplay(Point p, int threshold)
{
Point2D pW, pD;
float x, y;
Object objVal;
CoordinateSystem cs = getGraphArea().getCoordinateSystem();
for (int i=0; i<getTotalNumSamples(); i++){
objVal = getValueAt(i, 0);
if (!(objVal instanceof Float)) continue;
x = ((Float)objVal).floatValue();
objVal = getValueAt(i, 1);
if (!(objVal instanceof Float)) continue;
y = ((Float)objVal).floatValue();
pW = new Point2D.Double(x,y);
pD = cs.transformToDisplay(pW);
//Threshold
if (Math.abs(pD.getX() - p.getX()) <= threshold &&
Math.abs(pD.getY() - p.getY()) <= threshold){
return i;
}
}
return -1;
}
/*
//It would be nice to have something like this:
public float[] getYValue(float xValue)
{
}
public float[] getYValue(float xValue)
{
}
*/
public void releaseAll()
{
if (dataStore != null){
dataStore.removeDataStoreListener(this);
}
if (graphArea != null){
graphArea.removeChangeListener(this);
}
remove();
}
public void setLocked(boolean locked) {
this.locked = locked;
}
public boolean isLocked() {
return locked;
}
/**
* @return Returns the lineWidth.
*/
public float getLineWidth()
{
return lineWidth;
}
} |
package org.digidoc4j.impl;
import eu.europa.ec.markt.dss.DSSXMLUtils;
import eu.europa.ec.markt.dss.validation102853.report.Conclusion;
import eu.europa.ec.markt.dss.validation102853.report.Reports;
import eu.europa.ec.markt.dss.validation102853.report.SimpleReport;
import org.digidoc4j.ValidationResult;
import org.digidoc4j.exceptions.DigiDoc4JException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.util.ArrayList;
import java.util.List;
/**
* Overview of errors and warnings for BDoc
*/
public class ValidationResultForBDoc implements ValidationResult {
static final Logger logger = LoggerFactory.getLogger(ValidationResultForDDoc.class);
private List<DigiDoc4JException> errors = new ArrayList<>();
private List<DigiDoc4JException> warnings = new ArrayList<>();
private Document reportDocument;
/**
* Constructor
*
* @param report creates validation result from report
* @param manifestErrors was there any issues with manifest file
*/
public ValidationResultForBDoc(Reports report, List<String> manifestErrors) {
logger.debug("");
initializeReportDOM();
for (String manifestError : manifestErrors) {
errors.add(new DigiDoc4JException(manifestError));
}
do {
SimpleReport simpleReport = report.getSimpleReport();
String signatureId = simpleReport.getSignatureIds().get(0);
List<Conclusion.BasicInfo> results = simpleReport.getErrors(signatureId);
for (Conclusion.BasicInfo result : results) {
String message = result.toString();
logger.debug("Validation error: " + message);
errors.add(new DigiDoc4JException(message));
}
results = simpleReport.getWarnings(signatureId);
for (Conclusion.BasicInfo result : results) {
String message = result.toString();
logger.debug("Validation warning: " + message);
warnings.add(new DigiDoc4JException(message));
}
createXMLReport(simpleReport);
if (logger.isDebugEnabled()) {
logger.debug(simpleReport.toString());
}
report = report.getNextReports();
} while (report != null);
addErrorsToXMLReport(manifestErrors);
}
private void addErrorsToXMLReport(List<String> manifestErrors) {
for (int i = 0; i < manifestErrors.size(); i++) {
Element manifestValidation = reportDocument.createElement("ManifestValidation");
manifestValidation.setAttribute("Error", Integer.toString(i));
Element manifestChild = reportDocument.createElement("ManifestError");
manifestChild.setAttribute("Error", manifestErrors.get(i));
manifestValidation.appendChild(manifestChild);
reportDocument.getDocumentElement().appendChild(manifestValidation);
}
}
private void initializeReportDOM() {
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
reportDocument = docBuilder.newDocument();
reportDocument.appendChild(reportDocument.createElement("ValidationReport"));
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
}
private void createXMLReport(SimpleReport simpleReport) {
Element signatureValidation = reportDocument.createElement("SignatureValidation");
signatureValidation.setAttribute("ID", simpleReport.getSignatureIds().get(0));
reportDocument.getDocumentElement().appendChild(signatureValidation);
Element rootElement = simpleReport.getRootElement();
NodeList childNodes = rootElement.getChildNodes();
for (int i = 0; i < childNodes.getLength(); i++) {
Node node = childNodes.item(i);
removeNamespace(node);
Node importNode = reportDocument.importNode(node, true);
signatureValidation.appendChild(importNode);
}
}
private static void removeNamespace(Node node) {
Document document = node.getOwnerDocument();
if (node.getNodeType() == Node.ELEMENT_NODE) {
document.renameNode(node, null, node.getNodeName());
}
NodeList list = node.getChildNodes();
for (int i = 0; i < list.getLength(); ++i) {
removeNamespace(list.item(i));
}
}
@Override
public List<DigiDoc4JException> getErrors() {
return errors;
}
@Override
public List<DigiDoc4JException> getWarnings() {
return warnings;
}
@Override
public boolean hasErrors() {
return (errors.size() != 0);
}
@Override
public boolean hasWarnings() {
return (warnings.size() != 0);
}
@Override
public boolean isValid() {
return !hasErrors();
}
@Override
public String getReport() {
return new String(DSSXMLUtils.transformDomToByteArray(reportDocument));
}
} |
package org.exist.xmldb;
import java.util.Iterator;
import org.exist.EXistException;
import org.exist.dom.DocumentImpl;
import org.exist.security.Permission;
import org.exist.security.PermissionDeniedException;
import org.exist.security.SecurityManager;
import org.exist.security.User;
import org.exist.storage.BrokerPool;
import org.exist.storage.DBBroker;
import org.exist.storage.lock.Lock;
import org.exist.storage.txn.TransactionManager;
import org.exist.storage.txn.Txn;
import org.exist.util.LockException;
import org.exist.util.SyntaxException;
import org.xmldb.api.base.Collection;
import org.xmldb.api.base.ErrorCodes;
import org.xmldb.api.base.Resource;
import org.xmldb.api.base.XMLDBException;
public class LocalUserManagementService implements UserManagementService {
private LocalCollection collection;
private BrokerPool pool;
private User user;
public LocalUserManagementService(
User user,
BrokerPool pool,
LocalCollection collection) {
this.pool = pool;
this.collection = collection;
this.user = user;
}
public void addUser(User u) throws XMLDBException {
org.exist.security.SecurityManager manager = pool.getSecurityManager();
if (!manager.hasAdminPrivileges(user))
throw new XMLDBException(
ErrorCodes.PERMISSION_DENIED,
" you are not allowed to change this user");
if (manager.hasUser(u.getName()))
throw new XMLDBException(
ErrorCodes.VENDOR_ERROR,
"user " + user.getName() + " exists");
manager.setUser(u);
}
public void setPermissions(Resource resource, Permission perm)
throws XMLDBException {
org.exist.security.SecurityManager manager = pool.getSecurityManager();
DocumentImpl document = null;
DBBroker broker = null;
try {
broker = pool.get(user);
document = ((AbstractEXistResource) resource).openDocument(broker, Lock.WRITE_LOCK);
if (!(document.getPermissions().getOwner().equals(user.getName())
|| manager.hasAdminPrivileges(user)))
throw new XMLDBException(
ErrorCodes.PERMISSION_DENIED,
"you are not the owner of this resource; owner = "
+ document.getPermissions().getOwner());
document.setPermissions(perm);
collection.saveCollection();
} catch (EXistException e) {
throw new XMLDBException(
ErrorCodes.VENDOR_ERROR,
e.getMessage(),
e);
} finally {
((AbstractEXistResource)resource).closeDocument(document, Lock.WRITE_LOCK);
pool.release(broker);
}
}
public void setPermissions(Collection child, Permission perm)
throws XMLDBException {
org.exist.security.SecurityManager manager = pool.getSecurityManager();
org.exist.collections.Collection coll = null;
DBBroker broker = null;
TransactionManager transact = pool.getTransactionManager();
Txn transaction = transact.beginTransaction();
try {
broker = pool.get(user);
coll = broker.openCollection(collection.getPath(), Lock.WRITE_LOCK);
if(coll == null)
throw new XMLDBException(ErrorCodes.INVALID_COLLECTION, "Collection " + collection.getPath() +
" not found");
if (!collection.checkOwner(coll, user) && !manager.hasAdminPrivileges(user)) {
transact.abort(transaction);
throw new XMLDBException(
ErrorCodes.PERMISSION_DENIED,
"you are not the owner of this collection");
}
coll.setPermissions(perm);
broker.saveCollection(transaction, coll);
transact.commit(transaction);
broker.flush();
} catch (EXistException e) {
transact.abort(transaction);
throw new XMLDBException(
ErrorCodes.VENDOR_ERROR,
e.getMessage(),
e);
} catch (PermissionDeniedException e) {
transact.abort(transaction);
throw new XMLDBException(
ErrorCodes.PERMISSION_DENIED,
e.getMessage(),
e);
} catch (LockException e) {
transact.abort(transaction);
throw new XMLDBException(
ErrorCodes.VENDOR_ERROR,
"Failed to acquire lock on collections.dbx",
e);
} finally {
if(coll != null)
coll.release();
pool.release(broker);
}
}
public void chmod(String modeStr) throws XMLDBException {
org.exist.security.SecurityManager manager = pool.getSecurityManager();
org.exist.collections.Collection coll = null;
DBBroker broker = null;
TransactionManager transact = pool.getTransactionManager();
Txn transaction = transact.beginTransaction();
try {
broker = pool.get(user);
coll = broker.openCollection(collection.getPath(), Lock.WRITE_LOCK);
if(coll == null)
throw new XMLDBException(ErrorCodes.INVALID_COLLECTION, "Collection " + collection.getPath() +
" not found");
if (!collection.checkOwner(coll, user) && !manager.hasAdminPrivileges(user)) {
transact.abort(transaction);
throw new XMLDBException(
ErrorCodes.PERMISSION_DENIED,
"you are not the owner of this collection");
}
coll.setPermissions(modeStr);
broker.saveCollection(transaction, coll);
transact.commit(transaction);
broker.flush();
} catch (SyntaxException e) {
transact.abort(transaction);
throw new XMLDBException(
ErrorCodes.VENDOR_ERROR,
e.getMessage(),
e);
} catch (LockException e) {
transact.abort(transaction);
throw new XMLDBException(
ErrorCodes.VENDOR_ERROR,
"Failed to acquire lock on collections.dbx",
e);
} catch (EXistException e) {
transact.abort(transaction);
throw new XMLDBException(
ErrorCodes.VENDOR_ERROR,
e.getMessage(),
e);
} catch (PermissionDeniedException e) {
transact.abort(transaction);
throw new XMLDBException(
ErrorCodes.PERMISSION_DENIED,
e.getMessage(),
e);
} finally {
if(coll != null)
coll.release();
pool.release(broker);
}
}
public void chmod(Resource resource, int mode) throws XMLDBException {
org.exist.security.SecurityManager manager = pool.getSecurityManager();
DocumentImpl document = null;
DBBroker broker = null;
TransactionManager transact = pool.getTransactionManager();
Txn transaction = transact.beginTransaction();
try {
broker = pool.get(user);
document = ((AbstractEXistResource) resource).openDocument(broker, Lock.WRITE_LOCK);
if (!document.getPermissions().getOwner().equals(user.getName())
&& !manager.hasAdminPrivileges(user)) {
transact.abort(transaction);
throw new XMLDBException(
ErrorCodes.PERMISSION_DENIED,
"you are not the owner of this resource");
}
document.setPermissions(mode);
broker.storeDocument(transaction, document);
transact.commit(transaction);
} catch (EXistException e) {
transact.abort(transaction);
throw new XMLDBException(
ErrorCodes.VENDOR_ERROR,
e.getMessage(),
e);
} finally {
((AbstractEXistResource) resource).closeDocument(document, Lock.WRITE_LOCK);
pool.release(broker);
}
}
public void chmod(int mode) throws XMLDBException {
org.exist.security.SecurityManager manager = pool.getSecurityManager();
org.exist.collections.Collection coll = null;
DBBroker broker = null;
TransactionManager transact = pool.getTransactionManager();
Txn transaction = transact.beginTransaction();
try {
broker = pool.get(user);
coll = broker.openCollection(collection.getPath(), Lock.WRITE_LOCK);
if(coll == null)
throw new XMLDBException(ErrorCodes.INVALID_COLLECTION, "Collection " + collection.getPath() +
" not found");
if (!collection.checkOwner(coll, user) && !manager.hasAdminPrivileges(user)) {
transact.abort(transaction);
throw new XMLDBException(
ErrorCodes.PERMISSION_DENIED,
"you are not the owner of this collection");
}
coll.setPermissions(mode);
broker.saveCollection(transaction, coll);
transact.commit(transaction);
broker.flush();
} catch (EXistException e) {
transact.abort(transaction);
throw new XMLDBException(
ErrorCodes.VENDOR_ERROR,
e.getMessage(),
e);
} catch (PermissionDeniedException e) {
transact.abort(transaction);
throw new XMLDBException(
ErrorCodes.PERMISSION_DENIED,
e.getMessage(),
e);
} catch (LockException e) {
transact.abort(transaction);
throw new XMLDBException(
ErrorCodes.VENDOR_ERROR,
"Failed to acquire lock on collections.dbx",
e);
} finally {
if(coll != null)
coll.release();
pool.release(broker);
}
}
public void chmod(Resource resource, String modeStr)
throws XMLDBException {
org.exist.security.SecurityManager manager = pool.getSecurityManager();
DocumentImpl document = null;
DBBroker broker = null;
TransactionManager transact = pool.getTransactionManager();
Txn transaction = transact.beginTransaction();
try {
broker = pool.get(user);
document = ((AbstractEXistResource) resource).openDocument(broker, Lock.WRITE_LOCK);
if (!document.getPermissions().getOwner().equals(user.getName())
&& !manager.hasAdminPrivileges(user)) {
transact.abort(transaction);
throw new XMLDBException(
ErrorCodes.PERMISSION_DENIED,
"you are not the owner of this resource");
}
document.setPermissions(modeStr);
broker.storeDocument(transaction, document);
} catch (EXistException e) {
transact.abort(transaction);
throw new XMLDBException(
ErrorCodes.VENDOR_ERROR,
e.getMessage(),
e);
} catch (SyntaxException e) {
transact.abort(transaction);
throw new XMLDBException(
ErrorCodes.VENDOR_ERROR,
e.getMessage(),
e);
} finally {
((AbstractEXistResource) resource).closeDocument(document, Lock.WRITE_LOCK);
pool.release(broker);
}
}
public void chown(User u, String group) throws XMLDBException {
org.exist.security.SecurityManager manager = pool.getSecurityManager();
if (!manager.hasUser(u.getName()))
throw new XMLDBException(ErrorCodes.PERMISSION_DENIED, "Unknown user");
if (!manager.hasAdminPrivileges(user))
throw new XMLDBException(
ErrorCodes.PERMISSION_DENIED,
"need admin privileges for chown");
org.exist.collections.Collection coll = null;
DBBroker broker = null;
TransactionManager transact = pool.getTransactionManager();
Txn transaction = transact.beginTransaction();
try {
broker = pool.get(user);
coll = broker.openCollection(collection.getPath(), Lock.WRITE_LOCK);
coll.getPermissions().setOwner(u);
coll.getPermissions().setGroup(group);
broker.saveCollection(transaction, coll);
transact.commit(transaction);
broker.flush();
//broker.sync();
} catch (EXistException e) {
transact.abort(transaction);
throw new XMLDBException(
ErrorCodes.VENDOR_ERROR,
e.getMessage(),
e);
} catch (PermissionDeniedException e) {
transact.abort(transaction);
throw new XMLDBException(
ErrorCodes.PERMISSION_DENIED,
e.getMessage(),
e);
} finally {
if(coll != null)
coll.release();
pool.release(broker);
}
}
public void chown(Resource res, User u, String group)
throws XMLDBException {
org.exist.security.SecurityManager manager = pool.getSecurityManager();
if (!manager.hasUser(u.getName()))
throw new XMLDBException(ErrorCodes.PERMISSION_DENIED, "Unknown user");
if (!manager.hasAdminPrivileges(user))
throw new XMLDBException(
ErrorCodes.PERMISSION_DENIED,
"need admin privileges for chown");
DocumentImpl document = null;
DBBroker broker = null;
try {
broker = pool.get(user);
document = ((AbstractEXistResource) res).openDocument(broker, Lock.WRITE_LOCK);
Permission perm = document.getPermissions();
perm.setOwner(u);
perm.setGroup(group);
collection.saveCollection();
broker.flush();
} catch (EXistException e) {
throw new XMLDBException(
ErrorCodes.VENDOR_ERROR,
e.getMessage(),
e);
} finally {
((AbstractEXistResource) res).closeDocument(document, Lock.WRITE_LOCK);
pool.release(broker);
}
}
/* (non-Javadoc)
* @see org.exist.xmldb.UserManagementService#hasUserLock(org.xmldb.api.base.Resource)
*/
public String hasUserLock(Resource res) throws XMLDBException {
DocumentImpl doc = null;
DBBroker broker = null;
try {
broker = pool.get(user);
doc = ((AbstractEXistResource) res).openDocument(broker, Lock.READ_LOCK);
User lockOwner = doc.getUserLock();
return lockOwner == null ? null : lockOwner.getName();
} catch (EXistException e) {
throw new XMLDBException(
ErrorCodes.VENDOR_ERROR,
e.getMessage(),
e);
} finally {
((AbstractEXistResource) res).closeDocument(doc, Lock.READ_LOCK);
pool.release(broker);
}
}
public void lockResource(Resource res, User u) throws XMLDBException {
DocumentImpl doc = null;
DBBroker broker = null;
try {
broker = pool.get(user);
doc = ((AbstractEXistResource) res).openDocument(broker, Lock.WRITE_LOCK);
if (!doc.getPermissions().validate(user, Permission.UPDATE))
throw new XMLDBException(ErrorCodes.PERMISSION_DENIED,
"User is not allowed to lock resource " + res.getId());
org.exist.security.SecurityManager manager = pool.getSecurityManager();
if(!(user.equals(u) || manager.hasAdminPrivileges(user))) {
throw new XMLDBException(ErrorCodes.PERMISSION_DENIED,
"User " + user.getName() + " is not allowed to lock resource for " +
"user " + u.getName());
}
User lockOwner = doc.getUserLock();
if(lockOwner != null) {
if(lockOwner.equals(u))
return;
else if(!manager.hasAdminPrivileges(user))
throw new XMLDBException(ErrorCodes.PERMISSION_DENIED,
"Resource is already locked by user " + lockOwner.getName());
}
doc.setUserLock(u);
collection.saveCollection();
} catch (EXistException e) {
throw new XMLDBException(ErrorCodes.VENDOR_ERROR,
e.getMessage(), e);
} finally {
((AbstractEXistResource) res).closeDocument(doc, Lock.WRITE_LOCK);
pool.release(broker);
}
}
public void unlockResource(Resource res) throws XMLDBException {
DocumentImpl doc = null;
DBBroker broker = null;
try {
broker = pool.get(user);
doc = ((AbstractEXistResource) res).openDocument(broker, Lock.WRITE_LOCK);
if (!doc.getPermissions().validate(user, Permission.UPDATE))
throw new XMLDBException(ErrorCodes.PERMISSION_DENIED,
"User is not allowed to lock resource " + res.getId());
org.exist.security.SecurityManager manager = pool.getSecurityManager();
User lockOwner = doc.getUserLock();
if(lockOwner != null && !(lockOwner.equals(user) || manager.hasAdminPrivileges(user))) {
throw new XMLDBException(ErrorCodes.PERMISSION_DENIED,
"Resource is already locked by user " + lockOwner.getName());
}
doc.setUserLock(null);
collection.saveCollection();
} catch (EXistException e) {
throw new XMLDBException(ErrorCodes.VENDOR_ERROR,
e.getMessage(), e);
} finally {
((AbstractEXistResource) res).closeDocument(doc, Lock.WRITE_LOCK);
pool.release(broker);
}
}
public String getName() {
return "UserManagementService";
}
public Permission getPermissions(Collection coll) throws XMLDBException {
if (coll instanceof LocalCollection)
return ((LocalCollection) coll).getCollection().getPermissions();
return null;
}
public Permission getPermissions(Resource resource) throws XMLDBException {
DBBroker broker = null;
DocumentImpl doc = null;
try {
broker = pool.get(user);
doc = ((AbstractEXistResource) resource).openDocument(broker, Lock.READ_LOCK);
return doc.getPermissions();
} catch (EXistException e) {
throw new XMLDBException(
ErrorCodes.VENDOR_ERROR,
e.getMessage(),
e);
} finally {
((AbstractEXistResource) resource).closeDocument(doc, Lock.READ_LOCK);
pool.release(broker);
}
}
public Permission[] listResourcePermissions() throws XMLDBException {
DBBroker broker = null;
org.exist.collections.Collection c = null;
try {
broker = pool.get(user);
c = broker.openCollection(collection.getPath(), Lock.READ_LOCK);
if (!c .getPermissions().validate(user, Permission.READ))
return new Permission[0];
Permission perms[] =
new Permission[c.getDocumentCount()];
int j = 0;
DocumentImpl doc;
for (Iterator i = c.iterator(broker); i.hasNext(); j++) {
doc = (DocumentImpl) i.next();
perms[j] = doc.getPermissions();
}
return perms;
} catch (EXistException e) {
throw new XMLDBException(
ErrorCodes.VENDOR_ERROR,
e.getMessage(),
e);
} finally {
if(c != null)
c.release();
pool.release(broker);
}
}
public Permission[] listCollectionPermissions() throws XMLDBException {
DBBroker broker = null;
org.exist.collections.Collection c = null;
try {
broker = pool.get(user);
c = broker.openCollection(collection.getPath(), Lock.READ_LOCK);
if (!c.getPermissions().validate(user, Permission.READ))
return new Permission[0];
Permission perms[] =
new Permission[c.getChildCollectionCount()];
String child;
org.exist.collections.Collection childColl;
int j = 0;
for (Iterator i = c.collectionIterator();
i.hasNext();
j++) {
child = (String) i.next();
childColl =
broker.openCollection(collection.getPath() + '/' + child, Lock.READ_LOCK);
if(childColl != null) {
try {
perms[j] = childColl.getPermissions();
} finally {
childColl.release();
}
}
}
return perms;
} catch (EXistException e) {
throw new XMLDBException(
ErrorCodes.VENDOR_ERROR,
e.getMessage(),
e);
} finally {
if(c != null)
c.release();
pool.release(broker);
}
}
public String getProperty(String property) throws XMLDBException {
return null;
}
public User getUser(String name) throws XMLDBException {
org.exist.security.SecurityManager manager = pool.getSecurityManager();
return manager.getUser(name);
}
public User[] getUsers() throws XMLDBException {
org.exist.security.SecurityManager manager = pool.getSecurityManager();
return manager.getUsers();
}
public String[] getGroups() throws XMLDBException {
org.exist.security.SecurityManager manager = pool.getSecurityManager();
return manager.getGroups();
}
public String getVersion() {
return "1.0";
}
public void removeUser(User u) throws XMLDBException {
org.exist.security.SecurityManager manager = pool.getSecurityManager();
if (!manager.hasAdminPrivileges(user))
throw new XMLDBException(
ErrorCodes.PERMISSION_DENIED,
"you are not allowed to remove users");
try {
manager.deleteUser(u);
} catch (PermissionDeniedException e) {
throw new XMLDBException(
ErrorCodes.PERMISSION_DENIED,
"unable to remove user " + u.getName(),
e);
}
}
public void setCollection(Collection collection) throws XMLDBException {
this.collection = (LocalCollection) collection;
}
public void setProperty(String property, String value)
throws XMLDBException {
}
public void updateUser(User u) throws XMLDBException {
org.exist.security.SecurityManager manager = pool.getSecurityManager();
if (!(u.getName().equals(user.getName())
|| manager.hasAdminPrivileges(user)))
throw new XMLDBException(
ErrorCodes.PERMISSION_DENIED,
" you are not allowed to change this user");
if(u.getName().equals(SecurityManager.GUEST_USER))
throw new XMLDBException(
ErrorCodes.PERMISSION_DENIED,
"guest user cannot be modified");
User old = manager.getUser(u.getName());
if (old == null)
throw new XMLDBException(
ErrorCodes.PERMISSION_DENIED,
"user " + u.getName() + " does not exist");
for(Iterator i = u.getGroups(); i.hasNext(); ) {
String g = (String)i.next();
if(!(old.hasGroup(g) || manager.hasAdminPrivileges(user)))
throw new XMLDBException(
ErrorCodes.PERMISSION_DENIED,
"not allowed to change group memberships");
}
u.setUID(old.getUID());
manager.setUser(u);
}
} |
package org.helioviewer.jhv.plugins.swek;
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.image.BufferedImage;
import java.nio.FloatBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import javax.annotation.Nullable;
import javax.swing.ImageIcon;
import javax.swing.JCheckBox;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import org.helioviewer.jhv.astronomy.Position;
import org.helioviewer.jhv.astronomy.Sun;
import org.helioviewer.jhv.base.BufferUtils;
import org.helioviewer.jhv.base.FloatArray;
import org.helioviewer.jhv.base.scale.GridScale;
import org.helioviewer.jhv.base.scale.Transform;
import org.helioviewer.jhv.camera.Camera;
import org.helioviewer.jhv.display.Display;
import org.helioviewer.jhv.display.Viewport;
import org.helioviewer.jhv.events.JHVEvent;
import org.helioviewer.jhv.events.JHVEventCache;
import org.helioviewer.jhv.events.JHVEventHandler;
import org.helioviewer.jhv.events.JHVEventParameter;
import org.helioviewer.jhv.events.JHVPositionInformation;
import org.helioviewer.jhv.events.JHVRelatedEvents;
import org.helioviewer.jhv.events.SWEKGroup;
import org.helioviewer.jhv.gui.ComponentUtils;
import org.helioviewer.jhv.gui.ImageViewerGui;
import org.helioviewer.jhv.layers.AbstractLayer;
import org.helioviewer.jhv.layers.Movie;
import org.helioviewer.jhv.layers.TimespanListener;
import org.helioviewer.jhv.math.MathUtils;
import org.helioviewer.jhv.math.Quat;
import org.helioviewer.jhv.math.Vec2;
import org.helioviewer.jhv.math.Vec3;
import org.helioviewer.jhv.opengl.GLLine;
import org.helioviewer.jhv.opengl.GLHelper;
import org.helioviewer.jhv.opengl.GLText;
import org.helioviewer.jhv.opengl.GLTexture;
import org.json.JSONObject;
import com.jogamp.opengl.GL2;
// has to be public for state
public class SWEKLayer extends AbstractLayer implements TimespanListener, JHVEventHandler {
private static final SWEKPopupController controller = new SWEKPopupController(ImageViewerGui.getGLComponent());
private final JPanel optionsPanel;
private static final int DIVPOINTS = 10;
private static final double LINEWIDTH = 0.002;
private static final double LINEWIDTH_HIGHLIGHT = 0.003;
private static final double LINEWIDTH_CACTUS = 0.003;
private static final HashMap<String, GLTexture> iconCacheId = new HashMap<>();
private static final double ICON_SIZE = 0.1;
private static final double ICON_SIZE_HIGHLIGHTED = 0.16;
private boolean icons = true;
public SWEKLayer(JSONObject jo) {
if (jo != null)
icons = jo.optBoolean("icons", icons);
else
setEnabled(true);
optionsPanel = optionsPanel();
}
@Override
public void serialize(JSONObject jo) {
jo.put("icons", icons);
}
private static void bindTexture(GL2 gl, SWEKGroup group) {
String key = group.getName();
GLTexture tex = iconCacheId.get(key);
if (tex == null) {
ImageIcon icon = group.getIcon();
BufferedImage bi = new BufferedImage(icon.getIconWidth(), icon.getIconHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics graph = bi.createGraphics();
icon.paintIcon(null, graph, 0, 0);
graph.dispose();
tex = new GLTexture(gl);
tex.bind(gl, GL2.GL_TEXTURE_2D, GL2.GL_TEXTURE0);
GLTexture.copyBufferedImage2D(gl, bi);
iconCacheId.put(key, tex);
}
tex.bind(gl, GL2.GL_TEXTURE_2D, GL2.GL_TEXTURE0);
}
private static void interPolatedDraw(int mres, double r_start, double r_end, double t_start, double t_end, Quat q, FloatArray pos, FloatArray col, float[] color) {
Vec3 v = new Vec3();
for (int i = 0; i <= mres; i++) {
double alpha = 1. - i / (double) mres;
double r = alpha * r_start + (1 - alpha) * r_end;
double theta = alpha * t_start + (1 - alpha) * t_end;
v.x = r * Math.cos(theta);
v.y = r * Math.sin(theta);
Vec3 res = q.rotateInverseVector(v);
if (i == 0) {
pos.put3f((float) res.x, (float) res.y, (float) res.z);
col.put4f(BufferUtils.colorNull);
}
pos.put3f((float) res.x, (float) res.y, (float) res.z);
col.put4f(color);
}
pos.repeat3f();
col.put4f(BufferUtils.colorNull);
}
private final float texCoord1[][] = { { 0, 0 }, { 1, 0 }, { 1, 1 }, { 0, 1 } };
private final float texCoord2[][] = { { 1, 1 }, { 1, 0 }, { 0, 0 }, { 0, 1 } };
private final FloatBuffer texBuf1 = BufferUtils.newFloatBuffer(8);
private final FloatBuffer texBuf2 = BufferUtils.newFloatBuffer(8);
private void drawCactusArc(Viewport vp, GL2 gl, JHVRelatedEvents evtr, JHVEvent evt, long timestamp) {
double angularWidthDegree = SWEKData.readCMEAngularWidthDegree(evt);
double angularWidth = Math.toRadians(angularWidthDegree);
double principalAngleDegree = SWEKData.readCMEPrincipalAngleDegree(evt);
double principalAngle = Math.toRadians(principalAngleDegree);
double speed = SWEKData.readCMESpeed(evt);
double factor = Sun.RadiusMeter;
double distSunBegin = 2.4;
double distSun = distSunBegin + speed * (timestamp - evt.start) / factor;
int lineResolution = 2;
int angularResolution = (int) (angularWidthDegree / 4);
Quat q = evt.getPositionInformation().getEarth().toQuat();
Color c = evtr.getColor();
float[] color = { c.getRed() / 255f, c.getGreen() / 255f, c.getBlue() / 255f, 1 };
double thetaStart = principalAngle - angularWidth / 2.;
double thetaEnd = principalAngle + angularWidth / 2.;
FloatArray pos = new FloatArray();
FloatArray col = new FloatArray();
interPolatedDraw(angularResolution, distSun, distSun, thetaStart, principalAngle, q, pos, col, color);
interPolatedDraw(angularResolution, distSun, distSun, principalAngle, thetaEnd, q, pos, col, color);
interPolatedDraw(lineResolution, distSunBegin, distSun + 0.05, thetaStart, thetaStart, q, pos, col, color);
interPolatedDraw(lineResolution, distSunBegin, distSun + 0.05, principalAngle, principalAngle, q, pos, col, color);
interPolatedDraw(lineResolution, distSunBegin, distSun + 0.05, thetaEnd, thetaEnd, q, pos, col, color);
GLLine line = new GLLine();
line.init(gl);
line.setData(gl, pos.toBuffer(), col.toBuffer());
line.render(gl, vp.aspect, LINEWIDTH_CACTUS);
line.dispose(gl);
if (icons) {
bindTexture(gl, evtr.getSupplier().getGroup());
double sz = ICON_SIZE;
if (evtr.isHighlighted()) {
sz = ICON_SIZE_HIGHLIGHTED;
}
gl.glEnable(GL2.GL_TEXTURE_2D);
FloatBuffer vertex = BufferUtils.newFloatBuffer(12);
{
Vec3 v = new Vec3();
for (float[] el : texCoord1) {
double deltatheta = sz / distSun * (el[1] * 2 - 1);
double deltar = sz * (el[0] * 2 - 1);
double r = distSun + deltar;
double theta = principalAngle + deltatheta;
v.x = r * Math.cos(theta);
v.y = r * Math.sin(theta);
Vec3 res = q.rotateInverseVector(v);
BufferUtils.put3f(vertex, res);
}
vertex.rewind();
}
GLHelper.drawTexQuad(gl, vertex, texBuf1);
gl.glDisable(GL2.GL_TEXTURE_2D);
}
}
private static void drawPolygon(Camera camera, Viewport vp, GL2 gl, JHVRelatedEvents evtr, JHVEvent evt) {
JHVPositionInformation pi = evt.getPositionInformation();
if (pi == null)
return;
float[] points = pi.getBoundBox();
if (points.length == 0) {
return;
}
Color c = evtr.getColor();
float[] color = { c.getRed() / 255f, c.getGreen() / 255f, c.getBlue() / 255f, 1 };
// draw bounds
Vec3 pt = new Vec3();
float[] oldBoundaryPoint3d = new float[0];
Vec2 previous = null;
int plen = points.length / 3;
FloatArray pos = new FloatArray();
FloatArray col = new FloatArray();
for (int i = 0; i < plen; i++) {
if (oldBoundaryPoint3d.length != 0) {
for (int j = 0; j <= DIVPOINTS; j++) {
double alpha = 1. - j / (double) DIVPOINTS;
double xnew = alpha * oldBoundaryPoint3d[0] + (1 - alpha) * points[3 * i];
double ynew = alpha * oldBoundaryPoint3d[1] + (1 - alpha) * points[3 * i + 1];
double znew = alpha * oldBoundaryPoint3d[2] + (1 - alpha) * points[3 * i + 2];
double r = Math.sqrt(xnew * xnew + ynew * ynew + znew * znew);
if (Display.mode == Display.DisplayMode.Orthographic) {
float x = (float) (xnew / r);
float y = -(float) (ynew / r);
float z = (float) (znew / r);
if (j == 0) {
pos.put3f(x, y, z);
col.put4f(BufferUtils.colorNull);
}
pos.put3f(x, y, z);
col.put4f(color);
} else {
pt.x = xnew / r;
pt.y = ynew / r;
pt.z = znew / r;
if (j == 0) {
previous = GLHelper.drawVertex(camera, vp, pt, previous, pos, col, BufferUtils.colorNull);
}
previous = GLHelper.drawVertex(camera, vp, pt, previous, pos, col, color);
}
}
pos.repeat3f();
col.put4f(BufferUtils.colorNull);
}
oldBoundaryPoint3d = new float[] { points[3 * i], points[3 * i + 1], points[3 * i + 2] };
}
GLLine line = new GLLine();
line.init(gl);
line.setData(gl, pos.toBuffer(), col.toBuffer());
line.render(gl, vp.aspect, evtr.isHighlighted() ? LINEWIDTH_HIGHLIGHT : LINEWIDTH);
line.dispose(gl);
}
private void drawIcon(GL2 gl, JHVRelatedEvents evtr, JHVEvent evt) {
JHVPositionInformation pi = evt.getPositionInformation();
if (pi == null)
return;
Vec3 pt = pi.centralPoint();
if (pt != null) {
bindTexture(gl, evtr.getSupplier().getGroup());
Color color = evtr.getColor();
float alpha = 0.6f;
gl.glColor4f(color.getRed() / 255f * alpha, color.getGreen() / 255f * alpha, color.getBlue() / 255f * alpha, alpha);
if (evtr.isHighlighted()) {
drawImage3d(gl, pt.x, pt.y, pt.z, ICON_SIZE_HIGHLIGHTED, ICON_SIZE_HIGHLIGHTED);
} else {
drawImage3d(gl, pt.x, pt.y, pt.z, ICON_SIZE, ICON_SIZE);
}
}
}
private void drawImageScale(GL2 gl, double theta, double r, double width, double height) {
double width2 = width / 4.;
double height2 = height / 4.;
gl.glEnable(GL2.GL_TEXTURE_2D);
FloatBuffer vertex = BufferUtils.newFloatBuffer(12);
{
BufferUtils.put3f(vertex, (float) (theta + width2), (float) (r - height2), 0);
BufferUtils.put3f(vertex, (float) (theta + width2), (float) (r + height2), 0);
BufferUtils.put3f(vertex, (float) (theta - width2), (float) (r + height2), 0);
BufferUtils.put3f(vertex, (float) (theta - width2), (float) (r - height2), 0);
vertex.rewind();
}
GLHelper.drawTexQuad(gl, vertex, texBuf2);
gl.glDisable(GL2.GL_TEXTURE_2D);
}
private void drawIconScale(Camera camera, Viewport vp, GL2 gl, JHVRelatedEvents evtr, JHVEvent evt, GridScale scale, Transform xform) {
JHVPositionInformation pi = evt.getPositionInformation();
if (pi == null)
return;
Vec3 pt = pi.centralPoint();
if (pt != null) {
Position viewpoint = camera.getViewpoint();
pt = viewpoint.toQuat().rotateVector(pt);
Vec2 tf = xform.transform(viewpoint, pt, scale);
bindTexture(gl, evtr.getSupplier().getGroup());
if (evtr.isHighlighted()) {
drawImageScale(gl, tf.x * vp.aspect, tf.y, ICON_SIZE_HIGHLIGHTED, ICON_SIZE_HIGHLIGHTED);
} else {
drawImageScale(gl, tf.x * vp.aspect, tf.y, ICON_SIZE, ICON_SIZE);
}
}
}
private void drawCactusArcScale(Viewport vp, GL2 gl, JHVRelatedEvents evtr, JHVEvent evt, long timestamp, GridScale scale) {
double angularWidthDegree = SWEKData.readCMEAngularWidthDegree(evt);
double principalAngleDegree = SWEKData.readCMEPrincipalAngleDegree(evt) - 90;
double speed = SWEKData.readCMESpeed(evt);
double factor = Sun.RadiusMeter;
double distSunBegin = 2.4;
double distSun = distSunBegin + speed * (timestamp - evt.start) / factor;
double thetaStart = MathUtils.mapTo0To360(principalAngleDegree - angularWidthDegree / 2.);
double thetaEnd = MathUtils.mapTo0To360(principalAngleDegree + angularWidthDegree / 2.);
Color c = evtr.getColor();
float[] color = { c.getRed() / 255f, c.getGreen() / 255f, c.getBlue() / 255f, 1 };
float x, y;
FloatArray pos = new FloatArray();
FloatArray col = new FloatArray();
x = (float) (scale.getXValueInv(thetaStart) * vp.aspect);
y = (float) scale.getYValueInv(distSunBegin);
pos.put3f(x, y, 0);
col.put4f(BufferUtils.colorNull);
pos.put3f(x, y, 0);
col.put4f(color);
y = (float) scale.getYValueInv(distSun + 0.05);
pos.put3f(x, y, 0);
col.put4f(color);
pos.put3f(x, y, 0);
col.put4f(BufferUtils.colorNull);
x = (float) (scale.getXValueInv(principalAngleDegree) * vp.aspect);
y = (float) scale.getYValueInv(distSunBegin);
pos.put3f(x, y, 0);
col.put4f(BufferUtils.colorNull);
pos.put3f(x, y, 0);
col.put4f(color);
y = (float) scale.getYValueInv(distSun + 0.05);
pos.put3f(x, y, 0);
col.put4f(color);
pos.put3f(x, y, 0);
col.put4f(BufferUtils.colorNull);
x = (float) (scale.getXValueInv(thetaEnd) * vp.aspect);
y = (float) scale.getYValueInv(distSunBegin);
pos.put3f(x, y, 0);
col.put4f(BufferUtils.colorNull);
pos.put3f(x, y, 0);
col.put4f(color);
y = (float) scale.getYValueInv(distSun + 0.05);
pos.put3f(x, y, 0);
col.put4f(color);
pos.put3f(x, y, 0);
col.put4f(BufferUtils.colorNull);
y = (float) scale.getYValueInv(distSun);
pos.put3f(x, y, 0);
col.put4f(BufferUtils.colorNull);
pos.put3f(x, y, 0);
col.put4f(color);
x = (float) (scale.getXValueInv(thetaStart) * vp.aspect);
pos.put3f(x, y, 0);
col.put4f(color);
pos.put3f(x, y, 0);
col.put4f(BufferUtils.colorNull);
GLLine line = new GLLine();
line.init(gl);
line.setData(gl, pos.toBuffer(), col.toBuffer());
line.render(gl, vp.aspect, LINEWIDTH_CACTUS);
line.dispose(gl);
if (icons) {
bindTexture(gl, evtr.getSupplier().getGroup());
if (evtr.isHighlighted()) {
drawImageScale(gl, scale.getXValueInv(principalAngleDegree) * vp.aspect, scale.getYValueInv(distSun), ICON_SIZE_HIGHLIGHTED, ICON_SIZE_HIGHLIGHTED);
} else {
drawImageScale(gl, scale.getXValueInv(principalAngleDegree) * vp.aspect, scale.getYValueInv(distSun), ICON_SIZE, ICON_SIZE);
}
}
}
private void drawImage3d(GL2 gl, double x, double y, double z, double width, double height) {
y = -y;
double width2 = width / 2.;
double height2 = height / 2.;
Vec3 targetDir = new Vec3(x, y, z);
Quat q = Quat.rotate(Quat.createRotation(Math.atan2(x, z), Vec3.YAxis), Quat.createRotation(-Math.asin(y / targetDir.length()), Vec3.XAxis));
Vec3 p0 = q.rotateVector(new Vec3(-width2, -height2, 0));
Vec3 p1 = q.rotateVector(new Vec3(-width2, height2, 0));
Vec3 p2 = q.rotateVector(new Vec3(width2, height2, 0));
Vec3 p3 = q.rotateVector(new Vec3(width2, -height2, 0));
p0.add(targetDir);
p1.add(targetDir);
p2.add(targetDir);
p3.add(targetDir);
gl.glEnable(GL2.GL_TEXTURE_2D);
FloatBuffer vertex = BufferUtils.newFloatBuffer(12);
{
BufferUtils.put3f(vertex, p3);
BufferUtils.put3f(vertex, p2);
BufferUtils.put3f(vertex, p1);
BufferUtils.put3f(vertex, p0);
vertex.rewind();
}
GLHelper.drawTexQuad(gl, vertex, texBuf2);
gl.glDisable(GL2.GL_TEXTURE_2D);
}
private static final int MOUSE_OFFSET_X = 25;
private static final int MOUSE_OFFSET_Y = 25;
private static void drawText(Viewport vp, GL2 gl, JHVRelatedEvents mouseOverJHVEvent, int x, int y) {
ArrayList<String> txts = new ArrayList<>();
for (JHVEventParameter p : mouseOverJHVEvent.getClosestTo(controller.currentTime).getSimpleVisibleEventParameters()) {
String name = p.getParameterName();
if (name != "event_description" && name != "event_title") { // interned
txts.add(p.getParameterDisplayName() + " : " + p.getSimpleDisplayParameterValue());
}
}
GLText.drawText(gl, vp, txts, x + MOUSE_OFFSET_X, y + MOUSE_OFFSET_Y);
}
@Override
public void render(Camera camera, Viewport vp, GL2 gl) {
if (isVisible[vp.idx]) {
for (JHVRelatedEvents evtr : SWEKData.getActiveEvents(controller.currentTime)) {
JHVEvent evt = evtr.getClosestTo(controller.currentTime);
if (evt.isCactus()) {
drawCactusArc(vp, gl, evtr, evt, controller.currentTime);
} else {
drawPolygon(camera, vp, gl, evtr, evt);
if (icons) {
gl.glDisable(GL2.GL_DEPTH_TEST);
drawIcon(gl, evtr, evt);
gl.glEnable(GL2.GL_DEPTH_TEST);
}
}
}
}
}
@Override
public void renderScale(Camera camera, Viewport vp, GL2 gl) {
if (isVisible[vp.idx]) {
for (JHVRelatedEvents evtr : SWEKData.getActiveEvents(controller.currentTime)) {
JHVEvent evt = evtr.getClosestTo(controller.currentTime);
if (evt.isCactus() && (Display.mode == Display.DisplayMode.LogPolar || Display.mode == Display.DisplayMode.Polar)) {
drawCactusArcScale(vp, gl, evtr, evt, controller.currentTime, Display.mode.scale);
} else {
drawPolygon(camera, vp, gl, evtr, evt);
if (icons) {
gl.glDisable(GL2.GL_DEPTH_TEST);
drawIconScale(camera, vp, gl, evtr, evt, Display.mode.scale, Display.mode.xform);
gl.glEnable(GL2.GL_DEPTH_TEST);
}
}
}
}
}
@Override
public void renderFullFloat(Camera camera, Viewport vp, GL2 gl) {
if (SWEKPopupController.mouseOverJHVEvent != null) {
drawText(vp, gl, SWEKPopupController.mouseOverJHVEvent, SWEKPopupController.mouseOverX, SWEKPopupController.mouseOverY);
}
}
@Override
public void remove(GL2 gl) {
setEnabled(false);
dispose(gl);
}
@Override
public Component getOptionsPanel() {
return optionsPanel;
}
@Override
public String getName() {
return "SWEK Events";
}
@Override
public void setEnabled(boolean _enabled) {
super.setEnabled(_enabled);
if (enabled) {
Movie.addTimespanListener(this);
cacheUpdated();
Movie.addTimeListener(controller);
controller.timeChanged(Movie.getTime().milli);
ImageViewerGui.getInputController().addPlugin(controller);
} else {
ImageViewerGui.getInputController().removePlugin(controller);
Movie.removeTimeListener(controller);
Movie.removeTimespanListener(this);
}
}
@Nullable
@Override
public String getTimeString() {
return null;
}
@Override
public boolean isDeletable() {
return false;
}
@Override
public void init(GL2 gl) {
for (float[] tc : texCoord1)
texBuf1.put(tc);
for (float[] tc : texCoord2)
texBuf2.put(tc);
texBuf1.rewind();
texBuf2.rewind();
}
@Override
public void dispose(GL2 gl) {
for (GLTexture el : iconCacheId.values())
el.delete(gl);
iconCacheId.clear();
}
private static long startTime = Movie.getTime().milli;
private static long endTime = startTime;
private void requestEvents(boolean force, long start, long end) {
if (force || start < startTime || end > endTime) {
startTime = start;
endTime = end;
JHVEventCache.requestForInterval(start, end, this);
}
}
@Override
public void timespanChanged(long start, long end) {
requestEvents(false, start, end);
}
@Override
public void newEventsReceived() {
if (enabled)
Display.display();
}
@Override
public void cacheUpdated() {
requestEvents(true, Movie.getStartTime(), Movie.getEndTime());
}
private JPanel optionsPanel() {
JPanel panel = new JPanel(new GridBagLayout());
JCheckBox check = new JCheckBox("Icons", icons);
check.setHorizontalTextPosition(SwingConstants.LEFT);
check.addActionListener(e -> {
icons = !icons;
Display.display();
});
GridBagConstraints c0 = new GridBagConstraints();
c0.anchor = GridBagConstraints.CENTER;
c0.weightx = 1.;
c0.weighty = 1.;
c0.gridy = 0;
c0.gridx = 0;
panel.add(check, c0);
ComponentUtils.smallVariant(panel);
return panel;
}
} |
package org.helioviewer.jhv.plugins.swek;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.image.BufferedImage;
import java.nio.FloatBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import javax.annotation.Nullable;
import javax.swing.ImageIcon;
import javax.swing.JCheckBox;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import org.helioviewer.jhv.astronomy.Sun;
import org.helioviewer.jhv.base.Buf;
import org.helioviewer.jhv.base.BufferUtils;
import org.helioviewer.jhv.base.Colors;
import org.helioviewer.jhv.base.scale.GridScale;
import org.helioviewer.jhv.base.scale.Transform;
import org.helioviewer.jhv.camera.Camera;
import org.helioviewer.jhv.display.Display;
import org.helioviewer.jhv.display.Viewport;
import org.helioviewer.jhv.events.JHVEvent;
import org.helioviewer.jhv.events.JHVEventCache;
import org.helioviewer.jhv.events.JHVEventHandler;
import org.helioviewer.jhv.events.JHVEventParameter;
import org.helioviewer.jhv.events.JHVPositionInformation;
import org.helioviewer.jhv.events.JHVRelatedEvents;
import org.helioviewer.jhv.events.SWEKGroup;
import org.helioviewer.jhv.gui.ComponentUtils;
import org.helioviewer.jhv.gui.ImageViewerGui;
import org.helioviewer.jhv.layers.AbstractLayer;
import org.helioviewer.jhv.layers.Movie;
import org.helioviewer.jhv.layers.TimespanListener;
import org.helioviewer.jhv.math.MathUtils;
import org.helioviewer.jhv.math.Quat;
import org.helioviewer.jhv.math.Vec2;
import org.helioviewer.jhv.math.Vec3;
import org.helioviewer.jhv.opengl.GLHelper;
import org.helioviewer.jhv.opengl.GLSLLine;
import org.helioviewer.jhv.opengl.GLSLTexture;
import org.helioviewer.jhv.opengl.GLText;
import org.helioviewer.jhv.opengl.GLTexture;
import org.helioviewer.jhv.position.Position;
import org.json.JSONObject;
import com.jogamp.opengl.GL2;
// has to be public for state
public class SWEKLayer extends AbstractLayer implements TimespanListener, JHVEventHandler {
private final SWEKPopupController controller = new SWEKPopupController(ImageViewerGui.getGLComponent());
private final JPanel optionsPanel;
private static final int DIVPOINTS = 10;
private static final double LINEWIDTH = 0.002;
private static final double LINEWIDTH_HIGHLIGHT = 2 * LINEWIDTH;
private static final HashMap<String, GLTexture> iconCacheId = new HashMap<>();
private static final double ICON_ALPHA = 0.6;
private static final double ICON_SIZE = 0.1;
private static final double ICON_SIZE_HIGHLIGHTED = 0.16;
private static final float texCoord[][] = {{0, 1}, {1, 1}, {0, 0}, {1, 0}};
private boolean icons = true;
private final GLSLLine lineEvent = new GLSLLine(true);
private final Buf bufEvent = new Buf(512 * GLSLLine.stride); // pre-allocate
private final GLSLLine lineThick = new GLSLLine(true);
private final Buf bufThick = new Buf(64 * GLSLLine.stride); // pre-allocate
private final GLSLTexture glslTexture = new GLSLTexture();
private final FloatBuffer texBuf = BufferUtils.newFloatBuffer(16 + 8);
public SWEKLayer(JSONObject jo) {
if (jo != null)
icons = jo.optBoolean("icons", icons);
else
setEnabled(true);
optionsPanel = optionsPanel();
}
@Override
public void serialize(JSONObject jo) {
jo.put("icons", icons);
}
private static void bindTexture(GL2 gl, SWEKGroup group) {
String key = group.getName();
GLTexture tex = iconCacheId.get(key);
if (tex == null) {
ImageIcon icon = group.getIcon();
BufferedImage bi = new BufferedImage(icon.getIconWidth(), icon.getIconHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics graph = bi.createGraphics();
icon.paintIcon(null, graph, 0, 0);
graph.dispose();
tex = new GLTexture(gl, GL2.GL_TEXTURE_2D, GLTexture.Unit.ZERO);
tex.bind(gl);
GLTexture.copyBufferedImage2D(gl, bi);
iconCacheId.put(key, tex);
}
tex.bind(gl);
}
private void interPolatedDraw(int mres, double r_start, double r_end, double t_start, double t_end, Quat q, Buf buf, byte[] color) {
Vec3 v = new Vec3();
for (int i = 0; i <= mres; i++) {
double alpha = 1. - i / (double) mres;
double r = alpha * r_start + (1 - alpha) * r_end;
double theta = alpha * t_start + (1 - alpha) * t_end;
v.x = r * Math.cos(theta);
v.y = r * Math.sin(theta);
Vec3 res = q.rotateInverseVector(v);
if (i == 0) {
buf.put4f(res).put4b(Colors.Null);
}
buf.put4f(res).put4b(color);
}
buf.repeat4f().put4b(Colors.Null);
}
private void drawCactusArc(GL2 gl, JHVRelatedEvents evtr, JHVEvent evt, long timestamp) {
double angularWidthDegree = SWEKData.readCMEAngularWidthDegree(evt);
double angularWidth = Math.toRadians(angularWidthDegree);
double principalAngleDegree = SWEKData.readCMEPrincipalAngleDegree(evt);
double principalAngle = Math.toRadians(principalAngleDegree);
double speed = SWEKData.readCMESpeed(evt);
double factor = Sun.RadiusMeter;
double distSunBegin = 2.4;
double distSun = distSunBegin + speed * (timestamp - evt.start) / factor;
int lineResolution = 2;
int angularResolution = (int) (angularWidthDegree / 4);
Quat q = evt.getPositionInformation().getEarth().toQuat();
double thetaStart = principalAngle - angularWidth / 2.;
double thetaEnd = principalAngle + angularWidth / 2.;
Buf buf = evtr.isHighlighted() ? bufThick : bufEvent;
byte[] color = Colors.bytes(evtr.getColor());
interPolatedDraw(angularResolution, distSun, distSun, thetaStart, principalAngle, q, buf, color);
interPolatedDraw(angularResolution, distSun, distSun, principalAngle, thetaEnd, q, buf, color);
interPolatedDraw(lineResolution, distSunBegin, distSun + 0.05, thetaStart, thetaStart, q, buf, color);
interPolatedDraw(lineResolution, distSunBegin, distSun + 0.05, principalAngle, principalAngle, q, buf, color);
interPolatedDraw(lineResolution, distSunBegin, distSun + 0.05, thetaEnd, thetaEnd, q, buf, color);
if (icons) {
double sz = evtr.isHighlighted() ? ICON_SIZE_HIGHLIGHTED : ICON_SIZE;
Vec3 v = new Vec3();
for (float[] el : texCoord) {
double deltatheta = sz / distSun * (el[0] * 2 - 1);
double deltar = sz * (el[1] * 2 - 1);
double r = distSun - deltar;
double theta = principalAngle - deltatheta;
v.x = r * Math.cos(theta);
v.y = r * Math.sin(theta);
BufferUtils.put4f(texBuf, q.rotateInverseVector(v));
BufferUtils.put2f(texBuf, el);
}
texBuf.rewind();
bindTexture(gl, evtr.getSupplier().getGroup());
glslTexture.setData(gl, texBuf);
glslTexture.render(gl, GL2.GL_TRIANGLE_STRIP, Colors.floats(evtr.getColor()), 4);
}
}
private void drawPolygon(Camera camera, Viewport vp, JHVRelatedEvents evtr, JHVEvent evt) {
JHVPositionInformation pi = evt.getPositionInformation();
if (pi == null)
return;
float[] points = pi.getBoundBox();
if (points.length == 0) {
return;
}
Buf buf = evtr.isHighlighted() ? bufThick : bufEvent;
byte[] color = Colors.bytes(evtr.getColor());
// draw bounds
Vec3 pt = new Vec3();
float[] oldBoundaryPoint3d = new float[0];
Vec2 previous = null;
int plen = points.length / 3;
for (int i = 0; i < plen; i++) {
if (oldBoundaryPoint3d.length != 0) {
for (int j = 0; j <= DIVPOINTS; j++) {
double alpha = 1. - j / (double) DIVPOINTS;
double xnew = alpha * oldBoundaryPoint3d[0] + (1 - alpha) * points[3 * i];
double ynew = alpha * oldBoundaryPoint3d[1] + (1 - alpha) * points[3 * i + 1];
double znew = alpha * oldBoundaryPoint3d[2] + (1 - alpha) * points[3 * i + 2];
double r = Math.sqrt(xnew * xnew + ynew * ynew + znew * znew);
if (Display.mode == Display.DisplayMode.Orthographic) {
float x = (float) (xnew / r);
float y = -(float) (ynew / r);
float z = (float) (znew / r);
if (j == 0) {
buf.put4f(x, y, z, 1).put4b(Colors.Null);
}
buf.put4f(x, y, z, 1).put4b(color);
} else {
pt.x = xnew / r;
pt.y = ynew / r;
pt.z = znew / r;
if (j == 0) {
previous = GLHelper.drawVertex(camera, vp, pt, previous, buf, Colors.Null);
}
previous = GLHelper.drawVertex(camera, vp, pt, previous, buf, color);
}
}
buf.repeat4f().put4b(Colors.Null);
}
oldBoundaryPoint3d = new float[]{points[3 * i], points[3 * i + 1], points[3 * i + 2]};
}
}
private void drawImage3d(GL2 gl, double x, double y, double z, double width, double height, float[] color) {
y = -y;
double width2 = width / 2.;
double height2 = height / 2.;
Vec3 targetDir = new Vec3(x, y, z);
Quat q = Quat.rotate(Quat.createRotation(Math.atan2(x, z), Vec3.YAxis), Quat.createRotation(-Math.asin(y / targetDir.length()), Vec3.XAxis));
Vec3 p0 = q.rotateVector(new Vec3(-width2, -height2, 0));
Vec3 p1 = q.rotateVector(new Vec3(width2, -height2, 0));
Vec3 p2 = q.rotateVector(new Vec3(-width2, height2, 0));
Vec3 p3 = q.rotateVector(new Vec3(width2, height2, 0));
p0.add(targetDir);
p1.add(targetDir);
p2.add(targetDir);
p3.add(targetDir);
BufferUtils.put4f(texBuf, p0);
BufferUtils.put2f(texBuf, texCoord[0]);
BufferUtils.put4f(texBuf, p1);
BufferUtils.put2f(texBuf, texCoord[1]);
BufferUtils.put4f(texBuf, p2);
BufferUtils.put2f(texBuf, texCoord[2]);
BufferUtils.put4f(texBuf, p3);
BufferUtils.put2f(texBuf, texCoord[3]);
texBuf.rewind();
glslTexture.setData(gl, texBuf);
glslTexture.render(gl, GL2.GL_TRIANGLE_STRIP, color, 4);
}
private void drawIcon(GL2 gl, JHVRelatedEvents evtr, JHVEvent evt) {
JHVPositionInformation pi = evt.getPositionInformation();
if (pi == null)
return;
Vec3 pt = pi.centralPoint();
if (pt != null) {
double sz = evtr.isHighlighted() ? ICON_SIZE_HIGHLIGHTED : ICON_SIZE;
bindTexture(gl, evtr.getSupplier().getGroup());
drawImage3d(gl, pt.x, pt.y, pt.z, sz, sz, Colors.floats(evtr.getColor(), ICON_ALPHA));
}
}
private void drawImageScale(GL2 gl, double theta, double r, double width, double height, float[] color) {
double width2 = width / 4.;
double height2 = height / 4.;
BufferUtils.put4f(texBuf, (float) (theta - width2), (float) (r - height2), 0, 1);
BufferUtils.put2f(texBuf, texCoord[0]);
BufferUtils.put4f(texBuf, (float) (theta + width2), (float) (r - height2), 0, 1);
BufferUtils.put2f(texBuf, texCoord[1]);
BufferUtils.put4f(texBuf, (float) (theta - width2), (float) (r + height2), 0, 1);
BufferUtils.put2f(texBuf, texCoord[2]);
BufferUtils.put4f(texBuf, (float) (theta + width2), (float) (r + height2), 0, 1);
BufferUtils.put2f(texBuf, texCoord[3]);
texBuf.rewind();
glslTexture.setData(gl, texBuf);
glslTexture.render(gl, GL2.GL_TRIANGLE_STRIP, color, 4);
}
private void drawIconScale(Camera camera, Viewport vp, GL2 gl, JHVRelatedEvents evtr, JHVEvent evt, GridScale scale, Transform xform) {
JHVPositionInformation pi = evt.getPositionInformation();
if (pi == null)
return;
Vec3 pt = pi.centralPoint();
if (pt != null) {
Position viewpoint = camera.getViewpoint();
pt = viewpoint.toQuat().rotateVector(pt);
Vec2 tf = xform.transform(viewpoint, pt, scale);
double sz = evtr.isHighlighted() ? ICON_SIZE_HIGHLIGHTED : ICON_SIZE;
bindTexture(gl, evtr.getSupplier().getGroup());
drawImageScale(gl, tf.x * vp.aspect, tf.y, sz, sz, Colors.floats(evtr.getColor(), ICON_ALPHA));
}
}
private void drawCactusArcScale(Viewport vp, GL2 gl, JHVRelatedEvents evtr, JHVEvent evt, long timestamp, GridScale scale) {
double angularWidthDegree = SWEKData.readCMEAngularWidthDegree(evt);
double principalAngleDegree = SWEKData.readCMEPrincipalAngleDegree(evt) - 90;
double speed = SWEKData.readCMESpeed(evt);
double factor = Sun.RadiusMeter;
double distSunBegin = 2.4;
double distSun = distSunBegin + speed * (timestamp - evt.start) / factor;
double thetaStart = MathUtils.mapTo0To360(principalAngleDegree - angularWidthDegree / 2.);
double thetaEnd = MathUtils.mapTo0To360(principalAngleDegree + angularWidthDegree / 2.);
Buf buf = evtr.isHighlighted() ? bufThick : bufEvent;
byte[] color = Colors.bytes(evtr.getColor());
float x = (float) (scale.getXValueInv(thetaStart) * vp.aspect);
float y = (float) scale.getYValueInv(distSunBegin);
buf.put4f(x, y, 0, 1).put4b(Colors.Null);
buf.repeat4f().put4b(color);
y = (float) scale.getYValueInv(distSun + 0.05);
buf.put4f(x, y, 0, 1).put4b(color);
buf.repeat4f().put4b(Colors.Null);
x = (float) (scale.getXValueInv(principalAngleDegree) * vp.aspect);
y = (float) scale.getYValueInv(distSunBegin);
buf.put4f(x, y, 0, 1).put4b(Colors.Null);
buf.repeat4f().put4b(color);
y = (float) scale.getYValueInv(distSun + 0.05);
buf.put4f(x, y, 0, 1).put4b(color);
buf.repeat4f().put4b(Colors.Null);
x = (float) (scale.getXValueInv(thetaEnd) * vp.aspect);
y = (float) scale.getYValueInv(distSunBegin);
buf.put4f(x, y, 0, 1).put4b(Colors.Null);
buf.repeat4f().put4b(color);
y = (float) scale.getYValueInv(distSun + 0.05);
buf.put4f(x, y, 0, 1).put4b(color);
buf.repeat4f().put4b(Colors.Null);
y = (float) scale.getYValueInv(distSun);
buf.put4f(x, y, 0, 1).put4b(Colors.Null);
buf.repeat4f().put4b(color);
x = (float) (scale.getXValueInv(thetaStart) * vp.aspect);
buf.put4f(x, y, 0, 1).put4b(color);
buf.repeat4f().put4b(Colors.Null);
if (icons) {
double sz = evtr.isHighlighted() ? ICON_SIZE_HIGHLIGHTED : ICON_SIZE;
bindTexture(gl, evtr.getSupplier().getGroup());
drawImageScale(gl, scale.getXValueInv(principalAngleDegree) * vp.aspect, scale.getYValueInv(distSun), sz, sz, Colors.floats(evtr.getColor()));
}
}
private static final int MOUSE_OFFSET_X = 25;
private static final int MOUSE_OFFSET_Y = 25;
private void drawText(Viewport vp, JHVRelatedEvents mouseOverJHVEvent, int x, int y) {
ArrayList<String> txts = new ArrayList<>();
for (JHVEventParameter p : mouseOverJHVEvent.getClosestTo(controller.currentTime).getSimpleVisibleEventParameters()) {
String name = p.getParameterName();
if (name != "event_description" && name != "event_title") { // interned
txts.add(p.getParameterDisplayName() + " : " + p.getSimpleDisplayParameterValue());
}
}
GLText.drawText(vp, txts, x + MOUSE_OFFSET_X, y + MOUSE_OFFSET_Y);
}
private void renderEvents(Viewport vp, GL2 gl) {
lineEvent.setData(gl, bufEvent);
lineThick.setData(gl, bufThick);
lineEvent.render(gl, vp, LINEWIDTH);
lineThick.render(gl, vp, LINEWIDTH_HIGHLIGHT);
}
@Override
public void render(Camera camera, Viewport vp, GL2 gl) {
if (isVisible[vp.idx]) {
for (JHVRelatedEvents evtr : SWEKData.getActiveEvents(controller.currentTime)) {
JHVEvent evt = evtr.getClosestTo(controller.currentTime);
if (evt.isCactus()) {
drawCactusArc(gl, evtr, evt, controller.currentTime);
} else {
drawPolygon(camera, vp, evtr, evt);
if (icons) {
gl.glDisable(GL2.GL_DEPTH_TEST);
drawIcon(gl, evtr, evt);
gl.glEnable(GL2.GL_DEPTH_TEST);
}
}
}
renderEvents(vp, gl);
}
}
@Override
public void renderScale(Camera camera, Viewport vp, GL2 gl) {
if (isVisible[vp.idx]) {
for (JHVRelatedEvents evtr : SWEKData.getActiveEvents(controller.currentTime)) {
JHVEvent evt = evtr.getClosestTo(controller.currentTime);
if (evt.isCactus() && (Display.mode == Display.DisplayMode.LogPolar || Display.mode == Display.DisplayMode.Polar)) {
drawCactusArcScale(vp, gl, evtr, evt, controller.currentTime, Display.mode.scale);
} else {
drawPolygon(camera, vp, evtr, evt);
if (icons) {
gl.glDisable(GL2.GL_DEPTH_TEST);
drawIconScale(camera, vp, gl, evtr, evt, Display.mode.scale, Display.mode.xform);
gl.glEnable(GL2.GL_DEPTH_TEST);
}
}
}
renderEvents(vp, gl);
}
}
@Override
public void renderFullFloat(Camera camera, Viewport vp, GL2 gl) {
if (SWEKPopupController.mouseOverJHVEvent != null) {
drawText(vp, SWEKPopupController.mouseOverJHVEvent, SWEKPopupController.mouseOverX, SWEKPopupController.mouseOverY);
}
}
@Override
public void remove(GL2 gl) {
setEnabled(false);
dispose(gl);
}
@Override
public Component getOptionsPanel() {
return optionsPanel;
}
@Override
public String getName() {
return "SWEK Events";
}
@Override
public void setEnabled(boolean _enabled) {
super.setEnabled(_enabled);
if (enabled) {
Movie.addTimespanListener(this);
cacheUpdated();
Movie.addTimeListener(controller);
controller.timeChanged(Movie.getTime().milli);
ImageViewerGui.getInputController().addPlugin(controller);
} else {
ImageViewerGui.getInputController().removePlugin(controller);
Movie.removeTimeListener(controller);
Movie.removeTimespanListener(this);
}
}
@Nullable
@Override
public String getTimeString() {
return null;
}
@Override
public boolean isDeletable() {
return false;
}
@Override
public void init(GL2 gl) {
lineEvent.init(gl);
lineThick.init(gl);
glslTexture.init(gl);
}
@Override
public void dispose(GL2 gl) {
lineEvent.dispose(gl);
lineThick.dispose(gl);
for (GLTexture el : iconCacheId.values())
el.delete(gl);
iconCacheId.clear();
}
private long startTime = Movie.getStartTime();
private long endTime = Movie.getEndTime();
private void requestEvents(boolean force, long start, long end) {
if (force || start < startTime || end > endTime) {
startTime = start;
endTime = end;
JHVEventCache.requestForInterval(start, end, this);
}
}
@Override
public void timespanChanged(long start, long end) {
requestEvents(false, start, end);
}
@Override
public void newEventsReceived() {
if (enabled)
Display.display();
}
@Override
public void cacheUpdated() {
requestEvents(true, Movie.getStartTime(), Movie.getEndTime());
}
private JPanel optionsPanel() {
JPanel panel = new JPanel(new GridBagLayout());
JCheckBox check = new JCheckBox("Icons", icons);
check.setHorizontalTextPosition(SwingConstants.LEFT);
check.addActionListener(e -> {
icons = !icons;
Display.display();
});
GridBagConstraints c0 = new GridBagConstraints();
c0.anchor = GridBagConstraints.CENTER;
c0.weightx = 1.;
c0.weighty = 1.;
c0.gridy = 0;
c0.gridx = 0;
panel.add(check, c0);
ComponentUtils.smallVariant(panel);
return panel;
}
} |
package org.jcodings.specific;
import org.jcodings.CaseFoldMapEncoding;
import org.jcodings.Config;
import org.jcodings.ISOEncoding;
import org.jcodings.IntHolder;
import org.jcodings.constants.CharacterType;
final public class Windows_1254Encoding extends CaseFoldMapEncoding {
protected Windows_1254Encoding() {
super("Windows-1254", CP1254_CtypeTable, CP1254_ToLowerCaseTable, CP1254_CaseFoldMap, true);
}
static final int DOTLESS_i = 0xFD;
static final int I_WITH_DOT_ABOVE = 0xDD;
@Override
public int caseMap(IntHolder flagP, byte[] bytes, IntHolder pp, int end, byte[] to, int toP, int toEnd) {
int toStart = toP;
int flags = flagP.value;
while (pp.value < end && toP < toEnd) {
int code = bytes[pp.value++] & 0xff;
if (code == ISOEncoding.SHARP_s) {
if ((flags & Config.CASE_UPCASE) != 0) {
flags |= Config.CASE_MODIFIED;
to[toP++] = 'S';
code = (flags & Config.CASE_TITLECASE) != 0 ? 's' : 'S';
} else if ((flags & Config.CASE_FOLD) != 0) {
flags |= Config.CASE_MODIFIED;
to[toP++] = 's';
code = 's';
}
} else if ((CP1254_CtypeTable[code] & CharacterType.BIT_UPPER) != 0 && (flags & (Config.CASE_DOWNCASE | Config.CASE_FOLD)) != 0) {
flags |= Config.CASE_MODIFIED;
if (code == 'I') {
code = (flags & Config.CASE_FOLD_TURKISH_AZERI) != 0 ? DOTLESS_i : 'i';
} else {
code = LowerCaseTable[code];
}
} else if (code == 0x83 || code == 0xAA || code == 0xBA || code == 0xB5) {
} else if ((CP1254_CtypeTable[code] & CharacterType.BIT_LOWER) != 0 && (flags & Config.CASE_UPCASE) != 0) {
flags |= Config.CASE_MODIFIED;
if (code == 'i') {
code = (flags & Config.CASE_FOLD_TURKISH_AZERI) != 0 ? I_WITH_DOT_ABOVE : 'I';
} else if (code == DOTLESS_i) {
code = 'I';
} else if (code == 0x9A || code == 0x9C || code == 0x9E)
code -= 0x10;
else if (code == 0xFF)
code -= 0x60;
else
code -= 0x20;
}
to[toP++] = (byte)code;
if ((flags & Config.CASE_TITLECASE) != 0) {
flags ^= (Config.CASE_UPCASE | Config.CASE_DOWNCASE | Config.CASE_TITLECASE);
}
}
flagP.value = flags;
return toP - toStart;
}
@Override
public int mbcCaseFold(int flag, byte[]bytes, IntHolder pp, int end, byte[]lower) {
int p = pp.value;
int lowerP = 0;
lower[lowerP] = LowerCaseTable[bytes[p] & 0xff];
pp.value++;
return 1;
}
@Override
public boolean isCodeCType(int code, int ctype) {
return code < 256 ? isCodeCTypeInternal(code, ctype) : false;
}
static final short CP1254_CtypeTable[] = {
0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x4008,
0x4008, 0x420c, 0x4209, 0x4208, 0x4208, 0x4208, 0x4008, 0x4008,
0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x4008,
0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x4008,
0x4284, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x41a0,
0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x41a0,
0x78b0, 0x78b0, 0x78b0, 0x78b0, 0x78b0, 0x78b0, 0x78b0, 0x78b0,
0x78b0, 0x78b0, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x41a0,
0x41a0, 0x7ca2, 0x7ca2, 0x7ca2, 0x7ca2, 0x7ca2, 0x7ca2, 0x74a2,
0x74a2, 0x74a2, 0x74a2, 0x74a2, 0x74a2, 0x74a2, 0x74a2, 0x74a2,
0x74a2, 0x74a2, 0x74a2, 0x74a2, 0x74a2, 0x74a2, 0x74a2, 0x74a2,
0x74a2, 0x74a2, 0x74a2, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x51a0,
0x41a0, 0x78e2, 0x78e2, 0x78e2, 0x78e2, 0x78e2, 0x78e2, 0x70e2,
0x70e2, 0x70e2, 0x70e2, 0x70e2, 0x70e2, 0x70e2, 0x70e2, 0x70e2,
0x70e2, 0x70e2, 0x70e2, 0x70e2, 0x70e2, 0x70e2, 0x70e2, 0x70e2,
0x70e2, 0x70e2, 0x70e2, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x4008,
0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008,
0x0008, 0x0008, 0x34a2, 0x0008, 0x34a2, 0x0008, 0x0008, 0x0008,
0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008,
0x0008, 0x0008, 0x30e2, 0x0008, 0x30e2, 0x0008, 0x0008, 0x34a2,
0x0284, 0x01a0, 0x00a0, 0x00a0, 0x00a0, 0x00a0, 0x00a0, 0x00a0,
0x00a0, 0x00a0, 0x30e2, 0x01a0, 0x00a0, 0x01a0, 0x00a0, 0x00a0,
0x00a0, 0x00a0, 0x10a0, 0x10a0, 0x00a0, 0x30e2, 0x00a0, 0x01a0,
0x00a0, 0x10a0, 0x30e2, 0x01a0, 0x10a0, 0x10a0, 0x10a0, 0x01a0,
0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2,
0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2,
0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x00a0,
0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x30e2,
0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2,
0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2,
0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x00a0,
0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2
};
static final byte CP1254_ToLowerCaseTable[] = new byte[]{
(byte)'\000', (byte)'\001', (byte)'\002', (byte)'\003', (byte)'\004', (byte)'\005', (byte)'\006', (byte)'\007',
(byte)'\010', (byte)'\011', (byte)'\012', (byte)'\013', (byte)'\014', (byte)'\015', (byte)'\016', (byte)'\017',
(byte)'\020', (byte)'\021', (byte)'\022', (byte)'\023', (byte)'\024', (byte)'\025', (byte)'\026', (byte)'\027',
(byte)'\030', (byte)'\031', (byte)'\032', (byte)'\033', (byte)'\034', (byte)'\035', (byte)'\036', (byte)'\037',
(byte)'\040', (byte)'\041', (byte)'\042', (byte)'\043', (byte)'\044', (byte)'\045', (byte)'\046', (byte)'\047',
(byte)'\050', (byte)'\051', (byte)'\052', (byte)'\053', (byte)'\054', (byte)'\055', (byte)'\056', (byte)'\057',
(byte)'\060', (byte)'\061', (byte)'\062', (byte)'\063', (byte)'\064', (byte)'\065', (byte)'\066', (byte)'\067',
(byte)'\070', (byte)'\071', (byte)'\072', (byte)'\073', (byte)'\074', (byte)'\075', (byte)'\076', (byte)'\077',
(byte)'\100', (byte)'\141', (byte)'\142', (byte)'\143', (byte)'\144', (byte)'\145', (byte)'\146', (byte)'\147',
(byte)'\150', (byte)'\151', (byte)'\152', (byte)'\153', (byte)'\154', (byte)'\155', (byte)'\156', (byte)'\157',
(byte)'\160', (byte)'\161', (byte)'\162', (byte)'\163', (byte)'\164', (byte)'\165', (byte)'\166', (byte)'\167',
(byte)'\170', (byte)'\171', (byte)'\172', (byte)'\133', (byte)'\134', (byte)'\135', (byte)'\136', (byte)'\137',
(byte)'\140', (byte)'\141', (byte)'\142', (byte)'\143', (byte)'\144', (byte)'\145', (byte)'\146', (byte)'\147',
(byte)'\150', (byte)'\151', (byte)'\152', (byte)'\153', (byte)'\154', (byte)'\155', (byte)'\156', (byte)'\157',
(byte)'\160', (byte)'\161', (byte)'\162', (byte)'\163', (byte)'\164', (byte)'\165', (byte)'\166', (byte)'\167',
(byte)'\170', (byte)'\171', (byte)'\172', (byte)'\173', (byte)'\174', (byte)'\175', (byte)'\176', (byte)'\177',
(byte)'\200', (byte)'\201', (byte)'\202', (byte)'\203', (byte)'\204', (byte)'\205', (byte)'\206', (byte)'\207',
(byte)'\210', (byte)'\211', (byte)'\232', (byte)'\213', (byte)'\234', (byte)'\215', (byte)'\216', (byte)'\217',
(byte)'\220', (byte)'\221', (byte)'\222', (byte)'\223', (byte)'\224', (byte)'\225', (byte)'\226', (byte)'\227',
(byte)'\230', (byte)'\231', (byte)'\232', (byte)'\233', (byte)'\234', (byte)'\235', (byte)'\236', (byte)'\377',
(byte)'\240', (byte)'\241', (byte)'\242', (byte)'\243', (byte)'\244', (byte)'\245', (byte)'\246', (byte)'\247',
(byte)'\250', (byte)'\251', (byte)'\252', (byte)'\253', (byte)'\254', (byte)'\255', (byte)'\256', (byte)'\257',
(byte)'\260', (byte)'\261', (byte)'\262', (byte)'\263', (byte)'\264', (byte)'\265', (byte)'\266', (byte)'\267',
(byte)'\270', (byte)'\271', (byte)'\272', (byte)'\273', (byte)'\274', (byte)'\275', (byte)'\276', (byte)'\277',
(byte)'\340', (byte)'\341', (byte)'\342', (byte)'\343', (byte)'\344', (byte)'\345', (byte)'\346', (byte)'\347',
(byte)'\350', (byte)'\351', (byte)'\352', (byte)'\353', (byte)'\354', (byte)'\355', (byte)'\356', (byte)'\357',
(byte)'\360', (byte)'\361', (byte)'\362', (byte)'\363', (byte)'\364', (byte)'\365', (byte)'\366', (byte)'\327',
(byte)'\370', (byte)'\371', (byte)'\372', (byte)'\373', (byte)'\374', (byte)'\151', (byte)'\376', (byte)'\337',
(byte)'\340', (byte)'\341', (byte)'\342', (byte)'\343', (byte)'\344', (byte)'\345', (byte)'\346', (byte)'\347',
(byte)'\350', (byte)'\351', (byte)'\352', (byte)'\353', (byte)'\354', (byte)'\355', (byte)'\356', (byte)'\357',
(byte)'\360', (byte)'\361', (byte)'\362', (byte)'\363', (byte)'\364', (byte)'\365', (byte)'\366', (byte)'\367',
(byte)'\370', (byte)'\371', (byte)'\372', (byte)'\373', (byte)'\374', (byte)'\375', (byte)'\376', (byte)'\377'
};
static final int CP1254_CaseFoldMap[][] = {
{ 0xc0, 0xe0 },
{ 0xc1, 0xe1 },
{ 0xc2, 0xe2 },
{ 0xc3, 0xe3 },
{ 0xc4, 0xe4 },
{ 0xc5, 0xe5 },
{ 0xc6, 0xe6 },
{ 0xc7, 0xe7 },
{ 0xc8, 0xe8 },
{ 0xc9, 0xe9 },
{ 0xca, 0xea },
{ 0xcb, 0xeb },
{ 0xcc, 0xec },
{ 0xcd, 0xed },
{ 0xce, 0xee },
{ 0xcf, 0xef },
{ 0xd0, 0xf0 },
{ 0xd1, 0xf1 },
{ 0xd2, 0xf2 },
{ 0xd3, 0xf3 },
{ 0xd4, 0xf4 },
{ 0xd5, 0xf5 },
{ 0xd6, 0xf6 },
{ 0xd8, 0xf8 },
{ 0xd9, 0xf9 },
{ 0xda, 0xfa },
{ 0xdb, 0xfb },
{ 0xdc, 0xfc },
{ 0xdd, 0xfd },
{ 0xde, 0xfe }
};
public static final Windows_1254Encoding INSTANCE = new Windows_1254Encoding();
} |
// $Id: ClientGmsImpl.java,v 1.21 2005/09/14 08:57:07 belaban Exp $
package org.jgroups.protocols.pbcast;
import org.jgroups.*;
import org.jgroups.protocols.PingRsp;
import org.jgroups.util.Promise;
import org.jgroups.util.Util;
import java.util.*;
/**
* Client part of GMS. Whenever a new member wants to join a group, it starts in the CLIENT role.
* No multicasts to the group will be received and processed until the member has been joined and
* turned into a SERVER (either coordinator or participant, mostly just participant). This class
* only implements <code>Join</code> (called by clients who want to join a certain group, and
* <code>ViewChange</code> which is called by the coordinator that was contacted by this client, to
* tell the client what its initial membership is.
* @author Bela Ban
* @version $Revision: 1.21 $
*/
public class ClientGmsImpl extends GmsImpl {
private final Vector initial_mbrs=new Vector(11);
private boolean initial_mbrs_received=false;
private final Promise join_promise=new Promise();
public ClientGmsImpl(GMS g) {
gms=g;
}
public void init() throws Exception {
super.init();
synchronized(initial_mbrs) {
initial_mbrs.clear();
initial_mbrs_received=false;
}
join_promise.reset();
}
/**
* Joins this process to a group. Determines the coordinator and sends a unicast
* handleJoin() message to it. The coordinator returns a JoinRsp and then broadcasts the new view, which
* contains a message digest and the current membership (including the joiner). The joiner is then
* supposed to install the new view and the digest and starts accepting mcast messages. Previous
* mcast messages were discarded (this is done in PBCAST).<p>
* If successful, impl is changed to an instance of ParticipantGmsImpl.
* Otherwise, we continue trying to send join() messages to the coordinator,
* until we succeed (or there is no member in the group. In this case, we create our own singleton group).
* <p>When GMS.disable_initial_coord is set to true, then we won't become coordinator on receiving an initial
* membership of 0, but instead will retry (forever) until we get an initial membership of > 0.
* @param mbr Our own address (assigned through SET_LOCAL_ADDRESS)
*/
public void join(Address mbr) {
Address coord;
JoinRsp rsp;
Digest tmp_digest;
leaving=false;
join_promise.reset();
while(!leaving) {
findInitialMembers();
if(log.isDebugEnabled()) log.debug("initial_mbrs are " + initial_mbrs);
if(initial_mbrs.size() == 0) {
if(gms.disable_initial_coord) {
if(trace)
log.trace("received an initial membership of 0, but cannot become coordinator " +
"(disable_initial_coord=true), will retry fetching the initial membership");
continue;
}
if(log.isDebugEnabled())
log.debug("no initial members discovered: creating group as first member");
becomeSingletonMember(mbr);
return;
}
coord=determineCoord(initial_mbrs);
if(coord == null) { // e.g. because we have all clients only
if(trace)
log.trace("could not determine coordinator from responses " + initial_mbrs);
// so the member to become singleton member (and thus coord) is the first of all clients
Set clients=new TreeSet(); // sorted
clients.add(mbr); // add myself again (was removed by findInitialMembers())
for(int i=0; i < initial_mbrs.size(); i++) {
PingRsp pingRsp=(PingRsp)initial_mbrs.elementAt(i);
Address client_addr=pingRsp.getAddress();
if(client_addr != null)
clients.add(client_addr);
}
if(trace)
log.trace("clients to choose new coord from are: " + clients);
Address new_coord=(Address)clients.iterator().next();
if(new_coord.equals(mbr)) {
if(trace)
log.trace("I'm the first of the clients, will become singleton");
becomeSingletonMember(mbr);
return;
}
else {
if(trace)
log.trace("I'm not the first of the clients, waiting for another client to become coord");
Util.sleep(500);
}
continue;
}
try {
if(log.isDebugEnabled())
log.debug("sending handleJoin(" + mbr + ") to " + coord);
sendJoinMessage(coord, mbr);
rsp=(JoinRsp)join_promise.getResult(gms.join_timeout);
if(rsp == null) {
if(warn) log.warn("join(" + mbr + ") failed (coord=" + coord + "), retrying");
}
else {
// 1. Install digest
tmp_digest=rsp.getDigest();
if(tmp_digest != null) {
tmp_digest.incrementHighSeqno(coord); // see DESIGN for an explanantion
if(log.isDebugEnabled()) log.debug("digest is " + tmp_digest);
gms.setDigest(tmp_digest);
}
else
if(log.isErrorEnabled()) log.error("digest of JOIN response is null");
// 2. Install view
if(log.isDebugEnabled()) log.debug("[" + gms.local_addr + "]: JoinRsp=" + rsp.getView() +
" [size=" + rsp.getView().size() + "]\n\n");
if(rsp.getView() != null) {
if(!installView(rsp.getView())) {
if(log.isErrorEnabled()) log.error("view installation failed, retrying to join group");
continue;
}
gms.passUp(new Event(Event.BECOME_SERVER));
gms.passDown(new Event(Event.BECOME_SERVER));
return;
}
else
if(log.isErrorEnabled()) log.error("view of JOIN response is null");
}
}
catch(Exception e) {
if(log.isDebugEnabled()) log.debug("exception=" + e.toString() + ", retrying");
}
Util.sleep(gms.join_retry_timeout);
}
}
public void leave(Address mbr) {
leaving=true;
wrongMethod("leave");
}
public void handleJoinResponse(JoinRsp join_rsp) {
join_promise.setResult(join_rsp); // will wake up join() method
}
public void handleLeaveResponse() {
}
public void suspect(Address mbr) {
}
public void unsuspect(Address mbr) {
wrongMethod("unsuspect");
}
public JoinRsp handleJoin(Address mbr) {
wrongMethod("handleJoin");
return null;
}
/** Returns false. Clients don't handle leave() requests */
public void handleLeave(Address mbr, boolean suspected) {
wrongMethod("handleLeave");
}
/**
* Does nothing. Discards all views while still client.
*/
public synchronized void handleViewChange(View new_view, Digest digest) {
if(log.isDebugEnabled()) log.debug("view " + new_view.getMembers() +
" is discarded as we are not a participant");
}
/**
* Called by join(). Installs the view returned by calling Coord.handleJoin() and
* becomes coordinator.
*/
private boolean installView(View new_view) {
Vector mems=new_view.getMembers();
if(log.isDebugEnabled()) log.debug("new_view=" + new_view);
if(gms.local_addr == null || mems == null || !mems.contains(gms.local_addr)) {
if(log.isErrorEnabled()) log.error("I (" + gms.local_addr +
") am not member of " + mems + ", will not install view");
return false;
}
gms.installView(new_view);
gms.becomeParticipant();
gms.passUp(new Event(Event.BECOME_SERVER));
gms.passDown(new Event(Event.BECOME_SERVER));
return true;
}
/** Returns immediately. Clients don't handle suspect() requests */
public void handleSuspect(Address mbr) {
wrongMethod("handleSuspect");
}
public boolean handleUpEvent(Event evt) {
Vector tmp;
switch(evt.getType()) {
case Event.FIND_INITIAL_MBRS_OK:
tmp=(Vector)evt.getArg();
synchronized(initial_mbrs) {
if(tmp != null && tmp.size() > 0) {
initial_mbrs.addAll(tmp);
}
initial_mbrs_received=true;
initial_mbrs.notifyAll();
}
return false; // don't pass up the stack
}
return true;
}
void sendJoinMessage(Address coord, Address mbr) {
Message msg;
GMS.GmsHeader hdr;
msg=new Message(coord, null, null);
hdr=new GMS.GmsHeader(GMS.GmsHeader.JOIN_REQ, mbr);
msg.putHeader(gms.getName(), hdr);
gms.passDown(new Event(Event.MSG, msg));
}
/**
* Pings initial members. Removes self before returning vector of initial members.
* Uses IP multicast or gossiping, depending on parameters.
*/
void findInitialMembers() {
PingRsp ping_rsp;
synchronized(initial_mbrs) {
initial_mbrs.removeAllElements();
initial_mbrs_received=false;
gms.passDown(new Event(Event.FIND_INITIAL_MBRS));
// the initial_mbrs_received flag is needed when passDown() is executed on the same thread, so when
// it returns, a response might actually have been received (even though the initial_mbrs might still be empty)
if(initial_mbrs_received == false) {
try {
initial_mbrs.wait();
}
catch(Exception e) {
}
}
for(int i=0; i < initial_mbrs.size(); i++) {
ping_rsp=(PingRsp)initial_mbrs.elementAt(i);
if(ping_rsp.own_addr != null && gms.local_addr != null &&
ping_rsp.own_addr.equals(gms.local_addr)) {
initial_mbrs.removeElementAt(i);
break;
}
}
}
}
/**
The coordinator is determined by a majority vote. If there are an equal number of votes for
more than 1 candidate, we determine the winner randomly.
*/
Address determineCoord(Vector mbrs) {
PingRsp mbr;
Hashtable votes;
int count, most_votes;
Address winner=null, tmp;
if(mbrs == null || mbrs.size() < 1)
return null;
votes=new Hashtable(5);
// count *all* the votes (unlike the 2000 election)
for(int i=0; i < mbrs.size(); i++) {
mbr=(PingRsp)mbrs.elementAt(i);
if(mbr.is_server && mbr.coord_addr != null) {
if(!votes.containsKey(mbr.coord_addr))
votes.put(mbr.coord_addr, new Integer(1));
else {
count=((Integer)votes.get(mbr.coord_addr)).intValue();
votes.put(mbr.coord_addr, new Integer(count + 1));
}
}
}
if(log.isDebugEnabled()) {
if(votes.size() > 1)
if(warn) log.warn("there was more than 1 candidate for coordinator: " + votes);
else
if(log.isDebugEnabled()) log.debug("election results: " + votes);
}
// determine who got the most votes
most_votes=0;
for(Enumeration e=votes.keys(); e.hasMoreElements();) {
tmp=(Address)e.nextElement();
count=((Integer)votes.get(tmp)).intValue();
if(count > most_votes) {
winner=tmp;
// fixed July 15 2003 (patch submitted by Darren Hobbs, patch-id=771418)
most_votes=count;
}
}
votes.clear();
return winner;
}
void becomeSingletonMember(Address mbr) {
Digest initial_digest;
ViewId view_id;
Vector mbrs=new Vector(1);
// set the initial digest (since I'm the first member)
initial_digest=new Digest(1); // 1 member (it's only me)
initial_digest.add(gms.local_addr, 0, 0); // initial seqno mcast by me will be 1 (highest seen +1)
gms.setDigest(initial_digest);
view_id=new ViewId(mbr); // create singleton view with mbr as only member
mbrs.addElement(mbr);
gms.installView(new View(view_id, mbrs));
gms.becomeCoordinator(); // not really necessary - installView() should do it
gms.passUp(new Event(Event.BECOME_SERVER));
gms.passDown(new Event(Event.BECOME_SERVER));
if(log.isDebugEnabled()) log.debug("created group (first member). My view is " + gms.view_id +
", impl is " + gms.getImpl().getClass().getName());
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.