lang
stringclasses 1
value | license
stringclasses 13
values | stderr
stringlengths 0
350
| commit
stringlengths 40
40
| returncode
int64 0
128
| repos
stringlengths 7
45.1k
| new_contents
stringlengths 0
1.87M
| new_file
stringlengths 6
292
| old_contents
stringlengths 0
1.87M
| message
stringlengths 6
9.26k
| old_file
stringlengths 6
292
| subject
stringlengths 0
4.45k
|
|---|---|---|---|---|---|---|---|---|---|---|---|
Java
|
apache-2.0
|
74b7374b48466fdb6d55acd2dc4d4ab96e85a663
| 0
|
pstorch/cgeo,samueltardieu/cgeo,rsudev/c-geo-opensource,tobiasge/cgeo,S-Bartfast/cgeo,pstorch/cgeo,cgeo/cgeo,tobiasge/cgeo,matej116/cgeo,S-Bartfast/cgeo,cgeo/cgeo,Bananeweizen/cgeo,superspindel/cgeo,auricgoldfinger/cgeo,samueltardieu/cgeo,mucek4/cgeo,kumy/cgeo,auricgoldfinger/cgeo,S-Bartfast/cgeo,samueltardieu/cgeo,rsudev/c-geo-opensource,superspindel/cgeo,auricgoldfinger/cgeo,SammysHP/cgeo,pstorch/cgeo,kumy/cgeo,kumy/cgeo,SammysHP/cgeo,mucek4/cgeo,SammysHP/cgeo,Bananeweizen/cgeo,tobiasge/cgeo,cgeo/cgeo,Bananeweizen/cgeo,cgeo/cgeo,matej116/cgeo,matej116/cgeo,superspindel/cgeo,mucek4/cgeo,rsudev/c-geo-opensource
|
package cgeo.geocaching.connector.gc;
import static org.assertj.core.api.Assertions.assertThat;
import cgeo.geocaching.SearchResult;
import cgeo.geocaching.connector.ConnectorFactory;
import cgeo.geocaching.connector.ConnectorFactoryTest;
import cgeo.geocaching.connector.trackable.TravelBugConnector;
import cgeo.geocaching.enumerations.CacheType;
import cgeo.geocaching.location.Geopoint;
import cgeo.geocaching.location.Viewport;
import cgeo.geocaching.settings.Settings;
import cgeo.geocaching.settings.TestSettings;
import cgeo.geocaching.test.AbstractResourceInstrumentationTestCase;
import org.assertj.core.api.AbstractBooleanAssert;
import java.util.Set;
public class GCConnectorTest extends AbstractResourceInstrumentationTestCase {
public static void testGetViewport() {
// backup user settings
final boolean excludeMine = Settings.isExcludeMyCaches();
final CacheType cacheType = Settings.getCacheType();
try {
// set up settings required for test
TestSettings.setExcludeMine(false);
Settings.setCacheType(CacheType.ALL);
GCLogin.getInstance().login();
final MapTokens tokens = GCLogin.getInstance().getMapTokens();
{
final Viewport viewport = new Viewport(new Geopoint("N 52° 25.369 E 9° 35.499"), new Geopoint("N 52° 25.600 E 9° 36.200"));
final SearchResult searchResult = ConnectorFactory.searchByViewport(viewport, tokens);
assertThat(searchResult).isNotNull();
assertThat(searchResult.isEmpty()).isFalse();
assertThat(searchResult.getGeocodes()).contains("GC4ER5H");
}
{
final Viewport viewport = new Viewport(new Geopoint("N 52° 24.000 E 9° 34.500"), new Geopoint("N 52° 26.000 E 9° 38.500"));
final SearchResult searchResult = ConnectorFactory.searchByViewport(viewport, tokens);
assertThat(searchResult).isNotNull();
assertThat(searchResult.getGeocodes()).contains("GC4ER5H");
}
} finally {
// restore user settings
TestSettings.setExcludeMine(excludeMine);
Settings.setCacheType(cacheType);
}
}
public static void testCanHandle() {
assertCanHandle("GC2MEGA").isTrue();
assertCanHandle("OXZZZZZ").isFalse();
assertCanHandle("gc77").isTrue();
}
public static void testGeocodeForbiddenChars() {
assertCanHandle("GC123").isTrue();
assertCanHandle("GC123M").isTrue();
assertCanHandle("GC123L").overridingErrorMessage("L is not allowed in GC codes").isFalse();
}
private static AbstractBooleanAssert<?> assertCanHandle(final String geocode) {
return assertThat(GCConnector.getInstance().canHandle(geocode));
}
/**
* functionality moved to {@link TravelBugConnector}
*/
public static void testCanNotHandleTrackablesAnymore() {
assertCanHandle("TB3F651").isFalse();
}
public static void testBaseCodings() {
assertThat(GCConstants.gccodeToGCId("GC2MEGA")).isEqualTo(2045702);
}
/** Tile computation with different zoom levels */
public static void testTile() {
// http://coord.info/GC2CT8K = N 52° 30.462 E 013° 27.906
assertTileAt(8804, 5374, new Tile(new Geopoint(52.5077, 13.4651), 14));
// (8633, 5381); N 52° 24,516 E 009° 42,592
assertTileAt(8633, 5381, new Tile(new Geopoint("N 52° 24,516 E 009° 42,592"), 14));
// Hannover, GC22VTB UKM Memorial Tour
assertTileAt(2159, 1346, new Tile(new Geopoint("N 52° 22.177 E 009° 45.385"), 12));
// Seattle, GCK25B Groundspeak Headquarters
assertTileAt(5248, 11440, new Tile(new Geopoint("N 47° 38.000 W 122° 20.000"), 15));
// Sydney, GCXT2R Victoria Cross
assertTileAt(7536, 4915, new Tile(new Geopoint("S 33° 50.326 E 151° 12.426"), 13));
}
private static void assertTileAt(final int x, final int y, final Tile tile) {
assertThat(tile.getX()).isEqualTo(x);
assertThat(tile.getY()).isEqualTo(y);
}
public static void testGetGeocodeFromUrl() {
assertThat(GCConnector.getInstance().getGeocodeFromUrl("some string")).isNull();
assertThat(GCConnector.getInstance().getGeocodeFromUrl("http://coord.info/GC12ABC")).isEqualTo("GC12ABC");
assertThat(GCConnector.getInstance().getGeocodeFromUrl("http://www.coord.info/GC12ABC")).isEqualTo("GC12ABC");
assertThat(GCConnector.getInstance().getGeocodeFromUrl("https://www.geocaching.com/geocache/GC12ABC_die-muhlen-im-schondratal-muhle-munchau")).isEqualTo("GC12ABC");
assertThat(GCConnector.getInstance().getGeocodeFromUrl("http://geocaching.com/geocache/GC12ABC_die-muhlen-im-schondratal-muhle-munchau")).isEqualTo("GC12ABC");
assertThat(GCConnector.getInstance().getGeocodeFromUrl("http://coord.info/TB1234")).isNull();
assertThat(GCConnector.getInstance().getGeocodeFromUrl("http://www.coord.info/TB1234")).isNull();
assertThat(GCConnector.getInstance().getGeocodeFromUrl("http://www.coord.info/WM1234")).isNull();
// uppercase is managed in ConnectorFactory
assertThat(GCConnector.getInstance().getGeocodeFromUrl("http://coord.info/gc77")).isEqualTo("gc77");
}
public static void testHandledGeocodes() {
final Set<String> geocodes = ConnectorFactoryTest.getGeocodeSample();
assertThat(GCConnector.getInstance().handledGeocodes(geocodes)).containsOnly("GC1234", "GC5678");
}
}
|
tests/src-android/cgeo/geocaching/connector/gc/GCConnectorTest.java
|
package cgeo.geocaching.connector.gc;
import static org.assertj.core.api.Assertions.assertThat;
import cgeo.geocaching.SearchResult;
import cgeo.geocaching.connector.ConnectorFactory;
import cgeo.geocaching.connector.ConnectorFactoryTest;
import cgeo.geocaching.connector.trackable.TravelBugConnector;
import cgeo.geocaching.enumerations.CacheType;
import cgeo.geocaching.location.Geopoint;
import cgeo.geocaching.location.Viewport;
import cgeo.geocaching.settings.Settings;
import cgeo.geocaching.settings.TestSettings;
import cgeo.geocaching.test.AbstractResourceInstrumentationTestCase;
import java.util.Set;
public class GCConnectorTest extends AbstractResourceInstrumentationTestCase {
public static void testGetViewport() {
// backup user settings
final boolean excludeMine = Settings.isExcludeMyCaches();
final CacheType cacheType = Settings.getCacheType();
try {
// set up settings required for test
TestSettings.setExcludeMine(false);
Settings.setCacheType(CacheType.ALL);
GCLogin.getInstance().login();
final MapTokens tokens = GCLogin.getInstance().getMapTokens();
{
final Viewport viewport = new Viewport(new Geopoint("N 52° 25.369 E 9° 35.499"), new Geopoint("N 52° 25.600 E 9° 36.200"));
final SearchResult searchResult = ConnectorFactory.searchByViewport(viewport, tokens);
assertThat(searchResult).isNotNull();
assertThat(searchResult.isEmpty()).isFalse();
assertThat(searchResult.getGeocodes()).contains("GC4ER5H");
// 22.10.13: Changed from GC211WG (archived) to GC4ER5H in same area
}
{
final Viewport viewport = new Viewport(new Geopoint("N 52° 24.000 E 9° 34.500"), new Geopoint("N 52° 26.000 E 9° 38.500"));
final SearchResult searchResult = ConnectorFactory.searchByViewport(viewport, tokens);
assertThat(searchResult).isNotNull();
assertThat(searchResult.getGeocodes()).contains("GC4ER5H");
}
} finally {
// restore user settings
TestSettings.setExcludeMine(excludeMine);
Settings.setCacheType(cacheType);
}
}
public static void testCanHandle() {
assertThat(GCConnector.getInstance().canHandle("GC2MEGA")).isTrue();
assertThat(GCConnector.getInstance().canHandle("OXZZZZZ")).isFalse();
assertThat(GCConnector.getInstance().canHandle("gc77")).isTrue();
}
/**
* functionality moved to {@link TravelBugConnector}
*/
public static void testCanNotHandleTrackablesAnymore() {
assertThat(GCConnector.getInstance().canHandle("TB3F651")).isFalse();
}
public static void testBaseCodings() {
assertThat(GCConstants.gccodeToGCId("GC2MEGA")).isEqualTo(2045702);
}
/** Tile computation with different zoom levels */
public static void testTile() {
// http://coord.info/GC2CT8K = N 52° 30.462 E 013° 27.906
assertTileAt(8804, 5374, new Tile(new Geopoint(52.5077, 13.4651), 14));
// (8633, 5381); N 52° 24,516 E 009° 42,592
assertTileAt(8633, 5381, new Tile(new Geopoint("N 52° 24,516 E 009° 42,592"), 14));
// Hannover, GC22VTB UKM Memorial Tour
assertTileAt(2159, 1346, new Tile(new Geopoint("N 52° 22.177 E 009° 45.385"), 12));
// Seattle, GCK25B Groundspeak Headquarters
assertTileAt(5248, 11440, new Tile(new Geopoint("N 47° 38.000 W 122° 20.000"), 15));
// Sydney, GCXT2R Victoria Cross
assertTileAt(7536, 4915, new Tile(new Geopoint("S 33° 50.326 E 151° 12.426"), 13));
}
private static void assertTileAt(final int x, final int y, final Tile tile) {
assertThat(tile.getX()).isEqualTo(x);
assertThat(tile.getY()).isEqualTo(y);
}
public static void testGetGeocodeFromUrl() {
assertThat(GCConnector.getInstance().getGeocodeFromUrl("some string")).isNull();
assertThat(GCConnector.getInstance().getGeocodeFromUrl("http://coord.info/GC12ABC")).isEqualTo("GC12ABC");
assertThat(GCConnector.getInstance().getGeocodeFromUrl("http://www.coord.info/GC12ABC")).isEqualTo("GC12ABC");
assertThat(GCConnector.getInstance().getGeocodeFromUrl("https://www.geocaching.com/geocache/GC12ABC_die-muhlen-im-schondratal-muhle-munchau")).isEqualTo("GC12ABC");
assertThat(GCConnector.getInstance().getGeocodeFromUrl("http://geocaching.com/geocache/GC12ABC_die-muhlen-im-schondratal-muhle-munchau")).isEqualTo("GC12ABC");
assertThat(GCConnector.getInstance().getGeocodeFromUrl("http://coord.info/TB1234")).isNull();
assertThat(GCConnector.getInstance().getGeocodeFromUrl("http://www.coord.info/TB1234")).isNull();
assertThat(GCConnector.getInstance().getGeocodeFromUrl("http://www.coord.info/WM1234")).isNull();
// uppercase is managed in ConnectorFactory
assertThat(GCConnector.getInstance().getGeocodeFromUrl("http://coord.info/gc77")).isEqualTo("gc77");
}
public static void testHandledGeocodes() {
Set<String> geocodes = ConnectorFactoryTest.getGeocodeSample();
assertThat(GCConnector.getInstance().handledGeocodes(geocodes)).containsOnly("GC1234", "GC5678");
}
}
|
add test for geocode restrictions
|
tests/src-android/cgeo/geocaching/connector/gc/GCConnectorTest.java
|
add test for geocode restrictions
|
|
Java
|
apache-2.0
|
4f4be0f911b41038626b91b0fb48c1ea41bde0e7
| 0
|
Drooids/Android-Jigsaw-Puzzle,julesbond007/Android-Jigsaw-Puzzle,prashant31191/Android-Jigsaw-Puzzle,RudraNilBasu/Android-Jigsaw-Puzzle,suxinde2009/Android-Jigsaw-Puzzle,julesbond007/Android-Jigsaw-Puzzle,sergio11/Android-Jigsaw-Puzzle
|
package com.jigdraw.draw.views;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Xfermode;
import android.support.annotation.NonNull;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.View;
import com.jigdraw.draw.R;
/**
* Custom view to represent the drawing view the user use to draw.
*
* @author Jay Paulynice
*/
public class DrawingView extends View {
private Path drawPath;
private Paint drawPaint, canvasPaint;
private int paintColor = 0xFF660000;
private Canvas drawCanvas;
private Bitmap canvasBitmap;
private float brushSize, lastBrushSize;
/**
* Create new drawing view with context and attributes and setting up the
* default parameters.
*
* @param context the context
* @param attrs the attributes
*/
public DrawingView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
/**
* Init parameters
*/
private void init() {
brushSize = getResources().getInteger(R.integer.medium_size);
lastBrushSize = brushSize;
drawPath = new Path();
drawPaint = new Paint();
drawPaint.setColor(paintColor);
drawPaint.setAntiAlias(true);
drawPaint.setStrokeWidth(brushSize);
drawPaint.setStyle(Paint.Style.STROKE);
drawPaint.setStrokeJoin(Paint.Join.ROUND);
drawPaint.setStrokeCap(Paint.Cap.ROUND);
canvasPaint = new Paint(Paint.DITHER_FLAG);
}
@Override
public boolean onTouchEvent(@NonNull MotionEvent event) {
float touchX = event.getX();
float touchY = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
drawPath.moveTo(touchX, touchY);
break;
case MotionEvent.ACTION_MOVE:
drawPath.lineTo(touchX, touchY);
break;
case MotionEvent.ACTION_UP:
drawPath.lineTo(touchX, touchY);
drawCanvas.drawPath(drawPath, drawPaint);
drawPath.reset();
break;
default:
return false;
}
invalidate();
return true;
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
canvasBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
drawCanvas = new Canvas(canvasBitmap);
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawBitmap(canvasBitmap, 0, 0, canvasPaint);
canvas.drawPath(drawPath, drawPaint);
}
/**
* Set new color for drawing
*
* @param newColor the new color
*/
public void setColor(int newColor) {
invalidate();
paintColor = newColor;
drawPaint.setColor(newColor);
}
/**
* Set new brush size for drawing
*
* @param newSize the new color
*/
public void setBrushSize(float newSize) {
lastBrushSize = brushSize;
brushSize = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
newSize, getResources().getDisplayMetrics());
drawPaint.setStrokeWidth(brushSize);
}
/**
* Set erase to true when the erase button is clicked.
*
* @param isErase {@code true} if erase is clicked {@code false} otherwise
*/
public void setErase(boolean isErase) {
Xfermode xfermode = isErase ? new PorterDuffXfermode(
PorterDuff.Mode.CLEAR) : null;
drawPaint.setXfermode(xfermode);
}
/**
* Create new canvas
*/
public void startNew() {
drawCanvas.drawColor(0, PorterDuff.Mode.CLEAR);
invalidate();
}
/**
* @return the paint color
*/
public int getPaintColor() {
return paintColor;
}
}
|
app/src/main/java/com/jigdraw/draw/views/DrawingView.java
|
package com.jigdraw.draw.views;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Xfermode;
import android.support.annotation.NonNull;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.View;
import com.jigdraw.draw.R;
/**
* Custom view to represent the drawing view the user use to draw.
*
* @author Jay Paulynice
*/
public class DrawingView extends View {
private Path drawPath;
private Paint drawPaint, canvasPaint;
private int paintColor = 0xFF660000;
private Canvas drawCanvas;
private Bitmap canvasBitmap;
private float brushSize, lastBrushSize;
/**
* Create new drawing view with context and attributes and setting up the
* default parameters.
*
* @param context the context
* @param attrs the attributes
*/
public DrawingView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
/**
* Init parameters
*/
private void init() {
brushSize = getResources().getInteger(R.integer.medium_size);
lastBrushSize = brushSize;
drawPath = new Path();
drawPaint = new Paint();
drawPaint.setColor(paintColor);
drawPaint.setAntiAlias(true);
drawPaint.setStrokeWidth(brushSize);
drawPaint.setStyle(Paint.Style.STROKE);
drawPaint.setStrokeJoin(Paint.Join.ROUND);
drawPaint.setStrokeCap(Paint.Cap.ROUND);
canvasPaint = new Paint(Paint.DITHER_FLAG);
}
@Override
public boolean onTouchEvent(@NonNull MotionEvent event) {
float touchX = event.getX();
float touchY = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
drawPath.moveTo(touchX, touchY);
break;
case MotionEvent.ACTION_MOVE:
drawPath.lineTo(touchX, touchY);
break;
case MotionEvent.ACTION_UP:
drawPath.lineTo(touchX, touchY);
drawCanvas.drawPath(drawPath, drawPaint);
drawPath.reset();
break;
default:
return false;
}
invalidate();
return true;
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
canvasBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
drawCanvas = new Canvas(canvasBitmap);
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawBitmap(canvasBitmap, 0, 0, canvasPaint);
canvas.drawPath(drawPath, drawPaint);
}
/**
* Set new color for drawing
*
* @param newColor the new color
*/
public void setColor(int newColor) {
invalidate();
paintColor = newColor;
drawPaint.setColor(newColor);
}
/**
* Set new brush size for drawing
*
* @param newSize the new color
*/
public void setBrushSize(float newSize) {
lastBrushSize = brushSize;
brushSize = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
newSize, getResources().getDisplayMetrics());
drawPaint.setStrokeWidth(brushSize);
}
/**
* @return last brush size
*/
public float getLastBrushSize() {
return lastBrushSize;
}
/**
* Set erase to true when the erase button is clicked.
*
* @param isErase {@code true} if erase is clicked {@code false} otherwise
*/
public void setErase(boolean isErase) {
Xfermode xfermode = isErase ? new PorterDuffXfermode(
PorterDuff.Mode.CLEAR) : null;
drawPaint.setXfermode(xfermode);
}
/**
* Create new canvas
*/
public void startNew() {
drawCanvas.drawColor(0, PorterDuff.Mode.CLEAR);
invalidate();
}
/**
* @return the paint color
*/
public int getPaintColor() {
return paintColor;
}
}
|
clean up
|
app/src/main/java/com/jigdraw/draw/views/DrawingView.java
|
clean up
|
|
Java
|
apache-2.0
|
f738b9f86c101b9cd6f33b3413d77d49a818f22b
| 0
|
vidstige/jadb,vidstige/jadb
|
package se.vidstige.jadb.server;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
// >set ANDROID_ADB_SERVER_PORT=15037
public abstract class SocketServer implements Runnable {
private final int port;
private ServerSocket socket;
private Thread thread;
private boolean isStarted = false;
private final Object lockObject = new Object();
protected SocketServer(int port) {
this.port = port;
}
public void start() throws InterruptedException {
thread = new Thread(this, "Fake Adb Server");
thread.setDaemon(true);
thread.start();
waitForServer();
}
public int getPort() {
return port;
}
@SuppressWarnings("squid:S2189") // server is stopped by closing SocketServer
@Override
public void run() {
try {
socket = new ServerSocket(port);
socket.setReuseAddress(true);
serverReady();
while (true) {
Socket c = socket.accept();
createResponder(c).run();
}
} catch (IOException e) {
// Empty on purpose
}
}
private void serverReady() {
synchronized (lockObject) {
isStarted = true;
lockObject.notifyAll();
}
}
private void waitForServer() throws InterruptedException {
synchronized (lockObject) {
while (!isStarted) {
lockObject.wait();
}
}
}
protected abstract Runnable createResponder(Socket socket);
public void stop() throws IOException, InterruptedException {
socket.close();
thread.join();
}
}
|
src/se/vidstige/jadb/server/SocketServer.java
|
package se.vidstige.jadb.server;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
// >set ANDROID_ADB_SERVER_PORT=15037
public abstract class SocketServer implements Runnable {
private final int port;
private ServerSocket socket;
private Thread thread;
private boolean isStarted = false;
private final Object lockObject = new Object();
protected SocketServer(int port) {
this.port = port;
}
public void start() throws InterruptedException {
thread = new Thread(this, "Fake Adb Server");
thread.setDaemon(true);
thread.start();
waitForServer();
}
public int getPort() {
return port;
}
@SuppressWarnings("squid:S2189") // server is stopped by closing SocketServer
@Override
public void run() {
try {
socket = new ServerSocket(port);
socket.setReuseAddress(true);
serverReady();
while (true) {
Socket c = socket.accept();
Thread clientThread = new Thread(createResponder(c), "AdbClientWorker");
clientThread.setDaemon(true);
clientThread.start();
}
} catch (IOException e) {
// Empty on purpose
}
}
private void serverReady() {
synchronized (lockObject) {
isStarted = true;
lockObject.notifyAll();
}
}
private void waitForServer() throws InterruptedException {
synchronized (lockObject) {
while (!isStarted) {
lockObject.wait();
}
}
}
protected abstract Runnable createResponder(Socket socket);
public void stop() throws IOException, InterruptedException {
socket.close();
thread.join();
}
}
|
adbserver: no client threads
|
src/se/vidstige/jadb/server/SocketServer.java
|
adbserver: no client threads
|
|
Java
|
bsd-3-clause
|
e8d5a98529d927a77bfbbdca6c607550b517d67e
| 0
|
bdezonia/zorbage,bdezonia/zorbage
|
/*
* Zorbage: an algebraic data hierarchy for use in numeric processing.
*
* Copyright (C) 2016-2018 Barry DeZonia
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package nom.bdezonia.zorbage.type.data.int16;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import nom.bdezonia.zorbage.groups.G;
/**
*
* @author Barry DeZonia
*
*/
public class TestUnsignedInt16Group {
@Test
public void testPred() {
UnsignedInt16Member v = new UnsignedInt16Member();
v.setV(3);
assertEquals(3, v.v());
G.UINT16.pred().call(v, v);
assertEquals(2, v.v());
G.UINT16.pred().call(v, v);
assertEquals(1, v.v());
G.UINT16.pred().call(v, v);
assertEquals(0, v.v());
G.UINT16.pred().call(v, v);
assertEquals(0xffff, v.v());
G.UINT16.pred().call(v, v);
assertEquals(0xfffe, v.v());
G.UINT16.pred().call(v, v);
assertEquals(0xfffd, v.v());
v.setV(0x8002);
assertEquals(0x8002, v.v());
G.UINT16.pred().call(v, v);
assertEquals(0x8001, v.v());
G.UINT16.pred().call(v, v);
assertEquals(0x8000, v.v());
G.UINT16.pred().call(v, v);
assertEquals(0x7fff, v.v());
G.UINT16.pred().call(v, v);
assertEquals(0x7ffe, v.v());
G.UINT16.pred().call(v, v);
assertEquals(0x7ffd, v.v());
}
@Test
public void testSucc() {
UnsignedInt16Member v = new UnsignedInt16Member();
v.setV(0xfffd);
assertEquals(0xfffd, v.v());
G.UINT16.succ().call(v, v);
assertEquals(0xfffe, v.v());
G.UINT16.succ().call(v, v);
assertEquals(0xffff, v.v());
G.UINT16.succ().call(v, v);
assertEquals(0, v.v());
G.UINT16.succ().call(v, v);
assertEquals(1, v.v());
G.UINT16.succ().call(v, v);
assertEquals(2, v.v());
G.UINT16.succ().call(v, v);
assertEquals(3, v.v());
v.setV(0x7ffd);
assertEquals(0x7ffd, v.v());
G.UINT16.succ().call(v, v);
assertEquals(0x7ffe, v.v());
G.UINT16.succ().call(v, v);
assertEquals(0x7fff, v.v());
G.UINT16.succ().call(v, v);
assertEquals(0x8000, v.v());
G.UINT16.succ().call(v, v);
assertEquals(0x8001, v.v());
G.UINT16.succ().call(v, v);
assertEquals(0x8002, v.v());
}
}
|
src/test/java/nom/bdezonia/zorbage/type/data/int16/TestUnsignedInt16Group.java
|
/*
* Zorbage: an algebraic data hierarchy for use in numeric processing.
*
* Copyright (C) 2016-2018 Barry DeZonia
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package nom.bdezonia.zorbage.type.data.int16;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import nom.bdezonia.zorbage.groups.G;
/**
*
* @author Barry DeZonia
*
*/
public class TestUnsignedInt16Group {
@Test
public void testPred() {
UnsignedInt16Member v = new UnsignedInt16Member();
v.setV(3);
assertEquals(3, v.v());
G.UINT16.pred(v, v);
assertEquals(2, v.v());
G.UINT16.pred(v, v);
assertEquals(1, v.v());
G.UINT16.pred(v, v);
assertEquals(0, v.v());
G.UINT16.pred(v, v);
assertEquals(0xffff, v.v());
G.UINT16.pred(v, v);
assertEquals(0xfffe, v.v());
G.UINT16.pred(v, v);
assertEquals(0xfffd, v.v());
v.setV(0x8002);
assertEquals(0x8002, v.v());
G.UINT16.pred(v, v);
assertEquals(0x8001, v.v());
G.UINT16.pred(v, v);
assertEquals(0x8000, v.v());
G.UINT16.pred(v, v);
assertEquals(0x7fff, v.v());
G.UINT16.pred(v, v);
assertEquals(0x7ffe, v.v());
G.UINT16.pred(v, v);
assertEquals(0x7ffd, v.v());
}
@Test
public void testSucc() {
UnsignedInt16Member v = new UnsignedInt16Member();
v.setV(0xfffd);
assertEquals(0xfffd, v.v());
G.UINT16.succ(v, v);
assertEquals(0xfffe, v.v());
G.UINT16.succ(v, v);
assertEquals(0xffff, v.v());
G.UINT16.succ(v, v);
assertEquals(0, v.v());
G.UINT16.succ(v, v);
assertEquals(1, v.v());
G.UINT16.succ(v, v);
assertEquals(2, v.v());
G.UINT16.succ(v, v);
assertEquals(3, v.v());
v.setV(0x7ffd);
assertEquals(0x7ffd, v.v());
G.UINT16.succ(v, v);
assertEquals(0x7ffe, v.v());
G.UINT16.succ(v, v);
assertEquals(0x7fff, v.v());
G.UINT16.succ(v, v);
assertEquals(0x8000, v.v());
G.UINT16.succ(v, v);
assertEquals(0x8001, v.v());
G.UINT16.succ(v, v);
assertEquals(0x8002, v.v());
}
}
|
Further refactoring: fix compilation errors in tests
|
src/test/java/nom/bdezonia/zorbage/type/data/int16/TestUnsignedInt16Group.java
|
Further refactoring: fix compilation errors in tests
|
|
Java
|
mit
|
d2eee20c73211a5d9b4e2e0cd6ead4add4554f16
| 0
|
lemmy/tlaplus,tlaplus/tlaplus,lemmy/tlaplus,tlaplus/tlaplus,tlaplus/tlaplus,tlaplus/tlaplus,lemmy/tlaplus,lemmy/tlaplus
|
package org.lamport.tla.toolbox.ui.view;
import java.io.IOException;
import java.net.URL;
import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.swt.SWT;
import org.eclipse.swt.SWTError;
import org.eclipse.swt.browser.Browser;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.part.ViewPart;
import org.lamport.tla.toolbox.Activator;
import org.lamport.tla.toolbox.util.UIHelper;
import org.osgi.framework.Bundle;
/**
* The toolbox view that is shown when no spec is loaded.
* @author Daniel Ricketts
* @version $Id$
*/
public class ToolboxWelcomeView extends ViewPart
{
private Composite parentComposite;
public static final String ID = "toolbox.view.ToolboxWelcomeView";
public ToolboxWelcomeView()
{
}
public void createPartControl(Composite parent)
{
parentComposite = parent;
Browser browser = null;
try
{
browser = new Browser(parent, SWT.NONE);
} catch (SWTError e)
{
Activator.logError("Error instantiating browser widget.", e);
}
// this code is necessary for opening a local file in the plugin
Bundle plugin = Activator.getDefault().getBundle();
IPath relativePagePath = new Path("welcome\\welcomeView.html");
URL fileInPlugin = FileLocator.find(plugin, relativePagePath, null);
URL pageUrl;
try
{
pageUrl = FileLocator.toFileURL(fileInPlugin);
browser.setUrl(pageUrl.toString());
} catch (IOException e)
{
Activator.logError("Error opening toolbox welcome view file.", e);
}
UIHelper.setHelp(parent, "org.lamport.tla.toolbox.WelcomeView");
}
public void setFocus()
{
if (parentComposite != null)
{
parentComposite.setFocus();
}
}
}
|
org.lamport.tla.toolbox/src/org/lamport/tla/toolbox/ui/view/ToolboxWelcomeView.java
|
package org.lamport.tla.toolbox.ui.view;
import java.io.IOException;
import java.net.URL;
import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.swt.SWT;
import org.eclipse.swt.SWTError;
import org.eclipse.swt.browser.Browser;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.ViewPart;
import org.lamport.tla.toolbox.Activator;
import org.osgi.framework.Bundle;
/**
* The toolbox view that is shown when no spec is loaded.
* @author Daniel Ricketts
* @version $Id$
*/
public class ToolboxWelcomeView extends ViewPart
{
private Composite parentComposite;
public static final String ID = "toolbox.view.ToolboxWelcomeView";
public ToolboxWelcomeView()
{
}
public void createPartControl(Composite parent)
{
parentComposite = parent;
Browser browser = null;
try
{
browser = new Browser(parent, SWT.NONE);
} catch (SWTError e)
{
Activator.logError("Error instantiating browser widget.", e);
}
// this code is necessary for opening a local file in the plugin
Bundle plugin = Activator.getDefault().getBundle();
IPath relativePagePath = new Path("welcome\\welcomeView.html");
URL fileInPlugin = FileLocator.find(plugin, relativePagePath, null);
URL pageUrl;
try
{
pageUrl = FileLocator.toFileURL(fileInPlugin);
browser.setUrl(pageUrl.toString());
} catch (IOException e)
{
Activator.logError("Error opening toolbox welcome view file.", e);
}
PlatformUI.getWorkbench().getHelpSystem().setHelp(parent, "org.lamport.tla.toolbox.WelcomeView");
}
public void setFocus()
{
if (parentComposite != null)
{
parentComposite.setFocus();
}
}
}
|
Changed line to pre-exisitng method.
git-svn-id: 7acc490bd371dbc82047a939b87dc892fdc31f59@14401 76a6fc44-f60b-0410-a9a8-e67b0e8fc65c
|
org.lamport.tla.toolbox/src/org/lamport/tla/toolbox/ui/view/ToolboxWelcomeView.java
|
Changed line to pre-exisitng method.
|
|
Java
|
mit
|
0371d12dbf397f6590d1a6345ce32ca2c484f30a
| 0
|
elBukkit/MagicPlugin,elBukkit/MagicPlugin,elBukkit/MagicPlugin
|
package com.elmakers.mine.bukkit.action.builtin;
import com.elmakers.mine.bukkit.action.BaseSpellAction;
import com.elmakers.mine.bukkit.api.action.CastContext;
import com.elmakers.mine.bukkit.api.action.GUIAction;
import com.elmakers.mine.bukkit.api.block.MaterialAndData;
import com.elmakers.mine.bukkit.api.magic.Mage;
import com.elmakers.mine.bukkit.api.magic.MageClass;
import com.elmakers.mine.bukkit.api.magic.MageController;
import com.elmakers.mine.bukkit.api.magic.Messages;
import com.elmakers.mine.bukkit.api.spell.Spell;
import com.elmakers.mine.bukkit.api.spell.SpellKey;
import com.elmakers.mine.bukkit.api.spell.SpellResult;
import com.elmakers.mine.bukkit.api.spell.SpellTemplate;
import com.elmakers.mine.bukkit.heroes.HeroesManager;
import com.elmakers.mine.bukkit.magic.MagicController;
import com.elmakers.mine.bukkit.utility.CompatibilityUtils;
import com.elmakers.mine.bukkit.utility.InventoryUtils;
import com.elmakers.mine.bukkit.wand.Wand;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.ClickType;
import org.bukkit.event.inventory.InventoryAction;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryDragEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import javax.annotation.Nonnull;
public class SkillSelectorAction extends BaseSpellAction implements GUIAction {
private int page;
private List<SkillDescription> allSkills = new ArrayList<>();
private boolean quickCast = true;
private String classKey;
private int inventoryLimit = 0;
private String inventoryTitle;
private CastContext context;
@Override
public SpellResult perform(CastContext context) {
this.context = context;
MageController apiController = context.getController();
Player player = context.getMage().getPlayer();
if (player == null) {
return SpellResult.PLAYER_REQUIRED;
}
if (!(apiController instanceof MagicController)) return SpellResult.FAIL;
MagicController controller = (MagicController) apiController;
Messages messages = controller.getMessages();
HeroesManager heroes = controller.getHeroes();
allSkills.clear();
if (controller.useHeroesSkills() && heroes != null) {
@Nonnull String classString = heroes.getClassName(player);
@Nonnull String class2String = heroes.getSecondaryClassName(player);
String messageKey = !class2String.isEmpty() ? "skills.inventory_title_secondary" : "skills.inventory_title";
inventoryTitle = controller.getMessages().get(messageKey, "Skills ($page/$pages)");
inventoryTitle = inventoryTitle
.replace("$class2", class2String)
.replace("$class", classString);
List<String> heroesSkills = heroes.getSkillList(player, true, true);
for (String heroesSkill : heroesSkills) {
allSkills.add(new SkillDescription(heroes, controller, player, heroesSkill));
}
} else {
inventoryTitle = messages.get("skills.inventory_title");
}
if (controller.usePermissionSkills()) {
boolean bypassHidden = player.hasPermission("Magic.bypass_hidden");
Collection<SpellTemplate> spells = controller.getSpellTemplates(bypassHidden);
for (SpellTemplate spell : spells) {
SpellKey key = spell.getSpellKey();
if (key.isVariant()) continue;
if (key.getBaseKey().startsWith("heroes*")) continue;
if (!spell.hasCastPermission(player)) continue;
allSkills.add(new SkillDescription(spell));
}
} else {
Mage mage = controller.getMage(player);
MageClass activeClass = mage.getActiveClass();
if (activeClass != null) {
classKey = activeClass.getKey();
quickCast = activeClass.getProperty("quick_cast", true);
inventoryLimit = activeClass.getProperty("skill_limit", 0);
Collection<String> spells = activeClass.getSpells();
for (String spellKey : spells) {
SpellTemplate spell = controller.getSpellTemplate(spellKey);
if (spell != null) {
allSkills.add(new SkillDescription(spell));
}
}
}
}
if (allSkills.size() == 0) {
player.sendMessage(messages.get("skills.none"));
return SpellResult.NO_ACTION;
}
Collections.sort(allSkills);
openInventory();
return SpellResult.CAST;
}
class SkillDescription implements Comparable<SkillDescription> {
public String heroesSkill;
public SpellTemplate spell;
private int skillLevel = 0;
public SkillDescription(SpellTemplate spell) {
this.spell = spell;
}
public SkillDescription(HeroesManager heroes, MageController controller, Player player, String heroesSkill) {
this.heroesSkill = heroesSkill;
this.spell = controller.getSpellTemplate(getSpellKey());
skillLevel = heroes.getSkillLevel(player, heroesSkill);
}
public String getSkillKey() {
String key = getSpellKey();
if (key != null) {
key = "skill:" + key;
}
return key;
}
public String getSpellKey() {
if (heroesSkill != null) {
return "heroes*" + heroesSkill;
}
if (spell != null) {
return spell.getKey();
}
return null;
}
public String getSpellName() {
if (spell != null) return spell.getName();
return heroesSkill;
}
public boolean isHeroes() {
return heroesSkill != null;
}
@Override
public int compareTo(SkillDescription other) {
if (heroesSkill != null && skillLevel != other.skillLevel) {
return Integer.compare(skillLevel, other.skillLevel);
}
return getSpellName().compareTo(other.getSpellName());
}
};
public SkillSelectorAction() {
}
public void setPage(int page) {
this.page = page;
}
protected void openInventory() {
MageController apiController = context.getController();
if (!(apiController instanceof MagicController)) return;
MagicController controller = (MagicController) apiController;
HeroesManager heroes = controller.getHeroes();
int inventorySize = 9 * controller.getSkillInventoryRows();
int numPages = (int)Math.ceil((float)allSkills.size() / inventorySize);
if (page < 1) page = numPages;
else if (page > numPages) page = 1;
Mage mage = context.getMage();
Player player = mage.getPlayer();
int pageIndex = page - 1;
int startIndex = pageIndex * inventorySize;
int maxIndex = (pageIndex + 1) * inventorySize - 1;
List<SkillDescription> skills = new ArrayList<>();
for (int i = startIndex; i <= maxIndex && i < allSkills.size(); i++) {
skills.add(allSkills.get(i));
}
if (skills.size() == 0)
{
String messageTemplate = controller.getMessages().get("skills.none_on_page", "$page");
player.sendMessage(messageTemplate.replace("$page", Integer.toString(page)));
return;
}
int invSize = (int)Math.ceil(skills.size() / 9.0f) * 9;
String title = inventoryTitle;
title = title
.replace("$pages", Integer.toString(numPages))
.replace("$page", Integer.toString(page));
Inventory displayInventory = CompatibilityUtils.createInventory(null, invSize, title);
for (SkillDescription skill : skills)
{
ItemStack skillItem = controller.getAPI().createItem(skill.getSkillKey(), mage);
if (skillItem == null) continue;
if (!quickCast) {
Object spellNode = InventoryUtils.getNode(skillItem, "spell");
if (spellNode != null) {
InventoryUtils.setMetaBoolean(spellNode, "quick_cast", false);
}
}
if (classKey != null) {
Object spellNode = InventoryUtils.getNode(skillItem, "spell");
if (spellNode != null) {
InventoryUtils.setMeta(spellNode, "class", classKey);
}
}
if (skill.isHeroes() && heroes != null && !heroes.canUseSkill(player, skill.heroesSkill))
{
String nameTemplate = controller.getMessages().get("skills.item_name_unavailable", "$skill");
String spellName = skill.spell != null ? skill.spell.getName() : skill.heroesSkill;
CompatibilityUtils.setDisplayName(skillItem, nameTemplate.replace("$skill", spellName));
InventoryUtils.setMetaBoolean(skillItem, "unavailable", true);
if (skill.spell != null) {
MaterialAndData disabledIcon = skill.spell.getDisabledIcon();
if (disabledIcon != null) {
disabledIcon.applyToItem(skillItem);
} else {
String disabledIconURL = skill.spell.getDisabledIconURL();
if (disabledIconURL != null && !disabledIconURL.isEmpty()) {
InventoryUtils.setNewSkullURL(skillItem, disabledIconURL);
}
}
}
}
displayInventory.addItem(skillItem);
}
mage.deactivateGUI();
mage.activateGUI(this, displayInventory);
}
@Override
public void deactivated() {
}
@Override
public void clicked(InventoryClickEvent event) {
InventoryAction action = event.getAction();
if (action == InventoryAction.NOTHING) {
int direction = event.getClick() == ClickType.LEFT ? 1 : -1;
page = page + direction;
openInventory();
event.setCancelled(true);
return;
}
ItemStack clickedItem = event.getCurrentItem();
if (clickedItem != null && InventoryUtils.getMetaBoolean(clickedItem, "unavailable", false)) {
event.setCancelled(true);
return;
}
Mage mage = context.getMage();
MageController controller = mage.getController();
Inventory inventory = mage.getInventory();
boolean isContainerSlot = event.getSlot() == event.getRawSlot();
boolean isDrop = action == InventoryAction.DROP_ALL_CURSOR || action == InventoryAction.DROP_ALL_SLOT
|| action == InventoryAction.DROP_ONE_CURSOR || action == InventoryAction.DROP_ONE_SLOT;
if (!isContainerSlot && isDrop && controller.isSkill(clickedItem)) {
inventory.setItem(event.getSlot(), null);
return;
}
if (inventoryLimit > 0) {
boolean isHotbar = event.getAction() == InventoryAction.HOTBAR_SWAP || event.getAction() == InventoryAction.HOTBAR_MOVE_AND_READD;
if (isHotbar) {
ItemStack destinationItem = inventory.getItem(event.getHotbarButton());
if (controller.isSkill(destinationItem)) return;
isHotbar = controller.isSkill(clickedItem);
}
if (!isContainerSlot && !isHotbar) return;
int skillCount = 0;
for (int i = 0; i < inventory.getSize(); i++) {
ItemStack item = inventory.getItem(i);
if (controller.isSkill(item)) skillCount++;
}
if (skillCount >= inventoryLimit) {
event.setCancelled(true);
}
return;
}
// We don't allow quick-casting here if there is an inventory limit.
if (action == InventoryAction.PICKUP_HALF && mage != null)
{
Spell spell = mage.getSpell(Wand.getSpell(clickedItem));
if (spell != null) {
spell.cast();
}
mage.getPlayer().closeInventory();
event.setCancelled(true);
}
}
@Override
public void dragged(InventoryDragEvent event) {
}
}
|
Magic/src/main/java/com/elmakers/mine/bukkit/action/builtin/SkillSelectorAction.java
|
package com.elmakers.mine.bukkit.action.builtin;
import com.elmakers.mine.bukkit.action.BaseSpellAction;
import com.elmakers.mine.bukkit.api.action.CastContext;
import com.elmakers.mine.bukkit.api.action.GUIAction;
import com.elmakers.mine.bukkit.api.block.MaterialAndData;
import com.elmakers.mine.bukkit.api.magic.Mage;
import com.elmakers.mine.bukkit.api.magic.MageClass;
import com.elmakers.mine.bukkit.api.magic.MageController;
import com.elmakers.mine.bukkit.api.magic.Messages;
import com.elmakers.mine.bukkit.api.spell.Spell;
import com.elmakers.mine.bukkit.api.spell.SpellKey;
import com.elmakers.mine.bukkit.api.spell.SpellResult;
import com.elmakers.mine.bukkit.api.spell.SpellTemplate;
import com.elmakers.mine.bukkit.heroes.HeroesManager;
import com.elmakers.mine.bukkit.magic.MagicController;
import com.elmakers.mine.bukkit.utility.CompatibilityUtils;
import com.elmakers.mine.bukkit.utility.InventoryUtils;
import com.elmakers.mine.bukkit.wand.Wand;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.ClickType;
import org.bukkit.event.inventory.InventoryAction;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryDragEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import javax.annotation.Nonnull;
public class SkillSelectorAction extends BaseSpellAction implements GUIAction {
private int page;
private List<SkillDescription> allSkills = new ArrayList<>();
private boolean quickCast = true;
private int inventoryLimit = 0;
private String inventoryTitle;
private CastContext context;
@Override
public SpellResult perform(CastContext context) {
this.context = context;
MageController apiController = context.getController();
Player player = context.getMage().getPlayer();
if (player == null) {
return SpellResult.PLAYER_REQUIRED;
}
if (!(apiController instanceof MagicController)) return SpellResult.FAIL;
MagicController controller = (MagicController) apiController;
Messages messages = controller.getMessages();
HeroesManager heroes = controller.getHeroes();
allSkills.clear();
if (controller.useHeroesSkills() && heroes != null) {
@Nonnull String classString = heroes.getClassName(player);
@Nonnull String class2String = heroes.getSecondaryClassName(player);
String messageKey = !class2String.isEmpty() ? "skills.inventory_title_secondary" : "skills.inventory_title";
inventoryTitle = controller.getMessages().get(messageKey, "Skills ($page/$pages)");
inventoryTitle = inventoryTitle
.replace("$class2", class2String)
.replace("$class", classString);
List<String> heroesSkills = heroes.getSkillList(player, true, true);
for (String heroesSkill : heroesSkills) {
allSkills.add(new SkillDescription(heroes, controller, player, heroesSkill));
}
} else {
inventoryTitle = messages.get("skills.inventory_title");
}
if (controller.usePermissionSkills()) {
boolean bypassHidden = player.hasPermission("Magic.bypass_hidden");
Collection<SpellTemplate> spells = controller.getSpellTemplates(bypassHidden);
for (SpellTemplate spell : spells) {
SpellKey key = spell.getSpellKey();
if (key.isVariant()) continue;
if (key.getBaseKey().startsWith("heroes*")) continue;
if (!spell.hasCastPermission(player)) continue;
allSkills.add(new SkillDescription(spell));
}
} else {
Mage mage = controller.getMage(player);
MageClass activeClass = mage.getActiveClass();
if (activeClass != null) {
quickCast = activeClass.getProperty("quick_cast", true);
inventoryLimit = activeClass.getProperty("skill_limit", 0);
Collection<String> spells = activeClass.getSpells();
for (String spellKey : spells) {
SpellTemplate spell = controller.getSpellTemplate(spellKey);
if (spell != null) {
allSkills.add(new SkillDescription(spell));
}
}
}
}
if (allSkills.size() == 0) {
player.sendMessage(messages.get("skills.none"));
return SpellResult.NO_ACTION;
}
Collections.sort(allSkills);
openInventory();
return SpellResult.CAST;
}
class SkillDescription implements Comparable<SkillDescription> {
public String heroesSkill;
public SpellTemplate spell;
private int skillLevel = 0;
public SkillDescription(SpellTemplate spell) {
this.spell = spell;
}
public SkillDescription(HeroesManager heroes, MageController controller, Player player, String heroesSkill) {
this.heroesSkill = heroesSkill;
this.spell = controller.getSpellTemplate(getSpellKey());
skillLevel = heroes.getSkillLevel(player, heroesSkill);
}
public String getSkillKey() {
String key = getSpellKey();
if (key != null) {
key = "skill:" + key;
}
return key;
}
public String getSpellKey() {
if (heroesSkill != null) {
return "heroes*" + heroesSkill;
}
if (spell != null) {
return spell.getKey();
}
return null;
}
public String getSpellName() {
if (spell != null) return spell.getName();
return heroesSkill;
}
public boolean isHeroes() {
return heroesSkill != null;
}
@Override
public int compareTo(SkillDescription other) {
if (heroesSkill != null && skillLevel != other.skillLevel) {
return Integer.compare(skillLevel, other.skillLevel);
}
return getSpellName().compareTo(other.getSpellName());
}
};
public SkillSelectorAction() {
}
public void setPage(int page) {
this.page = page;
}
protected void openInventory() {
MageController apiController = context.getController();
if (!(apiController instanceof MagicController)) return;
MagicController controller = (MagicController) apiController;
HeroesManager heroes = controller.getHeroes();
int inventorySize = 9 * controller.getSkillInventoryRows();
int numPages = (int)Math.ceil((float)allSkills.size() / inventorySize);
if (page < 1) page = numPages;
else if (page > numPages) page = 1;
Mage mage = context.getMage();
Player player = mage.getPlayer();
int pageIndex = page - 1;
int startIndex = pageIndex * inventorySize;
int maxIndex = (pageIndex + 1) * inventorySize - 1;
List<SkillDescription> skills = new ArrayList<>();
for (int i = startIndex; i <= maxIndex && i < allSkills.size(); i++) {
skills.add(allSkills.get(i));
}
if (skills.size() == 0)
{
String messageTemplate = controller.getMessages().get("skills.none_on_page", "$page");
player.sendMessage(messageTemplate.replace("$page", Integer.toString(page)));
return;
}
int invSize = (int)Math.ceil(skills.size() / 9.0f) * 9;
String title = inventoryTitle;
title = title
.replace("$pages", Integer.toString(numPages))
.replace("$page", Integer.toString(page));
Inventory displayInventory = CompatibilityUtils.createInventory(null, invSize, title);
for (SkillDescription skill : skills)
{
ItemStack skillItem = controller.getAPI().createItem(skill.getSkillKey(), mage);
if (skillItem == null) continue;
if (!quickCast) {
Object spellNode = InventoryUtils.getNode(skillItem, "spell");
if (spellNode != null) {
InventoryUtils.setMetaBoolean(spellNode, "quick_cast", false);
}
}
if (skill.isHeroes() && heroes != null && !heroes.canUseSkill(player, skill.heroesSkill))
{
String nameTemplate = controller.getMessages().get("skills.item_name_unavailable", "$skill");
String spellName = skill.spell != null ? skill.spell.getName() : skill.heroesSkill;
CompatibilityUtils.setDisplayName(skillItem, nameTemplate.replace("$skill", spellName));
InventoryUtils.setMetaBoolean(skillItem, "unavailable", true);
if (skill.spell != null) {
MaterialAndData disabledIcon = skill.spell.getDisabledIcon();
if (disabledIcon != null) {
disabledIcon.applyToItem(skillItem);
} else {
String disabledIconURL = skill.spell.getDisabledIconURL();
if (disabledIconURL != null && !disabledIconURL.isEmpty()) {
InventoryUtils.setNewSkullURL(skillItem, disabledIconURL);
}
}
}
}
displayInventory.addItem(skillItem);
}
mage.deactivateGUI();
mage.activateGUI(this, displayInventory);
}
@Override
public void deactivated() {
}
@Override
public void clicked(InventoryClickEvent event) {
InventoryAction action = event.getAction();
if (action == InventoryAction.NOTHING) {
int direction = event.getClick() == ClickType.LEFT ? 1 : -1;
page = page + direction;
openInventory();
event.setCancelled(true);
return;
}
ItemStack clickedItem = event.getCurrentItem();
if (clickedItem != null && InventoryUtils.getMetaBoolean(clickedItem, "unavailable", false)) {
event.setCancelled(true);
return;
}
Mage mage = context.getMage();
MageController controller = mage.getController();
Inventory inventory = mage.getInventory();
boolean isContainerSlot = event.getSlot() == event.getRawSlot();
boolean isDrop = action == InventoryAction.DROP_ALL_CURSOR || action == InventoryAction.DROP_ALL_SLOT
|| action == InventoryAction.DROP_ONE_CURSOR || action == InventoryAction.DROP_ONE_SLOT;
if (!isContainerSlot && isDrop && controller.isSkill(clickedItem)) {
inventory.setItem(event.getSlot(), null);
return;
}
if (inventoryLimit > 0) {
boolean isHotbar = event.getAction() == InventoryAction.HOTBAR_SWAP || event.getAction() == InventoryAction.HOTBAR_MOVE_AND_READD;
if (isHotbar) {
ItemStack destinationItem = inventory.getItem(event.getHotbarButton());
if (controller.isSkill(destinationItem)) return;
isHotbar = controller.isSkill(clickedItem);
}
if (!isContainerSlot && !isHotbar) return;
int skillCount = 0;
for (int i = 0; i < inventory.getSize(); i++) {
ItemStack item = inventory.getItem(i);
if (controller.isSkill(item)) skillCount++;
}
if (skillCount >= inventoryLimit) {
event.setCancelled(true);
}
return;
}
// We don't allow quick-casting here if there is an inventory limit.
if (action == InventoryAction.PICKUP_HALF && mage != null)
{
Spell spell = mage.getSpell(Wand.getSpell(clickedItem));
if (spell != null) {
spell.cast();
}
mage.getPlayer().closeInventory();
event.setCancelled(true);
}
}
@Override
public void dragged(InventoryDragEvent event) {
}
}
|
Skill selector should assign active class to skill icons
|
Magic/src/main/java/com/elmakers/mine/bukkit/action/builtin/SkillSelectorAction.java
|
Skill selector should assign active class to skill icons
|
|
Java
|
mit
|
43e9296749710477bd41a59bd50b518daf560b15
| 0
|
scr/j8iterables
|
package com.github.scr.j8iterables;
import com.github.scr.j8iterables.core.ConsumingIdentity;
import com.github.scr.j8iterables.core.Ends;
import com.github.scr.j8iterables.core.J8PrimitiveIterable;
import com.github.scr.j8iterables.core.PeekIterator;
import com.github.scr.j8iterables.core.StreamIterable;
import com.github.scr.j8iterables.core.SupplierIterable;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.Iterables;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.*;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.BinaryOperator;
import java.util.function.Consumer;
import java.util.function.Supplier;
import java.util.function.ToDoubleFunction;
import java.util.function.ToIntFunction;
import java.util.function.ToLongFunction;
import java.util.stream.Collector;
import java.util.stream.DoubleStream;
import java.util.stream.IntStream;
import java.util.stream.LongStream;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
/**
* Utility methods to extend Guava Iterables with Java 8 Stream-like classes such as Collectors.
*
* @author scr
*/
@SuppressWarnings({"WeakerAccess", "Guava"})
public class J8Iterables {
/**
* The empty iterable to be shared across calls to {@link #emptyIterable()}.
*/
public static final FluentIterable EMPTY_ITERABLE = fromSupplier(Collections::emptyIterator);
@VisibleForTesting
J8Iterables() {
}
/**
* Collect iterable of iterables into a mutable container.
*
* @param iterables The iterable of iterables
* @param supplier The container supplier
* @param accumulator The accumulator function
* @param combiner The combiner function
* @param <T> The type of elements
* @param <R> The return type
* @return Collected result
* @see Stream#collect(Supplier, BiConsumer, BiConsumer)
*/
@Nullable
public static <T, R> R collect(Iterable<Iterable<T>> iterables,
Supplier<R> supplier,
BiConsumer<R, ? super T> accumulator,
BiConsumer<R, R> combiner) {
R result = supplier.get();
for (Iterable<T> iterable : iterables) {
R innerResult = supplier.get();
for (T element : iterable) {
accumulator.accept(innerResult, element);
}
combiner.accept(result, innerResult);
}
return result;
}
/**
* Collect iterable into a mutable container.
*
* @param iterable The iterable
* @param collector The collector object
* @param <T> The type of elements
* @param <A> The type of accumulator
* @param <R> The return type
* @return Collected result
* @see Stream#collect(Collector)
*/
@Nullable
public static <T, A, R> R collect(Iterable<T> iterable, Collector<? super T, A, R> collector) {
A container = collector.supplier().get();
BiConsumer<A, ? super T> accumulator = collector.accumulator();
for (T t : iterable) {
accumulator.accept(container, t);
}
return collector.finisher().apply(container);
}
/**
* Perform a reduction on iterable.
*
* @param iterable The iterable
* @param accumulator The accumulator function
* @param <T> The type of elements
* @return The reduced result
* @see Stream#reduce(BinaryOperator)
*/
@Nullable
public static <T> Optional<T> reduce(Iterable<T> iterable, BinaryOperator<T> accumulator) {
boolean foundAny = false;
T result = null;
for (T element : iterable) {
if (!foundAny) {
foundAny = true;
result = element;
} else {
result = accumulator.apply(result, element);
}
}
return foundAny ? Optional.of(result) : Optional.empty();
}
/**
* Perform a reduction on an iterable.
*
* @param iterable The iterable
* @param identity The identity to start reduction with
* @param accumulator The accumulator function
* @param <T> The type of elements
* @return The reduced result
* @see Stream#reduce(Object, BinaryOperator)
*/
@Nullable
public static <T> T reduce(Iterable<T> iterable,
@SuppressWarnings("SameParameterValue") @Nullable T identity,
BinaryOperator<T> accumulator) {
T result = identity;
for (T element : iterable) {
result = accumulator.apply(result, element);
}
return result;
}
/**
* Perform a reduction on an iterable of iterables.
*
* @param iterables An iterator of iterables.
* @param identity The identity to start reduction with
* @param accumulator The accumulator function
* @param combiner The combiner function
* @param <T> The type of elements
* @param <U> The reduced type
* @return The reduced result
* @see Stream#reduce(Object, BiFunction, BinaryOperator)
*/
@Nullable
public static <T, U> U reduce(Iterable<Iterable<T>> iterables,
@SuppressWarnings("SameParameterValue") @Nullable U identity,
BiFunction<U, ? super T, U> accumulator,
BinaryOperator<U> combiner) {
U result = identity;
for (Iterable<T> iterable : iterables) {
U innerResult = identity;
for (T element : iterable) {
innerResult = accumulator.apply(innerResult, element);
}
result = combiner.apply(result, innerResult);
}
return result;
}
/**
* Return the first and last elements or {@link Optional#empty()} if {@code Iterables.isEmpty(iterable)}.
*
* @param iterable The iterable to get the ends from
* @param <T> The type of element in the iterable
* @return optional {@link Ends} with the first and last of the iterable
*/
@Nonnull
public static <T> Optional<Ends<T>> ends(Iterable<T> iterable) {
return J8Iterators.ends(iterable.iterator());
}
/**
* Peek at the iterable without modifying the result.
*
* @param iterable The iterable to peek at
* @param consumer The peeking function
* @param <T> The type of elements
* @return an Iterable that, when traversed will invoke the consumer on each element
* @see Stream#peek(Consumer)
*/
@Nonnull
public static <T> FluentIterable<T> peek(Iterable<T> iterable, Consumer<? super T> consumer) {
return fromSupplier(() -> new PeekIterator<>(iterable.iterator(), consumer));
}
/**
* Return a peeking transformer - a UnaryOperator that will send each element to the consumer and return identity.
*
* @param consumer The peeking function
* @param <T> The type of elements
* @return a peeking (non-transforming) transformer
*/
@Nonnull
public static <T> ConsumingIdentity<T> peeker(Consumer<T> consumer) {
return new ConsumingIdentity<>(consumer);
}
/**
* Create a one-time Iterable from a Stream.
*
* @param stream The Stream to use in creating an Iterable
* @param <T> The type of elements
* @return Iterable from the given stream
*/
@Nonnull
public static <T> FluentIterable<T> fromStream(Stream<T> stream) {
return new StreamIterable<>(stream);
}
/**
* Create a {@link Stream} from the given {@link Iterable}.
*
* @param iterable The Iterable to use in creating a Stream
* @param <T> The type of elements
* @return Stream from the given iterable
*/
@Nonnull
public static <T> Stream<T> toStream(Iterable<T> iterable) {
if (iterable instanceof Collection) {
return ((Collection<T>) iterable).stream();
}
// TODO(scr): Is it possible to do late-binding (iterable::spliterator)? Need to know characteristics.
return StreamSupport.stream(iterable.spliterator(), false);
}
/**
* Create an {@link DoubleStream} from the given {@code doubleIterable}.
*
* @param doubleIterable The iterable to use in creating a DoubleStream
* @return DoubleStream from the given iterable
*/
@Nonnull
public static DoubleStream toStream(J8PrimitiveIterable.OfDouble doubleIterable) {
// TODO(scr): Is it possible to do late-binding (iterable::spliterator)? Need to know characteristics.
return StreamSupport.doubleStream(doubleIterable.primitiveSpliterator(), false);
}
/**
* Create an {@link IntStream} from the given {@code intIterable}.
*
* @param intIterable The iterable to use in creating an IntStream
* @return IntStream from the given iterable
*/
@Nonnull
public static IntStream toStream(J8PrimitiveIterable.OfInt intIterable) {
// TODO(scr): Is it possible to do late-binding (iterable::spliterator)? Need to know characteristics.
return StreamSupport.intStream(intIterable.primitiveSpliterator(), false);
}
/**
* Create a {@link LongStream} from the given {@code iterable}.
*
* @param longIterable The iterable to use in creating a LongStream
* @return LongStream from the given iterable
*/
@Nonnull
public static LongStream toStream(J8PrimitiveIterable.OfLong longIterable) {
// TODO(scr): Is it possible to do late-binding (iterable::spliterator)? Need to know characteristics.
return StreamSupport.longStream(longIterable.primitiveSpliterator(), false);
}
/**
* Return a {@link FluentIterable} that is always empty.
*
* @param <T> The type of the FluentIterable
* @return an empty FluentIterable
*/
@SuppressWarnings("unchecked")
@Nonnull
public static <T> FluentIterable<T> emptyIterable() {
return (FluentIterable<T>) EMPTY_ITERABLE;
}
/**
* Create a FluentIterable for elements.
* <p>
* Provides a wrapper to help where {@link FluentIterable} falls short - no varargs static constructor for testing.
*
* @param elements the elements to iterate over
* @param <T> the type of elements
* @return a FluentIterable for elements
*/
@SafeVarargs
@Nonnull
public static <T> FluentIterable<T> of(T... elements) {
return FluentIterable.from(Arrays.asList(elements));
}
/**
* Reverse the given {@code iterable}.
*
* @param iterable an iterable to reverse
* @param <T> the type of elements
* @return an iterable that reverses the navigableSet
*/
@Nonnull
public static <T> FluentIterable<T> reverse(Iterable<? extends T> iterable) {
// If it's already reversable, return it.
if (iterable instanceof NavigableSet) {
@SuppressWarnings("unchecked")
NavigableSet<T> navigableSet = (NavigableSet<T>) iterable;
return fromSupplier(navigableSet::descendingIterator);
} else if (iterable instanceof Deque) {
@SuppressWarnings("unchecked")
Deque<T> deque = (Deque<T>) iterable;
return fromSupplier(deque::descendingIterator);
} else if (iterable instanceof List) {
@SuppressWarnings("unchecked")
List<T> list = (List<T>) iterable;
return fromSupplier(() -> J8Iterators.reverse(list.listIterator(list.size())));
}
// Slurp everything into a deque and then reverse its order.
return fromSupplier(() -> {
Deque<T> deque = new ArrayDeque<>();
Iterables.addAll(deque, iterable);
return deque.descendingIterator();
});
}
/**
* Create a {@link FluentIterable} from the given {@link Supplier}.
*
* @param supplier the supplier
* @param <T> the type of elements of the supplied iterable
* @return an iterable
*/
@Nonnull
public static <T> SupplierIterable<T> fromSupplier(Supplier<Iterator<? extends T>> supplier) {
@SuppressWarnings("unchecked")
Supplier<Iterator<T>> tSupplier = (Supplier<Iterator<T>>) (Supplier) supplier;
return new SupplierIterable<>(tSupplier);
}
@Nonnull
public static <T> J8PrimitiveIterable.OfDouble mapToDouble(
Iterable<T> iterable, ToDoubleFunction<T> toDoubleFunction) {
return new J8PrimitiveIterable.OfDouble() {
@Override
public PrimitiveIterator.OfDouble primitiveIterator() {
return J8Iterators.mapToDouble(iterable.iterator(), toDoubleFunction);
}
@Override
public Spliterator.OfDouble primitiveSpliterator() {
return J8Spliterators.mapToDouble(iterable.spliterator(), toDoubleFunction);
}
};
}
@Nonnull
public static <T> J8PrimitiveIterable.OfInt mapToInt(
Iterable<T> iterable, ToIntFunction<T> toIntFunction) {
return new J8PrimitiveIterable.OfInt() {
@Override
public PrimitiveIterator.OfInt primitiveIterator() {
return J8Iterators.mapToInt(iterable.iterator(), toIntFunction);
}
@Override
public Spliterator.OfInt primitiveSpliterator() {
return J8Spliterators.mapToInt(iterable.spliterator(), toIntFunction);
}
};
}
@Nonnull
public static <T> J8PrimitiveIterable.OfLong mapToLong(
Iterable<T> iterable, ToLongFunction<T> toLongFunction) {
return new J8PrimitiveIterable.OfLong() {
@Override
public PrimitiveIterator.OfLong primitiveIterator() {
return J8Iterators.mapToLong(iterable.iterator(), toLongFunction);
}
@Override
public Spliterator.OfLong primitiveSpliterator() {
return J8Spliterators.mapToLong(iterable.spliterator(), toLongFunction);
}
};
}
}
|
src/main/java/com/github/scr/j8iterables/J8Iterables.java
|
package com.github.scr.j8iterables;
import com.github.scr.j8iterables.core.ConsumingIdentity;
import com.github.scr.j8iterables.core.Ends;
import com.github.scr.j8iterables.core.J8PrimitiveIterable;
import com.github.scr.j8iterables.core.PeekIterator;
import com.github.scr.j8iterables.core.StreamIterable;
import com.github.scr.j8iterables.core.SupplierIterable;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.Iterables;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.ArrayDeque;
import java.util.Collection;
import java.util.Collections;
import java.util.Deque;
import java.util.Iterator;
import java.util.List;
import java.util.NavigableSet;
import java.util.Optional;
import java.util.PrimitiveIterator;
import java.util.Spliterator;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.BinaryOperator;
import java.util.function.Consumer;
import java.util.function.Supplier;
import java.util.function.ToDoubleFunction;
import java.util.function.ToIntFunction;
import java.util.function.ToLongFunction;
import java.util.stream.Collector;
import java.util.stream.DoubleStream;
import java.util.stream.IntStream;
import java.util.stream.LongStream;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
/**
* Utility methods to extend Guava Iterables with Java 8 Stream-like classes such as Collectors.
*
* @author scr
*/
@SuppressWarnings({"WeakerAccess", "Guava"})
public class J8Iterables {
/**
* The empty iterable to be shared across calls to {@link #emptyIterable()}.
*/
public static final FluentIterable EMPTY_ITERABLE = fromSupplier(Collections::emptyIterator);
@VisibleForTesting
J8Iterables() {
}
/**
* Collect iterable of iterables into a mutable container.
*
* @param iterables The iterable of iterables
* @param supplier The container supplier
* @param accumulator The accumulator function
* @param combiner The combiner function
* @param <T> The type of elements
* @param <R> The return type
* @return Collected result
* @see Stream#collect(Supplier, BiConsumer, BiConsumer)
*/
@Nullable
public static <T, R> R collect(Iterable<Iterable<T>> iterables,
Supplier<R> supplier,
BiConsumer<R, ? super T> accumulator,
BiConsumer<R, R> combiner) {
R result = supplier.get();
for (Iterable<T> iterable : iterables) {
R innerResult = supplier.get();
for (T element : iterable) {
accumulator.accept(innerResult, element);
}
combiner.accept(result, innerResult);
}
return result;
}
/**
* Collect iterable into a mutable container.
*
* @param iterable The iterable
* @param collector The collector object
* @param <T> The type of elements
* @param <A> The type of accumulator
* @param <R> The return type
* @return Collected result
* @see Stream#collect(Collector)
*/
@Nullable
public static <T, A, R> R collect(Iterable<T> iterable, Collector<? super T, A, R> collector) {
A container = collector.supplier().get();
BiConsumer<A, ? super T> accumulator = collector.accumulator();
for (T t : iterable) {
accumulator.accept(container, t);
}
return collector.finisher().apply(container);
}
/**
* Perform a reduction on iterable.
*
* @param iterable The iterable
* @param accumulator The accumulator function
* @param <T> The type of elements
* @return The reduced result
* @see Stream#reduce(BinaryOperator)
*/
@Nullable
public static <T> Optional<T> reduce(Iterable<T> iterable, BinaryOperator<T> accumulator) {
boolean foundAny = false;
T result = null;
for (T element : iterable) {
if (!foundAny) {
foundAny = true;
result = element;
} else {
result = accumulator.apply(result, element);
}
}
return foundAny ? Optional.of(result) : Optional.empty();
}
/**
* Perform a reduction on an iterable.
*
* @param iterable The iterable
* @param identity The identity to start reduction with
* @param accumulator The accumulator function
* @param <T> The type of elements
* @return The reduced result
* @see Stream#reduce(Object, BinaryOperator)
*/
@Nullable
public static <T> T reduce(Iterable<T> iterable,
@SuppressWarnings("SameParameterValue") @Nullable T identity,
BinaryOperator<T> accumulator) {
T result = identity;
for (T element : iterable) {
result = accumulator.apply(result, element);
}
return result;
}
/**
* Perform a reduction on an iterable of iterables.
*
* @param iterables An iterator of iterables.
* @param identity The identity to start reduction with
* @param accumulator The accumulator function
* @param combiner The combiner function
* @param <T> The type of elements
* @param <U> The reduced type
* @return The reduced result
* @see Stream#reduce(Object, BiFunction, BinaryOperator)
*/
@Nullable
public static <T, U> U reduce(Iterable<Iterable<T>> iterables,
@SuppressWarnings("SameParameterValue") @Nullable U identity,
BiFunction<U, ? super T, U> accumulator,
BinaryOperator<U> combiner) {
U result = identity;
for (Iterable<T> iterable : iterables) {
U innerResult = identity;
for (T element : iterable) {
innerResult = accumulator.apply(innerResult, element);
}
result = combiner.apply(result, innerResult);
}
return result;
}
/**
* Return the first and last elements or {@link Optional#empty()} if {@code Iterables.isEmpty(iterable)}.
*
* @param iterable The iterable to get the ends from
* @param <T> The type of element in the iterable
* @return optional {@link Ends} with the first and last of the iterable
*/
@Nonnull
public static <T> Optional<Ends<T>> ends(Iterable<T> iterable) {
return J8Iterators.ends(iterable.iterator());
}
/**
* Peek at the iterable without modifying the result.
*
* @param iterable The iterable to peek at
* @param consumer The peeking function
* @param <T> The type of elements
* @return an Iterable that, when traversed will invoke the consumer on each element
* @see Stream#peek(Consumer)
*/
@Nonnull
public static <T> FluentIterable<T> peek(Iterable<T> iterable, Consumer<? super T> consumer) {
return fromSupplier(() -> new PeekIterator<>(iterable.iterator(), consumer));
}
/**
* Return a peeking transformer - a UnaryOperator that will send each element to the consumer and return identity.
*
* @param consumer The peeking function
* @param <T> The type of elements
* @return a peeking (non-transforming) transformer
*/
@Nonnull
public static <T> ConsumingIdentity<T> peeker(Consumer<T> consumer) {
return new ConsumingIdentity<>(consumer);
}
/**
* Create a one-time Iterable from a Stream.
*
* @param stream The Stream to use in creating an Iterable
* @param <T> The type of elements
* @return Iterable from the given stream
*/
@Nonnull
public static <T> FluentIterable<T> fromStream(Stream<T> stream) {
return new StreamIterable<>(stream);
}
/**
* Create a {@link Stream} from the given {@link Iterable}.
*
* @param iterable The Iterable to use in creating a Stream
* @param <T> The type of elements
* @return Stream from the given iterable
*/
@Nonnull
public static <T> Stream<T> toStream(Iterable<T> iterable) {
if (iterable instanceof Collection) {
return ((Collection<T>) iterable).stream();
}
// TODO(scr): Is it possible to do late-binding (iterable::spliterator)? Need to know characteristics.
return StreamSupport.stream(iterable.spliterator(), false);
}
/**
* Create an {@link DoubleStream} from the given {@code doubleIterable}.
*
* @param doubleIterable The iterable to use in creating a DoubleStream
* @return DoubleStream from the given iterable
*/
@Nonnull
public static DoubleStream toStream(J8PrimitiveIterable.OfDouble doubleIterable) {
// TODO(scr): Is it possible to do late-binding (iterable::spliterator)? Need to know characteristics.
return StreamSupport.doubleStream(doubleIterable.primitiveSpliterator(), false);
}
/**
* Create an {@link IntStream} from the given {@code intIterable}.
*
* @param intIterable The iterable to use in creating an IntStream
* @return IntStream from the given iterable
*/
@Nonnull
public static IntStream toStream(J8PrimitiveIterable.OfInt intIterable) {
// TODO(scr): Is it possible to do late-binding (iterable::spliterator)? Need to know characteristics.
return StreamSupport.intStream(intIterable.primitiveSpliterator(), false);
}
/**
* Create a {@link LongStream} from the given {@code iterable}.
*
* @param longIterable The iterable to use in creating a LongStream
* @return LongStream from the given iterable
*/
@Nonnull
public static LongStream toStream(J8PrimitiveIterable.OfLong longIterable) {
// TODO(scr): Is it possible to do late-binding (iterable::spliterator)? Need to know characteristics.
return StreamSupport.longStream(longIterable.primitiveSpliterator(), false);
}
/**
* Return a {@link FluentIterable} that is always empty.
*
* @param <T> The type of the FluentIterable
* @return an empty FluentIterable
*/
@SuppressWarnings("unchecked")
@Nonnull
public static <T> FluentIterable<T> emptyIterable() {
return (FluentIterable<T>) EMPTY_ITERABLE;
}
/**
* Create a FluentIterable for elements.
* <p>
* Provides a wrapper to help where {@link FluentIterable} falls short - no varargs static constructor for testing.
*
* @param elements the elements to iterate over
* @param <T> the type of elements
* @return a FluentIterable for elements
*/
@SafeVarargs
@Nonnull
public static <T> FluentIterable<T> of(T... elements) {
return FluentIterable.of(elements);
}
/**
* Reverse the given {@code iterable}.
*
* @param iterable an iterable to reverse
* @param <T> the type of elements
* @return an iterable that reverses the navigableSet
*/
@Nonnull
public static <T> FluentIterable<T> reverse(Iterable<? extends T> iterable) {
// If it's already reversable, return it.
if (iterable instanceof NavigableSet) {
@SuppressWarnings("unchecked")
NavigableSet<T> navigableSet = (NavigableSet<T>) iterable;
return fromSupplier(navigableSet::descendingIterator);
} else if (iterable instanceof Deque) {
@SuppressWarnings("unchecked")
Deque<T> deque = (Deque<T>) iterable;
return fromSupplier(deque::descendingIterator);
} else if (iterable instanceof List) {
@SuppressWarnings("unchecked")
List<T> list = (List<T>) iterable;
return fromSupplier(() -> J8Iterators.reverse(list.listIterator(list.size())));
}
// Slurp everything into a deque and then reverse its order.
return fromSupplier(() -> {
Deque<T> deque = new ArrayDeque<>();
Iterables.addAll(deque, iterable);
return deque.descendingIterator();
});
}
/**
* Create a {@link FluentIterable} from the given {@link Supplier}.
*
* @param supplier the supplier
* @param <T> the type of elements of the supplied iterable
* @return an iterable
*/
@Nonnull
public static <T> SupplierIterable<T> fromSupplier(Supplier<Iterator<? extends T>> supplier) {
@SuppressWarnings("unchecked")
Supplier<Iterator<T>> tSupplier = (Supplier<Iterator<T>>) (Supplier) supplier;
return new SupplierIterable<>(tSupplier);
}
@Nonnull
public static <T> J8PrimitiveIterable.OfDouble mapToDouble(
Iterable<T> iterable, ToDoubleFunction<T> toDoubleFunction) {
return new J8PrimitiveIterable.OfDouble() {
@Override
public PrimitiveIterator.OfDouble primitiveIterator() {
return J8Iterators.mapToDouble(iterable.iterator(), toDoubleFunction);
}
@Override
public Spliterator.OfDouble primitiveSpliterator() {
return J8Spliterators.mapToDouble(iterable.spliterator(), toDoubleFunction);
}
};
}
@Nonnull
public static <T> J8PrimitiveIterable.OfInt mapToInt(
Iterable<T> iterable, ToIntFunction<T> toIntFunction) {
return new J8PrimitiveIterable.OfInt() {
@Override
public PrimitiveIterator.OfInt primitiveIterator() {
return J8Iterators.mapToInt(iterable.iterator(), toIntFunction);
}
@Override
public Spliterator.OfInt primitiveSpliterator() {
return J8Spliterators.mapToInt(iterable.spliterator(), toIntFunction);
}
};
}
@Nonnull
public static <T> J8PrimitiveIterable.OfLong mapToLong(
Iterable<T> iterable, ToLongFunction<T> toLongFunction) {
return new J8PrimitiveIterable.OfLong() {
@Override
public PrimitiveIterator.OfLong primitiveIterator() {
return J8Iterators.mapToLong(iterable.iterator(), toLongFunction);
}
@Override
public Spliterator.OfLong primitiveSpliterator() {
return J8Spliterators.mapToLong(iterable.spliterator(), toLongFunction);
}
};
}
}
|
Avoid using FluentIterable.of with a single array value, as it is gone from newer Guava. (#21)
Co-authored-by: Sheridan C Rawlins <1f21d5692312a6c45cae99966af87e204aa8762c@verizonmedia.com>
|
src/main/java/com/github/scr/j8iterables/J8Iterables.java
|
Avoid using FluentIterable.of with a single array value, as it is gone from newer Guava. (#21)
|
|
Java
|
mit
|
2b426f19ccf5ffbc46dad25c3f9f5e36085c6d65
| 0
|
SquidDev-CC/plethora,SquidDev-CC/plethora
|
package org.squiddev.plethora.integration.vanilla.method;
import dan200.computercraft.api.lua.LuaException;
import net.minecraft.block.BlockNote;
import net.minecraft.util.EnumParticleTypes;
import net.minecraft.util.Vec3;
import net.minecraft.world.World;
import net.minecraft.world.WorldServer;
import net.minecraftforge.fml.common.ObfuscationReflectionHelper;
import org.squiddev.plethora.api.IWorldLocation;
import org.squiddev.plethora.api.method.IUnbakedContext;
import org.squiddev.plethora.api.method.MethodResult;
import org.squiddev.plethora.api.module.IModuleContainer;
import org.squiddev.plethora.api.module.SubtargetedModuleMethod;
import org.squiddev.plethora.integration.vanilla.IntegrationVanilla;
import java.util.List;
import java.util.concurrent.Callable;
import static org.squiddev.plethora.api.method.ArgumentHelper.*;
/**
* Various methods for playing sounds in world
*/
public class MethodsNoteblock {
private static List<String> instruments;
private static List<String> getInstruments() {
if (instruments == null) {
instruments = ObfuscationReflectionHelper.getPrivateValue(BlockNote.class, null, "field_176434_a");
}
return instruments;
}
@SubtargetedModuleMethod.Inject(
module = IntegrationVanilla.noteblock, target = IWorldLocation.class,
doc = "function(instrument:string|number, pitch:number[, volume:number]) -- Plays a note block note"
)
public static MethodResult playNote(final IUnbakedContext<IModuleContainer> context, Object[] arguments) throws LuaException {
List<String> instruments = getInstruments();
final String name;
if (arguments.length == 0) {
throw badArgument(null, 0, "string|number");
} else if (arguments[0] instanceof Number) {
int instrument = ((Number) arguments[0]).intValue();
assertBetween(instrument, 0, instruments.size() - 1, "Instrument out of bounds (%s)");
name = instruments.get(instrument);
} else if (arguments[0] instanceof String) {
name = (String) arguments[0];
if (!(instruments.contains(name))) {
throw new LuaException("Unknown instrument '" + name + "'");
}
} else {
throw badArgument(arguments[0], 0, "string|number");
}
final int pitch = getInt(arguments, 1);
final float volume = (float) optNumber(arguments, 2, 3);
assertBetween(pitch, 0, 24, "Pitch out of bounds (%s)");
assertBetween(volume, 0.1, 5, "Volume out of bounds (%s)");
final float adjPitch = (float) Math.pow(2d, (double) (pitch - 12) / 12d);
context.safeBake();
context.getExecutor().executeAsync(MethodResult.nextTick(new Callable<MethodResult>() {
@Override
public MethodResult call() throws Exception {
IWorldLocation location = context.bake().getContext(IWorldLocation.class);
Vec3 pos = location.getLoc();
World world = location.getWorld();
world.playSoundEffect(pos.xCoord, pos.yCoord, pos.zCoord, "note." + name, volume, adjPitch);
if (world instanceof WorldServer) {
((WorldServer) world).spawnParticle(EnumParticleTypes.NOTE, false, pos.xCoord, pos.yCoord, pos.zCoord, 0, pitch / 24.0, 0, 0, 1.0);
}
return MethodResult.empty();
}
}));
return MethodResult.empty();
}
@SubtargetedModuleMethod.Inject(
module = IntegrationVanilla.noteblock, target = IWorldLocation.class,
doc = "function(sound:string[, pitch:number][, volume:number]) -- Play a sound"
)
public static MethodResult playSound(final IUnbakedContext<IModuleContainer> context, Object[] arguments) throws LuaException {
final String sound = getString(arguments, 0);
final float pitch = (float) optNumber(arguments, 1, 0);
final float volume = (float) optNumber(arguments, 2, 1);
assertBetween(pitch, 0, 2, "Pitch out of bounds (%s)");
assertBetween(volume, 0.1, 5, "Volume out of bounds (%s)");
context.safeBake();
context.getExecutor().executeAsync(MethodResult.nextTick(new Callable<MethodResult>() {
@Override
public MethodResult call() throws Exception {
IWorldLocation location = context.bake().getContext(IWorldLocation.class);
Vec3 pos = location.getLoc();
location.getWorld().playSoundEffect(pos.xCoord, pos.yCoord, pos.zCoord, sound, volume, pitch);
return MethodResult.empty();
}
}));
return MethodResult.empty();
}
}
|
src/main/java/org/squiddev/plethora/integration/vanilla/method/MethodsNoteblock.java
|
package org.squiddev.plethora.integration.vanilla.method;
import dan200.computercraft.api.lua.LuaException;
import net.minecraft.block.BlockNote;
import net.minecraft.util.Vec3;
import net.minecraftforge.fml.common.ObfuscationReflectionHelper;
import org.squiddev.plethora.api.IWorldLocation;
import org.squiddev.plethora.api.method.IUnbakedContext;
import org.squiddev.plethora.api.method.MethodResult;
import org.squiddev.plethora.api.module.IModuleContainer;
import org.squiddev.plethora.api.module.SubtargetedModuleMethod;
import org.squiddev.plethora.integration.vanilla.IntegrationVanilla;
import java.util.List;
import java.util.concurrent.Callable;
import static org.squiddev.plethora.api.method.ArgumentHelper.*;
/**
* Various methods for playing sounds in world
*/
public class MethodsNoteblock {
private static List<String> instruments;
private static List<String> getInstruments() {
if (instruments == null) {
instruments = ObfuscationReflectionHelper.getPrivateValue(BlockNote.class, null, "field_176434_a");
}
return instruments;
}
@SubtargetedModuleMethod.Inject(
module = IntegrationVanilla.noteblock, target = IWorldLocation.class,
doc = "function(instrument:string|number, pitch:number[, volume:number]) -- Plays a note block note"
)
public static MethodResult playNote(final IUnbakedContext<IModuleContainer> context, Object[] arguments) throws LuaException {
List<String> instruments = getInstruments();
final String name;
if (arguments.length == 0) {
throw badArgument(null, 0, "string|number");
} else if (arguments[0] instanceof Number) {
int instrument = ((Number) arguments[0]).intValue();
assertBetween(instrument, 0, instruments.size() - 1, "Instrument out of bounds (%s)");
name = instruments.get(instrument);
} else if (arguments[0] instanceof String) {
name = (String) arguments[0];
if (!(instruments.contains(name))) {
throw new LuaException("Unknown instrument '" + name + "'");
}
} else {
throw badArgument(arguments[0], 0, "string|number");
}
int pitch = getInt(arguments, 1);
final float volume = (float) optNumber(arguments, 2, 3);
assertBetween(pitch, 0, 24, "Pitch out of bounds (%s)");
assertBetween(volume, 0.1, 5, "Volume out of bounds (%s)");
final float adjPitch = (float) Math.pow(2d, (double) (pitch - 12) / 12d);
context.safeBake();
context.getExecutor().executeAsync(MethodResult.nextTick(new Callable<MethodResult>() {
@Override
public MethodResult call() throws Exception {
IWorldLocation location = context.bake().getContext(IWorldLocation.class);
Vec3 pos = location.getLoc();
location.getWorld().playSoundEffect(pos.xCoord, pos.yCoord, pos.zCoord, "note." + name, volume, adjPitch);
return MethodResult.empty();
}
}));
return MethodResult.empty();
}
@SubtargetedModuleMethod.Inject(
module = IntegrationVanilla.noteblock, target = IWorldLocation.class,
doc = "function(sound:string[, pitch:number][, volume:number]) -- Play a sound"
)
public static MethodResult playSound(final IUnbakedContext<IModuleContainer> context, Object[] arguments) throws LuaException {
final String sound = getString(arguments, 0);
final float pitch = (float) optNumber(arguments, 1, 0);
final float volume = (float) optNumber(arguments, 2, 1);
assertBetween(pitch, 0, 2, "Pitch out of bounds (%s)");
assertBetween(volume, 0.1, 5, "Volume out of bounds (%s)");
context.safeBake();
context.getExecutor().executeAsync(MethodResult.nextTick(new Callable<MethodResult>() {
@Override
public MethodResult call() throws Exception {
IWorldLocation location = context.bake().getContext(IWorldLocation.class);
Vec3 pos = location.getLoc();
location.getWorld().playSoundEffect(pos.xCoord, pos.yCoord, pos.zCoord, sound, volume, pitch);
return MethodResult.empty();
}
}));
return MethodResult.empty();
}
}
|
Spawn note particle
|
src/main/java/org/squiddev/plethora/integration/vanilla/method/MethodsNoteblock.java
|
Spawn note particle
|
|
Java
|
mit
|
114546f538e001b7c5fc44add6e92868b2c7c2ce
| 0
|
v1v/jenkins,stephenc/jenkins,msrb/jenkins,vlajos/jenkins,liorhson/jenkins,ns163/jenkins,samatdav/jenkins,AustinKwang/jenkins,abayer/jenkins,vvv444/jenkins,gitaccountforprashant/gittest,jhoblitt/jenkins,aldaris/jenkins,MichaelPranovich/jenkins_sc,shahharsh/jenkins,amruthsoft9/Jenkis,synopsys-arc-oss/jenkins,NehemiahMi/jenkins,pselle/jenkins,seanlin816/jenkins,alvarolobato/jenkins,hplatou/jenkins,arcivanov/jenkins,github-api-test-org/jenkins,lordofthejars/jenkins,svanoort/jenkins,liupugong/jenkins,kzantow/jenkins,scoheb/jenkins,lvotypko/jenkins2,hashar/jenkins,Jochen-A-Fuerbacher/jenkins,olivergondza/jenkins,hemantojhaa/jenkins,pselle/jenkins,mattclark/jenkins,FarmGeek4Life/jenkins,abayer/jenkins,mpeltonen/jenkins,abayer/jenkins,damianszczepanik/jenkins,mrobinet/jenkins,everyonce/jenkins,lvotypko/jenkins3,gusreiber/jenkins,damianszczepanik/jenkins,jtnord/jenkins,csimons/jenkins,jzjzjzj/jenkins,keyurpatankar/hudson,goldchang/jenkins,liupugong/jenkins,khmarbaise/jenkins,ikedam/jenkins,intelchen/jenkins,ChrisA89/jenkins,scoheb/jenkins,jcarrothers-sap/jenkins,Jimilian/jenkins,mattclark/jenkins,maikeffi/hudson,jcarrothers-sap/jenkins,jhoblitt/jenkins,Jimilian/jenkins,patbos/jenkins,lvotypko/jenkins,my7seven/jenkins,christ66/jenkins,my7seven/jenkins,fbelzunc/jenkins,ajshastri/jenkins,escoem/jenkins,oleg-nenashev/jenkins,mrooney/jenkins,mcanthony/jenkins,maikeffi/hudson,wangyikai/jenkins,luoqii/jenkins,guoxu0514/jenkins,6WIND/jenkins,petermarcoen/jenkins,yonglehou/jenkins,MadsNielsen/jtemp,mcanthony/jenkins,yonglehou/jenkins,arcivanov/jenkins,mpeltonen/jenkins,kohsuke/hudson,huybrechts/hudson,mrooney/jenkins,ndeloof/jenkins,liupugong/jenkins,godfath3r/jenkins,brunocvcunha/jenkins,olivergondza/jenkins,ajshastri/jenkins,lilyJi/jenkins,KostyaSha/jenkins,DoctorQ/jenkins,lvotypko/jenkins3,andresrc/jenkins,vvv444/jenkins,mattclark/jenkins,goldchang/jenkins,jcarrothers-sap/jenkins,gorcz/jenkins,Ykus/jenkins,maikeffi/hudson,azweb76/jenkins,evernat/jenkins,singh88/jenkins,MarkEWaite/jenkins,github-api-test-org/jenkins,tastatur/jenkins,vlajos/jenkins,escoem/jenkins,gusreiber/jenkins,jenkinsci/jenkins,luoqii/jenkins,svanoort/jenkins,chbiel/jenkins,petermarcoen/jenkins,MichaelPranovich/jenkins_sc,Krasnyanskiy/jenkins,jenkinsci/jenkins,kohsuke/hudson,hplatou/jenkins,pjanouse/jenkins,msrb/jenkins,guoxu0514/jenkins,protazy/jenkins,fbelzunc/jenkins,deadmoose/jenkins,MadsNielsen/jtemp,Wilfred/jenkins,dbroady1/jenkins,tangkun75/jenkins,rsandell/jenkins,ydubreuil/jenkins,seanlin816/jenkins,varmenise/jenkins,aquarellian/jenkins,arcivanov/jenkins,amuniz/jenkins,bkmeneguello/jenkins,vijayto/jenkins,tfennelly/jenkins,lindzh/jenkins,mdonohue/jenkins,mdonohue/jenkins,kohsuke/hudson,KostyaSha/jenkins,lvotypko/jenkins2,jpbriend/jenkins,stephenc/jenkins,goldchang/jenkins,oleg-nenashev/jenkins,lordofthejars/jenkins,gitaccountforprashant/gittest,pselle/jenkins,svanoort/jenkins,h4ck3rm1k3/jenkins,akshayabd/jenkins,daspilker/jenkins,KostyaSha/jenkins,NehemiahMi/jenkins,akshayabd/jenkins,huybrechts/hudson,nandan4/Jenkins,NehemiahMi/jenkins,goldchang/jenkins,chbiel/jenkins,ChrisA89/jenkins,damianszczepanik/jenkins,FarmGeek4Life/jenkins,arunsingh/jenkins,chbiel/jenkins,maikeffi/hudson,iqstack/jenkins,FTG-003/jenkins,Jimilian/jenkins,sathiya-mit/jenkins,iqstack/jenkins,wangyikai/jenkins,mrooney/jenkins,jenkinsci/jenkins,andresrc/jenkins,khmarbaise/jenkins,lindzh/jenkins,ChrisA89/jenkins,varmenise/jenkins,bkmeneguello/jenkins,dbroady1/jenkins,evernat/jenkins,tastatur/jenkins,intelchen/jenkins,duzifang/my-jenkins,vjuranek/jenkins,vlajos/jenkins,DanielWeber/jenkins,evernat/jenkins,jenkinsci/jenkins,github-api-test-org/jenkins,lvotypko/jenkins3,recena/jenkins,aldaris/jenkins,msrb/jenkins,tastatur/jenkins,luoqii/jenkins,protazy/jenkins,oleg-nenashev/jenkins,MadsNielsen/jtemp,brunocvcunha/jenkins,paulwellnerbou/jenkins,nandan4/Jenkins,ajshastri/jenkins,hashar/jenkins,iterate/coding-dojo,paulwellnerbou/jenkins,gitaccountforprashant/gittest,deadmoose/jenkins,dbroady1/jenkins,alvarolobato/jenkins,gusreiber/jenkins,albers/jenkins,jzjzjzj/jenkins,Ykus/jenkins,thomassuckow/jenkins,yonglehou/jenkins,huybrechts/hudson,jcsirot/jenkins,1and1/jenkins,gusreiber/jenkins,mrooney/jenkins,CodeShane/jenkins,aduprat/jenkins,rsandell/jenkins,andresrc/jenkins,varmenise/jenkins,rsandell/jenkins,everyonce/jenkins,mpeltonen/jenkins,amruthsoft9/Jenkis,olivergondza/jenkins,synopsys-arc-oss/jenkins,ikedam/jenkins,FarmGeek4Life/jenkins,andresrc/jenkins,damianszczepanik/jenkins,godfath3r/jenkins,liupugong/jenkins,pselle/jenkins,aquarellian/jenkins,rsandell/jenkins,lvotypko/jenkins,wangyikai/jenkins,tastatur/jenkins,ikedam/jenkins,maikeffi/hudson,github-api-test-org/jenkins,ydubreuil/jenkins,jhoblitt/jenkins,verbitan/jenkins,jpbriend/jenkins,MarkEWaite/jenkins,FTG-003/jenkins,gusreiber/jenkins,lordofthejars/jenkins,synopsys-arc-oss/jenkins,rlugojr/jenkins,lordofthejars/jenkins,liorhson/jenkins,iqstack/jenkins,samatdav/jenkins,v1v/jenkins,aheritier/jenkins,christ66/jenkins,wangyikai/jenkins,msrb/jenkins,ndeloof/jenkins,FarmGeek4Life/jenkins,elkingtonmcb/jenkins,h4ck3rm1k3/jenkins,evernat/jenkins,amruthsoft9/Jenkis,singh88/jenkins,vjuranek/jenkins,varmenise/jenkins,mpeltonen/jenkins,292388900/jenkins,thomassuckow/jenkins,mpeltonen/jenkins,kohsuke/hudson,FarmGeek4Life/jenkins,dbroady1/jenkins,ikedam/jenkins,Ykus/jenkins,Jimilian/jenkins,ErikVerheul/jenkins,jglick/jenkins,viqueen/jenkins,SebastienGllmt/jenkins,bpzhang/jenkins,rsandell/jenkins,rashmikanta-1984/jenkins,jglick/jenkins,amuniz/jenkins,verbitan/jenkins,rashmikanta-1984/jenkins,vijayto/jenkins,soenter/jenkins,seanlin816/jenkins,viqueen/jenkins,luoqii/jenkins,amruthsoft9/Jenkis,shahharsh/jenkins,Vlatombe/jenkins,protazy/jenkins,maikeffi/hudson,arunsingh/jenkins,csimons/jenkins,ErikVerheul/jenkins,hemantojhaa/jenkins,lilyJi/jenkins,paulmillar/jenkins,paulmillar/jenkins,synopsys-arc-oss/jenkins,dariver/jenkins,goldchang/jenkins,liupugong/jenkins,vijayto/jenkins,ChrisA89/jenkins,SenolOzer/jenkins,CodeShane/jenkins,deadmoose/jenkins,Wilfred/jenkins,akshayabd/jenkins,batmat/jenkins,duzifang/my-jenkins,scoheb/jenkins,Ykus/jenkins,dennisjlee/jenkins,6WIND/jenkins,daspilker/jenkins,lordofthejars/jenkins,dariver/jenkins,DoctorQ/jenkins,gorcz/jenkins,wuwen5/jenkins,recena/jenkins,Jochen-A-Fuerbacher/jenkins,duzifang/my-jenkins,oleg-nenashev/jenkins,aduprat/jenkins,azweb76/jenkins,everyonce/jenkins,daniel-beck/jenkins,mpeltonen/jenkins,jpederzolli/jenkins-1,MarkEWaite/jenkins,vvv444/jenkins,dbroady1/jenkins,mdonohue/jenkins,svanoort/jenkins,292388900/jenkins,aldaris/jenkins,alvarolobato/jenkins,andresrc/jenkins,github-api-test-org/jenkins,my7seven/jenkins,kohsuke/hudson,morficus/jenkins,protazy/jenkins,abayer/jenkins,paulwellnerbou/jenkins,292388900/jenkins,MichaelPranovich/jenkins_sc,AustinKwang/jenkins,albers/jenkins,kohsuke/hudson,guoxu0514/jenkins,verbitan/jenkins,liupugong/jenkins,godfath3r/jenkins,jglick/jenkins,amuniz/jenkins,AustinKwang/jenkins,jzjzjzj/jenkins,sathiya-mit/jenkins,patbos/jenkins,jcarrothers-sap/jenkins,SebastienGllmt/jenkins,mdonohue/jenkins,batmat/jenkins,h4ck3rm1k3/jenkins,SebastienGllmt/jenkins,ajshastri/jenkins,MichaelPranovich/jenkins_sc,albers/jenkins,my7seven/jenkins,Krasnyanskiy/jenkins,hemantojhaa/jenkins,SebastienGllmt/jenkins,AustinKwang/jenkins,NehemiahMi/jenkins,Ykus/jenkins,jk47/jenkins,damianszczepanik/jenkins,mrobinet/jenkins,lilyJi/jenkins,vvv444/jenkins,paulmillar/jenkins,damianszczepanik/jenkins,jcarrothers-sap/jenkins,goldchang/jenkins,rashmikanta-1984/jenkins,FTG-003/jenkins,alvarolobato/jenkins,liorhson/jenkins,thomassuckow/jenkins,Vlatombe/jenkins,petermarcoen/jenkins,recena/jenkins,mattclark/jenkins,liupugong/jenkins,dariver/jenkins,jzjzjzj/jenkins,MadsNielsen/jtemp,Wilfred/jenkins,bkmeneguello/jenkins,mattclark/jenkins,arcivanov/jenkins,mrobinet/jenkins,verbitan/jenkins,rashmikanta-1984/jenkins,FarmGeek4Life/jenkins,shahharsh/jenkins,ErikVerheul/jenkins,pjanouse/jenkins,tfennelly/jenkins,aheritier/jenkins,escoem/jenkins,rashmikanta-1984/jenkins,Jochen-A-Fuerbacher/jenkins,lordofthejars/jenkins,gusreiber/jenkins,bpzhang/jenkins,v1v/jenkins,ndeloof/jenkins,v1v/jenkins,ajshastri/jenkins,paulwellnerbou/jenkins,hemantojhaa/jenkins,ErikVerheul/jenkins,v1v/jenkins,mcanthony/jenkins,ydubreuil/jenkins,verbitan/jenkins,deadmoose/jenkins,DanielWeber/jenkins,jhoblitt/jenkins,v1v/jenkins,verbitan/jenkins,jcsirot/jenkins,Vlatombe/jenkins,jzjzjzj/jenkins,github-api-test-org/jenkins,viqueen/jenkins,goldchang/jenkins,rlugojr/jenkins,soenter/jenkins,rlugojr/jenkins,gitaccountforprashant/gittest,dennisjlee/jenkins,morficus/jenkins,sathiya-mit/jenkins,bkmeneguello/jenkins,jhoblitt/jenkins,wuwen5/jenkins,kzantow/jenkins,duzifang/my-jenkins,arunsingh/jenkins,fbelzunc/jenkins,pselle/jenkins,paulwellnerbou/jenkins,dariver/jenkins,MarkEWaite/jenkins,singh88/jenkins,jenkinsci/jenkins,iqstack/jenkins,ns163/jenkins,batmat/jenkins,synopsys-arc-oss/jenkins,liorhson/jenkins,Krasnyanskiy/jenkins,paulwellnerbou/jenkins,tastatur/jenkins,deadmoose/jenkins,morficus/jenkins,MichaelPranovich/jenkins_sc,gorcz/jenkins,stephenc/jenkins,damianszczepanik/jenkins,noikiy/jenkins,Krasnyanskiy/jenkins,ikedam/jenkins,KostyaSha/jenkins,wuwen5/jenkins,mcanthony/jenkins,amuniz/jenkins,singh88/jenkins,seanlin816/jenkins,gitaccountforprashant/gittest,huybrechts/hudson,khmarbaise/jenkins,my7seven/jenkins,sathiya-mit/jenkins,liorhson/jenkins,1and1/jenkins,stephenc/jenkins,v1v/jenkins,gorcz/jenkins,fbelzunc/jenkins,protazy/jenkins,mdonohue/jenkins,KostyaSha/jenkins,AustinKwang/jenkins,DoctorQ/jenkins,petermarcoen/jenkins,KostyaSha/jenkins,duzifang/my-jenkins,DanielWeber/jenkins,jtnord/jenkins,AustinKwang/jenkins,wangyikai/jenkins,daniel-beck/jenkins,CodeShane/jenkins,ChrisA89/jenkins,soenter/jenkins,nandan4/Jenkins,jcarrothers-sap/jenkins,oleg-nenashev/jenkins,Vlatombe/jenkins,dariver/jenkins,aldaris/jenkins,evernat/jenkins,singh88/jenkins,CodeShane/jenkins,jcsirot/jenkins,hashar/jenkins,everyonce/jenkins,christ66/jenkins,seanlin816/jenkins,seanlin816/jenkins,yonglehou/jenkins,shahharsh/jenkins,scoheb/jenkins,github-api-test-org/jenkins,DoctorQ/jenkins,rlugojr/jenkins,morficus/jenkins,maikeffi/hudson,duzifang/my-jenkins,lilyJi/jenkins,aldaris/jenkins,petermarcoen/jenkins,jtnord/jenkins,lvotypko/jenkins2,aduprat/jenkins,noikiy/jenkins,olivergondza/jenkins,Jochen-A-Fuerbacher/jenkins,aduprat/jenkins,gitaccountforprashant/gittest,duzifang/my-jenkins,6WIND/jenkins,aquarellian/jenkins,SebastienGllmt/jenkins,292388900/jenkins,h4ck3rm1k3/jenkins,ErikVerheul/jenkins,hashar/jenkins,synopsys-arc-oss/jenkins,DoctorQ/jenkins,jglick/jenkins,nandan4/Jenkins,lvotypko/jenkins2,verbitan/jenkins,hplatou/jenkins,khmarbaise/jenkins,iterate/coding-dojo,ndeloof/jenkins,batmat/jenkins,1and1/jenkins,hashar/jenkins,azweb76/jenkins,albers/jenkins,arunsingh/jenkins,batmat/jenkins,vjuranek/jenkins,goldchang/jenkins,csimons/jenkins,fbelzunc/jenkins,MadsNielsen/jtemp,khmarbaise/jenkins,jk47/jenkins,1and1/jenkins,sathiya-mit/jenkins,thomassuckow/jenkins,godfath3r/jenkins,vijayto/jenkins,soenter/jenkins,deadmoose/jenkins,gorcz/jenkins,azweb76/jenkins,jhoblitt/jenkins,jpederzolli/jenkins-1,vjuranek/jenkins,vlajos/jenkins,paulwellnerbou/jenkins,jk47/jenkins,protazy/jenkins,FTG-003/jenkins,my7seven/jenkins,jtnord/jenkins,morficus/jenkins,292388900/jenkins,shahharsh/jenkins,ChrisA89/jenkins,vjuranek/jenkins,dariver/jenkins,iterate/coding-dojo,batmat/jenkins,batmat/jenkins,jpederzolli/jenkins-1,NehemiahMi/jenkins,pselle/jenkins,rlugojr/jenkins,dbroady1/jenkins,samatdav/jenkins,SenolOzer/jenkins,dennisjlee/jenkins,MarkEWaite/jenkins,huybrechts/hudson,SenolOzer/jenkins,godfath3r/jenkins,csimons/jenkins,iterate/coding-dojo,SenolOzer/jenkins,evernat/jenkins,Vlatombe/jenkins,aquarellian/jenkins,h4ck3rm1k3/jenkins,recena/jenkins,akshayabd/jenkins,jpbriend/jenkins,noikiy/jenkins,dennisjlee/jenkins,mcanthony/jenkins,hplatou/jenkins,chbiel/jenkins,fbelzunc/jenkins,AustinKwang/jenkins,DoctorQ/jenkins,daniel-beck/jenkins,mrobinet/jenkins,bkmeneguello/jenkins,jcarrothers-sap/jenkins,singh88/jenkins,arcivanov/jenkins,chbiel/jenkins,hashar/jenkins,hashar/jenkins,jk47/jenkins,mpeltonen/jenkins,lindzh/jenkins,yonglehou/jenkins,guoxu0514/jenkins,lindzh/jenkins,keyurpatankar/hudson,NehemiahMi/jenkins,khmarbaise/jenkins,Vlatombe/jenkins,keyurpatankar/hudson,jcsirot/jenkins,mattclark/jenkins,varmenise/jenkins,gorcz/jenkins,Wilfred/jenkins,recena/jenkins,ns163/jenkins,Wilfred/jenkins,paulmillar/jenkins,olivergondza/jenkins,elkingtonmcb/jenkins,protazy/jenkins,lilyJi/jenkins,arunsingh/jenkins,nandan4/Jenkins,Vlatombe/jenkins,292388900/jenkins,jpbriend/jenkins,kzantow/jenkins,jtnord/jenkins,scoheb/jenkins,ErikVerheul/jenkins,6WIND/jenkins,jzjzjzj/jenkins,viqueen/jenkins,FTG-003/jenkins,dennisjlee/jenkins,lilyJi/jenkins,MarkEWaite/jenkins,oleg-nenashev/jenkins,CodeShane/jenkins,DanielWeber/jenkins,CodeShane/jenkins,albers/jenkins,MarkEWaite/jenkins,mrobinet/jenkins,jpederzolli/jenkins-1,aduprat/jenkins,MadsNielsen/jtemp,svanoort/jenkins,keyurpatankar/hudson,abayer/jenkins,MarkEWaite/jenkins,tangkun75/jenkins,lindzh/jenkins,fbelzunc/jenkins,chbiel/jenkins,iterate/coding-dojo,FTG-003/jenkins,vijayto/jenkins,keyurpatankar/hudson,amruthsoft9/Jenkis,daniel-beck/jenkins,elkingtonmcb/jenkins,gorcz/jenkins,arunsingh/jenkins,ChrisA89/jenkins,everyonce/jenkins,albers/jenkins,daspilker/jenkins,jpederzolli/jenkins-1,seanlin816/jenkins,jhoblitt/jenkins,bkmeneguello/jenkins,MichaelPranovich/jenkins_sc,elkingtonmcb/jenkins,kzantow/jenkins,github-api-test-org/jenkins,Krasnyanskiy/jenkins,jcarrothers-sap/jenkins,pjanouse/jenkins,CodeShane/jenkins,mdonohue/jenkins,csimons/jenkins,ydubreuil/jenkins,stephenc/jenkins,ndeloof/jenkins,huybrechts/hudson,aheritier/jenkins,daspilker/jenkins,keyurpatankar/hudson,samatdav/jenkins,thomassuckow/jenkins,mcanthony/jenkins,lvotypko/jenkins2,msrb/jenkins,yonglehou/jenkins,iterate/coding-dojo,christ66/jenkins,keyurpatankar/hudson,albers/jenkins,varmenise/jenkins,lvotypko/jenkins,h4ck3rm1k3/jenkins,iqstack/jenkins,wangyikai/jenkins,shahharsh/jenkins,godfath3r/jenkins,amuniz/jenkins,olivergondza/jenkins,vlajos/jenkins,csimons/jenkins,jcsirot/jenkins,msrb/jenkins,amruthsoft9/Jenkis,elkingtonmcb/jenkins,soenter/jenkins,escoem/jenkins,ajshastri/jenkins,brunocvcunha/jenkins,nandan4/Jenkins,shahharsh/jenkins,evernat/jenkins,daniel-beck/jenkins,ns163/jenkins,amuniz/jenkins,my7seven/jenkins,DoctorQ/jenkins,ns163/jenkins,vjuranek/jenkins,noikiy/jenkins,liorhson/jenkins,noikiy/jenkins,tastatur/jenkins,wuwen5/jenkins,NehemiahMi/jenkins,intelchen/jenkins,1and1/jenkins,lvotypko/jenkins2,jk47/jenkins,chbiel/jenkins,kzantow/jenkins,vlajos/jenkins,aheritier/jenkins,jcsirot/jenkins,svanoort/jenkins,mdonohue/jenkins,hemantojhaa/jenkins,synopsys-arc-oss/jenkins,jenkinsci/jenkins,kzantow/jenkins,ns163/jenkins,1and1/jenkins,intelchen/jenkins,DoctorQ/jenkins,aquarellian/jenkins,tfennelly/jenkins,rashmikanta-1984/jenkins,kohsuke/hudson,akshayabd/jenkins,svanoort/jenkins,tastatur/jenkins,vvv444/jenkins,everyonce/jenkins,kohsuke/hudson,ydubreuil/jenkins,mcanthony/jenkins,ndeloof/jenkins,jzjzjzj/jenkins,brunocvcunha/jenkins,andresrc/jenkins,bpzhang/jenkins,aheritier/jenkins,akshayabd/jenkins,stephenc/jenkins,hplatou/jenkins,SenolOzer/jenkins,morficus/jenkins,luoqii/jenkins,sathiya-mit/jenkins,mrooney/jenkins,elkingtonmcb/jenkins,patbos/jenkins,ns163/jenkins,everyonce/jenkins,DanielWeber/jenkins,Jochen-A-Fuerbacher/jenkins,dbroady1/jenkins,Jochen-A-Fuerbacher/jenkins,arcivanov/jenkins,KostyaSha/jenkins,rlugojr/jenkins,lvotypko/jenkins3,daspilker/jenkins,brunocvcunha/jenkins,bkmeneguello/jenkins,6WIND/jenkins,rashmikanta-1984/jenkins,mrooney/jenkins,sathiya-mit/jenkins,noikiy/jenkins,6WIND/jenkins,vjuranek/jenkins,tangkun75/jenkins,rsandell/jenkins,1and1/jenkins,lordofthejars/jenkins,jpederzolli/jenkins-1,jglick/jenkins,abayer/jenkins,viqueen/jenkins,wuwen5/jenkins,gitaccountforprashant/gittest,rsandell/jenkins,lilyJi/jenkins,petermarcoen/jenkins,aldaris/jenkins,morficus/jenkins,christ66/jenkins,daniel-beck/jenkins,escoem/jenkins,luoqii/jenkins,jk47/jenkins,huybrechts/hudson,samatdav/jenkins,SenolOzer/jenkins,jzjzjzj/jenkins,Ykus/jenkins,pjanouse/jenkins,msrb/jenkins,dennisjlee/jenkins,patbos/jenkins,andresrc/jenkins,brunocvcunha/jenkins,liorhson/jenkins,vvv444/jenkins,soenter/jenkins,aldaris/jenkins,paulmillar/jenkins,jpbriend/jenkins,jk47/jenkins,samatdav/jenkins,jcsirot/jenkins,KostyaSha/jenkins,DanielWeber/jenkins,aduprat/jenkins,amuniz/jenkins,guoxu0514/jenkins,patbos/jenkins,noikiy/jenkins,pjanouse/jenkins,kzantow/jenkins,jenkinsci/jenkins,intelchen/jenkins,vvv444/jenkins,paulmillar/jenkins,daspilker/jenkins,hplatou/jenkins,abayer/jenkins,mrobinet/jenkins,Jochen-A-Fuerbacher/jenkins,azweb76/jenkins,patbos/jenkins,lindzh/jenkins,ikedam/jenkins,keyurpatankar/hudson,ikedam/jenkins,tfennelly/jenkins,tfennelly/jenkins,soenter/jenkins,arunsingh/jenkins,yonglehou/jenkins,SebastienGllmt/jenkins,wuwen5/jenkins,viqueen/jenkins,vijayto/jenkins,lvotypko/jenkins,azweb76/jenkins,mattclark/jenkins,gusreiber/jenkins,alvarolobato/jenkins,ikedam/jenkins,nandan4/Jenkins,tangkun75/jenkins,MichaelPranovich/jenkins_sc,aheritier/jenkins,tangkun75/jenkins,tfennelly/jenkins,csimons/jenkins,pjanouse/jenkins,daniel-beck/jenkins,jglick/jenkins,aheritier/jenkins,olivergondza/jenkins,mrobinet/jenkins,intelchen/jenkins,arcivanov/jenkins,bpzhang/jenkins,christ66/jenkins,thomassuckow/jenkins,intelchen/jenkins,jpbriend/jenkins,dariver/jenkins,wuwen5/jenkins,aquarellian/jenkins,pjanouse/jenkins,jtnord/jenkins,lvotypko/jenkins3,jpederzolli/jenkins-1,samatdav/jenkins,lvotypko/jenkins,maikeffi/hudson,bpzhang/jenkins,Ykus/jenkins,FTG-003/jenkins,MadsNielsen/jtemp,lindzh/jenkins,SenolOzer/jenkins,ydubreuil/jenkins,daniel-beck/jenkins,ErikVerheul/jenkins,Krasnyanskiy/jenkins,gorcz/jenkins,luoqii/jenkins,wangyikai/jenkins,akshayabd/jenkins,Krasnyanskiy/jenkins,rlugojr/jenkins,daspilker/jenkins,scoheb/jenkins,azweb76/jenkins,iterate/coding-dojo,shahharsh/jenkins,viqueen/jenkins,recena/jenkins,ydubreuil/jenkins,ndeloof/jenkins,DanielWeber/jenkins,pselle/jenkins,patbos/jenkins,oleg-nenashev/jenkins,bpzhang/jenkins,jenkinsci/jenkins,SebastienGllmt/jenkins,godfath3r/jenkins,lvotypko/jenkins,Wilfred/jenkins,paulmillar/jenkins,christ66/jenkins,thomassuckow/jenkins,hemantojhaa/jenkins,6WIND/jenkins,khmarbaise/jenkins,alvarolobato/jenkins,Jimilian/jenkins,guoxu0514/jenkins,escoem/jenkins,jtnord/jenkins,dennisjlee/jenkins,escoem/jenkins,aduprat/jenkins,bpzhang/jenkins,292388900/jenkins,scoheb/jenkins,stephenc/jenkins,ajshastri/jenkins,singh88/jenkins,Wilfred/jenkins,tangkun75/jenkins,petermarcoen/jenkins,varmenise/jenkins,lvotypko/jenkins,jglick/jenkins,FarmGeek4Life/jenkins,recena/jenkins,vlajos/jenkins,deadmoose/jenkins,jpbriend/jenkins,tangkun75/jenkins,lvotypko/jenkins3,Jimilian/jenkins,tfennelly/jenkins,hplatou/jenkins,lvotypko/jenkins3,h4ck3rm1k3/jenkins,elkingtonmcb/jenkins,damianszczepanik/jenkins,hemantojhaa/jenkins,alvarolobato/jenkins,Jimilian/jenkins,rsandell/jenkins,amruthsoft9/Jenkis,aquarellian/jenkins,lvotypko/jenkins2,guoxu0514/jenkins,brunocvcunha/jenkins,iqstack/jenkins,iqstack/jenkins,mrooney/jenkins,vijayto/jenkins
|
/*
* The MIT License
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Stephen Connolly
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.slaves;
import hudson.ExtensionPoint;
import hudson.Extension;
import hudson.model.*;
import hudson.remoting.Channel;
import hudson.util.DescriptorList;
import hudson.util.StreamTaskListener;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* Extension point to allow control over how {@link Computer}s are "launched",
* meaning how they get connected to their slave agent program.
*
* <h2>Associated View</h2>
* <dl>
* <dt>main.jelly</dt>
* <dd>
* This page will be rendered into the top page of the computer (/computer/NAME/)
* Useful for showing launch related commands and status reports.
* </dl>
*
* @author Stephen Connolly
* @since 24-Apr-2008 22:12:35
* @see ComputerConnector
*/
public abstract class ComputerLauncher extends AbstractDescribableImpl<ComputerLauncher> implements ExtensionPoint {
/**
* Returns true if this {@link ComputerLauncher} supports
* programatic launch of the slave agent in the target {@link Computer}.
*/
public boolean isLaunchSupported() {
return true;
}
/**
* Launches the slave agent for the given {@link Computer}.
*
* <p>
* If the slave agent is launched successfully, {@link SlaveComputer#setChannel(InputStream, OutputStream, TaskListener, Channel.Listener)}
* should be invoked in the end to notify Hudson of the established connection.
* The operation could also fail, in which case there's no need to make any callback notification,
* (except to notify the user of the failure through {@link StreamTaskListener}.)
* Also note that the normal return of this method call does not necessarily signify a successful launch.
* If someone programmatically calls this method and wants to find out if the launch was a success,
* use {@link SlaveComputer#isOnline()} at the end.
*
* <p>
* This method must operate synchronously. Asynchrony is provided by {@link Computer#connect(boolean)} and
* its correct operation depends on this.
*
* @param listener
* The progress of the launch, as well as any error, should be sent to this listener.
*
* @throws IOException
* if the method throws an {@link IOException} or {@link InterruptedException}, the launch was considered
* a failure and the stack trace is reported into the listener. This handling is just so that the implementation
* of this method doesn't have to dilligently catch those exceptions.
*/
public void launch(SlaveComputer computer, TaskListener listener) throws IOException , InterruptedException {
// to remain compatible with the legacy implementation that overrides the old signature
launch(computer,cast(listener));
}
/**
* @deprecated as of 1.304
* Use {@link #launch(SlaveComputer, TaskListener)}
*/
public void launch(SlaveComputer computer, StreamTaskListener listener) throws IOException , InterruptedException {
throw new UnsupportedOperationException(getClass()+" must implement the launch method");
}
/**
* Allows the {@link ComputerLauncher} to tidy-up after a disconnect.
*
* <p>
* This method is invoked after the {@link Channel} to this computer is terminated.
*
* <p>
* Disconnect operation is performed asynchronously, so there's no guarantee
* that the corresponding {@link SlaveComputer} exists for the duration of the
* operation.
*/
public void afterDisconnect(SlaveComputer computer, TaskListener listener) {
// to remain compatible with the legacy implementation that overrides the old signature
afterDisconnect(computer,cast(listener));
}
/**
* @deprecated as of 1.304
* Use {@link #afterDisconnect(SlaveComputer, TaskListener)}
*/
public void afterDisconnect(SlaveComputer computer, StreamTaskListener listener) {
}
/**
* Allows the {@link ComputerLauncher} to prepare for a disconnect.
*
* <p>
* This method is invoked before the {@link Channel} to this computer is terminated,
* thus the channel is still accessible from {@link SlaveComputer#getChannel()}.
* If the channel is terminated unexpectedly, this method will not be invoked,
* as the channel is already gone.
*
* <p>
* Disconnect operation is performed asynchronously, so there's no guarantee
* that the corresponding {@link SlaveComputer} exists for the duration of the
* operation.
*/
public void beforeDisconnect(SlaveComputer computer, TaskListener listener) {
// to remain compatible with the legacy implementation that overrides the old signature
beforeDisconnect(computer,cast(listener));
}
/**
* @deprecated as of 1.304
* Use {@link #beforeDisconnect(SlaveComputer, TaskListener)}
*/
public void beforeDisconnect(SlaveComputer computer, StreamTaskListener listener) {
}
private StreamTaskListener cast(TaskListener listener) {
if (listener instanceof StreamTaskListener)
return (StreamTaskListener) listener;
return new StreamTaskListener(listener.getLogger());
}
/**
* All registered {@link ComputerLauncher} implementations.
*
* @deprecated as of 1.281
* Use {@link Extension} for registration, and use
* {@link Hudson#getDescriptorList(Class)} for read access.
*/
public static final DescriptorList<ComputerLauncher> LIST = new DescriptorList<ComputerLauncher>(ComputerLauncher.class);
}
|
core/src/main/java/hudson/slaves/ComputerLauncher.java
|
/*
* The MIT License
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Stephen Connolly
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.slaves;
import hudson.ExtensionPoint;
import hudson.Extension;
import hudson.model.*;
import hudson.remoting.Channel;
import hudson.util.DescriptorList;
import hudson.util.StreamTaskListener;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* Extension point to allow control over how {@link Computer}s are "launched",
* meaning how they get connected to their slave agent program.
*
* <h2>Associated View</h2>
* <dl>
* <dt>main.jelly</dt>
* <dd>
* This page will be rendered into the top page of the computer (/computer/NAME/)
* Useful for showing launch related commands and status reports.
* </dl>
*
* @author Stephen Connolly
* @since 24-Apr-2008 22:12:35
* @see ComputerConnector
*/
public abstract class ComputerLauncher extends AbstractDescribableImpl<ComputerLauncher> implements ExtensionPoint {
/**
* Returns true if this {@link ComputerLauncher} supports
* programatic launch of the slave agent in the target {@link Computer}.
*/
public boolean isLaunchSupported() {
return true;
}
/**
* Launches the slave agent for the given {@link Computer}.
*
* <p>
* If the slave agent is launched successfully, {@link SlaveComputer#setChannel(InputStream, OutputStream, TaskListener, Channel.Listener)}
* should be invoked in the end to notify Hudson of the established connection.
* The operation could also fail, in which case there's no need to make any callback notification,
* (except to notify the user of the failure through {@link StreamTaskListener}.)
*
* <p>
* This method must operate synchronously. Asynchrony is provided by {@link Computer#connect(boolean)} and
* its correct operation depends on this.
*
* @param listener
* The progress of the launch, as well as any error, should be sent to this listener.
*
* @throws IOException
* if the method throws an {@link IOException} or {@link InterruptedException}, the launch was considered
* a failure and the stack trace is reported into the listener. This handling is just so that the implementation
* of this method doesn't have to dilligently catch those exceptions.
*/
public void launch(SlaveComputer computer, TaskListener listener) throws IOException , InterruptedException {
// to remain compatible with the legacy implementation that overrides the old signature
launch(computer,cast(listener));
}
/**
* @deprecated as of 1.304
* Use {@link #launch(SlaveComputer, TaskListener)}
*/
public void launch(SlaveComputer computer, StreamTaskListener listener) throws IOException , InterruptedException {
throw new UnsupportedOperationException(getClass()+" must implement the launch method");
}
/**
* Allows the {@link ComputerLauncher} to tidy-up after a disconnect.
*
* <p>
* This method is invoked after the {@link Channel} to this computer is terminated.
*
* <p>
* Disconnect operation is performed asynchronously, so there's no guarantee
* that the corresponding {@link SlaveComputer} exists for the duration of the
* operation.
*/
public void afterDisconnect(SlaveComputer computer, TaskListener listener) {
// to remain compatible with the legacy implementation that overrides the old signature
afterDisconnect(computer,cast(listener));
}
/**
* @deprecated as of 1.304
* Use {@link #afterDisconnect(SlaveComputer, TaskListener)}
*/
public void afterDisconnect(SlaveComputer computer, StreamTaskListener listener) {
}
/**
* Allows the {@link ComputerLauncher} to prepare for a disconnect.
*
* <p>
* This method is invoked before the {@link Channel} to this computer is terminated,
* thus the channel is still accessible from {@link SlaveComputer#getChannel()}.
* If the channel is terminated unexpectedly, this method will not be invoked,
* as the channel is already gone.
*
* <p>
* Disconnect operation is performed asynchronously, so there's no guarantee
* that the corresponding {@link SlaveComputer} exists for the duration of the
* operation.
*/
public void beforeDisconnect(SlaveComputer computer, TaskListener listener) {
// to remain compatible with the legacy implementation that overrides the old signature
beforeDisconnect(computer,cast(listener));
}
/**
* @deprecated as of 1.304
* Use {@link #beforeDisconnect(SlaveComputer, TaskListener)}
*/
public void beforeDisconnect(SlaveComputer computer, StreamTaskListener listener) {
}
private StreamTaskListener cast(TaskListener listener) {
if (listener instanceof StreamTaskListener)
return (StreamTaskListener) listener;
return new StreamTaskListener(listener.getLogger());
}
/**
* All registered {@link ComputerLauncher} implementations.
*
* @deprecated as of 1.281
* Use {@link Extension} for registration, and use
* {@link Hudson#getDescriptorList(Class)} for read access.
*/
public static final DescriptorList<ComputerLauncher> LIST = new DescriptorList<ComputerLauncher>(ComputerLauncher.class);
}
|
doc improvement
|
core/src/main/java/hudson/slaves/ComputerLauncher.java
|
doc improvement
|
|
Java
|
mit
|
c27bf337a42325158f0bedb29bff380abad90c89
| 0
|
shortcutmedia/shortcut-deeplink-sdk-android,shortcutmedia/shortcut-android-sdk
|
package sc.shortcut.sdk.android.deeplinking;
import android.net.Uri;
import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
public class SCServerRequest {
private static final String LOG_TAG = SCServerRequest.class.getSimpleName();
private static final String REQUEST_BASE_URL = "https://shortcut-service.shortcutmedia.com";
private static final String JSON_DEVICE_ID_KEY = "sc_device_id";
private static final String JSON_SESSION_ID_KEY = "sc_session_id";
private String mRequestUrl;
private Map<String, String> mPostData;
private SCPreference mPreference;
private SCSession mSession;
public SCServerRequest(String requestPath, SCSession session) {
Uri requestUri = Uri.parse(REQUEST_BASE_URL).buildUpon()
.appendEncodedPath(requestPath)
.build();
mRequestUrl = requestUri.toString();
mPreference = SCDeepLinking.getInstance().getPreference();
mSession = session;
}
public JSONObject doRequest() {
if (!shouldSend()) {
return null;
}
Log.d(LOG_TAG, "doRequest " + mRequestUrl);
try {
String postData = buildPostData();
URL url = new URL(mRequestUrl);
// Create the request to OpenWeatherMap, and open the connection
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true); // required to upload data via POST
urlConnection.setDoInput(true);
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Accept", "application/json");
urlConnection.setFixedLengthStreamingMode(postData.length()); // performance optimization
// Send POST output.
OutputStreamWriter out = new OutputStreamWriter(urlConnection.getOutputStream());
out.write(postData);
out.flush();
out.close();
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
if (inputStream == null) {
// Nothing to do.
return null;
}
StringBuffer buffer = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
Log.d(LOG_TAG, buffer.toString());
JSONObject responseJson = new JSONObject(buffer.toString());
responseJson.get("uri");
return responseJson;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected Map<String, String> getPostData() {
return mPostData;
}
protected void setPostData(Map<String, String> postData) {
mPostData = postData;
}
private String buildPostData() {
Map<String, String> postData = getPostData();
Map<String, String> commonData = getCommonPostData();
Map<String, String> combinedData = new HashMap<>(postData.size() + commonData.size());
combinedData.putAll(postData);
combinedData.putAll(commonData);
return new JSONObject(combinedData).toString();
}
protected Map<String, String> getCommonPostData() {
Map<String, String> commonParams = new HashMap<>(1);
commonParams.put(JSON_DEVICE_ID_KEY, mPreference.getDeviceId());
commonParams.put(JSON_SESSION_ID_KEY, ""+mSession.getId());
return commonParams;
}
/** Returns false if Request is initialized with insufficient or invalid data. */
protected boolean shouldSend() {
return true;
}
}
|
DeepLinkingSDK/src/main/java/sc/shortcut/sdk/android/deeplinking/SCServerRequest.java
|
package sc.shortcut.sdk.android.deeplinking;
import android.net.Uri;
import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
public class SCServerRequest {
private static final String TAG = SCServerRequest.class.getSimpleName();
private static final String REQUEST_BASE_URL = "https://shortcut-service.shortcutmedia.com";
private static final String JSON_DEVICE_ID_KEY = "sc_device_id";
private static final String JSON_SESSION_ID_KEY = "sc_session_id";
private String mRequestUrl;
private Map<String, String> mPostData;
private SCPreference mPreference;
private SCSession mSession;
public SCServerRequest(String requestPath, SCSession session) {
Uri requestUri = Uri.parse(REQUEST_BASE_URL).buildUpon()
.appendEncodedPath(requestPath)
.build();
mRequestUrl = requestUri.toString();
mPreference = SCDeepLinking.getInstance().getPreference();
mSession = session;
}
public JSONObject doRequest() {
if (!shouldSend()) {
return null;
}
Log.d(TAG, "doRequest " + mRequestUrl);
try {
String postData = buildPostData();
URL url = new URL(mRequestUrl);
// Create the request to OpenWeatherMap, and open the connection
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true); // required to upload data via POST
urlConnection.setDoInput(true);
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Accept", "application/json");
urlConnection.setFixedLengthStreamingMode(postData.length()); // performance optimization
// Send POST output.
OutputStreamWriter out = new OutputStreamWriter(urlConnection.getOutputStream());
out.write(postData);
out.flush();
out.close();
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
if (inputStream == null) {
// Nothing to do.
return null;
}
StringBuffer buffer = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
Log.d(TAG, buffer.toString());
JSONObject responseJson = new JSONObject(buffer.toString());
responseJson.get("uri");
return responseJson;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected Map<String, String> getPostData() {
return mPostData;
}
protected void setPostData(Map<String, String> postData) {
mPostData = postData;
}
private String buildPostData() {
Map<String, String> postData = getPostData();
Map<String, String> commonData = getCommonPostData();
Map<String, String> combinedData = new HashMap<>(postData.size() + commonData.size());
combinedData.putAll(postData);
combinedData.putAll(commonData);
return new JSONObject(combinedData).toString();
}
protected Map<String, String> getCommonPostData() {
Map<String, String> commonParams = new HashMap<>(1);
commonParams.put(JSON_DEVICE_ID_KEY, mPreference.getDeviceId());
commonParams.put(JSON_SESSION_ID_KEY, ""+mSession.getId());
return commonParams;
}
/** Returns false if Request is initialized with insufficient or invalid data. */
protected boolean shouldSend() {
return true;
}
}
|
style: renamed LOG_TAG constant to be consistent
|
DeepLinkingSDK/src/main/java/sc/shortcut/sdk/android/deeplinking/SCServerRequest.java
|
style: renamed LOG_TAG constant to be consistent
|
|
Java
|
mit
|
1c6bc830c939d4677f5a5c8df546d86b37ad1ab7
| 0
|
InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service
|
package org.innovateuk.ifs.authentication.validator;
import org.innovateuk.ifs.commons.error.Error;
import org.innovateuk.ifs.commons.service.ServiceResult;
import org.innovateuk.ifs.organisation.domain.Organisation;
import org.innovateuk.ifs.organisation.repository.OrganisationRepository;
import org.innovateuk.ifs.user.resource.UserResource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import static java.lang.String.format;
import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import static java.util.regex.Pattern.CASE_INSENSITIVE;
import static java.util.stream.Collectors.summingInt;
import static org.innovateuk.ifs.commons.service.ServiceResult.serviceFailure;
import static org.innovateuk.ifs.commons.service.ServiceResult.serviceSuccess;
import static org.innovateuk.ifs.util.CollectionFunctions.*;
import static org.innovateuk.ifs.util.MapFunctions.asMap;
import static org.springframework.http.HttpStatus.BAD_REQUEST;
/**
* A component that is able to enforce certain additional rules for the Innovate UK password policy
* that are not handled in the Identity Provider (Shibboleth REST API)
*/
@Component
public class PasswordPolicyValidator {
static final String PASSWORD_MUST_NOT_CONTAIN_FIRST_NAME = "PASSWORD_MUST_NOT_CONTAIN_FIRST_NAME";
static final String PASSWORD_MUST_NOT_CONTAIN_LAST_NAME = "PASSWORD_MUST_NOT_CONTAIN_LAST_NAME";
static final String PASSWORD_MUST_NOT_CONTAIN_FULL_NAME = "PASSWORD_MUST_NOT_CONTAIN_FULL_NAME";
static final String PASSWORD_MUST_NOT_CONTAIN_FIRST_OR_LAST_NAME = "PASSWORD_MUST_NOT_CONTAIN_FIRST_OR_LAST_NAME";
static final String PASSWORD_MUST_NOT_CONTAIN_ORGANISATION_NAME = "PASSWORD_MUST_NOT_CONTAIN_ORGANISATION_NAME";
@Autowired
private OrganisationRepository organisationRepository;
private List<ExclusionRule> exclusionRules;
private List<ExclusionRulePatternGenerator> exclusionRulePatternGenerators;
/**
* A class representing a facet of a User that we wish to exclude from their password e.g. first name, last name,
* full name, organisation name(s)
*/
class ExclusionRule {
private String errorKey;
private Function<ExclusionRuleTarget, List<String>> exclusionSupplier;
private int lengthThresholdForRuleToApply;
private boolean mustContainAllExcludedWords;
public ExclusionRule(String errorKey, int lengthThresholdForRuleToApply, boolean mustContainAllExcludedWords, Function<ExclusionRuleTarget, List<String>> exclusionSupplier) {
this.errorKey = errorKey;
this.exclusionSupplier = exclusionSupplier;
this.lengthThresholdForRuleToApply = lengthThresholdForRuleToApply;
this.mustContainAllExcludedWords = mustContainAllExcludedWords;
}
}
/**
* A marker interface representing a component that, given a regular expression Pattern, can produce alternative
* Patterns based on some set of rules (e.g. disallowing common numerical replacements of letters that would otherwise
* produce an excluded word)
*/
interface ExclusionRulePatternGenerator extends Function<String, List<Pattern>> {
}
/**
* A component that, given a regular expression that defines an exclusion rule (e.g. for checking for the presence of
* a first name in a string "*.first.*name.*"), is able to produce variations on this regex for additional checking of
* common numerical replacements for letters. e.g. given a pattern checking for ".*hello.*there.*", this generator
* would allow numberical replacements to be checked for as well like ".*h[e3][l1][l1][o0].*th[e3]r[e3].*"
*/
private ExclusionRulePatternGeneratorImpl lettersForNumbersGenerator = new ExclusionRulePatternGeneratorImpl();
private class ExclusionRulePatternGeneratorImpl implements ExclusionRulePatternGenerator {
private Map<String, String> interchangeableLettersAndNumbers = asMap(
"a", "4",
"b", "8",
"e", "3",
"i", "1",
"l", "1",
"o", "0",
"s", "5",
"z", "2");
@Override
public List<Pattern> apply(String currentExcludedRegexPattern) {
/**
* The Regex (a-zA-Z0-9-.*\s]*) check for all the characters which can include in the patterns to be checked in the password.
* These patterns could be first name, last name, organisation....
* The pattern includes alpha numerics, *, -, spaces.
*/
boolean containNoSpecialCharacters = Pattern.compile("[a-zA-Z0-9-.*\\s]*").matcher(currentExcludedRegexPattern).matches();
String currentExcludedWordWithNumericalReplacements = currentExcludedRegexPattern.toLowerCase();
for (Map.Entry<String, String> replacement : interchangeableLettersAndNumbers.entrySet()) {
String searchString = format("([%s])", replacement.getKey());
String replacementString = format("[$1%s]", replacement.getValue());
currentExcludedWordWithNumericalReplacements =
currentExcludedWordWithNumericalReplacements.replaceAll(searchString, replacementString);
}
String excludePattern = containNoSpecialCharacters ? currentExcludedWordWithNumericalReplacements :
Pattern.quote(currentExcludedWordWithNumericalReplacements);
Pattern currentExcludedWordWithNumericalReplacementsPattern =
Pattern.compile(excludePattern, CASE_INSENSITIVE);
return singletonList(currentExcludedWordWithNumericalReplacementsPattern);
}
}
private class ExclusionRuleTarget {
private UserResource user;
private Long organisationId;
public ExclusionRuleTarget(UserResource user) {
this.user = user;
}
public ExclusionRuleTarget(UserResource user, Long organisationId) {
this.user = user;
this.organisationId = organisationId;
}
public UserResource getUser() {
return user;
}
public Long getOrganisationId() {
return organisationId;
}
}
@PostConstruct
void postConstruct() {
ExclusionRule containsFirstName = new ExclusionRule(PASSWORD_MUST_NOT_CONTAIN_FIRST_OR_LAST_NAME, 4, true, target -> singletonList(target.getUser().getFirstName()));
ExclusionRule containsLastName = new ExclusionRule(PASSWORD_MUST_NOT_CONTAIN_FIRST_OR_LAST_NAME, 4, true, target -> singletonList(target.getUser().getLastName()));
ExclusionRule containsFullName = new ExclusionRule(PASSWORD_MUST_NOT_CONTAIN_FIRST_OR_LAST_NAME, 5, true, target -> asList(target.getUser().getFirstName(), target.getUser().getLastName()));
ExclusionRule containsOrganisationName = new ExclusionRule(PASSWORD_MUST_NOT_CONTAIN_ORGANISATION_NAME, 4, false, target -> getOrganisationNamesForUser(target.getUser(), target.getOrganisationId()));
exclusionRules = asList(containsFirstName, containsLastName, containsFullName, containsOrganisationName);
exclusionRulePatternGenerators = asList(lettersForNumbersGenerator);
}
private List<String> getOrganisationNamesForUser(UserResource user, Long organisationId) {
if (user.getId() == null) {
if (organisationId != null) {
Organisation organisation = organisationRepository.findOne(organisationId);
return asList(organisation.getName());
} else {
return emptyList();
}
}
return organisationRepository.findDistinctByUsersId(user.getId()).stream()
.filter(organisation -> organisation.getName() != null)
.map(Organisation::getName)
.collect(Collectors.toList());
}
/**
* Validate the password, returning a list of errors if one or more exclusions were found
*
* @param password
* @param userResource
* @return
*/
public ServiceResult<Void> validatePassword(String password, UserResource userResource) {
List<ServiceResult<Void>> exclusionResults = flattenLists(simpleMap(exclusionRules, rule ->
simpleMap(exclusionRulePatternGenerators, patternGenerator -> {
List<String> excludedWords = rule.exclusionSupplier.apply(new ExclusionRuleTarget(userResource));
if (rule.mustContainAllExcludedWords) {
return checkForExclusionWordsWithinPassword(password, rule, patternGenerator, excludedWords);
} else {
List<ServiceResult<Void>> results = simpleMap(excludedWords, excludedWord -> checkForExclusionWordsWithinPassword(password, rule, patternGenerator, singletonList(excludedWord)));
return returnSuccessOrCollateFailures(results);
}
})
));
return returnSuccessOrCollateFailures(exclusionResults);
}
/**
* Validate the password for organisationId, returning a list of errors if one or more exclusions were found
*
* @param password
* @param userResource
* @return
*/
public ServiceResult<Void> validatePassword(String password, UserResource userResource, Long organisationId) {
List<ServiceResult<Void>> exclusionResults = flattenLists(simpleMap(exclusionRules, rule ->
simpleMap(exclusionRulePatternGenerators, patternGenerator -> {
List<String> excludedWords = rule.exclusionSupplier.apply(new ExclusionRuleTarget(userResource, organisationId));
if (rule.mustContainAllExcludedWords) {
return checkForExclusionWordsWithinPassword(password, rule, patternGenerator, excludedWords);
} else {
List<ServiceResult<Void>> results = simpleMap(excludedWords, excludedWord -> checkForExclusionWordsWithinPassword(password, rule, patternGenerator, singletonList(excludedWord)));
return returnSuccessOrCollateFailures(results);
}
})
));
return returnSuccessOrCollateFailures(exclusionResults);
}
private ServiceResult<Void> returnSuccessOrCollateFailures(List<ServiceResult<Void>> exclusionResults) {
List<ServiceResult<Void>> failures = simpleFilter(exclusionResults, ServiceResult::isFailure);
if (!failures.isEmpty()) {
List<Error> allErrors = flattenLists(simpleMap(failures, failure -> failure.getFailure().getErrors()));
List<Error> uniqueErrors = removeDuplicates(allErrors);
return serviceFailure(uniqueErrors);
} else {
return serviceSuccess();
}
}
/**
* This method, given a user, their chosen password, an exclusion rule (e.g. no full names) and a pattern generator, will
* check for the presence of excluded tokens (in different orders as well if, for instance, checking for more than one word
* for a single rule, like in the case of full name (that uses "first name" and "last name" in combination)).
*
* @param password
* @param rule
* @param patternGenerator
* @param excludedWords
* @return
*/
private ServiceResult<Void> checkForExclusionWordsWithinPassword(String password, ExclusionRule rule, ExclusionRulePatternGenerator patternGenerator, List<String> excludedWords) {
int lengthOfAllWords = excludedWords.stream().collect(summingInt(String::length));
if (lengthOfAllWords < rule.lengthThresholdForRuleToApply) {
return serviceSuccess();
}
List<List<String>> permutations = findPermutations(excludedWords);
List<String> permutationsAsRegexes = simpleMap(permutations, permutation -> ".*" + simpleJoiner(permutation, ".*") + ".*");
String permutationsAsSingleRegex = simpleJoiner(permutationsAsRegexes, "|");
List<Pattern> exclusionPatterns = patternGenerator.apply(permutationsAsSingleRegex);
boolean excluded = exclusionPatterns.stream().anyMatch(pattern -> pattern.matcher(password).matches());
return excluded ? serviceFailure(new Error(rule.errorKey, BAD_REQUEST)) : serviceSuccess();
}
}
|
ifs-data-layer/ifs-data-service/src/main/java/org/innovateuk/ifs/authentication/validator/PasswordPolicyValidator.java
|
package org.innovateuk.ifs.authentication.validator;
import org.innovateuk.ifs.commons.error.Error;
import org.innovateuk.ifs.commons.service.ServiceResult;
import org.innovateuk.ifs.organisation.domain.Organisation;
import org.innovateuk.ifs.organisation.repository.OrganisationRepository;
import org.innovateuk.ifs.user.resource.UserResource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import static java.lang.String.format;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;
import static java.util.regex.Pattern.CASE_INSENSITIVE;
import static java.util.stream.Collectors.summingInt;
import static org.innovateuk.ifs.commons.service.ServiceResult.serviceFailure;
import static org.innovateuk.ifs.commons.service.ServiceResult.serviceSuccess;
import static org.innovateuk.ifs.util.CollectionFunctions.*;
import static org.innovateuk.ifs.util.MapFunctions.asMap;
import static org.springframework.http.HttpStatus.BAD_REQUEST;
/**
* A component that is able to enforce certain additional rules for the Innovate UK password policy
* that are not handled in the Identity Provider (Shibboleth REST API)
*/
@Component
public class PasswordPolicyValidator {
static final String PASSWORD_MUST_NOT_CONTAIN_FIRST_NAME = "PASSWORD_MUST_NOT_CONTAIN_FIRST_NAME";
static final String PASSWORD_MUST_NOT_CONTAIN_LAST_NAME = "PASSWORD_MUST_NOT_CONTAIN_LAST_NAME";
static final String PASSWORD_MUST_NOT_CONTAIN_FULL_NAME = "PASSWORD_MUST_NOT_CONTAIN_FULL_NAME";
static final String PASSWORD_MUST_NOT_CONTAIN_FIRST_OR_LAST_NAME = "PASSWORD_MUST_NOT_CONTAIN_FIRST_OR_LAST_NAME";
static final String PASSWORD_MUST_NOT_CONTAIN_ORGANISATION_NAME = "PASSWORD_MUST_NOT_CONTAIN_ORGANISATION_NAME";
@Autowired
private OrganisationRepository organisationRepository;
private List<ExclusionRule> exclusionRules;
private List<ExclusionRulePatternGenerator> exclusionRulePatternGenerators;
/**
* A class representing a facet of a User that we wish to exclude from their password e.g. first name, last name,
* full name, organisation name(s)
*/
class ExclusionRule {
private String errorKey;
private Function<ExclusionRuleTarget, List<String>> exclusionSupplier;
private int lengthThresholdForRuleToApply;
private boolean mustContainAllExcludedWords;
public ExclusionRule(String errorKey, int lengthThresholdForRuleToApply, boolean mustContainAllExcludedWords, Function<ExclusionRuleTarget, List<String>> exclusionSupplier) {
this.errorKey = errorKey;
this.exclusionSupplier = exclusionSupplier;
this.lengthThresholdForRuleToApply = lengthThresholdForRuleToApply;
this.mustContainAllExcludedWords = mustContainAllExcludedWords;
}
}
/**
* A marker interface representing a component that, given a regular expression Pattern, can produce alternative
* Patterns based on some set of rules (e.g. disallowing common numerical replacements of letters that would otherwise
* produce an excluded word)
*/
interface ExclusionRulePatternGenerator extends Function<String, List<Pattern>> {
}
/**
* A component that, given a regular expression that defines an exclusion rule (e.g. for checking for the presence of
* a first name in a string "*.first.*name.*"), is able to produce variations on this regex for additional checking of
* common numerical replacements for letters. e.g. given a pattern checking for ".*hello.*there.*", this generator
* would allow numberical replacements to be checked for as well like ".*h[e3][l1][l1][o0].*th[e3]r[e3].*"
*/
private ExclusionRulePatternGeneratorImpl lettersForNumbersGenerator = new ExclusionRulePatternGeneratorImpl();
private class ExclusionRulePatternGeneratorImpl implements ExclusionRulePatternGenerator {
private Map<String, String> interchangeableLettersAndNumbers = asMap(
"a", "4",
"b", "8",
"e", "3",
"i", "1",
"l", "1",
"o", "0",
"s", "5",
"z", "2");
@Override
public List<Pattern> apply(String currentExcludedRegexPattern) {
/**
* The Regex (a-zA-Z0-9-.*\s]*) check for all the characters which can include in the patterns to be checked in the password.
* These patterns could be first name, last name, organisation....
* The pattern includes alpha numerics, *, -, spaces.
*/
boolean containNoSpecialCharacters = Pattern.compile("[a-zA-Z0-9-.*\\s]*").matcher(currentExcludedRegexPattern).matches();
String currentExcludedWordWithNumericalReplacements = currentExcludedRegexPattern.toLowerCase();
for (Map.Entry<String, String> replacement : interchangeableLettersAndNumbers.entrySet()) {
String searchString = format("([%s])", replacement.getKey());
String replacementString = format("[$1%s]", replacement.getValue());
currentExcludedWordWithNumericalReplacements =
currentExcludedWordWithNumericalReplacements.replaceAll(searchString, replacementString);
}
String excludePattern = containNoSpecialCharacters ? currentExcludedWordWithNumericalReplacements :
Pattern.quote(currentExcludedWordWithNumericalReplacements);
Pattern currentExcludedWordWithNumericalReplacementsPattern =
Pattern.compile(excludePattern, CASE_INSENSITIVE);
return singletonList(currentExcludedWordWithNumericalReplacementsPattern);
}
}
private class ExclusionRuleTarget {
private UserResource user;
private Long organisationId;
public ExclusionRuleTarget(UserResource user) {
this.user = user;
}
public ExclusionRuleTarget(UserResource user, Long organisationId) {
this.user = user;
this.organisationId = organisationId;
}
public UserResource getUser() {
return user;
}
public Long getOrganisationId() {
return organisationId;
}
}
@PostConstruct
void postConstruct() {
ExclusionRule containsFirstName = new ExclusionRule(PASSWORD_MUST_NOT_CONTAIN_FIRST_OR_LAST_NAME, 4, true, target -> singletonList(target.getUser().getFirstName()));
ExclusionRule containsLastName = new ExclusionRule(PASSWORD_MUST_NOT_CONTAIN_FIRST_OR_LAST_NAME, 4, true, target -> singletonList(target.getUser().getLastName()));
ExclusionRule containsFullName = new ExclusionRule(PASSWORD_MUST_NOT_CONTAIN_FIRST_OR_LAST_NAME, 5, true, target -> asList(target.getUser().getFirstName(), target.getUser().getLastName()));
ExclusionRule containsOrganisationName = new ExclusionRule(PASSWORD_MUST_NOT_CONTAIN_ORGANISATION_NAME, 4, false, target -> getOrganisationNamesForUser(target.getUser(), target.getOrganisationId()));
exclusionRules = asList(containsFirstName, containsLastName, containsFullName, containsOrganisationName);
exclusionRulePatternGenerators = asList(lettersForNumbersGenerator);
}
private List<String> getOrganisationNamesForUser(UserResource user, Long organisationId) {
if (user.getId() == null && organisationId != null) {
Organisation organisation = organisationRepository.findOne(organisationId);
return asList(organisation.getName());
}
return organisationRepository.findDistinctByUsersId(user.getId()).stream()
.filter(organisation -> organisation.getName() != null)
.map(Organisation::getName)
.collect(Collectors.toList());
}
/**
* Validate the password, returning a list of errors if one or more exclusions were found
*
* @param password
* @param userResource
* @return
*/
public ServiceResult<Void> validatePassword(String password, UserResource userResource) {
List<ServiceResult<Void>> exclusionResults = flattenLists(simpleMap(exclusionRules, rule ->
simpleMap(exclusionRulePatternGenerators, patternGenerator -> {
List<String> excludedWords = rule.exclusionSupplier.apply(new ExclusionRuleTarget(userResource));
if (rule.mustContainAllExcludedWords) {
return checkForExclusionWordsWithinPassword(password, rule, patternGenerator, excludedWords);
} else {
List<ServiceResult<Void>> results = simpleMap(excludedWords, excludedWord -> checkForExclusionWordsWithinPassword(password, rule, patternGenerator, singletonList(excludedWord)));
return returnSuccessOrCollateFailures(results);
}
})
));
return returnSuccessOrCollateFailures(exclusionResults);
}
/**
* Validate the password for organisationId, returning a list of errors if one or more exclusions were found
*
* @param password
* @param userResource
* @return
*/
public ServiceResult<Void> validatePassword(String password, UserResource userResource, Long organisationId) {
List<ServiceResult<Void>> exclusionResults = flattenLists(simpleMap(exclusionRules, rule ->
simpleMap(exclusionRulePatternGenerators, patternGenerator -> {
List<String> excludedWords = rule.exclusionSupplier.apply(new ExclusionRuleTarget(userResource, organisationId));
if (rule.mustContainAllExcludedWords) {
return checkForExclusionWordsWithinPassword(password, rule, patternGenerator, excludedWords);
} else {
List<ServiceResult<Void>> results = simpleMap(excludedWords, excludedWord -> checkForExclusionWordsWithinPassword(password, rule, patternGenerator, singletonList(excludedWord)));
return returnSuccessOrCollateFailures(results);
}
})
));
return returnSuccessOrCollateFailures(exclusionResults);
}
private ServiceResult<Void> returnSuccessOrCollateFailures(List<ServiceResult<Void>> exclusionResults) {
List<ServiceResult<Void>> failures = simpleFilter(exclusionResults, ServiceResult::isFailure);
if (!failures.isEmpty()) {
List<Error> allErrors = flattenLists(simpleMap(failures, failure -> failure.getFailure().getErrors()));
List<Error> uniqueErrors = removeDuplicates(allErrors);
return serviceFailure(uniqueErrors);
} else {
return serviceSuccess();
}
}
/**
* This method, given a user, their chosen password, an exclusion rule (e.g. no full names) and a pattern generator, will
* check for the presence of excluded tokens (in different orders as well if, for instance, checking for more than one word
* for a single rule, like in the case of full name (that uses "first name" and "last name" in combination)).
*
* @param password
* @param rule
* @param patternGenerator
* @param excludedWords
* @return
*/
private ServiceResult<Void> checkForExclusionWordsWithinPassword(String password, ExclusionRule rule, ExclusionRulePatternGenerator patternGenerator, List<String> excludedWords) {
int lengthOfAllWords = excludedWords.stream().collect(summingInt(String::length));
if (lengthOfAllWords < rule.lengthThresholdForRuleToApply) {
return serviceSuccess();
}
List<List<String>> permutations = findPermutations(excludedWords);
List<String> permutationsAsRegexes = simpleMap(permutations, permutation -> ".*" + simpleJoiner(permutation, ".*") + ".*");
String permutationsAsSingleRegex = simpleJoiner(permutationsAsRegexes, "|");
List<Pattern> exclusionPatterns = patternGenerator.apply(permutationsAsSingleRegex);
boolean excluded = exclusionPatterns.stream().anyMatch(pattern -> pattern.matcher(password).matches());
return excluded ? serviceFailure(new Error(rule.errorKey, BAD_REQUEST)) : serviceSuccess();
}
}
|
IFS-3513 fixing nullable
|
ifs-data-layer/ifs-data-service/src/main/java/org/innovateuk/ifs/authentication/validator/PasswordPolicyValidator.java
|
IFS-3513 fixing nullable
|
|
Java
|
mit
|
b1661be83f12439056db7b4d2244d8b47f707b74
| 0
|
adrielcafe/NMSAlphabetAndroidApp
|
package cafe.adriel.nmsalphabet.ui;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import cafe.adriel.nmsalphabet.Constant;
import cafe.adriel.nmsalphabet.R;
import cafe.adriel.nmsalphabet.util.LanguageUtil;
import cafe.adriel.nmsalphabet.util.Triple;
import cafe.adriel.nmsalphabet.util.Util;
public class TranslatorsActivity extends BaseActivity {
@BindView(R.id.translators_layout)
LinearLayout translatorsLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_translators);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
setTitle(R.string.translators);
ButterKnife.bind(this);
init();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
break;
}
return true;
}
@Override
protected void init() {
adjustMarginAndPadding();
for(Triple<String, String, String> translator : Constant.TRANSLATORS){
String language = translator.getA();
String name = translator.getB();
String twitter = translator.getC();
View translatorView = setupTranslator(language, name, twitter);
translatorsLayout.addView(translatorView);
}
}
private View setupTranslator(String language, String name, final String twitter){
View rootView = LayoutInflater.from(this).inflate(R.layout.list_item_translator, null, false);
rootView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(Util.isNotEmpty(twitter)) {
String url = "http://twitter.com/" + twitter.replace("@", "");
Util.openUrl(TranslatorsActivity.this, url);
}
}
});
TranslatorViewHolder holder = new TranslatorViewHolder(rootView);
holder.translatorNameView.setText(name);
holder.translatorTwitterView.setText(twitter);
switch (language){
case LanguageUtil.LANGUAGE_EN:
holder.countryFlagView.setImageResource(R.drawable.flag_uk_big);
break;
case LanguageUtil.LANGUAGE_PT:
holder.countryFlagView.setImageResource(R.drawable.flag_brazil_big);
break;
case LanguageUtil.LANGUAGE_DE:
holder.countryFlagView.setImageResource(R.drawable.flag_germany_big);
break;
}
return rootView;
}
public static class TranslatorViewHolder {
@BindView(R.id.country_flag)
public ImageView countryFlagView;
@BindView(R.id.translator_name)
public TextView translatorNameView;
@BindView(R.id.translator_twitter)
public TextView translatorTwitterView;
public TranslatorViewHolder(View v) {
ButterKnife.bind(this, v);
}
}
}
|
app/src/main/java/cafe/adriel/nmsalphabet/ui/TranslatorsActivity.java
|
package cafe.adriel.nmsalphabet.ui;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import cafe.adriel.nmsalphabet.Constant;
import cafe.adriel.nmsalphabet.R;
import cafe.adriel.nmsalphabet.util.LanguageUtil;
import cafe.adriel.nmsalphabet.util.Triple;
import cafe.adriel.nmsalphabet.util.Util;
public class TranslatorsActivity extends BaseActivity {
@BindView(R.id.translators_layout)
LinearLayout translatorsLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_translators);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
ButterKnife.bind(this);
init();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
break;
}
return true;
}
@Override
protected void init() {
adjustMarginAndPadding();
for(Triple<String, String, String> translator : Constant.TRANSLATORS){
String language = translator.getA();
String name = translator.getB();
String twitter = translator.getC();
View translatorView = setupTranslator(language, name, twitter);
translatorsLayout.addView(translatorView);
}
}
private View setupTranslator(String language, String name, final String twitter){
View rootView = LayoutInflater.from(this).inflate(R.layout.list_item_translator, null, false);
rootView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(Util.isNotEmpty(twitter)) {
String url = "http://twitter.com/" + twitter.replace("@", "");
Util.openUrl(TranslatorsActivity.this, url);
}
}
});
TranslatorViewHolder holder = new TranslatorViewHolder(rootView);
holder.translatorNameView.setText(name);
holder.translatorTwitterView.setText(twitter);
switch (language){
case LanguageUtil.LANGUAGE_EN:
holder.countryFlagView.setImageResource(R.drawable.flag_uk_big);
break;
case LanguageUtil.LANGUAGE_PT:
holder.countryFlagView.setImageResource(R.drawable.flag_brazil_big);
break;
case LanguageUtil.LANGUAGE_DE:
holder.countryFlagView.setImageResource(R.drawable.flag_germany_big);
break;
}
return rootView;
}
public static class TranslatorViewHolder {
@BindView(R.id.country_flag)
public ImageView countryFlagView;
@BindView(R.id.translator_name)
public TextView translatorNameView;
@BindView(R.id.translator_twitter)
public TextView translatorTwitterView;
public TranslatorViewHolder(View v) {
ButterKnife.bind(this, v);
}
}
}
|
Fix TranslatorsActivity title
|
app/src/main/java/cafe/adriel/nmsalphabet/ui/TranslatorsActivity.java
|
Fix TranslatorsActivity title
|
|
Java
|
mit
|
73a80e873a2b3fe7203b7c00782363ab355afa6a
| 0
|
CS2103JAN2017-W14-B4/main,CS2103JAN2017-W14-B4/main
|
package seedu.ezdo.ui;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.image.ImageView;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Region;
import seedu.ezdo.logic.parser.DateParser;
import seedu.ezdo.model.todo.ReadOnlyTask;
//@@author A0139177W
/**
* The task card for the UI.
*/
public class TaskCard extends UiPart<Region> {
private static final String NUMBERING_FORMAT = ". ";
private static final String HAS_COMPLETED_LINK = "/images/tick.png";
private static final String HAS_STARTED_LINK = "/images/wip.png";
private static final String DEFAULT_PRIORITY_NUMBER = "";
private static final String DEFAULT_PRIORITY_COLOR = "transparent";
private static final String HIGH_PRIORITY_NUMBER = "1";
private static final String HIGH_PRIORITY_COLOR = "red";
private static final String MEDIUM_PRIORITY_NUMBER = "2";
private static final String MEDIUM_PRIORITY_COLOR = "orange";
private static final String LOW_PRIORITY_NUMBER = "3";
private static final String LOW_PRIORITY_COLOR = "green";
private static final String FXML = "TaskListCard.fxml";
private static final String CSS_BACKGROUND_COLOR_PROPERTY = "-fx-background-color: ";
private static final String CSS_STARTDATE_PAST_CURRENT_DATE_COLOR =
"-fx-text-fill: darkgreen; -fx-font-weight: bold";
private static final String CSS_OVERDUE_COLOR =
"-fx-text-fill: red; -fx-font-weight: bold";
private static final String CSS_ABOUT_TO_DUE_COLOR =
"-fx-text-fill: orangered; -fx-font-weight: bold";
private static final DateFormat DATE_FORMAT = new SimpleDateFormat(DateParser.USER_DATE_OUTPUT_FORMAT);
public static final HashMap<String, String> PRIORITY_COLOR_HASHMAP = new HashMap<>();
private String priorityInString;
@FXML
private HBox cardPane;
@FXML
private AnchorPane priorityColor;
@FXML
private Label name;
@FXML
private Label id;
@FXML
private Label status;
@FXML
private Label priority;
@FXML
private Label startDate;
@FXML
private Label dueDate;
@FXML
private Label recur;
@FXML
private FlowPane tags;
/**
* Creates a TaskCard object with all fields to be shown in UI.
* @param task The task to be updated.
* @param displayedIndex The index of the task.
*/
public TaskCard(ReadOnlyTask task, int displayedIndex) {
super(FXML);
setPriorityColorHashMap();
name.setText(task.getName().fullName);
id.setText(displayedIndex + NUMBERING_FORMAT);
setPriority(task);
setStatus(task);
setStartDate(task);
setDueDate(task);
recur.setText(task.getRecur().value);
setStatus(task);
initTags(task);
}
// ========================= STARTDATE ============================ //
/**
* Sets the text of start date.
* Sets the color of start date when the date has commenced.
* @param task The task to be updated.
*/
private void setStartDate(ReadOnlyTask task) {
Date currentDate = new Date(); // current date and time
startDate.setText(task.getStartDate().value);
setStartDateColor(currentDate, CSS_STARTDATE_PAST_CURRENT_DATE_COLOR);
}
/**
* Sets the color of the start date when it has commenced.
* @param dateReference The date to be referenced.
* @param cssColor The CSS formatting to be used.
* @throws ParseException If the start date is optional and cannot be parsed
* as Date object.
*/
private void setStartDateColor(Date dateReference, String cssColor) {
try {
if (dateReference.after(DATE_FORMAT.parse(startDate.getText()))) {
startDate.setStyle(cssColor);
}
} catch (ParseException pe) {
// Do nothing as the date is optional
// and cannot be parsed as Date object.
}
}
// ========================= DUEDATE ============================ //
/**
* Sets the text of the due date.
* Sets the color of due date when it is overdue and when it's due in 7 days time.
* @param task The task to be updated.
* @throws ParseException If the due date is optional and cannot be parsed
* as Date object.
*/
private void setDueDate(ReadOnlyTask task) {
Date currentDate = new Date();
Date dateSevenDaysInAdvance = createDateSevenDaysInAdvance();
dueDate.setText(task.getDueDate().value);
setAboutToDueDateColor(dateSevenDaysInAdvance, CSS_ABOUT_TO_DUE_COLOR);
setDueDateColor(currentDate, CSS_OVERDUE_COLOR);
}
/**
* Removes the color of the start date when it's due in 7 days time.
* Sets the color of the due date when it's due in 7 days time.
* @param dateReference The date to be referenced.
* @param cssColor The CSS formatting to be used.
* @throws ParseException If the due date is optional and cannot be parsed
* as Date object.
*/
private void setAboutToDueDateColor(Date dateReference, String cssColor) {
try {
if (dateReference.after(DATE_FORMAT.parse(dueDate.getText()))) {
startDate.setStyle(null);
dueDate.setStyle(cssColor);
}
} catch (ParseException pe) {
// Do nothing as the date is optional
// and cannot be parsed as Date object.
}
}
/**
* Sets the color of the start date when the due date is overdue.
* Sets the color of the due date when the due date is overdue.
* @param dateReference The date to be referenced.
* @param cssColor The CSS formatting to be used.
* @throws ParseException If the due date is optional and cannot be parsed
* as Date object.
*/
private void setDueDateColor(Date dateReference, String cssColor) {
try {
if (dateReference.after(DATE_FORMAT.parse(dueDate.getText()))) {
startDate.setStyle(cssColor);
dueDate.setStyle(cssColor);
}
} catch (ParseException pe) {
// Do nothing as the date is optional
// and cannot be parsed as Date object.
}
}
/** Returns the date seven days in advance of the current date and time. */
private Date createDateSevenDaysInAdvance() {
int weekIncrement = 7;
Calendar cal = Calendar.getInstance(); // get current date and time
cal.add(Calendar.DATE, weekIncrement); // update to seven days ago
return cal.getTime();
}
// ========================= PRIORITY ============================ //
/** Sets priorityInString as a local variable. **/
private void setPriorityInString(ReadOnlyTask task) {
String priorityValue = task.getPriority().value;
this.priorityInString = priorityValue;
}
/** Initialises the colors and priority numbers in PRIORITY_COLOR_HASHMAP. **/
private void setPriorityColorHashMap() {
PRIORITY_COLOR_HASHMAP.put(DEFAULT_PRIORITY_NUMBER, DEFAULT_PRIORITY_COLOR);
PRIORITY_COLOR_HASHMAP.put(LOW_PRIORITY_NUMBER, LOW_PRIORITY_COLOR);
PRIORITY_COLOR_HASHMAP.put(MEDIUM_PRIORITY_NUMBER, MEDIUM_PRIORITY_COLOR);
PRIORITY_COLOR_HASHMAP.put(HIGH_PRIORITY_NUMBER, HIGH_PRIORITY_COLOR);
}
/**
* Sets the priority text and color.
* @param task The task to be updated.
*/
private void setPriority(ReadOnlyTask task) {
setPriorityInString(task);
priority.setText(priorityInString); // Invisible in UI (for testing purposes)
priorityColor.setStyle(CSS_BACKGROUND_COLOR_PROPERTY + PRIORITY_COLOR_HASHMAP.get(priorityInString));
}
// ========================= STATUS ============================ //
/**
* Sets the image if a task has selected or if the task has completed.
* @param task The task to be updated.
*/
private void setStatus(ReadOnlyTask task) {
if (task.getStarted()) {
status.setGraphic(new ImageView(HAS_STARTED_LINK));
}
if (task.getDone()) {
status.setGraphic(new ImageView(HAS_COMPLETED_LINK));
}
}
// ========================= TAGS ============================ //
/**
* Sets the tags given a task.
* @param task The task to be updated.
*/
private void initTags(ReadOnlyTask task) {
task.getTags().forEach(tag -> tags.getChildren().add(new Label(tag.tagName)));
}
}
//@@author
|
src/main/java/seedu/ezdo/ui/TaskCard.java
|
package seedu.ezdo.ui;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.image.ImageView;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Region;
import seedu.ezdo.logic.parser.DateParser;
import seedu.ezdo.model.todo.ReadOnlyTask;
//@@author A0139177W
/**
* The task card for the UI.
*/
public class TaskCard extends UiPart<Region> {
private static final String NUMBERING_FORMAT = ". ";
private static final String HAS_COMPLETED_LINK = "/images/tick.png";
private static final String HAS_STARTED_LINK = "/images/wip.png";
private static final String DEFAULT_PRIORITY_NUMBER = "";
private static final String DEFAULT_PRIORITY_COLOR = "transparent";
private static final String HIGH_PRIORITY_NUMBER = "1";
private static final String HIGH_PRIORITY_COLOR = "red";
private static final String MEDIUM_PRIORITY_NUMBER = "2";
private static final String MEDIUM_PRIORITY_COLOR = "orange";
private static final String LOW_PRIORITY_NUMBER = "3";
private static final String LOW_PRIORITY_COLOR = "green";
private static final String FXML = "TaskListCard.fxml";
private static final String CSS_BACKGROUND_COLOR_PROPERTY = "-fx-background-color: ";
private static final String CSS_STARTDATE_PAST_CURRENT_DATE_COLOR =
"-fx-text-fill: darkgreen; -fx-font-weight: bold";
private static final String CSS_OVERDUE_COLOR =
"-fx-text-fill: red; -fx-font-weight: bold";
private static final String CSS_ABOUT_TO_DUE_COLOR =
"-fx-text-fill: orangered; -fx-font-weight: bold";
private static final DateFormat DATE_FORMAT = new SimpleDateFormat(DateParser.USER_DATE_OUTPUT_FORMAT);
public static final HashMap<String, String> PRIORITY_COLOR_HASHMAP = new HashMap<>();
private String priorityInString;
@FXML
private HBox cardPane;
@FXML
private AnchorPane priorityColor;
@FXML
private Label name;
@FXML
private Label id;
@FXML
private Label status;
@FXML
private Label priority;
@FXML
private Label startDate;
@FXML
private Label dueDate;
@FXML
private Label recur;
@FXML
private FlowPane tags;
/**
* Creates a TaskCard object with all fields to be shown in UI.
* @param task The task to be updated.
* @param displayedIndex The index of the task.
*/
public TaskCard(ReadOnlyTask task, int displayedIndex) {
super(FXML);
setPriorityColorHashMap();
name.setText(task.getName().fullName);
id.setText(displayedIndex + NUMBERING_FORMAT);
setPriority(task);
setStatus(task);
setStartDate(task);
setDueDate(task);
recur.setText(task.getRecur().value);
setStatus(task);
initTags(task);
}
// ========================= STARTDATE ============================ //
/**
* Sets the text of start date.
* Sets the color of start date when the date has commenced.
* @param task The task to be updated.
*/
private void setStartDate(ReadOnlyTask task) {
Date currentDate = new Date(); // current date and time
startDate.setText(task.getStartDate().value);
setStartDateColor(currentDate, CSS_STARTDATE_PAST_CURRENT_DATE_COLOR);
}
/**
* Sets the color of the start date when it has commenced.
* @param dateReference The date to be referenced.
* @param cssColor The CSS formatting to be used.
* @throws ParseException If the start date is optional and cannot be parsed
* as Date object.
*/
private void setStartDateColor(Date dateReference, String cssColor) {
try {
if (dateReference.after(DATE_FORMAT.parse(startDate.getText()))) {
startDate.setStyle(cssColor);
}
} catch (ParseException pe) {
pe.printStackTrace();
}
}
// ========================= DUEDATE ============================ //
/**
* Sets the text of the due date.
* Sets the color of due date when it is overdue and when it's due in 7 days time.
* @param task The task to be updated.
* @throws ParseException If the due date is optional and cannot be parsed
* as Date object.
*/
private void setDueDate(ReadOnlyTask task) {
Date currentDate = new Date();
Date dateSevenDaysInAdvance = createDateSevenDaysInAdvance();
dueDate.setText(task.getDueDate().value);
setAboutToDueDateColor(dateSevenDaysInAdvance, CSS_ABOUT_TO_DUE_COLOR);
setDueDateColor(currentDate, CSS_OVERDUE_COLOR);
}
/**
* Removes the color of the start date when it's due in 7 days time.
* Sets the color of the due date when it's due in 7 days time.
* @param dateReference The date to be referenced.
* @param cssColor The CSS formatting to be used.
* @throws ParseException If the due date is optional and cannot be parsed
* as Date object.
*/
private void setAboutToDueDateColor(Date dateReference, String cssColor) {
try {
if (dateReference.after(DATE_FORMAT.parse(dueDate.getText()))) {
startDate.setStyle(null);
dueDate.setStyle(cssColor);
}
} catch (ParseException pe) {
pe.printStackTrace();
}
}
/**
* Sets the color of the start date when the due date is overdue.
* Sets the color of the due date when the due date is overdue.
* @param dateReference The date to be referenced.
* @param cssColor The CSS formatting to be used.
* @throws ParseException If the due date is optional and cannot be parsed
* as Date object.
*/
private void setDueDateColor(Date dateReference, String cssColor) {
try {
if (dateReference.after(DATE_FORMAT.parse(dueDate.getText()))) {
startDate.setStyle(cssColor);
dueDate.setStyle(cssColor);
}
} catch (ParseException pe) {
pe.printStackTrace();
}
}
/** Returns the date seven days in advance of the current date and time. */
private Date createDateSevenDaysInAdvance() {
int weekIncrement = 7;
Calendar cal = Calendar.getInstance(); // get current date and time
cal.add(Calendar.DATE, weekIncrement); // update to seven days ago
return cal.getTime();
}
// ========================= PRIORITY ============================ //
/** Sets priorityInString as a local variable. **/
private void setPriorityInString(ReadOnlyTask task) {
String priorityValue = task.getPriority().value;
this.priorityInString = priorityValue;
}
/** Initialises the colors and priority numbers in PRIORITY_COLOR_HASHMAP. **/
private void setPriorityColorHashMap() {
PRIORITY_COLOR_HASHMAP.put(DEFAULT_PRIORITY_NUMBER, DEFAULT_PRIORITY_COLOR);
PRIORITY_COLOR_HASHMAP.put(LOW_PRIORITY_NUMBER, LOW_PRIORITY_COLOR);
PRIORITY_COLOR_HASHMAP.put(MEDIUM_PRIORITY_NUMBER, MEDIUM_PRIORITY_COLOR);
PRIORITY_COLOR_HASHMAP.put(HIGH_PRIORITY_NUMBER, HIGH_PRIORITY_COLOR);
}
/**
* Sets the priority text and color.
* @param task The task to be updated.
*/
private void setPriority(ReadOnlyTask task) {
setPriorityInString(task);
priority.setText(priorityInString); // Invisible in UI (for testing purposes)
priorityColor.setStyle(CSS_BACKGROUND_COLOR_PROPERTY + PRIORITY_COLOR_HASHMAP.get(priorityInString));
}
// ========================= STATUS ============================ //
/**
* Sets the image if a task has selected or if the task has completed.
* @param task The task to be updated.
*/
private void setStatus(ReadOnlyTask task) {
if (task.getStarted()) {
status.setGraphic(new ImageView(HAS_STARTED_LINK));
}
if (task.getDone()) {
status.setGraphic(new ImageView(HAS_COMPLETED_LINK));
}
}
// ========================= TAGS ============================ //
/**
* Sets the tags given a task.
* @param task The task to be updated.
*/
private void initTags(ReadOnlyTask task) {
task.getTags().forEach(tag -> tags.getChildren().add(new Label(tag.tagName)));
}
}
//@@author A0139177W
|
Remove printStackTraces
|
src/main/java/seedu/ezdo/ui/TaskCard.java
|
Remove printStackTraces
|
|
Java
|
mit
|
9893033e24e40fbb66e871549e00d71df0f49eaa
| 0
|
piotr-rusin/yule,piotr-rusin/yule,piotr-rusin/yule,piotr-rusin/yule
|
package com.github.piotr_rusin.yule.entity;
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.PrePersist;
import javax.persistence.Table;
/**
* A class representing blog posts.
*
* @author Piotr Rusin <piotr.rusin88@gmail.com>
*/
@Entity
@Table(name="posts")
public class Post {
@Id
@Column(name="id")
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
private String title;
private String slug;
private String content;
@Column(name="creation_date")
private Date creationDate;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getSlug() {
return slug;
}
public void setSlug(String slug) {
this.slug = slug;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Date getCreationDate() {
return creationDate;
}
@PrePersist
protected void resetCreationDate() {
creationDate = new Date();
}
}
|
src/main/java/com/github/piotr_rusin/yule/entity/Post.java
|
package com.github.piotr_rusin.yule.entity;
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.PrePersist;
import javax.persistence.Table;
/**
* A class representing blog posts.
*
* @author Piotr Rusin <piotr.rusin88@gmail.com>
*/
@Entity
@Table(name="Post")
public class Post {
@Id
@Column(name="id")
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
private String title;
private String slug;
private String content;
@Column(name="creation_date")
private Date creationDate;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getSlug() {
return slug;
}
public void setSlug(String slug) {
this.slug = slug;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Date getCreationDate() {
return creationDate;
}
@PrePersist
protected void resetCreationDate() {
creationDate = new Date();
}
}
|
Rename a table for storing post entities
The table is being renamed from "Post" to "posts".
|
src/main/java/com/github/piotr_rusin/yule/entity/Post.java
|
Rename a table for storing post entities
|
|
Java
|
mit
|
b4ec1adaf1d8a6341168dd7e026e39e3aa3ec4f1
| 0
|
OpenCubicChunks/CubicChunks,OpenCubicChunks/CubicChunks
|
/*
* This file is part of Cubic Chunks Mod, licensed under the MIT License (MIT).
*
* Copyright (c) 2015-2019 OpenCubicChunks
* Copyright (c) 2015-2019 contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package io.github.opencubicchunks.cubicchunks.api.worldgen;
import mcp.MethodsReturnNonnullByDefault;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.init.Blocks;
import net.minecraft.world.biome.Biome;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.annotation.ParametersAreNonnullByDefault;
import java.util.Arrays;
@ParametersAreNonnullByDefault
@MethodsReturnNonnullByDefault
public class CubePrimer {
public static final IBlockState DEFAULT_STATE = Blocks.AIR.getDefaultState();
private final char[] data;
private byte[] extData = null; // NEID-compat
private Biome[] biomes3d = null;
public boolean hasBiomes() {
return biomes3d != null;
}
public CubePrimer() {
this(new char[4096]);
}
public static CubePrimer createFilled(IBlockState state) {
@SuppressWarnings("deprecation")
int value = Block.BLOCK_STATE_IDS.get(state);
char lsb = (char) value;
char[] data = new char[4096];
Arrays.fill(data, lsb);
return new CubePrimer(data);
}
protected CubePrimer(char[] data) {
this.data = data;
}
/**
* Returns biome in a given 4x4x4 block section.
* <p>
* Note: in current implementation, internal storage is for 2x16x2 blocks. This will be changed soon due to changes in 1.15.x.
*
* @param localBiomeX cube-local X coordinate. One unit is 4 blocks
* @param localBiomeY cube-local Y coordinate. One unit is 4 blocks
* @param localBiomeZ cube-local Z coordinate. One unit is 4 blocks
* @return currently set biome at the given position in this cube. Null if no biome has been set.
*/
@SuppressWarnings("unused")
@Nullable
public Biome getBiome(int localBiomeX, int localBiomeY, int localBiomeZ) {
if (biomes3d == null) {
return null;
}
int biomeX = localBiomeX * 2;
int biomeZ = localBiomeZ * 2;
return this.biomes3d[biomeX << 3 | biomeZ];
}
/**
* Sets biome in a given 4x4x4 block section.
* <p>
* Note: in current implementation, internal storage is for 2x16x2 blocks. This will be changed soon due to changes in 1.15.x.
*
* @param localBiomeX cube-local X coordinate. One unit is 4 blocks
* @param localBiomeY cube-local Y coordinate. One unit is 4 blocks
* @param localBiomeZ cube-local Z coordinate. One unit is 4 blocks
* @param biome biome to set in this cube position. After thig method returns, {@link #getBiome(int, int, int)}
* is guaranteed to return this biome for the same supplied input coordinates. Currently it may also
* affect the returned value at other coordinates due to internal storage differences.
*/
@SuppressWarnings("unused")
public void setBiome(int localBiomeX, int localBiomeY, int localBiomeZ, Biome biome) {
if (this.biomes3d == null) {
this.biomes3d = new Biome[8 * 8];
}
int biomeX = localBiomeX * 2;
int biomeZ = localBiomeZ * 2;
for (int dx = 0; dx < 2; dx++) {
for (int dz = 0; dz < 2; dz++) {
this.biomes3d[(biomeX + dx) << 3 | (biomeZ + dz)] = biome;
}
}
}
/**
* Get the block state at the given location
*
* @param x cube local x
* @param y cube local y
* @param z cube local z
* @return the block state
*/
public IBlockState getBlockState(int x, int y, int z) {
int idx = getBlockIndex(x, y, z);
int block = this.data[idx];
if (extData != null) {
block |= extData[idx] << 16;
}
@SuppressWarnings("deprecation")
IBlockState iblockstate = Block.BLOCK_STATE_IDS.getByValue(block);
return iblockstate == null ? DEFAULT_STATE : iblockstate;
}
/**
* Set the block state at the given location
*
* @param x cube local x
* @param y cube local y
* @param z cube local z
* @param state the block state
*/
public void setBlockState(int x, int y, int z, @Nonnull IBlockState state) {
@SuppressWarnings("deprecation")
int value = Block.BLOCK_STATE_IDS.get(state);
char lsb = (char) value;
int idx = getBlockIndex(x, y, z);
this.data[idx] = lsb;
if (value > 0xFFFF) {
if (extData == null) {
extData = new byte[4096];
}
extData[idx] = (byte) (value >>> 16);
}
}
/**
* Resets this primer to a state as if it were newly constructed.
*/
public void reset() {
Arrays.fill(this.data, '\0');
// simply reset extra data and biomes to null, these are unlikely to be set in most cases anyway
this.extData = null;
this.biomes3d = null;
}
/**
* Map cube local coordinates to an array index in the range [0, 4095].
*
* @param x cube local x
* @param y cube local y
* @param z cube local z
* @return a unique array index for that coordinate
*/
private static int getBlockIndex(int x, int y, int z) {
return y << 8 | z << 4 | x;
}
}
|
CubicChunksAPI/src/main/java/io/github/opencubicchunks/cubicchunks/api/worldgen/CubePrimer.java
|
/*
* This file is part of Cubic Chunks Mod, licensed under the MIT License (MIT).
*
* Copyright (c) 2015-2019 OpenCubicChunks
* Copyright (c) 2015-2019 contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package io.github.opencubicchunks.cubicchunks.api.worldgen;
import mcp.MethodsReturnNonnullByDefault;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.init.Blocks;
import net.minecraft.world.biome.Biome;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.annotation.ParametersAreNonnullByDefault;
import java.util.Arrays;
@ParametersAreNonnullByDefault
@MethodsReturnNonnullByDefault
public class CubePrimer {
public static final IBlockState DEFAULT_STATE = Blocks.AIR.getDefaultState();
private final char[] data;
private byte[] extData = null; // NEID-compat
private Biome[] biomes3d = null;
public boolean hasBiomes() {
return biomes3d != null;
}
public CubePrimer() {
this(new char[4096]);
}
protected CubePrimer(char[] data) {
this.data = data;
}
/**
* Returns biome in a given 4x4x4 block section.
* <p>
* Note: in current implementation, internal storage is for 2x16x2 blocks. This will be changed soon due to changes in 1.15.x.
*
* @param localBiomeX cube-local X coordinate. One unit is 4 blocks
* @param localBiomeY cube-local Y coordinate. One unit is 4 blocks
* @param localBiomeZ cube-local Z coordinate. One unit is 4 blocks
* @return currently set biome at the given position in this cube. Null if no biome has been set.
*/
@SuppressWarnings("unused")
@Nullable
public Biome getBiome(int localBiomeX, int localBiomeY, int localBiomeZ) {
if (biomes3d == null) {
return null;
}
int biomeX = localBiomeX * 2;
int biomeZ = localBiomeZ * 2;
return this.biomes3d[biomeX << 3 | biomeZ];
}
/**
* Sets biome in a given 4x4x4 block section.
* <p>
* Note: in current implementation, internal storage is for 2x16x2 blocks. This will be changed soon due to changes in 1.15.x.
*
* @param localBiomeX cube-local X coordinate. One unit is 4 blocks
* @param localBiomeY cube-local Y coordinate. One unit is 4 blocks
* @param localBiomeZ cube-local Z coordinate. One unit is 4 blocks
* @param biome biome to set in this cube position. After thig method returns, {@link #getBiome(int, int, int)}
* is guaranteed to return this biome for the same supplied input coordinates. Currently it may also
* affect the returned value at other coordinates due to internal storage differences.
*/
@SuppressWarnings("unused")
public void setBiome(int localBiomeX, int localBiomeY, int localBiomeZ, Biome biome) {
if (this.biomes3d == null) {
this.biomes3d = new Biome[8 * 8];
}
int biomeX = localBiomeX * 2;
int biomeZ = localBiomeZ * 2;
for (int dx = 0; dx < 2; dx++) {
for (int dz = 0; dz < 2; dz++) {
this.biomes3d[(biomeX + dx) << 3 | (biomeZ + dz)] = biome;
}
}
}
/**
* Get the block state at the given location
*
* @param x cube local x
* @param y cube local y
* @param z cube local z
* @return the block state
*/
public IBlockState getBlockState(int x, int y, int z) {
int idx = getBlockIndex(x, y, z);
int block = this.data[idx];
if (extData != null) {
block |= extData[idx] << 16;
}
@SuppressWarnings("deprecation")
IBlockState iblockstate = Block.BLOCK_STATE_IDS.getByValue(block);
return iblockstate == null ? DEFAULT_STATE : iblockstate;
}
/**
* Set the block state at the given location
*
* @param x cube local x
* @param y cube local y
* @param z cube local z
* @param state the block state
*/
public void setBlockState(int x, int y, int z, @Nonnull IBlockState state) {
@SuppressWarnings("deprecation")
int value = Block.BLOCK_STATE_IDS.get(state);
char lsb = (char) value;
int idx = getBlockIndex(x, y, z);
this.data[idx] = lsb;
if (value > 0xFFFF) {
if (extData == null) {
extData = new byte[4096];
}
extData[idx] = (byte) (value >>> 16);
}
}
/**
* Resets this primer to a state as if it were newly constructed.
*/
public void reset() {
Arrays.fill(this.data, '\0');
// simply reset extra data and biomes to null, these are unlikely to be set in most cases anyway
this.extData = null;
this.biomes3d = null;
}
/**
* Map cube local coordinates to an array index in the range [0, 4095].
*
* @param x cube local x
* @param y cube local y
* @param z cube local z
* @return a unique array index for that coordinate
*/
private static int getBlockIndex(int x, int y, int z) {
return y << 8 | z << 4 | x;
}
}
|
Add factory method to create prefilled CubePrimer
|
CubicChunksAPI/src/main/java/io/github/opencubicchunks/cubicchunks/api/worldgen/CubePrimer.java
|
Add factory method to create prefilled CubePrimer
|
|
Java
|
mpl-2.0
|
1faebebbe605a414365f73957e5d7747e384dccd
| 0
|
zeromq/jeromq,fredoboulo/jeromq,c-rack/jeromq,zeromq/jeromq,trevorbernard/jeromq,trevorbernard/jeromq,fredoboulo/jeromq
|
/*
Copyright (c) 2007-2014 Contributors as noted in the AUTHORS file
This file is part of 0MQ.
0MQ is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
0MQ is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package zmq;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public abstract class EncoderBase implements IEncoder
{
// Where to get the data to write from.
private ByteBuffer writeBuf;
private FileChannel writeChannel;
private int writePos;
// Next step. If set to -1, it means that associated data stream
// is dead.
private int next;
// If true, first byte of the message is being written.
@SuppressWarnings("unused")
private boolean beginning;
// How much data to write before next step should be executed.
private int toWrite;
// The buffer for encoded data.
private ByteBuffer buffer;
private int bufferSize;
private boolean error;
protected EncoderBase(int bufferSize)
{
this.bufferSize = bufferSize;
buffer = ByteBuffer.allocateDirect(bufferSize);
error = false;
}
// The function returns a batch of binary data. The data
// are filled to a supplied buffer. If no buffer is supplied (data_
// points to NULL) decoder object will provide buffer of its own.
@Override
public Transfer getData(ByteBuffer buffer)
{
if (buffer == null) {
buffer = this.buffer;
}
buffer.clear();
while (buffer.hasRemaining()) {
// If there are no more data to return, run the state machine.
// If there are still no data, return what we already have
// in the buffer.
if (toWrite == 0) {
// If we are to encode the beginning of a new message,
// adjust the message offset.
if (!next()) {
break;
}
}
// If there is file channel to send,
// send current buffer and the channel together
if (writeChannel != null) {
buffer.flip();
Transfer t = new Transfer.FileChannelTransfer(buffer, writeChannel,
(long) writePos, (long) toWrite);
writePos = 0;
toWrite = 0;
return t;
}
// If there are no data in the buffer yet and we are able to
// fill whole buffer in a single go, let's use zero-copy.
// There's no disadvantage to it as we cannot stuck multiple
// messages into the buffer anyway. Note that subsequent
// write(s) are non-blocking, thus each single write writes
// at most SO_SNDBUF bytes at once not depending on how large
// is the chunk returned from here.
// As a consequence, large messages being sent won't block
// other engines running in the same I/O thread for excessive
// amounts of time.
if (this.buffer.position() == 0 && toWrite >= bufferSize) {
Transfer t;
writeBuf.position(writePos);
writeBuf.limit(writePos + toWrite);
t = new Transfer.ByteBufferTransfer(writeBuf);
writePos = 0;
toWrite = 0;
return t;
}
// Copy data to the buffer. If the buffer is full, return.
int toCopy = Math.min(toWrite, buffer.remaining());
if (toCopy > 0) {
writeBuf.position(writePos);
writeBuf.limit(writePos + toCopy);
buffer.put(writeBuf);
writePos += toCopy;
toWrite -= toCopy;
}
}
buffer.flip();
return new Transfer.ByteBufferTransfer(buffer);
}
@Override
public boolean hasData()
{
return toWrite > 0;
}
protected int state()
{
return next;
}
protected void state(int state)
{
next = state;
}
protected void encodingError()
{
error = true;
}
public final boolean isError()
{
return error;
}
protected abstract boolean next();
protected void nextStep(Msg msg, int state, boolean beginning)
{
if (msg == null) {
nextStep(null, 0, state, beginning);
}
else {
nextStep(msg.buf(), state, beginning);
}
}
protected void nextStep(byte[] buf, int toWrite,
int next, boolean beginning)
{
writeBuf = buf != null ? ByteBuffer.wrap(buf) : null;
writeChannel = null;
writePos = 0;
this.toWrite = toWrite;
this.next = next;
this.beginning = beginning;
}
protected void nextStep(ByteBuffer buf,
int next, boolean beginning)
{
writeBuf = buf;
writeChannel = null;
writePos = buf.position();
this.toWrite = buf.remaining();
this.next = next;
this.beginning = beginning;
}
protected void nextStep(FileChannel ch, long pos, long toWrite,
int next, boolean beginning)
{
writeBuf = null;
writeChannel = ch;
writePos = (int) pos;
this.toWrite = (int) toWrite;
this.next = next;
this.beginning = beginning;
}
}
|
src/main/java/zmq/EncoderBase.java
|
/*
Copyright (c) 2007-2014 Contributors as noted in the AUTHORS file
This file is part of 0MQ.
0MQ is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
0MQ is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package zmq;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public abstract class EncoderBase implements IEncoder
{
// Where to get the data to write from.
private byte[] writeBuf;
private FileChannel writeChannel;
private int writePos;
// Next step. If set to -1, it means that associated data stream
// is dead.
private int next;
// If true, first byte of the message is being written.
@SuppressWarnings("unused")
private boolean beginning;
// How much data to write before next step should be executed.
private int toWrite;
// The buffer for encoded data.
private ByteBuffer buffer;
private int bufferSize;
private boolean error;
protected EncoderBase(int bufferSize)
{
this.bufferSize = bufferSize;
buffer = ByteBuffer.allocateDirect(bufferSize);
error = false;
}
// The function returns a batch of binary data. The data
// are filled to a supplied buffer. If no buffer is supplied (data_
// points to NULL) decoder object will provide buffer of its own.
@Override
public Transfer getData(ByteBuffer buffer)
{
if (buffer == null) {
buffer = this.buffer;
}
buffer.clear();
while (buffer.hasRemaining()) {
// If there are no more data to return, run the state machine.
// If there are still no data, return what we already have
// in the buffer.
if (toWrite == 0) {
// If we are to encode the beginning of a new message,
// adjust the message offset.
if (!next()) {
break;
}
}
// If there is file channel to send,
// send current buffer and the channel together
if (writeChannel != null) {
buffer.flip();
Transfer t = new Transfer.FileChannelTransfer(buffer, writeChannel,
(long) writePos, (long) toWrite);
writePos = 0;
toWrite = 0;
return t;
}
// If there are no data in the buffer yet and we are able to
// fill whole buffer in a single go, let's use zero-copy.
// There's no disadvantage to it as we cannot stuck multiple
// messages into the buffer anyway. Note that subsequent
// write(s) are non-blocking, thus each single write writes
// at most SO_SNDBUF bytes at once not depending on how large
// is the chunk returned from here.
// As a consequence, large messages being sent won't block
// other engines running in the same I/O thread for excessive
// amounts of time.
if (this.buffer.position() == 0 && toWrite >= bufferSize) {
Transfer t;
ByteBuffer b = ByteBuffer.wrap(writeBuf);
b.position(writePos);
t = new Transfer.ByteBufferTransfer(b);
writePos = 0;
toWrite = 0;
return t;
}
// Copy data to the buffer. If the buffer is full, return.
int toCopy = Math.min(toWrite, buffer.remaining());
if (toCopy > 0) {
buffer.put(writeBuf, writePos, toCopy);
writePos += toCopy;
toWrite -= toCopy;
}
}
buffer.flip();
return new Transfer.ByteBufferTransfer(buffer);
}
@Override
public boolean hasData()
{
return toWrite > 0;
}
protected int state()
{
return next;
}
protected void state(int state)
{
next = state;
}
protected void encodingError()
{
error = true;
}
public final boolean isError()
{
return error;
}
protected abstract boolean next();
protected void nextStep(Msg msg, int state, boolean beginning)
{
if (msg == null) {
nextStep(null, 0, state, beginning);
}
else {
nextStep(msg.data(), msg.size(), state, beginning);
}
}
protected void nextStep(byte[] buf, int toWrite,
int next, boolean beginning)
{
writeBuf = buf;
writeChannel = null;
writePos = 0;
this.toWrite = toWrite;
this.next = next;
this.beginning = beginning;
}
protected void nextStep(FileChannel ch, long pos, long toWrite,
int next, boolean beginning)
{
writeBuf = null;
writeChannel = ch;
writePos = (int) pos;
this.toWrite = (int) toWrite;
this.next = next;
this.beginning = beginning;
}
}
|
Use ByteBuffer to avoid copying when DirectByteBuffer or pos!=0 || limit
!= capacity
|
src/main/java/zmq/EncoderBase.java
|
Use ByteBuffer to avoid copying when DirectByteBuffer or pos!=0 || limit != capacity
|
|
Java
|
agpl-3.0
|
f62274b75354bf9630ef5cf34969004babdb7c1a
| 0
|
axelor/axelor-development-kit,axelor/axelor-development-kit,axelor/axelor-development-kit,axelor/axelor-development-kit
|
/*
* Axelor Business Solutions
*
* Copyright (C) 2005-2018 Axelor (<http://axelor.com>).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.axelor.rpc;
import static com.axelor.common.StringUtils.isBlank;
import java.io.IOException;
import java.io.Writer;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import javax.inject.Inject;
import javax.inject.Provider;
import javax.persistence.EntityTransaction;
import javax.persistence.OptimisticLockException;
import javax.validation.ValidationException;
import org.hibernate.StaleObjectStateException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.axelor.app.AppSettings;
import com.axelor.auth.AuthService;
import com.axelor.auth.AuthUtils;
import com.axelor.auth.db.User;
import com.axelor.common.Inflector;
import com.axelor.common.StringUtils;
import com.axelor.db.EntityHelper;
import com.axelor.db.JPA;
import com.axelor.db.JpaRepository;
import com.axelor.db.JpaSecurity;
import com.axelor.db.Model;
import com.axelor.db.Query;
import com.axelor.db.QueryBinder;
import com.axelor.db.Repository;
import com.axelor.db.ValueEnum;
import com.axelor.db.hibernate.type.JsonFunction;
import com.axelor.db.mapper.Mapper;
import com.axelor.db.mapper.Property;
import com.axelor.db.mapper.PropertyType;
import com.axelor.db.search.SearchService;
import com.axelor.i18n.I18n;
import com.axelor.i18n.I18nBundle;
import com.axelor.i18n.L10n;
import com.axelor.inject.Beans;
import com.axelor.meta.MetaPermissions;
import com.axelor.meta.MetaStore;
import com.axelor.meta.db.MetaAction;
import com.axelor.meta.db.MetaJsonRecord;
import com.axelor.meta.db.MetaTranslation;
import com.axelor.meta.schema.views.Selection;
import com.axelor.rpc.filter.Filter;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.base.Objects;
import com.google.common.base.Splitter;
import com.google.common.collect.Collections2;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.primitives.Ints;
import com.google.common.primitives.Longs;
import com.google.inject.TypeLiteral;
import com.google.inject.persist.Transactional;
/**
* This class defines CRUD like interface.
*
*/
public class Resource<T extends Model> {
private Class<T> model;
private Provider<JpaSecurity> security;
private Logger LOG = LoggerFactory.getLogger(Resource.class);
private Resource(Class<T> model, Provider<JpaSecurity> security) {
this.model = model;
this.security = security;
}
@Inject
@SuppressWarnings("unchecked")
public Resource(TypeLiteral<T> typeLiteral, Provider<JpaSecurity> security) {
this((Class<T>) typeLiteral.getRawType(), security);
}
/**
* Returns the resource class.
*
*/
public Class<?> getModel() {
return model;
}
private Long findId(Map<String, Object> values) {
try {
return Long.parseLong(values.get("id").toString());
} catch (Exception e){}
return null;
}
public Response fields() {
final Response response = new Response();
final Repository<?> repository = JpaRepository.of(model);
final Map<String, Object> meta = Maps.newHashMap();
final List<Object> fields = Lists.newArrayList();
if (repository == null) {
for (Property p : JPA.fields(model)) {
fields.add(p.toMap());
}
} else {
for (Property p : repository.fields()) {
fields.add(p.toMap());
}
}
meta.put("model", model.getName());
meta.put("fields", fields);
response.setData(meta);
response.setStatus(Response.STATUS_SUCCESS);
return response;
}
public static Response models(Request request) {
Response response = new Response();
List<String> data = Lists.newArrayList();
for(Class<?> type : JPA.models()) {
data.add(type.getName());
}
Collections.sort(data);
response.setData(ImmutableList.copyOf(data));
response.setStatus(Response.STATUS_SUCCESS);
return response;
}
public Response perms() {
Set<JpaSecurity.AccessType> perms = security.get().getAccessTypes(model, null);
Response response = new Response();
response.setData(perms);
response.setStatus(Response.STATUS_SUCCESS);
return response;
}
public Response perms(Long id) {
Set<JpaSecurity.AccessType> perms = security.get().getAccessTypes(model, id);
Response response = new Response();
response.setData(perms);
response.setStatus(Response.STATUS_SUCCESS);
return response;
}
public Response perms(Long id, String perm) {
Response response = new Response();
JpaSecurity sec = security.get();
JpaSecurity.AccessType type = JpaSecurity.CAN_READ;
try {
type = JpaSecurity.AccessType.valueOf(perm.toUpperCase());
} catch (Exception e) {
}
try {
sec.check(type, model, id);
response.setStatus(Response.STATUS_SUCCESS);
} catch (Exception e) {
response.addError(perm, e.getMessage());
response.setStatus(Response.STATUS_VALIDATION_ERROR);
}
return response;
}
private List<String> getSortBy(Request request) {
final List<String> sortBy = Lists.newArrayList();
final List<String> sortOn = Lists.newArrayList();
final Mapper mapper = Mapper.of(model);
boolean unique = false;
boolean desc = true;
if (request.getSortBy() != null) {
sortOn.addAll(request.getSortBy());
}
if (sortOn.isEmpty()) {
Property nameField = mapper.getNameField();
if (nameField == null) {
nameField = mapper.getProperty("name");
}
if (nameField == null) {
nameField = mapper.getProperty("code");
}
if (nameField != null) {
sortOn.add(nameField.getName());
}
}
for(String spec : sortOn) {
String name = spec;
if (name.startsWith("-")) {
name = name.substring(1);
} else {
desc = false;
}
Property property = mapper.getProperty(name);
if (property == null || property.isPrimary()) {
// dotted field or primary key
sortBy.add(spec);
continue;
}
if (property.isReference()) {
// use name field to sort many-to-one column
Mapper m = Mapper.of(property.getTarget());
Property p = m.getNameField();
if (p != null) {
spec = spec + "." + p.getName();
}
}
if (property.isUnique() && property.isRequired()) {
unique = true;
}
sortBy.add(spec);
}
if (!unique && !(sortBy.contains("id") || sortBy.contains("-id"))) {
sortBy.add(desc ? "-id" : "id");
}
return sortBy;
}
private Criteria getCriteria(Request request) {
if (request.getData() != null) {
Object domain = request.getData().get("_domain");
if (domain != null) {
try {
String qs = request.getCriteria().createQuery(model).toString();
JPA.em().createQuery(qs);
} catch (Exception e) {
LOG.error("Error: " + e.getMessage(), e);
throw new IllegalArgumentException("Invalid domain: " + domain, e);
}
}
}
return request.getCriteria();
}
private boolean shouldCheckPermissions(Request request) {
final Context context = request.getContext();
// if o2m/m2m search request
if (context != null
&& context.containsKey("_field")
&& context.containsKey("_field_ids")
&& context.containsKey("id")) {
final Model parent = context.asType(Model.class);
return !security.get().isPermitted(JpaSecurity.CAN_READ, EntityHelper.getEntityClass(parent), parent.getId());
}
return true;
}
private Query<?> getQuery(Request request) {
return getQuery(request, security.get().getFilter(JpaSecurity.CAN_READ, model));
}
private Query<?> getQuery(Request request, Filter filter) {
Criteria criteria = getCriteria(request);
Query<?> query = JPA.all(model);
if (criteria != null) {
query = criteria.createQuery(model, filter);
} else if (filter != null) {
query = filter.build(model);
}
for(String spec : getSortBy(request)) {
query = query.order(spec);
}
return query;
}
private Query<?> getSearchQuery(Request request, Filter filter) {
final SearchService searchService = Beans.get(SearchService.class);
if (request.getData() == null || !searchService.isEnabled()) {
return filter == null ? getQuery(request) : getQuery(request, filter);
}
final Map<String, Object> data = request.getData();
final String searchText = (String) data.get("_searchText");
// try full-text search
if (!StringUtils.isEmpty(searchText)) {
try {
final List<Long> ids = searchService.fullTextSearch(model, searchText, request.getLimit());
if (ids.size() > 0) {
return JPA.all(model).filter("self.id in :ids").bind("ids", ids);
}
} catch (Exception e) {
// just log and fallback to default search
LOG.error("Unable to do full-text search: " + e.getMessage(), e);
}
}
return filter == null ? getQuery(request) : getQuery(request, filter);
}
@SuppressWarnings("all")
public Response search(Request request) {
final Filter filter = security.get().getFilter(JpaSecurity.CAN_READ, model);
boolean check = filter == null || shouldCheckPermissions(request);
if (check) {
security.get().check(JpaSecurity.CAN_READ, model);
}
LOG.debug("Searching '{}' with {}", model.getCanonicalName(), request.getData());
Response response = new Response();
int offset = request.getOffset();
int limit = request.getLimit();
Query<?> query = getSearchQuery(request, check ? filter : null).cacheable().readOnly();
List<?> data = null;
try {
if (limit > 0) {
response.setTotal(query.count());
}
if (request.getFields() != null) {
Query<?>.Selector selector = query.select(request.getFields().toArray(new String[] {}));
LOG.debug("JPQL: {}", selector);
data = selector.fetch(limit, offset);
} else {
LOG.debug("JPQL: {}", query);
data = query.fetch(limit, offset);
}
if (limit <= 0) {
response.setTotal(data.size());
}
} catch (Exception e) {
EntityTransaction txn = JPA.em().getTransaction();
if (txn.isActive()) {
txn.rollback();
}
data = Lists.newArrayList();
LOG.error("Error: {}", e, e);
}
LOG.debug("Records found: {}", data.size());
final Repository repo = JpaRepository.of(model);
final List<Object> jsonData = new ArrayList<>();
final boolean populate = request.getContext() != null && request.getContext().get("_populate") != Boolean.FALSE;
for (Object item : data) {
if (item instanceof Model) {
item = toMap(item);
}
if (item instanceof Map) {
Map<String, Object> map = (Map) item;
if (User.class.isAssignableFrom(model)) {
map.remove("password");
}
if (populate) {
item = repo.populate(map, request.getContext());
}
Translator.applyTranslatables(map, model);
}
jsonData.add(item);
}
try {
// check for children (used by tree view)
doChildCount(request, jsonData);
} catch (NullPointerException | ClassCastException e) {};
response.setData(jsonData);
response.setOffset(offset);
response.setStatus(Response.STATUS_SUCCESS);
return response;
}
@SuppressWarnings("all")
private void doChildCount(Request request, List<?> result) throws NullPointerException, ClassCastException {
if (result == null || result.isEmpty()) {
return;
}
final Map context = (Map) request.getData().get("_domainContext");
final Map childOn = (Map) context.get("_childOn");
final String countOn = (String) context.get("_countOn");
if (countOn == null && childOn == null) {
return;
}
final StringBuilder builder = new StringBuilder();
final List ids = Lists.newArrayList();
for (Object item : result) {
ids.add(((Map) item).get("id"));
}
String modelName = model.getName();
String parentName = countOn;
if (childOn != null) {
modelName = (String) childOn.get("model");
parentName = (String) childOn.get("parent");
}
builder.append("SELECT new map(_parent.id as id, count(self.id) as count) FROM ")
.append(modelName).append(" self ")
.append("LEFT JOIN self.").append(parentName).append(" AS _parent ")
.append("WHERE _parent.id IN (:ids) GROUP BY _parent");
javax.persistence.Query q = JPA.em().createQuery(builder.toString());
q.setParameter("ids", ids);
QueryBinder.of(q).setCacheable().setReadOnly();
Map counts = Maps.newHashMap();
for (Object item : q.getResultList()) {
counts.put(((Map)item).get("id"), ((Map)item).get("count"));
}
for (Object item : result) {
((Map) item).put("_children", counts.get(((Map) item).get("id")));
}
}
private static final int DEFAULT_EXPORT_MAX_SIZE = -1;
private static final int DEFAULT_EXPORT_FETCH_SIZE = 500;
private static final int EXPORT_MAX_SIZE = AppSettings.get().getInt("data.export.max-size", DEFAULT_EXPORT_MAX_SIZE);
private static final int EXPORT_FETCH_SIZE = AppSettings.get().getInt("data.export.fetch-size", DEFAULT_EXPORT_FETCH_SIZE);
@SuppressWarnings("all")
public int export(Request request, Writer writer) throws IOException {
security.get().check(JpaSecurity.CAN_READ, model);
security.get().check(JpaSecurity.CAN_EXPORT, model);
LOG.debug("Exporting '{}' with {}", model.getName(), request.getData());
List<String> fields = request.getFields();
List<String> header = new ArrayList<>();
List<String> names = new ArrayList<>();
Map<Integer, Map<String, String>> selection = new HashMap<>();
Map<String, Map<String, Object>> jsonFieldsMap = new HashMap<>();
Mapper mapper = Mapper.of(model);
MetaPermissions perms = Beans.get(MetaPermissions.class);
final Function<String, Map<String, Object>> findJsonFields = name -> jsonFieldsMap.computeIfAbsent(name,
(n) -> {
return MetaJsonRecord.class.isAssignableFrom(model)
? MetaStore.findJsonFields((String) request.getContext().get("jsonModel"))
: MetaStore.findJsonFields(model.getName(), n);
});
final Function<String, List<String>> findJsonPaths = name -> {
final Map<String, Object> map = findJsonFields.apply(name);
return map == null
? Collections.EMPTY_LIST
: map.keySet().stream().map(n -> name + "." + n).collect(Collectors.toList());
};
if (fields == null) {
fields = new ArrayList<>();
}
if (fields.isEmpty() && MetaJsonRecord.class.isAssignableFrom(model)) {
fields.add("id");
fields.addAll(findJsonPaths.apply("attrs"));
}
if (fields.isEmpty()) {
fields.add("id");
try {
fields.add(mapper.getNameField().getName());
} catch (Exception e) {}
for (Property property : mapper.getProperties()) {
if (property.isPrimary() ||
property.isTransient() ||
property.isVersion() ||
property.isCollection() ||
property.isPassword() ||
property.getType() == PropertyType.BINARY) {
continue;
}
String name = property.getName();
if (fields.contains(name) || name.matches("^(created|updated)(On|By)$")) {
continue;
}
if (property.isJson()) {
fields.addAll(findJsonPaths.apply(property.getName()));
} else {
fields.add(name);
}
}
}
for(String field : fields) {
Iterator<String> iter = Splitter.on(".").split(field).iterator();
Property prop = mapper.getProperty(iter.next());
while(iter.hasNext() && prop != null && !prop.isJson()) {
prop = Mapper.of(prop.getTarget()).getProperty(iter.next());
}
if (prop == null ||
prop.isCollection() ||
prop.isTransient() ||
prop.getType() == PropertyType.BINARY) {
continue;
}
if (prop.isJson() && !iter.hasNext()) {
continue;
}
String name = prop.getName();
String title = prop.getTitle();
String model = getModel().getName();
if (prop.isReference()) {
model = prop.getTarget().getName();
}
if (!perms.canExport(AuthUtils.getUser(), model, name)) {
continue;
}
if (iter != null) {
name = field;
}
List<Selection.Option> options = MetaStore.getSelectionList(prop.getSelection());
if (prop.isJson()) {
Map<String, Object> jsonFields = findJsonFields.apply(prop.getName());
Map<String, Object> jsonField = (Map) jsonFields.get(iter.next());
name = field;
if (jsonField != null) {
title = (String) jsonField.get("title");
if (title == null) {
title = (String) jsonField.get("autoTitle");
}
options = (List) jsonField.get("selectionList");
if ("many-to-one".equals(jsonField.get("type"))) {
try {
String targetName = jsonField.get("targetName").toString();
targetName = targetName.substring(targetName.indexOf(".") + 1);
name = name + "." + targetName;
} catch (Exception e) {
}
}
}
}
if (isBlank(title)) {
title = Inflector.getInstance().humanize(prop.getName());
}
if (prop.isReference()) {
prop = Mapper.of(prop.getTarget()).getNameField();
if (prop == null) {
continue;
}
name = name + '.' + prop.getName();
} else if(options != null && !options.isEmpty()) {
Map<String, String> map = new HashMap<>();
for (Selection.Option option : options) {
map.put(option.getValue(), option.getLocalizedTitle());
}
selection.put(header.size(), map);
}
title = I18n.get(title);
names.add(name);
header.add(escapeCsv(title));
}
writer.write(Joiner.on(";").join(header));
int limit = EXPORT_MAX_SIZE > 0 ? Math.min(EXPORT_FETCH_SIZE, EXPORT_MAX_SIZE) : EXPORT_FETCH_SIZE;
int offset = 0;
int count = 0;
Query<?> query = getQuery(request);
Query<?>.Selector selector = query.select(names.toArray(new String[0]));
List<?> data = selector.values(limit, offset);
final L10n formatter = L10n.getInstance();
while (!data.isEmpty()) {
for (Object item : data) {
List<?> row = (List<?>) item;
List<String> line = new ArrayList<>();
int index = 0;
for(Object value: row) {
if (index++ < 2) continue; // ignore first two items (id, version)
Object objValue = value == null ? "" : value;
if(selection.containsKey(index-3)) {
objValue = selection.get(index-3).get(objValue.toString());
}
if (objValue instanceof Number) {
objValue = formatter.format((Number) objValue, false);
}
if (objValue instanceof LocalDate) {
objValue = formatter.format((LocalDate) objValue);
}
if (objValue instanceof LocalDateTime) {
objValue = formatter.format((LocalDateTime) objValue);
}
if (objValue instanceof ZonedDateTime) {
objValue = formatter.format((ZonedDateTime) objValue);
}
String strValue = objValue == null ? "" : escapeCsv(objValue.toString());
line.add(strValue);
}
writer.write("\n");
writer.write(Joiner.on(";").join(line));
}
count += data.size();
int nextLimit = limit;
if (EXPORT_MAX_SIZE > -1) {
if (count >= EXPORT_MAX_SIZE) {
break;
}
nextLimit = Math.min(limit, EXPORT_MAX_SIZE - count);
}
offset += limit;
data = selector.values(nextLimit, offset);
}
return count;
}
private String escapeCsv(String value) {
if (value == null) return "";
if (value.indexOf('"') > -1) value = value.replaceAll("\"", "\"\"");
return '"' + value + '"';
}
public Response read(long id) {
security.get().check(JpaSecurity.CAN_READ, model, id);
Response response = new Response();
List<Object> data = Lists.newArrayList();
Model entity = JPA.find(model, id);
if (entity != null)
data.add(entity);
response.setData(data);
response.setStatus(Response.STATUS_SUCCESS);
return response;
}
public Response fetch(long id, Request request) {
security.get().check(JpaSecurity.CAN_READ, model, id);
final Response response = new Response();
final Repository<?> repository = JpaRepository.of(model);
final Model entity = repository.find(id);
response.setStatus(Response.STATUS_SUCCESS);
if (entity == null) {
return response;
}
final List<Object> data = Lists.newArrayList();
final String[] fields = request.getFields() == null ? null : request.getFields().toArray(new String[]{});
final Map<String, Object> values = mergeRelated(request, entity, toMap(entity, fields));
// special case for User/Group objects
if (values.get("homeAction") != null) {
MetaAction act = JpaRepository.of(MetaAction.class).all()
.filter("self.name = ?", values.get("homeAction"))
.fetchOne();
if (act != null) {
values.put("__actionSelect", toMapCompact(act));
}
}
data.add(repository.populate(values, request.getContext()));
response.setData(data);
return response;
}
@SuppressWarnings("all")
private Map<String, Object> mergeRelated(Request request, Model entity, Map<String, Object> values) {
final Map<String, List<String>> related = request.getRelated();
if (related == null) {
return values;
}
final Mapper mapper = Mapper.of(model);
related.entrySet().stream()
.filter(e -> e.getValue() != null)
.filter(e -> e.getValue().size() > 0)
.forEach(e -> {
final String name = e.getKey();
final String[] names = e.getValue().toArray(new String[] {});
Object old = values.get(name);
Object value = mapper.get(entity, name);
if (value instanceof Collection<?>) {
value = Collections2.transform((Collection<?>) value, input -> toMap(input, names));
} else if (value instanceof Model) {
value = toMap(value, names);
if (old instanceof Map) {
value = mergeMaps((Map) value, (Map) old);
}
}
values.put(name, value);
});
return values;
}
@SuppressWarnings("all")
private Map<String, Object> mergeMaps(Map<String, Object> target, Map<String, Object> source) {
if (target == null || source == null || source.isEmpty()) {
return target;
}
for (String key : source.keySet()) {
Object old = source.get(key);
Object val = target.get(key);
if (val instanceof Map && old instanceof Map) {
mergeMaps((Map) val, (Map) old);
} else if (val == null) {
target.put(key, old);
}
}
return target;
}
public Response verify(Request request) {
Response response = new Response();
try {
JPA.verify(model, request.getData());
response.setStatus(Response.STATUS_SUCCESS);
} catch (OptimisticLockException e) {
response.setStatus(Response.STATUS_VALIDATION_ERROR);
}
return response;
}
private User changeUserPassword(User user, Map<String, Object> values) {
final String oldPassword = (String) values.get("oldPassword");
final String newPassword = (String) values.get("newPassword");
final String chkPassword = (String) values.get("chkPassword");
// no password change
if (StringUtils.isBlank(newPassword)) {
return user;
}
if (StringUtils.isBlank(oldPassword)) {
throw new ValidationException("Current user password is not provided.");
}
if (!newPassword.equals(chkPassword)) {
throw new ValidationException("Confirm password doesn't match with new password.");
}
final User current = AuthUtils.getUser();
final AuthService authService = AuthService.getInstance();
if (!authService.match(oldPassword, current.getPassword())) {
throw new ValidationException("Current user password is wrong.");
}
user.setPassword(authService.encrypt(newPassword));
return user;
}
@Transactional
@SuppressWarnings("all")
public Response save(final Request request) {
final Response response = new Response();
final Repository repository = JpaRepository.of(model);
List<Object> records = request.getRecords();
List<Object> data = Lists.newArrayList();
if ((records == null || records.isEmpty()) && request.getData() == null) {
response.setStatus(Response.STATUS_FAILURE);
return response;
}
if (records == null) {
records = Lists.newArrayList();
records.add(request.getData());
}
String[] names = {};
if (request.getFields() != null) {
names = request.getFields().toArray(names);
}
for (Object record : records) {
if (record == null) {
continue;
}
record = (Map) repository.validate((Map) record, request.getContext());
Long id = findId((Map) record);
JpaSecurity.AccessType accessType = id == null || id <= 0L
? JpaSecurity.CAN_CREATE
: JpaSecurity.CAN_WRITE;
if (id == null || id <= 0L) {
security.get().check(JpaSecurity.CAN_CREATE, model);
}
Map<String, Object> orig = (Map) ((Map) record).get("_original");
JPA.verify(model, orig);
Model bean = JPA.edit(model, (Map) record);
id = bean.getId();
if (bean != null && id != null && id > 0L) {
security.get().check(JpaSecurity.CAN_WRITE, model, id);
}
// if user, update password
if (bean instanceof User) {
changeUserPassword((User) bean, (Map) record);
}
bean = JPA.manage(bean);
if (repository != null) {
bean = repository.save(bean);
}
// check permission rules again
security.get().check(accessType, model, bean.getId());
// if it's a translation object, invalidate cache
if (bean instanceof MetaTranslation) {
I18nBundle.invalidate();
}
data.add(repository.populate(toMap(bean, names), request.getContext()));
}
response.setData(data);
response.setStatus(Response.STATUS_SUCCESS);
return response;
}
@Transactional
public Response updateMass(Request request) {
security.get().check(JpaSecurity.CAN_WRITE, model);
LOG.debug("Mass update '{}' with {}", model.getCanonicalName(), request.getData());
Response response = new Response();
Query<?> query = getQuery(request);
List<?> data = request.getRecords();
LOG.debug("JPQL: {}", query);
@SuppressWarnings("all")
Map<String, Object> values = (Map) data.get(0);
response.setTotal(query.update(values, AuthUtils.getUser()));
LOG.debug("Records updated: {}", response.getTotal());
response.setStatus(Response.STATUS_SUCCESS);
return response;
}
@Transactional
@SuppressWarnings("all")
public Response remove(long id, Request request) {
security.get().check(JpaSecurity.CAN_REMOVE, model, id);
final Response response = new Response();
final Repository repository = JpaRepository.of(model);
final Map<String, Object> data = Maps.newHashMap();
data.put("id", id);
data.put("version", request.getData().get("version"));
Model bean = JPA.edit(model, data);
if (bean.getId() != null) {
if (repository == null) {
JPA.remove(bean);
} else {
repository.remove(bean);
}
}
response.setData(ImmutableList.of(toMapCompact(bean)));
response.setStatus(Response.STATUS_SUCCESS);
return response;
}
@Transactional
@SuppressWarnings("all")
public Response remove(Request request) {
final Response response = new Response();
final Repository repository = JpaRepository.of(model);
final List<Object> records = request.getRecords();
if (records == null || records.isEmpty()) {
return response.fail("No records provides.");
}
final List<Model> entities = Lists.newArrayList();
for(Object record : records) {
Map map = (Map) record;
Long id = Longs.tryParse(map.get("id").toString());
Integer version = null;
try {
version = Ints.tryParse(map.get("version").toString());
} catch (Exception e) {
}
security.get().check(JpaSecurity.CAN_REMOVE, model, id);
Model bean = JPA.find(model, id);
if (version != null && !Objects.equal(version, bean.getVersion())) {
throw new OptimisticLockException(
new StaleObjectStateException(model.getName(), id));
}
entities.add(bean);
}
for(Model entity : entities) {
if (JPA.em().contains(entity)) {
if (repository == null) {
JPA.remove(entity);
} else {
repository.remove(entity);
}
}
}
response.setData(records);
response.setStatus(Response.STATUS_SUCCESS);
return response;
}
@SuppressWarnings("all")
public Response copy(long id) {
security.get().check(JpaSecurity.CAN_CREATE, model, id);
final Response response = new Response();
final Repository repository = JpaRepository.of(model);
Model bean = JPA.find(model, id);
if (repository == null) {
bean = JPA.copy(bean, true);
} else {
bean = repository.copy(bean, true);
}
response.setData(ImmutableList.of(bean));
response.setStatus(Response.STATUS_SUCCESS);
return response;
}
public ActionResponse action(ActionRequest request) {
ActionResponse response = new ActionResponse();
String[] parts = request.getAction().split("\\:");
if (parts.length != 2) {
response.setStatus(Response.STATUS_FAILURE);
return response;
}
String controller = parts[0];
String method = parts[1];
try {
Class<?> klass = Class.forName(controller);
Method m = klass.getDeclaredMethod(method, ActionRequest.class, ActionResponse.class);
Object obj = Beans.get(klass);
m.setAccessible(true);
m.invoke(obj, new Object[] { request, response });
response.setStatus(Response.STATUS_SUCCESS);
} catch (Exception e) {
LOG.debug(e.toString(), e);
response.setException(e);
}
return response;
}
/**
* Get the name of the record. This method should be used to get the value
* of name field if it's a function field.
*
* @param request
* the request containing the current values of the record
* @return response with the updated values with record name
*/
public Response getRecordName(Request request) {
Response response = new Response();
Mapper mapper = Mapper.of(model);
Map<String, Object> data = request.getData();
String name = request.getFields().get(0);
if (name == null) {
name = "id";
}
Property property = null;
try {
property = mapper.getProperty(name);
} catch (Exception e) {
}
String selectName = null;
if (property == null && name.indexOf('.') > -1) {
JsonFunction func = JsonFunction.fromPath(name);
Property p = mapper.getProperty(func.getField());
if (p != null && p.isJson()) {
selectName = func.toString();
}
}
if (property == null && selectName == null) {
property = mapper.getNameField();
}
if (property != null && selectName == null) {
selectName = "self." + property.getName();
name = property.getName();
}
if (selectName != null) {
String qs = String.format(
"SELECT %s FROM %s self WHERE self.id = :id",
selectName, model.getSimpleName());
javax.persistence.Query query = JPA.em().createQuery(qs);
QueryBinder.of(query).setCacheable().setReadOnly().bind(data);
Object value = query.getSingleResult();
data.put(name, value);
}
response.setData(ImmutableList.of(data));
response.setStatus(Response.STATUS_SUCCESS);
return response;
}
public static Map<String, Object> toMap(Object bean, String... names) {
return _toMap(bean, unflatten(null, names), false, 0);
}
public static Map<String, Object> toMapCompact(Object bean) {
return _toMap(bean, null, true, 1);
}
@SuppressWarnings("all")
private static Map<String, Object> _toMap(Object bean, Map<String, Object> fields, boolean compact, int level) {
if (bean == null) {
return null;
}
bean = EntityHelper.getEntity(bean);
if (fields == null) {
fields = Maps.newHashMap();
}
Map<String, Object> result = new HashMap<String, Object>();
Mapper mapper = Mapper.of(bean.getClass());
boolean isSaved = ((Model)bean).getId() != null;
boolean isCompact = compact || fields.containsKey("$version");
final Set<Property> translatables = new HashSet<>();
if ((isCompact && isSaved) || (isSaved && level >= 1 ) || (level > 1)) {
Property pn = mapper.getNameField();
Property pc = mapper.getProperty("code");
result.put("id", mapper.get(bean, "id"));
result.put("$version", mapper.get(bean, "version"));
if (pn != null) {
result.put(pn.getName(), mapper.get(bean, pn.getName()));
}
if (pc != null) {
result.put(pc.getName(), mapper.get(bean, pc.getName()));
}
if (pn != null && pn.isTranslatable()) {
Translator.translate(result, pn);
}
if (pc != null && pc.isTranslatable()) {
Translator.translate(result, pc);
}
for (String name: fields.keySet()) {
Object child = mapper.get(bean, name);
if (child instanceof Model) {
child = _toMap(child, (Map) fields.get(name), true, level + 1);
}
if (child != null) {
result.put(name, child);
}
}
return result;
}
for (final Property prop : mapper.getProperties()) {
String name = prop.getName();
PropertyType type = prop.getType();
if (type == PropertyType.BINARY || prop.isPassword()) {
continue;
}
if (isSaved
&& !name.matches("id|version|archived")
&& !fields.isEmpty()
&& !fields.containsKey(name)) {
continue;
}
Object value = mapper.get(bean, name);
if (name.equals("archived") && value == null) {
continue;
}
if (prop.isImage() && byte[].class.isInstance(value)) {
value = new String((byte[]) value);
}
// decimal values should be rounded accordingly otherwise the
// json mapper may use wrong scale.
if (value instanceof BigDecimal) {
BigDecimal decimal = (BigDecimal) value;
int scale = prop.getScale();
if (decimal.scale() == 0 && scale > 0 && scale != decimal.scale()) {
value = decimal.setScale(scale, RoundingMode.HALF_UP);
}
}
if (value instanceof Model) { // m2o
Map<String, Object> _fields = (Map) fields.get(prop.getName());
value = _toMap(value, _fields, true, level + 1);
}
if (value instanceof Collection) { // o2m | m2m
List<Object> items = Lists.newArrayList();
for(Model input : (Collection<Model>) value) {
Map<String, Object> item;
if (input.getId() != null) {
item = _toMap(input, null, true, level+1);
} else {
item = _toMap(input, null, false, 1);
}
if (item != null) {
items.add(item);
}
}
value = items;
}
result.put(name, value);
if (prop.isTranslatable() && value instanceof String) {
Translator.translate(result, prop);
}
// include custom enum value
if (prop.isEnum() && value instanceof ValueEnum<?>) {
String enumName = ((Enum<?>) value).name();
Object enumValue = ((ValueEnum<?>) value).getValue();
if (!Objects.equal(enumName, enumValue)) {
result.put(name + "$value", ((ValueEnum<?>) value).getValue());
}
}
}
return result;
}
@SuppressWarnings("all")
private static Map<String, Object> unflatten(Map<String, Object> map, String... names) {
if (map == null) map = Maps.newHashMap();
if (names == null) return map;
for(String name : names) {
if (map.containsKey(name))
continue;
if (name.contains(".")) {
String[] parts = name.split("\\.", 2);
Map<String, Object> child = (Map) map.get(parts[0]);
if (child == null) {
child = Maps.newHashMap();
}
map.put(parts[0], unflatten(child, parts[1]));
} else {
map.put(name, Maps.newHashMap());
}
}
return map;
}
}
|
axelor-core/src/main/java/com/axelor/rpc/Resource.java
|
/*
* Axelor Business Solutions
*
* Copyright (C) 2005-2018 Axelor (<http://axelor.com>).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.axelor.rpc;
import static com.axelor.common.StringUtils.isBlank;
import java.io.IOException;
import java.io.Writer;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import javax.inject.Inject;
import javax.inject.Provider;
import javax.persistence.EntityTransaction;
import javax.persistence.OptimisticLockException;
import javax.validation.ValidationException;
import org.hibernate.StaleObjectStateException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.axelor.app.AppSettings;
import com.axelor.auth.AuthService;
import com.axelor.auth.AuthUtils;
import com.axelor.auth.db.User;
import com.axelor.common.Inflector;
import com.axelor.common.StringUtils;
import com.axelor.db.EntityHelper;
import com.axelor.db.JPA;
import com.axelor.db.JpaRepository;
import com.axelor.db.JpaSecurity;
import com.axelor.db.Model;
import com.axelor.db.Query;
import com.axelor.db.QueryBinder;
import com.axelor.db.Repository;
import com.axelor.db.ValueEnum;
import com.axelor.db.hibernate.type.JsonFunction;
import com.axelor.db.mapper.Mapper;
import com.axelor.db.mapper.Property;
import com.axelor.db.mapper.PropertyType;
import com.axelor.db.search.SearchService;
import com.axelor.i18n.I18n;
import com.axelor.i18n.I18nBundle;
import com.axelor.i18n.L10n;
import com.axelor.inject.Beans;
import com.axelor.meta.MetaPermissions;
import com.axelor.meta.MetaStore;
import com.axelor.meta.db.MetaAction;
import com.axelor.meta.db.MetaJsonRecord;
import com.axelor.meta.db.MetaTranslation;
import com.axelor.meta.schema.views.Selection;
import com.axelor.rpc.filter.Filter;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.base.Objects;
import com.google.common.base.Splitter;
import com.google.common.collect.Collections2;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.primitives.Ints;
import com.google.common.primitives.Longs;
import com.google.inject.TypeLiteral;
import com.google.inject.persist.Transactional;
/**
* This class defines CRUD like interface.
*
*/
public class Resource<T extends Model> {
private Class<T> model;
private Provider<JpaSecurity> security;
private Logger LOG = LoggerFactory.getLogger(Resource.class);
private Resource(Class<T> model, Provider<JpaSecurity> security) {
this.model = model;
this.security = security;
}
@Inject
@SuppressWarnings("unchecked")
public Resource(TypeLiteral<T> typeLiteral, Provider<JpaSecurity> security) {
this((Class<T>) typeLiteral.getRawType(), security);
}
/**
* Returns the resource class.
*
*/
public Class<?> getModel() {
return model;
}
private Long findId(Map<String, Object> values) {
try {
return Long.parseLong(values.get("id").toString());
} catch (Exception e){}
return null;
}
public Response fields() {
final Response response = new Response();
final Repository<?> repository = JpaRepository.of(model);
final Map<String, Object> meta = Maps.newHashMap();
final List<Object> fields = Lists.newArrayList();
if (repository == null) {
for (Property p : JPA.fields(model)) {
fields.add(p.toMap());
}
} else {
for (Property p : repository.fields()) {
fields.add(p.toMap());
}
}
meta.put("model", model.getName());
meta.put("fields", fields);
response.setData(meta);
response.setStatus(Response.STATUS_SUCCESS);
return response;
}
public static Response models(Request request) {
Response response = new Response();
List<String> data = Lists.newArrayList();
for(Class<?> type : JPA.models()) {
data.add(type.getName());
}
Collections.sort(data);
response.setData(ImmutableList.copyOf(data));
response.setStatus(Response.STATUS_SUCCESS);
return response;
}
public Response perms() {
Set<JpaSecurity.AccessType> perms = security.get().getAccessTypes(model, null);
Response response = new Response();
response.setData(perms);
response.setStatus(Response.STATUS_SUCCESS);
return response;
}
public Response perms(Long id) {
Set<JpaSecurity.AccessType> perms = security.get().getAccessTypes(model, id);
Response response = new Response();
response.setData(perms);
response.setStatus(Response.STATUS_SUCCESS);
return response;
}
public Response perms(Long id, String perm) {
Response response = new Response();
JpaSecurity sec = security.get();
JpaSecurity.AccessType type = JpaSecurity.CAN_READ;
try {
type = JpaSecurity.AccessType.valueOf(perm.toUpperCase());
} catch (Exception e) {
}
try {
sec.check(type, model, id);
response.setStatus(Response.STATUS_SUCCESS);
} catch (Exception e) {
response.addError(perm, e.getMessage());
response.setStatus(Response.STATUS_VALIDATION_ERROR);
}
return response;
}
private List<String> getSortBy(Request request) {
final List<String> sortBy = Lists.newArrayList();
final List<String> sortOn = Lists.newArrayList();
final Mapper mapper = Mapper.of(model);
boolean unique = false;
boolean desc = true;
if (request.getSortBy() != null) {
sortOn.addAll(request.getSortBy());
}
if (sortOn.isEmpty()) {
Property nameField = mapper.getNameField();
if (nameField == null) {
nameField = mapper.getProperty("name");
}
if (nameField == null) {
nameField = mapper.getProperty("code");
}
if (nameField != null) {
sortOn.add(nameField.getName());
}
}
for(String spec : sortOn) {
String name = spec;
if (name.startsWith("-")) {
name = name.substring(1);
} else {
desc = false;
}
Property property = mapper.getProperty(name);
if (property == null || property.isPrimary()) {
// dotted field or primary key
sortBy.add(spec);
continue;
}
if (property.isReference()) {
// use name field to sort many-to-one column
Mapper m = Mapper.of(property.getTarget());
Property p = m.getNameField();
if (p != null) {
spec = spec + "." + p.getName();
}
}
if (property.isUnique() && property.isRequired()) {
unique = true;
}
sortBy.add(spec);
}
if (!unique && !(sortBy.contains("id") || sortBy.contains("-id"))) {
sortBy.add(desc ? "-id" : "id");
}
return sortBy;
}
private Criteria getCriteria(Request request) {
if (request.getData() != null) {
Object domain = request.getData().get("_domain");
if (domain != null) {
try {
String qs = request.getCriteria().createQuery(model).toString();
JPA.em().createQuery(qs);
} catch (Exception e) {
LOG.error("Error: " + e.getMessage(), e);
throw new IllegalArgumentException("Invalid domain: " + domain, e);
}
}
}
return request.getCriteria();
}
private boolean shouldCheckPermissions(Request request) {
final Context context = request.getContext();
// if o2m/m2m search request
if (context != null
&& context.containsKey("_field")
&& context.containsKey("_field_ids")
&& context.containsKey("id")) {
final Model parent = context.asType(Model.class);
return !security.get().isPermitted(JpaSecurity.CAN_READ, EntityHelper.getEntityClass(parent), parent.getId());
}
return true;
}
private Query<?> getQuery(Request request) {
return getQuery(request, security.get().getFilter(JpaSecurity.CAN_READ, model));
}
private Query<?> getQuery(Request request, Filter filter) {
Criteria criteria = getCriteria(request);
Query<?> query = JPA.all(model);
if (criteria != null) {
query = criteria.createQuery(model, filter);
} else if (filter != null) {
query = filter.build(model);
}
for(String spec : getSortBy(request)) {
query = query.order(spec);
}
return query;
}
private Query<?> getSearchQuery(Request request, Filter filter) {
final SearchService searchService = Beans.get(SearchService.class);
if (request.getData() == null || !searchService.isEnabled()) {
return filter == null ? getQuery(request) : getQuery(request, filter);
}
final Map<String, Object> data = request.getData();
final String searchText = (String) data.get("_searchText");
// try full-text search
if (!StringUtils.isEmpty(searchText)) {
try {
final List<Long> ids = searchService.fullTextSearch(model, searchText, request.getLimit());
if (ids.size() > 0) {
return JPA.all(model).filter("self.id in :ids").bind("ids", ids);
}
} catch (Exception e) {
// just log and fallback to default search
LOG.error("Unable to do full-text search: " + e.getMessage(), e);
}
}
return filter == null ? getQuery(request) : getQuery(request, filter);
}
@SuppressWarnings("all")
public Response search(Request request) {
final Filter filter = security.get().getFilter(JpaSecurity.CAN_READ, model);
boolean check = filter == null || shouldCheckPermissions(request);
if (check) {
security.get().check(JpaSecurity.CAN_READ, model);
}
LOG.debug("Searching '{}' with {}", model.getCanonicalName(), request.getData());
Response response = new Response();
int offset = request.getOffset();
int limit = request.getLimit();
Query<?> query = getSearchQuery(request, check ? filter : null).cacheable().readOnly();
List<?> data = null;
try {
if (limit > 0) {
response.setTotal(query.count());
}
if (request.getFields() != null) {
Query<?>.Selector selector = query.select(request.getFields().toArray(new String[] {}));
LOG.debug("JPQL: {}", selector);
data = selector.fetch(limit, offset);
} else {
LOG.debug("JPQL: {}", query);
data = query.fetch(limit, offset);
}
if (limit <= 0) {
response.setTotal(data.size());
}
} catch (Exception e) {
EntityTransaction txn = JPA.em().getTransaction();
if (txn.isActive()) {
txn.rollback();
}
data = Lists.newArrayList();
LOG.error("Error: {}", e, e);
}
LOG.debug("Records found: {}", data.size());
final Repository repo = JpaRepository.of(model);
final List<Object> jsonData = new ArrayList<>();
final boolean populate = request.getContext() != null && request.getContext().get("_populate") != Boolean.FALSE;
for (Object item : data) {
if (item instanceof Model) {
item = toMap(item);
}
if (item instanceof Map) {
Map<String, Object> map = (Map) item;
if (User.class.isAssignableFrom(model)) {
map.remove("password");
}
if (populate) {
item = repo.populate(map, request.getContext());
}
Translator.applyTranslatables(map, model);
}
jsonData.add(item);
}
try {
// check for children (used by tree view)
doChildCount(request, jsonData);
} catch (NullPointerException | ClassCastException e) {};
response.setData(jsonData);
response.setOffset(offset);
response.setStatus(Response.STATUS_SUCCESS);
return response;
}
@SuppressWarnings("all")
private void doChildCount(Request request, List<?> result) throws NullPointerException, ClassCastException {
if (result == null || result.isEmpty()) {
return;
}
final Map context = (Map) request.getData().get("_domainContext");
final Map childOn = (Map) context.get("_childOn");
final String countOn = (String) context.get("_countOn");
if (countOn == null && childOn == null) {
return;
}
final StringBuilder builder = new StringBuilder();
final List ids = Lists.newArrayList();
for (Object item : result) {
ids.add(((Map) item).get("id"));
}
String modelName = model.getName();
String parentName = countOn;
if (childOn != null) {
modelName = (String) childOn.get("model");
parentName = (String) childOn.get("parent");
}
builder.append("SELECT new map(_parent.id as id, count(self.id) as count) FROM ")
.append(modelName).append(" self ")
.append("LEFT JOIN self.").append(parentName).append(" AS _parent ")
.append("WHERE _parent.id IN (:ids) GROUP BY _parent");
javax.persistence.Query q = JPA.em().createQuery(builder.toString());
q.setParameter("ids", ids);
QueryBinder.of(q).setCacheable().setReadOnly();
Map counts = Maps.newHashMap();
for (Object item : q.getResultList()) {
counts.put(((Map)item).get("id"), ((Map)item).get("count"));
}
for (Object item : result) {
((Map) item).put("_children", counts.get(((Map) item).get("id")));
}
}
private static final int DEFAULT_EXPORT_MAX_SIZE = -1;
private static final int DEFAULT_EXPORT_FETCH_SIZE = 500;
private static final int EXPORT_MAX_SIZE = AppSettings.get().getInt("data.export.max-size", DEFAULT_EXPORT_MAX_SIZE);
private static final int EXPORT_FETCH_SIZE = AppSettings.get().getInt("data.export.fetch-size", DEFAULT_EXPORT_FETCH_SIZE);
@SuppressWarnings("all")
public int export(Request request, Writer writer) throws IOException {
security.get().check(JpaSecurity.CAN_READ, model);
security.get().check(JpaSecurity.CAN_EXPORT, model);
LOG.debug("Exporting '{}' with {}", model.getName(), request.getData());
List<String> fields = request.getFields();
List<String> header = new ArrayList<>();
List<String> names = new ArrayList<>();
Map<Integer, Map<String, String>> selection = new HashMap<>();
Map<String, Map<String, Object>> jsonFieldsMap = new HashMap<>();
Mapper mapper = Mapper.of(model);
MetaPermissions perms = Beans.get(MetaPermissions.class);
final Function<String, Map<String, Object>> findJsonFields = name -> jsonFieldsMap.computeIfAbsent(name,
(n) -> {
return MetaJsonRecord.class.isAssignableFrom(model)
? MetaStore.findJsonFields((String) request.getContext().get("jsonModel"))
: MetaStore.findJsonFields(model.getName(), n);
});
final Function<String, List<String>> findJsonPaths = name -> {
final Map<String, Object> map = findJsonFields.apply(name);
return map == null
? Collections.EMPTY_LIST
: map.keySet().stream().map(n -> name + "." + n).collect(Collectors.toList());
};
if (fields == null) {
fields = new ArrayList<>();
}
if (fields.isEmpty() && MetaJsonRecord.class.isAssignableFrom(model)) {
fields.add("id");
fields.addAll(findJsonPaths.apply("attrs"));
}
if (fields.isEmpty()) {
fields.add("id");
try {
fields.add(mapper.getNameField().getName());
} catch (Exception e) {}
for (Property property : mapper.getProperties()) {
if (property.isPrimary() ||
property.isTransient() ||
property.isVersion() ||
property.isCollection() ||
property.isPassword() ||
property.getType() == PropertyType.BINARY) {
continue;
}
String name = property.getName();
if (fields.contains(name) || name.matches("^(created|updated)(On|By)$")) {
continue;
}
if (property.isJson()) {
fields.addAll(findJsonPaths.apply(property.getName()));
} else {
fields.add(name);
}
}
}
for(String field : fields) {
Iterator<String> iter = Splitter.on(".").split(field).iterator();
Property prop = mapper.getProperty(iter.next());
while(iter.hasNext() && prop != null && !prop.isJson()) {
prop = Mapper.of(prop.getTarget()).getProperty(iter.next());
}
if (prop == null ||
prop.isCollection() ||
prop.isTransient() ||
prop.getType() == PropertyType.BINARY) {
continue;
}
if (prop.isJson() && !iter.hasNext()) {
continue;
}
String name = prop.getName();
String title = prop.getTitle();
String model = getModel().getName();
if (prop.isReference()) {
model = prop.getTarget().getName();
}
if (!perms.canExport(AuthUtils.getUser(), model, name)) {
continue;
}
if (iter != null) {
name = field;
}
List<Selection.Option> options = MetaStore.getSelectionList(prop.getSelection());
if (prop.isJson()) {
Map<String, Object> jsonFields = findJsonFields.apply(prop.getName());
Map<String, Object> jsonField = (Map) jsonFields.get(iter.next());
name = field;
if (jsonField != null) {
title = (String) jsonField.get("title");
if (title == null) {
title = (String) jsonField.get("autoTitle");
}
options = (List) jsonField.get("selectionList");
if ("many-to-one".equals(jsonField.get("type"))) {
try {
String targetName = jsonField.get("targetName").toString();
targetName = targetName.substring(targetName.indexOf(".") + 1);
name = name + "." + targetName;
} catch (Exception e) {
}
}
}
}
if (isBlank(title)) {
title = Inflector.getInstance().humanize(prop.getName());
}
if (prop.isReference()) {
prop = Mapper.of(prop.getTarget()).getNameField();
if (prop == null) {
continue;
}
name = name + '.' + prop.getName();
} else if(options != null && !options.isEmpty()) {
Map<String, String> map = new HashMap<>();
for (Selection.Option option : options) {
map.put(option.getValue(), option.getLocalizedTitle());
}
selection.put(header.size(), map);
}
title = I18n.get(title);
names.add(name);
header.add(escapeCsv(title));
}
writer.write(Joiner.on(";").join(header));
int limit = EXPORT_MAX_SIZE > 0 ? Math.min(EXPORT_FETCH_SIZE, EXPORT_MAX_SIZE) : EXPORT_FETCH_SIZE;
int offset = 0;
int count = 0;
Query<?> query = getQuery(request);
Query<?>.Selector selector = query.select(names.toArray(new String[0]));
List<?> data = selector.values(limit, offset);
final L10n formatter = L10n.getInstance();
while (!data.isEmpty()) {
for (Object item : data) {
List<?> row = (List<?>) item;
List<String> line = new ArrayList<>();
int index = 0;
for(Object value: row) {
if (index++ < 2) continue; // ignore first two items (id, version)
Object objValue = value == null ? "" : value;
if(selection.containsKey(index-3)) {
objValue = selection.get(index-3).get(objValue.toString());
}
if (objValue instanceof Number) {
objValue = formatter.format((Number) objValue, false);
}
if (objValue instanceof LocalDate) {
objValue = formatter.format((LocalDate) objValue);
}
if (objValue instanceof LocalDateTime) {
objValue = formatter.format((LocalDateTime) objValue);
}
if (objValue instanceof ZonedDateTime) {
objValue = formatter.format((ZonedDateTime) objValue);
}
String strValue = objValue == null ? "" : escapeCsv(objValue.toString());
line.add(strValue);
}
writer.write("\n");
writer.write(Joiner.on(";").join(line));
}
count += data.size();
int nextLimit = limit;
if (EXPORT_MAX_SIZE > -1) {
if (count >= EXPORT_MAX_SIZE) {
break;
}
nextLimit = Math.min(limit, EXPORT_MAX_SIZE - count);
}
offset += limit;
data = selector.values(nextLimit, offset);
}
return count;
}
private String escapeCsv(String value) {
if (value == null) return "";
if (value.indexOf('"') > -1) value = value.replaceAll("\"", "\"\"");
return '"' + value + '"';
}
public Response read(long id) {
security.get().check(JpaSecurity.CAN_READ, model, id);
Response response = new Response();
List<Object> data = Lists.newArrayList();
Model entity = JPA.find(model, id);
if (entity != null)
data.add(entity);
response.setData(data);
response.setStatus(Response.STATUS_SUCCESS);
return response;
}
public Response fetch(long id, Request request) {
security.get().check(JpaSecurity.CAN_READ, model, id);
final Response response = new Response();
final Repository<?> repository = JpaRepository.of(model);
final Model entity = repository.find(id);
response.setStatus(Response.STATUS_SUCCESS);
if (entity == null) {
return response;
}
final List<Object> data = Lists.newArrayList();
final String[] fields = request.getFields() == null ? null : request.getFields().toArray(new String[]{});
final Map<String, Object> values = mergeRelated(request, entity, toMap(entity, fields));
// special case for User/Group objects
if (values.get("homeAction") != null) {
MetaAction act = JpaRepository.of(MetaAction.class).all()
.filter("self.name = ?", values.get("homeAction"))
.fetchOne();
if (act != null) {
values.put("__actionSelect", toMapCompact(act));
}
}
data.add(repository.populate(values, request.getContext()));
response.setData(data);
return response;
}
@SuppressWarnings("all")
private Map<String, Object> mergeRelated(Request request, Model entity, Map<String, Object> values) {
final Map<String, List<String>> related = request.getRelated();
if (related == null) {
return values;
}
final Mapper mapper = Mapper.of(model);
related.entrySet().stream()
.filter(e -> e.getValue() != null)
.filter(e -> e.getValue().size() > 0)
.forEach(e -> {
final String name = e.getKey();
final String[] names = e.getValue().toArray(new String[] {});
Object old = values.get(name);
Object value = mapper.get(entity, name);
if (value instanceof Collection<?>) {
value = Collections2.transform((Collection<?>) value, input -> toMap(input, names));
} else if (value instanceof Model) {
value = toMap(value, names);
if (old instanceof Map) {
value = mergeMaps((Map) value, (Map) old);
}
}
values.put(name, value);
});
return values;
}
@SuppressWarnings("all")
private Map<String, Object> mergeMaps(Map<String, Object> target, Map<String, Object> source) {
if (target == null || source == null || source.isEmpty()) {
return target;
}
for (String key : source.keySet()) {
Object old = source.get(key);
Object val = target.get(key);
if (val instanceof Map && old instanceof Map) {
mergeMaps((Map) val, (Map) old);
} else if (val == null) {
target.put(key, old);
}
}
return target;
}
public Response verify(Request request) {
Response response = new Response();
try {
JPA.verify(model, request.getData());
response.setStatus(Response.STATUS_SUCCESS);
} catch (OptimisticLockException e) {
response.setStatus(Response.STATUS_VALIDATION_ERROR);
}
return response;
}
private User changeUserPassword(User user, Map<String, Object> values) {
final String oldPassword = (String) values.get("oldPassword");
final String newPassword = (String) values.get("newPassword");
final String chkPassword = (String) values.get("chkPassword");
// no password change
if (StringUtils.isBlank(newPassword)) {
return user;
}
if (StringUtils.isBlank(oldPassword)) {
throw new ValidationException("Current user password is not provided.");
}
if (!newPassword.equals(chkPassword)) {
throw new ValidationException("Confirm password doesn't match with new password.");
}
final User current = AuthUtils.getUser();
final AuthService authService = AuthService.getInstance();
if (!authService.match(oldPassword, current.getPassword())) {
throw new ValidationException("Current user password is wrong.");
}
user.setPassword(authService.encrypt(newPassword));
return user;
}
@Transactional
@SuppressWarnings("all")
public Response save(final Request request) {
final Response response = new Response();
final Repository repository = JpaRepository.of(model);
List<Object> records = request.getRecords();
List<Object> data = Lists.newArrayList();
if ((records == null || records.isEmpty()) && request.getData() == null) {
response.setStatus(Response.STATUS_FAILURE);
return response;
}
if (records == null) {
records = Lists.newArrayList();
records.add(request.getData());
}
String[] names = {};
if (request.getFields() != null) {
names = request.getFields().toArray(names);
}
for (Object record : records) {
if (record == null) {
continue;
}
record = (Map) repository.validate((Map) record, request.getContext());
Long id = findId((Map) record);
if (id == null || id <= 0L) {
security.get().check(JpaSecurity.CAN_CREATE, model);
}
Map<String, Object> orig = (Map) ((Map) record).get("_original");
JPA.verify(model, orig);
Model bean = JPA.edit(model, (Map) record);
id = bean.getId();
if (bean != null && id != null && id > 0L) {
security.get().check(JpaSecurity.CAN_WRITE, model, id);
}
// if user, update password
if (bean instanceof User) {
changeUserPassword((User) bean, (Map) record);
}
bean = JPA.manage(bean);
if (repository != null) {
bean = repository.save(bean);
}
// if it's a translation object, invalidate cache
if (bean instanceof MetaTranslation) {
I18nBundle.invalidate();
}
data.add(repository.populate(toMap(bean, names), request.getContext()));
}
response.setData(data);
response.setStatus(Response.STATUS_SUCCESS);
return response;
}
@Transactional
public Response updateMass(Request request) {
security.get().check(JpaSecurity.CAN_WRITE, model);
LOG.debug("Mass update '{}' with {}", model.getCanonicalName(), request.getData());
Response response = new Response();
Query<?> query = getQuery(request);
List<?> data = request.getRecords();
LOG.debug("JPQL: {}", query);
@SuppressWarnings("all")
Map<String, Object> values = (Map) data.get(0);
response.setTotal(query.update(values, AuthUtils.getUser()));
LOG.debug("Records updated: {}", response.getTotal());
response.setStatus(Response.STATUS_SUCCESS);
return response;
}
@Transactional
@SuppressWarnings("all")
public Response remove(long id, Request request) {
security.get().check(JpaSecurity.CAN_REMOVE, model, id);
final Response response = new Response();
final Repository repository = JpaRepository.of(model);
final Map<String, Object> data = Maps.newHashMap();
data.put("id", id);
data.put("version", request.getData().get("version"));
Model bean = JPA.edit(model, data);
if (bean.getId() != null) {
if (repository == null) {
JPA.remove(bean);
} else {
repository.remove(bean);
}
}
response.setData(ImmutableList.of(toMapCompact(bean)));
response.setStatus(Response.STATUS_SUCCESS);
return response;
}
@Transactional
@SuppressWarnings("all")
public Response remove(Request request) {
final Response response = new Response();
final Repository repository = JpaRepository.of(model);
final List<Object> records = request.getRecords();
if (records == null || records.isEmpty()) {
return response.fail("No records provides.");
}
final List<Model> entities = Lists.newArrayList();
for(Object record : records) {
Map map = (Map) record;
Long id = Longs.tryParse(map.get("id").toString());
Integer version = null;
try {
version = Ints.tryParse(map.get("version").toString());
} catch (Exception e) {
}
security.get().check(JpaSecurity.CAN_REMOVE, model, id);
Model bean = JPA.find(model, id);
if (version != null && !Objects.equal(version, bean.getVersion())) {
throw new OptimisticLockException(
new StaleObjectStateException(model.getName(), id));
}
entities.add(bean);
}
for(Model entity : entities) {
if (JPA.em().contains(entity)) {
if (repository == null) {
JPA.remove(entity);
} else {
repository.remove(entity);
}
}
}
response.setData(records);
response.setStatus(Response.STATUS_SUCCESS);
return response;
}
@SuppressWarnings("all")
public Response copy(long id) {
security.get().check(JpaSecurity.CAN_CREATE, model, id);
final Response response = new Response();
final Repository repository = JpaRepository.of(model);
Model bean = JPA.find(model, id);
if (repository == null) {
bean = JPA.copy(bean, true);
} else {
bean = repository.copy(bean, true);
}
response.setData(ImmutableList.of(bean));
response.setStatus(Response.STATUS_SUCCESS);
return response;
}
public ActionResponse action(ActionRequest request) {
ActionResponse response = new ActionResponse();
String[] parts = request.getAction().split("\\:");
if (parts.length != 2) {
response.setStatus(Response.STATUS_FAILURE);
return response;
}
String controller = parts[0];
String method = parts[1];
try {
Class<?> klass = Class.forName(controller);
Method m = klass.getDeclaredMethod(method, ActionRequest.class, ActionResponse.class);
Object obj = Beans.get(klass);
m.setAccessible(true);
m.invoke(obj, new Object[] { request, response });
response.setStatus(Response.STATUS_SUCCESS);
} catch (Exception e) {
LOG.debug(e.toString(), e);
response.setException(e);
}
return response;
}
/**
* Get the name of the record. This method should be used to get the value
* of name field if it's a function field.
*
* @param request
* the request containing the current values of the record
* @return response with the updated values with record name
*/
public Response getRecordName(Request request) {
Response response = new Response();
Mapper mapper = Mapper.of(model);
Map<String, Object> data = request.getData();
String name = request.getFields().get(0);
if (name == null) {
name = "id";
}
Property property = null;
try {
property = mapper.getProperty(name);
} catch (Exception e) {
}
String selectName = null;
if (property == null && name.indexOf('.') > -1) {
JsonFunction func = JsonFunction.fromPath(name);
Property p = mapper.getProperty(func.getField());
if (p != null && p.isJson()) {
selectName = func.toString();
}
}
if (property == null && selectName == null) {
property = mapper.getNameField();
}
if (property != null && selectName == null) {
selectName = "self." + property.getName();
name = property.getName();
}
if (selectName != null) {
String qs = String.format(
"SELECT %s FROM %s self WHERE self.id = :id",
selectName, model.getSimpleName());
javax.persistence.Query query = JPA.em().createQuery(qs);
QueryBinder.of(query).setCacheable().setReadOnly().bind(data);
Object value = query.getSingleResult();
data.put(name, value);
}
response.setData(ImmutableList.of(data));
response.setStatus(Response.STATUS_SUCCESS);
return response;
}
public static Map<String, Object> toMap(Object bean, String... names) {
return _toMap(bean, unflatten(null, names), false, 0);
}
public static Map<String, Object> toMapCompact(Object bean) {
return _toMap(bean, null, true, 1);
}
@SuppressWarnings("all")
private static Map<String, Object> _toMap(Object bean, Map<String, Object> fields, boolean compact, int level) {
if (bean == null) {
return null;
}
bean = EntityHelper.getEntity(bean);
if (fields == null) {
fields = Maps.newHashMap();
}
Map<String, Object> result = new HashMap<String, Object>();
Mapper mapper = Mapper.of(bean.getClass());
boolean isSaved = ((Model)bean).getId() != null;
boolean isCompact = compact || fields.containsKey("$version");
final Set<Property> translatables = new HashSet<>();
if ((isCompact && isSaved) || (isSaved && level >= 1 ) || (level > 1)) {
Property pn = mapper.getNameField();
Property pc = mapper.getProperty("code");
result.put("id", mapper.get(bean, "id"));
result.put("$version", mapper.get(bean, "version"));
if (pn != null) {
result.put(pn.getName(), mapper.get(bean, pn.getName()));
}
if (pc != null) {
result.put(pc.getName(), mapper.get(bean, pc.getName()));
}
if (pn != null && pn.isTranslatable()) {
Translator.translate(result, pn);
}
if (pc != null && pc.isTranslatable()) {
Translator.translate(result, pc);
}
for (String name: fields.keySet()) {
Object child = mapper.get(bean, name);
if (child instanceof Model) {
child = _toMap(child, (Map) fields.get(name), true, level + 1);
}
if (child != null) {
result.put(name, child);
}
}
return result;
}
for (final Property prop : mapper.getProperties()) {
String name = prop.getName();
PropertyType type = prop.getType();
if (type == PropertyType.BINARY || prop.isPassword()) {
continue;
}
if (isSaved
&& !name.matches("id|version|archived")
&& !fields.isEmpty()
&& !fields.containsKey(name)) {
continue;
}
Object value = mapper.get(bean, name);
if (name.equals("archived") && value == null) {
continue;
}
if (prop.isImage() && byte[].class.isInstance(value)) {
value = new String((byte[]) value);
}
// decimal values should be rounded accordingly otherwise the
// json mapper may use wrong scale.
if (value instanceof BigDecimal) {
BigDecimal decimal = (BigDecimal) value;
int scale = prop.getScale();
if (decimal.scale() == 0 && scale > 0 && scale != decimal.scale()) {
value = decimal.setScale(scale, RoundingMode.HALF_UP);
}
}
if (value instanceof Model) { // m2o
Map<String, Object> _fields = (Map) fields.get(prop.getName());
value = _toMap(value, _fields, true, level + 1);
}
if (value instanceof Collection) { // o2m | m2m
List<Object> items = Lists.newArrayList();
for(Model input : (Collection<Model>) value) {
Map<String, Object> item;
if (input.getId() != null) {
item = _toMap(input, null, true, level+1);
} else {
item = _toMap(input, null, false, 1);
}
if (item != null) {
items.add(item);
}
}
value = items;
}
result.put(name, value);
if (prop.isTranslatable() && value instanceof String) {
Translator.translate(result, prop);
}
// include custom enum value
if (prop.isEnum() && value instanceof ValueEnum<?>) {
String enumName = ((Enum<?>) value).name();
Object enumValue = ((ValueEnum<?>) value).getValue();
if (!Objects.equal(enumName, enumValue)) {
result.put(name + "$value", ((ValueEnum<?>) value).getValue());
}
}
}
return result;
}
@SuppressWarnings("all")
private static Map<String, Object> unflatten(Map<String, Object> map, String... names) {
if (map == null) map = Maps.newHashMap();
if (names == null) return map;
for(String name : names) {
if (map.containsKey(name))
continue;
if (name.contains(".")) {
String[] parts = name.split("\\.", 2);
Map<String, Object> child = (Map) map.get(parts[0]);
if (child == null) {
child = Maps.newHashMap();
}
map.put(parts[0], unflatten(child, parts[1]));
} else {
map.put(name, Maps.newHashMap());
}
}
return map;
}
}
|
Always check permission condition after record is saved
In case of record update, condition should be checked before save
as well as after save. In case of record create, condition should
be checked after save.
If condition fails, current transaction will rollback.
Closes RM-12557
|
axelor-core/src/main/java/com/axelor/rpc/Resource.java
|
Always check permission condition after record is saved
|
|
Java
|
lgpl-2.1
|
03b6849bd017447f31b89a3bfd0651ae7082554d
| 0
|
xwiki/xwiki-platform,xwiki/xwiki-platform,pbondoer/xwiki-platform,xwiki/xwiki-platform,pbondoer/xwiki-platform,pbondoer/xwiki-platform,pbondoer/xwiki-platform,xwiki/xwiki-platform,pbondoer/xwiki-platform,xwiki/xwiki-platform
|
/*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.xwiki.test.ui.extension;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.math.RandomUtils;
import org.junit.Test;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.Select;
import org.xwiki.extension.DefaultExtensionAuthor;
import org.xwiki.extension.DefaultExtensionDependency;
import org.xwiki.extension.DefaultExtensionIssueManagement;
import org.xwiki.extension.DefaultExtensionScm;
import org.xwiki.extension.DefaultExtensionScmConnection;
import org.xwiki.extension.ExtensionId;
import org.xwiki.extension.ExtensionLicense;
import org.xwiki.extension.repository.xwiki.model.jaxb.ExtensionsSearchResult;
import org.xwiki.extension.test.po.AdvancedSearchPane;
import org.xwiki.extension.test.po.DependencyPane;
import org.xwiki.extension.test.po.ExtensionAdministrationPage;
import org.xwiki.extension.test.po.ExtensionDependenciesPane;
import org.xwiki.extension.test.po.ExtensionDescriptionPane;
import org.xwiki.extension.test.po.ExtensionPane;
import org.xwiki.extension.test.po.ExtensionProgressPane;
import org.xwiki.extension.test.po.LogItemPane;
import org.xwiki.extension.test.po.MergeConflictPane;
import org.xwiki.extension.test.po.PaginationFilterPane;
import org.xwiki.extension.test.po.ProgressBarPane;
import org.xwiki.extension.test.po.SearchResultsPane;
import org.xwiki.extension.test.po.SimpleSearchPane;
import org.xwiki.extension.test.po.UnusedPagesPane;
import org.xwiki.extension.version.internal.DefaultVersionConstraint;
import org.xwiki.repository.test.TestExtension;
import org.xwiki.test.ui.AbstractExtensionAdminAuthenticatedTest;
import org.xwiki.test.ui.po.ChangesPane;
import org.xwiki.test.ui.po.ViewPage;
import org.xwiki.test.ui.po.diff.EntityDiff;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
/**
* Functional tests for the Extension Manager user interface.
*
* @version $Id$
* @since 4.2M1
*/
public class ExtensionTest extends AbstractExtensionAdminAuthenticatedTest
{
@Override
public void setUp() throws Exception
{
super.setUp();
// Make sure the extensions we are playing with are not already installed.
getExtensionTestUtils().finishCurrentJob();
getExtensionTestUtils().uninstall("alice-xar-extension");
getExtensionTestUtils().uninstall("bob-xar-extension");
getExtensionTestUtils().uninstall("scriptServiceJarExtension");
// Delete the pages that are provided by the XAR extensions we use in tests.
getUtil().rest().deletePage("ExtensionTest", "Alice");
assertFalse(getUtil().pageExists("ExtensionTest", "Alice"));
getUtil().rest().deletePage("ExtensionTest", "Bob");
assertFalse(getUtil().pageExists("ExtensionTest", "Bob"));
// Delete from the repository the XAR extensions we use in tests.
// The extension page name is either the extension name, if specified, or the extension id. Most of the tests
// don't set the extension name but some do and we end up with two extensions (two pages) with the same id.
getRepositoryTestUtils().deleteExtension("Alice Wiki Macro");
getRepositoryTestUtils().deleteExtension("Bob Wiki Macro");
getRepositoryTestUtils().deleteExtension("alice-xar-extension");
getRepositoryTestUtils().deleteExtension("bob-xar-extension");
getRepositoryTestUtils().deleteExtension("scriptServiceJarExtension");
getRepositoryTestUtils().waitUntilReady();
// Double check that the XWiki Extension Repository is empty.
ExtensionsSearchResult searchResult =
getUtil().rest().getResource("repository/search", Collections.singletonMap("number", new Object[] {1}));
assertEquals(0, searchResult.getTotalHits());
}
/**
* The extension search results pagination.
*/
@Test
public void testPagination()
{
ExtensionAdministrationPage adminPage = ExtensionAdministrationPage.gotoPage().clickCoreExtensionsSection();
SearchResultsPane searchResults = adminPage.getSearchResults();
assertNull(searchResults.getNoResultsMessage());
assertEquals(20, searchResults.getDisplayedResultsCount());
PaginationFilterPane pagination = searchResults.getPagination();
assertEquals(1 + pagination.getResultsCount() / 20, pagination.getPageCount());
assertEquals("1 - 20", pagination.getCurrentRange());
assertEquals(1, pagination.getCurrentPageIndex());
assertFalse(pagination.hasPreviousPage());
assertTrue(pagination.hasNextPage());
assertTrue(pagination.getPageCount() > 5);
assertTrue(pagination.getResultsCount() > 100);
String firstExtensionName = searchResults.getExtension(0).getName();
pagination = pagination.gotoPage(4);
searchResults = new SearchResultsPane();
assertEquals(20, searchResults.getDisplayedResultsCount());
assertEquals("61 - 80", pagination.getCurrentRange());
assertEquals(4, pagination.getCurrentPageIndex());
assertTrue(pagination.hasNextPage());
String secondExtensionName = searchResults.getExtension(0).getName();
assertFalse(firstExtensionName.equals(secondExtensionName));
pagination = pagination.previousPage();
searchResults = new SearchResultsPane();
assertEquals(20, searchResults.getDisplayedResultsCount());
assertEquals("41 - 60", pagination.getCurrentRange());
assertEquals(3, pagination.getCurrentPageIndex());
String thirdExtensionName = searchResults.getExtension(0).getName();
assertFalse(firstExtensionName.equals(thirdExtensionName));
assertFalse(secondExtensionName.equals(thirdExtensionName));
pagination = pagination.nextPage();
searchResults = new SearchResultsPane();
assertEquals(20, searchResults.getDisplayedResultsCount());
assertEquals("61 - 80", pagination.getCurrentRange());
assertEquals(4, pagination.getCurrentPageIndex());
assertEquals(secondExtensionName, searchResults.getExtension(0).getName());
pagination = pagination.gotoPage(pagination.getPageCount());
searchResults = new SearchResultsPane();
assertEquals(pagination.getResultsCount() % 20, searchResults.getDisplayedResultsCount());
assertEquals(pagination.getPageCount(), pagination.getCurrentPageIndex());
assertFalse(pagination.hasNextPage());
assertTrue(pagination.hasPreviousPage());
}
/**
* Tests the simple search form.
*/
@Test
public void testSimpleSearch()
{
ExtensionAdministrationPage adminPage = ExtensionAdministrationPage.gotoPage().clickCoreExtensionsSection();
int coreExtensionCount = adminPage.getSearchResults().getPagination().getResultsCount();
SimpleSearchPane searchBar = adminPage.getSearchBar();
// Check if the tip is displayed.
assertEquals("search extension...", searchBar.getSearchInput().getAttribute("placeholder"));
// Check that the input is empty
assertEquals("", searchBar.getSearchInput().getAttribute("value"));
SearchResultsPane searchResults = searchBar.search("XWiki Commons");
assertTrue(searchResults.getPagination().getResultsCount() < coreExtensionCount);
// Make sure the search input is not cleared.
searchBar = new SimpleSearchPane();
assertEquals("XWiki Commons", searchBar.getSearchInput().getAttribute("value"));
assertNull(searchResults.getNoResultsMessage());
// Check that the result matches the search query.
ExtensionPane extension = searchResults.getExtension(RandomUtils.nextInt(20));
assertTrue(extension.getName().toLowerCase().contains("commons"));
assertEquals("core", extension.getStatus());
// Test search query with no results.
searchResults = new SimpleSearchPane().search("blahblah");
assertEquals(0, searchResults.getDisplayedResultsCount());
assertNull(searchResults.getPagination());
assertEquals("There were no extensions found matching 'blahblah'. Try different keywords. "
+ "Alternatively, if you know the identifier and the version of the extension you're "
+ "looking for, you can use the Advanced Search form above.", searchResults.getNoResultsMessage());
// Test a search query with only a few results (only one page).
searchResults = searchBar.search("restlet");
assertNull(searchResults.getNoResultsMessage());
assertNull(searchResults.getPagination());
assertTrue(searchResults.getDisplayedResultsCount() > 1);
extension = searchResults.getExtension(0);
assertEquals("core", extension.getStatus());
assertTrue(extension.getName().toLowerCase().contains("restlet"));
}
/**
* Tests the advanced search form.
*/
@Test
public void testAdvancedSearch()
{
ExtensionAdministrationPage adminPage = ExtensionAdministrationPage.gotoPage().clickCoreExtensionsSection();
SearchResultsPane searchResults = adminPage.getSearchBar().search("restlet");
String version = searchResults.getExtension(0).getVersion();
searchResults = new SimpleSearchPane().clickAdvancedSearch().search("org.restlet.jse:org.restlet", version);
assertEquals(1, searchResults.getDisplayedResultsCount());
assertNull(searchResults.getNoResultsMessage());
ExtensionPane extension = searchResults.getExtension(0);
assertEquals("core", extension.getStatus());
assertTrue(extension.getName().toLowerCase().contains("restlet"));
assertEquals(version, extension.getVersion());
searchResults = new SimpleSearchPane().clickAdvancedSearch().search("foo", "bar");
assertEquals(0, searchResults.getDisplayedResultsCount());
assertNull(searchResults.getPagination());
assertEquals("We couldn't find any extension with id 'foo' and version 'bar'. "
+ "Make sure you have the right extension repositories configured.", searchResults.getNoResultsMessage());
// Test cancel advanced search.
AdvancedSearchPane advancedSearchPane = new SimpleSearchPane().clickAdvancedSearch();
advancedSearchPane.getIdInput().sendKeys("id");
assertTrue(advancedSearchPane.getVersionInput().isDisplayed());
advancedSearchPane.getCancelButton().click();
assertFalse(advancedSearchPane.getVersionInput().isDisplayed());
}
/**
* Tests how core extensions are displayed.
*/
@Test
public void testCoreExtensions()
{
ExtensionAdministrationPage adminPage = ExtensionAdministrationPage.gotoPage().clickCoreExtensionsSection();
// Assert that the core extension repository is selected.
SimpleSearchPane searchBar = adminPage.getSearchBar();
assertEquals("Core extensions", searchBar.getRepositorySelect().getFirstSelectedOption().getText());
ExtensionPane extension = adminPage.getSearchResults().getExtension(RandomUtils.nextInt(20));
assertEquals("core", extension.getStatus());
assertEquals("Provided", extension.getStatusMessage());
assertNull(extension.getInstallButton());
assertNull(extension.getUninstallButton());
assertNull(extension.getUpgradeButton());
assertNull(extension.getDowngradeButton());
// Just test that the button to show the extension details is present.
assertEquals("core", extension.showDetails().getStatus());
}
/**
* Tests the extension repository selector (all, core, installed, local).
*/
@Test
public void testRepositorySelector() throws Exception
{
// Setup the extension.
ExtensionId extensionId = new ExtensionId("alice-xar-extension", "1.3");
TestExtension extension = getRepositoryTestUtils().getTestExtension(extensionId, "xar");
getRepositoryTestUtils().addExtension(extension);
getRepositoryTestUtils().waitUntilReady();
// Check if the section links point to the right repository.
ExtensionAdministrationPage adminPage = ExtensionAdministrationPage.gotoPage().clickAddExtensionsSection();
Select repositorySelect = adminPage.getSearchBar().getRepositorySelect();
assertEquals("All Extensions", repositorySelect.getFirstSelectedOption().getText());
adminPage = adminPage.clickCoreExtensionsSection();
repositorySelect = adminPage.getSearchBar().getRepositorySelect();
assertEquals("Core extensions", repositorySelect.getFirstSelectedOption().getText());
adminPage = adminPage.clickInstalledExtensionsSection();
repositorySelect = adminPage.getSearchBar().getRepositorySelect();
assertEquals("Installed extensions", repositorySelect.getFirstSelectedOption().getText());
// Check that a remote extension appears only in the list of "All Extensions".
SearchResultsPane searchResults = adminPage.getSearchBar().search("alice");
assertNull(searchResults.getExtension(extensionId));
new SimpleSearchPane().getRepositorySelect().selectByVisibleText("All Extensions");
adminPage = new ExtensionAdministrationPage();
adminPage.waitUntilPageIsLoaded();
// The value of the search input must be preserved when we switch the repository.
assertEquals("alice", adminPage.getSearchBar().getSearchInput().getAttribute("value"));
assertNotNull(adminPage.getSearchResults().getExtension(extensionId));
assertNull(new SimpleSearchPane().selectRepository("local").getExtension(extensionId));
// Check that an installed extension appears also in "Installed Extensions" and "Local Extensions".
getExtensionTestUtils().install(extensionId);
adminPage = ExtensionAdministrationPage.gotoPage().clickInstalledExtensionsSection();
searchResults = adminPage.getSearchBar().search("alice");
assertNotNull(searchResults.getExtension(extensionId));
assertNotNull(new SimpleSearchPane().selectRepository("local").getExtension(extensionId));
assertNotNull(new SimpleSearchPane().selectRepository("").getExtension(extensionId));
// Check local extension.
getExtensionTestUtils().uninstall(extensionId.getId(), true);
adminPage = ExtensionAdministrationPage.gotoPage().clickInstalledExtensionsSection();
searchResults = adminPage.getSearchBar().search("alice");
assertNull(searchResults.getExtension(extensionId));
assertNotNull(new SimpleSearchPane().selectRepository("local").getExtension(extensionId));
assertNotNull(new SimpleSearchPane().selectRepository("").getExtension(extensionId));
}
/**
* Tests the extension details (license, web site).
*/
@Test
public void testShowDetails() throws Exception
{
// Setup the extension.
ExtensionId extensionId = new ExtensionId("alice-xar-extension", "1.3");
TestExtension extension = getRepositoryTestUtils().getTestExtension(extensionId, "xar");
extension.setName("Alice Wiki Macro");
extension.setSummary("A **useless** macro");
extension.addAuthor(new DefaultExtensionAuthor("Thomas", null));
extension.addAuthor(new DefaultExtensionAuthor("Marius", null));
extension.addFeature("alice-extension");
extension.addLicense(new ExtensionLicense("My own license", null));
extension.setWebsite("http://www.alice.com");
extension.setScm(new DefaultExtensionScm("https://github.com/xwiki-contrib/alice-xar-extension",
new DefaultExtensionScmConnection("git", "git://github.com/xwiki-contrib/alice-xar-extension.git"),
new DefaultExtensionScmConnection("git", "git:git@github.com:xwiki-contrib/alice-xar-extension.git")));
extension.setIssueManagement(new DefaultExtensionIssueManagement("jira", "http://jira.xwiki.org/browse/ALICE"));
getRepositoryTestUtils().addExtension(extension);
// Search the extension and assert the displayed information.
ExtensionAdministrationPage adminPage = ExtensionAdministrationPage.gotoPage().clickAddExtensionsSection();
ExtensionPane extensionPane =
adminPage.getSearchBar().clickAdvancedSearch().search(extensionId).getExtension(0);
assertEquals("remote", extensionPane.getStatus());
assertNull(extensionPane.getStatusMessage());
assertEquals(extension.getName(), extensionPane.getName());
assertEquals(extensionId.getVersion().getValue(), extensionPane.getVersion());
List<WebElement> authors = extensionPane.getAuthors();
assertEquals(2, authors.size());
assertEquals("Thomas", authors.get(0).getText());
assertEquals("Marius", authors.get(1).getText());
assertEquals(extension.getSummary(), extensionPane.getSummary());
// Check the extension details.
ExtensionDescriptionPane descriptionPane = extensionPane.openDescriptionSection();
assertEquals(extension.getLicenses().iterator().next().getName(), descriptionPane.getLicense());
assertEquals(extension.getId().getId(), descriptionPane.getId());
assertEquals(extension.getFeatures().iterator().next(), descriptionPane.getFeatures().get(0));
assertEquals(extension.getType(), descriptionPane.getType());
WebElement webSiteLink = descriptionPane.getWebSite();
assertEquals(extension.getWebSite().substring("http://".length()), webSiteLink.getText());
assertEquals(extension.getWebSite() + '/', webSiteLink.getAttribute("href"));
// Install the extension to check the details that are specific to installed extensions.
Date beforeInstall = new Date();
descriptionPane = extensionPane.install().confirm().openDescriptionSection();
Date afterInstall = new Date();
List<String> namespaces = descriptionPane.getNamespaces();
assertEquals(1, namespaces.size());
String prefix = "Home, by superadmin on ";
assertTrue(namespaces.get(0).startsWith(prefix));
Date installDate = new SimpleDateFormat("yyyy/MM/dd HH:mm").parse(namespaces.get(0).substring(prefix.length()));
// Ignore the seconds as they are not displayed.
assertTrue(String.format("Install date [%s] should be after [%s].", installDate, beforeInstall),
installDate.getTime() / 60000 >= beforeInstall.getTime() / 60000);
assertTrue(String.format("Install date [%s] should be before [%s].", installDate, afterInstall),
installDate.before(afterInstall));
}
/**
* Tests how extension dependencies are displayed (both direct and backward dependencies).
*/
@Test
public void testDependencies() throws Exception
{
// Setup the extension and its dependencies.
ExtensionId dependencyId = new ExtensionId("bob-xar-extension", "2.5-milestone-2");
TestExtension dependency = getRepositoryTestUtils().getTestExtension(dependencyId, "xar");
dependency.setName("Bob Wiki Macro");
dependency.setSummary("Required by Alice");
getRepositoryTestUtils().addExtension(dependency);
ExtensionId extensionId = new ExtensionId("alice-xar-extension", "1.3");
TestExtension extension = getRepositoryTestUtils().getTestExtension(extensionId, "xar");
extension.addDependency(new DefaultExtensionDependency(dependencyId.getId(), new DefaultVersionConstraint(
dependencyId.getVersion().getValue())));
extension.addDependency(new DefaultExtensionDependency("missing-dependency",
new DefaultVersionConstraint("135")));
extension.addDependency(new DefaultExtensionDependency("org.xwiki.platform:xwiki-platform-sheet-api",
new DefaultVersionConstraint("[3.2,)")));
extension.addDependency(new DefaultExtensionDependency("org.xwiki.commons:xwiki-commons-diff-api",
new DefaultVersionConstraint("2.7")));
extension.addDependency(new DefaultExtensionDependency("org.xwiki.platform:xwiki-platform-display-api",
new DefaultVersionConstraint("100.1")));
getRepositoryTestUtils().addExtension(extension);
// Search the extension and assert the list of dependencies.
ExtensionAdministrationPage adminPage = ExtensionAdministrationPage.gotoPage().clickAddExtensionsSection();
ExtensionPane extensionPane =
adminPage.getSearchBar().clickAdvancedSearch().search(extensionId).getExtension(0);
ExtensionDependenciesPane dependenciesPane = extensionPane.openDependenciesSection();
List<DependencyPane> directDependencies = dependenciesPane.getDirectDependencies();
assertEquals(5, directDependencies.size());
assertEquals(dependency.getName(), directDependencies.get(0).getName());
assertEquals(dependencyId.getVersion().getValue(), directDependencies.get(0).getVersion());
assertEquals("remote", directDependencies.get(0).getStatus());
assertNull(directDependencies.get(0).getStatusMessage());
assertNull(directDependencies.get(1).getLink());
assertEquals("missing-dependency", directDependencies.get(1).getName());
assertEquals("135", directDependencies.get(1).getVersion());
assertEquals("unknown", directDependencies.get(1).getStatus());
assertNull(directDependencies.get(1).getStatusMessage());
assertNotNull(directDependencies.get(2).getLink());
assertEquals("XWiki Platform - Sheet - API", directDependencies.get(2).getName());
assertEquals("[3.2,)", directDependencies.get(2).getVersion());
assertEquals("core", directDependencies.get(2).getStatus());
assertEquals("Provided", directDependencies.get(2).getStatusMessage());
assertNotNull(directDependencies.get(3).getLink());
assertEquals("XWiki Commons - Diff API", directDependencies.get(3).getName());
assertEquals("2.7", directDependencies.get(3).getVersion());
assertEquals("remote-core", directDependencies.get(3).getStatus());
assertTrue(directDependencies.get(3).getStatusMessage().matches("Version [^\\s]+ is provided"));
assertEquals("XWiki Platform - Display API", directDependencies.get(4).getName());
assertEquals("100.1", directDependencies.get(4).getVersion());
assertEquals("remote-core-incompatible", directDependencies.get(4).getStatus());
assertTrue(directDependencies.get(4).getStatusMessage().matches("Incompatible with provided version [^\\s]+"));
assertTrue(dependenciesPane.getBackwardDependencies().isEmpty());
// Follow the link to a dependency.
directDependencies.get(0).getLink().click();
adminPage = new ExtensionAdministrationPage();
extensionPane = adminPage.getSearchResults().getExtension(0);
assertEquals(dependency.getName(), extensionPane.getName());
assertEquals(dependencyId.getVersion().getValue(), extensionPane.getVersion());
assertEquals(dependency.getSummary(), extensionPane.getSummary());
// Check that we are still in the administration.
adminPage.clickInstalledExtensionsSection();
}
/**
* Tests how an extension is installed.
*/
@Test
public void testInstall() throws Exception
{
// Setup the extension and its dependencies.
ExtensionId extensionId = new ExtensionId("alice-xar-extension", "1.3");
TestExtension extension = getRepositoryTestUtils().getTestExtension(extensionId, "xar");
ExtensionId dependencyId = new ExtensionId("bob-xar-extension", "2.5-milestone-2");
getRepositoryTestUtils().addExtension(getRepositoryTestUtils().getTestExtension(dependencyId, "xar"));
extension.addDependency(new DefaultExtensionDependency(dependencyId.getId(), new DefaultVersionConstraint(
dependencyId.getVersion().getValue())));
extension.addDependency(new DefaultExtensionDependency("org.xwiki.platform:xwiki-platform-sheet-api",
new DefaultVersionConstraint("[3.2,)")));
getRepositoryTestUtils().addExtension(extension);
// Search the extension and install it.
ExtensionAdministrationPage adminPage = ExtensionAdministrationPage.gotoPage().clickAddExtensionsSection();
ExtensionPane extensionPane =
adminPage.getSearchBar().clickAdvancedSearch().search(extensionId).getExtension(0);
extensionPane = extensionPane.install();
// Assert the install plan.
List<DependencyPane> installPlan = extensionPane.openProgressSection().getJobPlan();
assertEquals(2, installPlan.size());
assertEquals(dependencyId, installPlan.get(0).getId());
assertEquals(extensionId, installPlan.get(1).getId());
// Finish the install and assert the install log.
List<LogItemPane> log = extensionPane.confirm().openProgressSection().getJobLog();
int logSize = log.size();
assertTrue(logSize > 1);
assertEquals("info", log.get(0).getLevel());
assertEquals("Starting job of type [install] with identifier "
+ "[extension/action/alice-xar-extension/wiki:xwiki]", log.get(0).getMessage());
assertEquals("info", log.get(logSize - 1).getLevel());
assertEquals("Finished job of type [install] with identifier "
+ "[extension/action/alice-xar-extension/wiki:xwiki]", log.get(logSize - 1).getMessage());
// Test that both extensions are usable.
ViewPage viewPage = getUtil().createPage(getTestClassName(), getTestMethodName(), "{{alice/}}\n\n{{bob/}}", "");
String content = viewPage.getContent();
assertTrue(content.contains("Alice says hello!"));
assertTrue(content.contains("Bob says hi!"));
// Check the list of installed extensions.
adminPage = ExtensionAdministrationPage.gotoPage().clickInstalledExtensionsSection();
SearchResultsPane searchResults = adminPage.getSearchBar().search("bob");
assertEquals(1, searchResults.getDisplayedResultsCount());
extensionPane = searchResults.getExtension(0);
assertEquals("installed-dependency", extensionPane.getStatus());
assertEquals("Installed as dependency", extensionPane.getStatusMessage());
assertEquals(dependencyId, extensionPane.getId());
assertNotNull(extensionPane.getUninstallButton());
searchResults = new SimpleSearchPane().search("alice");
assertEquals(1, searchResults.getDisplayedResultsCount());
extensionPane = searchResults.getExtension(0);
assertEquals("installed", extensionPane.getStatus());
assertEquals("Installed", extensionPane.getStatusMessage());
assertEquals(extensionId, extensionPane.getId());
assertNotNull(extensionPane.getUninstallButton());
// Check if the progress log is persisted.
extensionPane = extensionPane.showDetails();
log = extensionPane.openProgressSection().getJobLog();
assertEquals(logSize, log.size());
assertEquals("info", log.get(0).getLevel());
assertEquals("Starting job of type [install] with identifier "
+ "[extension/action/alice-xar-extension/wiki:xwiki]", log.get(0).getMessage());
assertEquals("info", log.get(logSize - 1).getLevel());
assertEquals("Finished job of type [install] with identifier "
+ "[extension/action/alice-xar-extension/wiki:xwiki]", log.get(logSize - 1).getMessage());
// Check if the dependency is properly listed as installed.
List<DependencyPane> dependencies = extensionPane.openDependenciesSection().getDirectDependencies();
assertEquals(2, dependencies.size());
assertEquals(dependencyId, dependencies.get(0).getId());
assertEquals("installed-dependency", dependencies.get(0).getStatus());
assertEquals("Installed as dependency", dependencies.get(0).getStatusMessage());
// Check the backward dependency.
dependencies.get(0).getLink().click();
extensionPane = new ExtensionAdministrationPage().getSearchResults().getExtension(0);
dependencies = extensionPane.openDependenciesSection().getBackwardDependencies();
assertEquals(1, dependencies.size());
assertEquals(extensionId, dependencies.get(0).getId());
assertEquals("installed", dependencies.get(0).getStatus());
assertEquals("Installed", dependencies.get(0).getStatusMessage());
}
/**
* Tests how an extension is uninstalled.
*/
@Test
public void testUninstall() throws Exception
{
// Setup the extension and its dependencies.
ExtensionId dependencyId = new ExtensionId("bob-xar-extension", "2.5-milestone-2");
getRepositoryTestUtils().addExtension(getRepositoryTestUtils().getTestExtension(dependencyId, "xar"));
ExtensionId extensionId = new ExtensionId("alice-xar-extension", "1.3");
TestExtension extension = getRepositoryTestUtils().getTestExtension(extensionId, "xar");
extension.addDependency(new DefaultExtensionDependency(dependencyId.getId(), new DefaultVersionConstraint(
dependencyId.getVersion().getValue())));
getRepositoryTestUtils().addExtension(extension);
// Install the extensions.
getExtensionTestUtils().install(extensionId);
// Check if the installed pages are present.
assertTrue(getUtil().pageExists("ExtensionTest", "Alice"));
assertTrue(getUtil().pageExists("ExtensionTest", "Bob"));
// Uninstall the dependency.
ExtensionAdministrationPage adminPage =
ExtensionAdministrationPage.gotoPage().clickInstalledExtensionsSection();
ExtensionPane extensionPane =
adminPage.getSearchBar().clickAdvancedSearch().search(dependencyId).getExtension(0);
extensionPane = extensionPane.uninstall();
// Check the uninstall plan. Both extensions should be included.
List<DependencyPane> uninstallPlan = extensionPane.openProgressSection().getJobPlan();
assertEquals(2, uninstallPlan.size());
assertEquals(extensionId, uninstallPlan.get(0).getId());
assertEquals("installed", uninstallPlan.get(0).getStatus());
assertEquals("Installed", uninstallPlan.get(0).getStatusMessage());
assertEquals(dependencyId, uninstallPlan.get(1).getId());
assertEquals("installed-dependency", uninstallPlan.get(1).getStatus());
assertEquals("Installed as dependency", uninstallPlan.get(1).getStatusMessage());
// Check the confirmation to delete the unused wiki pages.
extensionPane = extensionPane.confirm();
UnusedPagesPane unusedPages = extensionPane.openProgressSection().getUnusedPages();
assertTrue(unusedPages.contains("ExtensionTest", "Alice"));
assertTrue(unusedPages.contains("ExtensionTest", "Bob"));
// Finish the uninstall and check the log.
extensionPane = extensionPane.confirm();
List<LogItemPane> log = extensionPane.openProgressSection().getJobLog();
assertTrue(log.size() > 2);
assertEquals("info", log.get(2).getLevel());
assertEquals("Resolving extension [bob-xar-extension 2.5-milestone-2] from namespace [Home]", log.get(2)
.getMessage());
assertEquals("info", log.get(log.size() - 1).getLevel());
assertEquals("Finished job of type [uninstall] with identifier "
+ "[extension/action/bob-xar-extension/wiki:xwiki]", log.get(log.size() - 1).getMessage());
// Check if the uninstalled pages have been deleted.
assertFalse(getUtil().pageExists("ExtensionTest", "Alice"));
assertFalse(getUtil().pageExists("ExtensionTest", "Bob"));
// Install both extension again and uninstall only the one with the dependency.
getExtensionTestUtils().install(extensionId);
adminPage = ExtensionAdministrationPage.gotoPage().clickInstalledExtensionsSection();
extensionPane = adminPage.getSearchBar().clickAdvancedSearch().search(extensionId).getExtension(0);
extensionPane = extensionPane.uninstall();
// Check the uninstall plan. Only one extension should be included.
uninstallPlan = extensionPane.openProgressSection().getJobPlan();
assertEquals(1, uninstallPlan.size());
assertEquals(extensionId, uninstallPlan.get(0).getId());
// Check the confirmation to delete the unused wiki pages.
extensionPane = extensionPane.confirm();
unusedPages = extensionPane.openProgressSection().getUnusedPages();
assertTrue(unusedPages.contains("ExtensionTest", "Alice"));
assertFalse(unusedPages.contains("ExtensionTest", "Bob"));
// Finish the uninstall and check the log.
log = extensionPane.confirm().openProgressSection().getJobLog();
assertTrue(log.size() > 2);
assertEquals("info", log.get(2).getLevel());
assertEquals("Resolving extension [alice-xar-extension 1.3] from namespace [Home]", log.get(2).getMessage());
assertEquals("info", log.get(log.size() - 1).getLevel());
assertEquals("Finished job of type [uninstall] with identifier "
+ "[extension/action/alice-xar-extension/wiki:xwiki]", log.get(log.size() - 1).getMessage());
// Check if the uninstalled pages have been deleted.
assertFalse(getUtil().pageExists("ExtensionTest", "Alice"));
assertTrue(getUtil().pageExists("ExtensionTest", "Bob"));
// Check the list of installed extensions. It should contain only the second extension.
adminPage = ExtensionAdministrationPage.gotoPage().clickInstalledExtensionsSection();
SearchResultsPane searchResults = adminPage.getSearchBar().search("alice");
assertEquals(0, searchResults.getDisplayedResultsCount());
assertNotNull(searchResults.getNoResultsMessage());
searchResults = new SimpleSearchPane().search("bob");
assertEquals(1, searchResults.getDisplayedResultsCount());
extensionPane = searchResults.getExtension(0);
assertEquals("installed-dependency", extensionPane.getStatus());
assertEquals(dependencyId, extensionPane.getId());
}
/**
* Tests that an extension can be installed and uninstalled without reloading the extension manager UI.
*/
@Test
public void testInstallAndUninstallWithoutReload() throws Exception
{
// Setup the extension.
ExtensionId extensionId = new ExtensionId("alice-xar-extension", "1.3");
getRepositoryTestUtils().addExtension(getRepositoryTestUtils().getTestExtension(extensionId, "xar"));
// Search the extension to install.
ExtensionAdministrationPage adminPage = ExtensionAdministrationPage.gotoPage().clickAddExtensionsSection();
ExtensionPane extensionPane =
adminPage.getSearchBar().clickAdvancedSearch().search(extensionId).getExtension(0);
// Install and uninstall.
extensionPane = extensionPane.install().confirm().uninstall().confirm().confirm().install();
assertEquals("remote", extensionPane.getStatus());
}
/**
* Tests how an extension is upgraded.
*/
@Test
public void testUpgrade() throws Exception
{
// Setup the extension.
String extensionId = "alice-xar-extension";
String oldVersion = "1.3";
String newVersion = "2.1.4";
TestExtension oldExtension =
getRepositoryTestUtils().getTestExtension(new ExtensionId(extensionId, oldVersion), "xar");
getRepositoryTestUtils().addExtension(oldExtension);
TestExtension newExtension =
getRepositoryTestUtils().getTestExtension(new ExtensionId(extensionId, newVersion), "xar");
getRepositoryTestUtils().attachFile(newExtension);
getRepositoryTestUtils().addVersionObject(newExtension, newVersion,
"attach:" + newExtension.getFile().getName());
// Make sure the old version is installed.
getExtensionTestUtils().install(new ExtensionId(extensionId, oldVersion));
// Upgrade the extension.
ExtensionAdministrationPage adminPage = ExtensionAdministrationPage.gotoPage().clickAddExtensionsSection();
ExtensionPane extensionPane =
adminPage.getSearchBar().clickAdvancedSearch().search(extensionId, newVersion).getExtension(0);
assertEquals("remote-installed", extensionPane.getStatus());
assertEquals("Version 1.3 is installed", extensionPane.getStatusMessage());
extensionPane = extensionPane.upgrade();
// Check the upgrade plan.
List<DependencyPane> upgradePlan = extensionPane.openProgressSection().getJobPlan();
assertEquals(1, upgradePlan.size());
assertEquals(extensionId, upgradePlan.get(0).getName());
assertEquals(newVersion, upgradePlan.get(0).getVersion());
assertEquals("remote-installed", upgradePlan.get(0).getStatus());
assertEquals("Version 1.3 is installed", upgradePlan.get(0).getStatusMessage());
// Finish the upgrade and check the upgrade log.
extensionPane = extensionPane.confirm();
assertEquals("installed", extensionPane.getStatus());
assertEquals("Installed", extensionPane.getStatusMessage());
List<LogItemPane> log = extensionPane.openProgressSection().getJobLog();
assertTrue(log.size() > 2);
assertEquals("info", log.get(2).getLevel());
assertEquals("Resolving extension [alice-xar-extension 2.1.4] on namespace [Home]", log.get(2).getMessage());
assertEquals("info", log.get(log.size() - 1).getLevel());
assertEquals("Finished job of type [install] with identifier "
+ "[extension/action/alice-xar-extension/wiki:xwiki]", log.get(log.size() - 1).getMessage());
// Assert the changes.
ViewPage viewPage = getUtil().gotoPage("ExtensionTest", "Alice");
assertEquals("Alice Wiki Macro (upgraded)", viewPage.getDocumentTitle());
assertTrue(viewPage.getContent().contains("Alice says hi guys!"));
}
/**
* Tests how an extension is upgraded when there is a merge conflict.
*/
@Test
public void testUpgradeWithMergeConflict() throws Exception
{
// Setup the extension.
String extensionId = "alice-xar-extension";
String oldVersion = "1.3";
String newVersion = "2.1.4";
TestExtension oldExtension =
getRepositoryTestUtils().getTestExtension(new ExtensionId(extensionId, oldVersion), "xar");
getRepositoryTestUtils().addExtension(oldExtension);
TestExtension newExtension =
getRepositoryTestUtils().getTestExtension(new ExtensionId(extensionId, newVersion), "xar");
getRepositoryTestUtils().attachFile(newExtension);
getRepositoryTestUtils().addVersionObject(newExtension, newVersion,
"attach:" + newExtension.getFile().getName());
// Make sure the old version is installed.
getExtensionTestUtils().install(new ExtensionId(extensionId, oldVersion));
// Edit the installed version so that we have a merge conflict.
Map<String, String> queryParameters = new HashMap<String, String>();
queryParameters.put("title", "Alice Extension");
queryParameters.put("content", "== Usage ==\n\n{{code language=\"none\"}}\n"
+ "{{alice/}}\n{{/code}}\n\n== Output ==\n\n{{alice/}}");
queryParameters.put("XWiki.WikiMacroClass_0_code", "{{info}}Alice says hello!{{/info}}");
getUtil().gotoPage("ExtensionTest", "Alice", "save", queryParameters);
// Initiate the upgrade process.
ExtensionAdministrationPage adminPage = ExtensionAdministrationPage.gotoPage().clickAddExtensionsSection();
SearchResultsPane searchResults =
adminPage.getSearchBar().clickAdvancedSearch().search(extensionId, newVersion);
ExtensionPane extensionPane = searchResults.getExtension(0);
extensionPane = extensionPane.upgrade().confirm();
// Check the merge conflict UI.
assertEquals("loading", extensionPane.getStatus());
assertNull(extensionPane.getStatusMessage());
ProgressBarPane progressBar = extensionPane.getProgressBar();
assertEquals(66, progressBar.getPercent());
assertEquals("Conflict between [@@ -1,1 +1,1 @@] and [@@ -1,1 +1,1 @@]", progressBar.getMessage());
ExtensionProgressPane progressPane = extensionPane.openProgressSection();
WebElement jobLogLabel = progressPane.getJobLogLabel();
assertEquals("INSTALL LOG".toLowerCase(), jobLogLabel.getText().toLowerCase());
// The job log is collapsed when the job is waiting for user input so we need to expand it before asserting its
// content (otherwise #getText() returns the empty string because the text is not visible).
jobLogLabel.click();
List<LogItemPane> upgradeLog = progressPane.getJobLog();
LogItemPane lastLogItem = upgradeLog.get(upgradeLog.size() - 1);
assertEquals("loading", lastLogItem.getLevel());
assertEquals(progressBar.getMessage(), lastLogItem.getMessage());
MergeConflictPane mergeConflictPane = progressPane.getMergeConflict();
ChangesPane changesPane = mergeConflictPane.getChanges();
assertEquals(Arrays.asList("Page properties", "XWiki.WikiMacroClass[0]"), changesPane.getChangedEntities());
EntityDiff pagePropertiesDiff = changesPane.getEntityDiff("Page properties");
assertEquals(Arrays.asList("Parent", "Content"), pagePropertiesDiff.getPropertyNames());
assertFalse(pagePropertiesDiff.getDiff("Content").isEmpty());
EntityDiff macroDiff = changesPane.getEntityDiff("XWiki.WikiMacroClass[0]");
assertEquals(Arrays.asList("Macro description"), macroDiff.getPropertyNames());
assertEquals(
Arrays.asList("@@ -1,1 +1,1 @@", "-<del>Test</del> macro.", "+<ins>A</ins> <ins>cool </ins>macro."),
macroDiff.getDiff("Macro description"));
mergeConflictPane.getFromVersionSelect().selectByVisibleText("Previous version");
mergeConflictPane.getToVersionSelect().selectByVisibleText("Current version");
mergeConflictPane = mergeConflictPane.clickShowChanges();
changesPane = mergeConflictPane.getChanges();
List<String> expectedDiff = new ArrayList<>();
expectedDiff.add("@@ -1,9 +1,9 @@");
expectedDiff.add("-= Usage =");
expectedDiff.add("+=<ins>=</ins> Usage =<ins>=</ins>");
expectedDiff.add(" ");
expectedDiff.add("-{{code}}");
expectedDiff.add("+{{code<ins> language=\"none\"</ins>}}");
expectedDiff.add(" {{alice/}}");
expectedDiff.add(" {{/code}}");
expectedDiff.add(" ");
expectedDiff.add("-= <del>Res</del>u<del>l</del>t =");
expectedDiff.add("+=<ins>=</ins> <ins>O</ins>ut<ins>put</ins> =<ins>=</ins>");
expectedDiff.add(" ");
expectedDiff.add(" {{alice/}}");
assertEquals(expectedDiff, changesPane.getEntityDiff("Page properties").getDiff("Content"));
assertEquals(1, changesPane.getDiffSummary().toggleObjectsDetails().getModifiedObjects().size());
assertEquals(Arrays.asList("@@ -1,1 +1,1 @@", "-Alice says hello!",
"+<ins>{{info}}</ins>Alice says hello!<ins>{{/info}}</ins>"),
changesPane.getEntityDiff("XWiki.WikiMacroClass[0]").getDiff("Macro code"));
// Finish the merge.
mergeConflictPane.getVersionToKeepSelect().selectByValue("NEXT");
// FIXME: We get the extension pane from the search results because it is reloaded when we compare the versions.
extensionPane = searchResults.getExtension(0).confirm();
assertEquals("installed", extensionPane.getStatus());
assertNull(extensionPane.getProgressBar());
upgradeLog = extensionPane.openProgressSection().getJobLog();
lastLogItem = upgradeLog.get(upgradeLog.size() - 1);
assertEquals("info", lastLogItem.getLevel());
assertEquals("Finished job of type [install] with identifier "
+ "[extension/action/alice-xar-extension/wiki:xwiki]", lastLogItem.getMessage());
// Check the merge result.
ViewPage mergedPage = getUtil().gotoPage("ExtensionTest", "Alice");
assertEquals("Alice Wiki Macro (upgraded)", mergedPage.getDocumentTitle());
}
/**
* Tests how an extension is downgraded.
*/
@Test
public void testDowngrade() throws Exception
{
// Setup the extension.
String extensionId = "alice-xar-extension";
String oldVersion = "1.3";
String newVersion = "2.1.4";
TestExtension oldExtension =
getRepositoryTestUtils().getTestExtension(new ExtensionId(extensionId, oldVersion), "xar");
getRepositoryTestUtils().addExtension(oldExtension);
TestExtension newExtension =
getRepositoryTestUtils().getTestExtension(new ExtensionId(extensionId, newVersion), "xar");
getRepositoryTestUtils().attachFile(newExtension);
getRepositoryTestUtils().addVersionObject(newExtension, newVersion,
"attach:" + newExtension.getFile().getName());
// Make sure the new version is installed.
getExtensionTestUtils().install(new ExtensionId(extensionId, newVersion));
// Downgrade the extension.
ExtensionAdministrationPage adminPage = ExtensionAdministrationPage.gotoPage().clickAddExtensionsSection();
ExtensionPane extensionPane =
adminPage.getSearchBar().clickAdvancedSearch().search(extensionId, oldVersion).getExtension(0);
assertEquals("remote-installed", extensionPane.getStatus());
assertEquals("Version 2.1.4 is installed", extensionPane.getStatusMessage());
extensionPane = extensionPane.downgrade();
// Check the downgrade plan.
List<DependencyPane> downgradePlan = extensionPane.openProgressSection().getJobPlan();
assertEquals(1, downgradePlan.size());
assertEquals(extensionId, downgradePlan.get(0).getName());
assertEquals(oldVersion, downgradePlan.get(0).getVersion());
assertEquals("remote-installed", downgradePlan.get(0).getStatus());
assertEquals("Version 2.1.4 is installed", downgradePlan.get(0).getStatusMessage());
// Finish the downgrade and check the downgrade log.
extensionPane = extensionPane.confirm();
assertEquals("installed", extensionPane.getStatus());
assertEquals("Installed", extensionPane.getStatusMessage());
List<LogItemPane> log = extensionPane.openProgressSection().getJobLog();
assertTrue(log.size() > 2);
assertEquals("info", log.get(2).getLevel());
assertEquals("Resolving extension [alice-xar-extension 1.3] on namespace [Home]", log.get(2).getMessage());
assertEquals("info", log.get(log.size() - 1).getLevel());
assertEquals("Finished job of type [install] with identifier "
+ "[extension/action/alice-xar-extension/wiki:xwiki]", log.get(log.size() - 1).getMessage());
// Assert the changes.
ViewPage viewPage = getUtil().gotoPage("ExtensionTest", "Alice");
assertEquals("Alice Macro", viewPage.getDocumentTitle());
assertTrue(viewPage.getContent().contains("Alice says hello!"));
}
/**
* Tests if a Java component script service is properly installed.
*/
@Test
public void testInstallScriptService() throws Exception
{
// Make sure the script service is not available before the extension is installed.
ViewPage viewPage =
getUtil().createPage(
getTestClassName(),
getTestMethodName(),
"{{velocity}}$services.greeter.greet('world') "
+ "$services.greeter.greet('XWiki', 'default'){{/velocity}}", "");
assertFalse(viewPage.getContent().contains("Hello world! Hello XWiki!"));
// Setup the extension.
ExtensionId extensionId = new ExtensionId("scriptServiceJarExtension", "4.2-milestone-1");
TestExtension extension = getRepositoryTestUtils().getTestExtension(extensionId, "jar");
getRepositoryTestUtils().addExtension(extension);
// Search the extension and install it.
ExtensionAdministrationPage adminPage = ExtensionAdministrationPage.gotoPage().clickAddExtensionsSection();
ExtensionPane extensionPane =
adminPage.getSearchBar().clickAdvancedSearch().search(extensionId).getExtension(0);
extensionPane.install().confirm();
// Check the result.
assertEquals("Hello world! Hello XWiki!", getUtil().gotoPage(getTestClassName(), getTestMethodName())
.getContent());
}
}
|
xwiki-platform-core/xwiki-platform-extension/xwiki-platform-extension-test/xwiki-platform-extension-test-tests/src/test/it/org/xwiki/test/ui/extension/ExtensionTest.java
|
/*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.xwiki.test.ui.extension;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.math.RandomUtils;
import org.junit.Test;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.Select;
import org.xwiki.extension.DefaultExtensionAuthor;
import org.xwiki.extension.DefaultExtensionDependency;
import org.xwiki.extension.DefaultExtensionIssueManagement;
import org.xwiki.extension.DefaultExtensionScm;
import org.xwiki.extension.DefaultExtensionScmConnection;
import org.xwiki.extension.ExtensionId;
import org.xwiki.extension.ExtensionLicense;
import org.xwiki.extension.repository.xwiki.model.jaxb.ExtensionsSearchResult;
import org.xwiki.extension.test.po.AdvancedSearchPane;
import org.xwiki.extension.test.po.DependencyPane;
import org.xwiki.extension.test.po.ExtensionAdministrationPage;
import org.xwiki.extension.test.po.ExtensionDependenciesPane;
import org.xwiki.extension.test.po.ExtensionDescriptionPane;
import org.xwiki.extension.test.po.ExtensionPane;
import org.xwiki.extension.test.po.ExtensionProgressPane;
import org.xwiki.extension.test.po.LogItemPane;
import org.xwiki.extension.test.po.MergeConflictPane;
import org.xwiki.extension.test.po.PaginationFilterPane;
import org.xwiki.extension.test.po.ProgressBarPane;
import org.xwiki.extension.test.po.SearchResultsPane;
import org.xwiki.extension.test.po.SimpleSearchPane;
import org.xwiki.extension.test.po.UnusedPagesPane;
import org.xwiki.extension.version.internal.DefaultVersionConstraint;
import org.xwiki.repository.test.TestExtension;
import org.xwiki.test.ui.AbstractExtensionAdminAuthenticatedTest;
import org.xwiki.test.ui.po.ChangesPane;
import org.xwiki.test.ui.po.ViewPage;
import org.xwiki.test.ui.po.diff.EntityDiff;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
/**
* Functional tests for the Extension Manager user interface.
*
* @version $Id$
* @since 4.2M1
*/
public class ExtensionTest extends AbstractExtensionAdminAuthenticatedTest
{
@Override
public void setUp() throws Exception
{
super.setUp();
// Make sure the extensions we are playing with are not already installed.
getExtensionTestUtils().finishCurrentJob();
getExtensionTestUtils().uninstall("alice-xar-extension");
getExtensionTestUtils().uninstall("bob-xar-extension");
getExtensionTestUtils().uninstall("scriptServiceJarExtension");
// Delete the pages that are provided by the XAR extensions we use in tests.
getUtil().rest().deletePage("ExtensionTest", "Alice");
assertFalse(getUtil().pageExists("ExtensionTest", "Alice"));
getUtil().rest().deletePage("ExtensionTest", "Bob");
assertFalse(getUtil().pageExists("ExtensionTest", "Bob"));
// Delete from the repository the XAR extensions we use in tests.
// The extension page name is either the extension name, if specified, or the extension id. Most of the tests
// don't set the extension name but some do and we end up with two extensions (two pages) with the same id.
getRepositoryTestUtils().deleteExtension("Alice Wiki Macro");
getRepositoryTestUtils().deleteExtension("Bob Wiki Macro");
getRepositoryTestUtils().deleteExtension("alice-xar-extension");
getRepositoryTestUtils().deleteExtension("bob-xar-extension");
getRepositoryTestUtils().deleteExtension("scriptServiceJarExtension");
getRepositoryTestUtils().waitUntilReady();
// Double check that the XWiki Extension Repository is empty.
ExtensionsSearchResult searchResult =
getUtil().rest().getResource("repository/search", Collections.singletonMap("number", new Object[] {1}));
assertEquals(0, searchResult.getTotalHits());
}
/**
* The extension search results pagination.
*/
@Test
public void testPagination()
{
ExtensionAdministrationPage adminPage = ExtensionAdministrationPage.gotoPage().clickCoreExtensionsSection();
SearchResultsPane searchResults = adminPage.getSearchResults();
assertNull(searchResults.getNoResultsMessage());
assertEquals(20, searchResults.getDisplayedResultsCount());
PaginationFilterPane pagination = searchResults.getPagination();
assertEquals(1 + pagination.getResultsCount() / 20, pagination.getPageCount());
assertEquals("1 - 20", pagination.getCurrentRange());
assertEquals(1, pagination.getCurrentPageIndex());
assertFalse(pagination.hasPreviousPage());
assertTrue(pagination.hasNextPage());
assertTrue(pagination.getPageCount() > 5);
assertTrue(pagination.getResultsCount() > 100);
String firstExtensionName = searchResults.getExtension(0).getName();
pagination = pagination.gotoPage(4);
searchResults = new SearchResultsPane();
assertEquals(20, searchResults.getDisplayedResultsCount());
assertEquals("61 - 80", pagination.getCurrentRange());
assertEquals(4, pagination.getCurrentPageIndex());
assertTrue(pagination.hasNextPage());
String secondExtensionName = searchResults.getExtension(0).getName();
assertFalse(firstExtensionName.equals(secondExtensionName));
pagination = pagination.previousPage();
searchResults = new SearchResultsPane();
assertEquals(20, searchResults.getDisplayedResultsCount());
assertEquals("41 - 60", pagination.getCurrentRange());
assertEquals(3, pagination.getCurrentPageIndex());
String thirdExtensionName = searchResults.getExtension(0).getName();
assertFalse(firstExtensionName.equals(thirdExtensionName));
assertFalse(secondExtensionName.equals(thirdExtensionName));
pagination = pagination.nextPage();
searchResults = new SearchResultsPane();
assertEquals(20, searchResults.getDisplayedResultsCount());
assertEquals("61 - 80", pagination.getCurrentRange());
assertEquals(4, pagination.getCurrentPageIndex());
assertEquals(secondExtensionName, searchResults.getExtension(0).getName());
pagination = pagination.gotoPage(pagination.getPageCount());
searchResults = new SearchResultsPane();
assertEquals(pagination.getResultsCount() % 20, searchResults.getDisplayedResultsCount());
assertEquals(pagination.getPageCount(), pagination.getCurrentPageIndex());
assertFalse(pagination.hasNextPage());
assertTrue(pagination.hasPreviousPage());
}
/**
* Tests the simple search form.
*/
@Test
public void testSimpleSearch()
{
ExtensionAdministrationPage adminPage = ExtensionAdministrationPage.gotoPage().clickCoreExtensionsSection();
int coreExtensionCount = adminPage.getSearchResults().getPagination().getResultsCount();
SimpleSearchPane searchBar = adminPage.getSearchBar();
// Check if the tip is displayed.
assertEquals("search extension...", searchBar.getSearchInput().getAttribute("placeholder"));
// Check that the input is empty
assertEquals("", searchBar.getSearchInput().getAttribute("value"));
SearchResultsPane searchResults = searchBar.search("XWiki Commons");
assertTrue(searchResults.getPagination().getResultsCount() < coreExtensionCount);
// Make sure the search input is not cleared.
searchBar = new SimpleSearchPane();
assertEquals("XWiki Commons", searchBar.getSearchInput().getAttribute("value"));
assertNull(searchResults.getNoResultsMessage());
// Check that the result matches the search query.
ExtensionPane extension = searchResults.getExtension(RandomUtils.nextInt(20));
assertTrue(extension.getName().toLowerCase().contains("commons"));
assertEquals("core", extension.getStatus());
// Test search query with no results.
searchResults = new SimpleSearchPane().search("blahblah");
assertEquals(0, searchResults.getDisplayedResultsCount());
assertNull(searchResults.getPagination());
assertEquals("There were no extensions found matching 'blahblah'. Try different keywords. "
+ "Alternatively, if you know the identifier and the version of the extension you're "
+ "looking for, you can use the Advanced Search form above.", searchResults.getNoResultsMessage());
// Test a search query with only a few results (only one page).
searchResults = searchBar.search("restlet");
assertNull(searchResults.getNoResultsMessage());
assertNull(searchResults.getPagination());
assertTrue(searchResults.getDisplayedResultsCount() > 1);
extension = searchResults.getExtension(0);
assertEquals("core", extension.getStatus());
assertTrue(extension.getName().toLowerCase().contains("restlet"));
}
/**
* Tests the advanced search form.
*/
@Test
public void testAdvancedSearch()
{
ExtensionAdministrationPage adminPage = ExtensionAdministrationPage.gotoPage().clickCoreExtensionsSection();
SearchResultsPane searchResults = adminPage.getSearchBar().search("restlet");
String version = searchResults.getExtension(0).getVersion();
searchResults = new SimpleSearchPane().clickAdvancedSearch().search("org.restlet.jse:org.restlet", version);
assertEquals(1, searchResults.getDisplayedResultsCount());
assertNull(searchResults.getNoResultsMessage());
ExtensionPane extension = searchResults.getExtension(0);
assertEquals("core", extension.getStatus());
assertTrue(extension.getName().toLowerCase().contains("restlet"));
assertEquals(version, extension.getVersion());
searchResults = new SimpleSearchPane().clickAdvancedSearch().search("foo", "bar");
assertEquals(0, searchResults.getDisplayedResultsCount());
assertNull(searchResults.getPagination());
assertEquals("We couldn't find any extension with id 'foo' and version 'bar'. "
+ "Make sure you have the right extension repositories configured.", searchResults.getNoResultsMessage());
// Test cancel advanced search.
AdvancedSearchPane advancedSearchPane = new SimpleSearchPane().clickAdvancedSearch();
advancedSearchPane.getIdInput().sendKeys("id");
assertTrue(advancedSearchPane.getVersionInput().isDisplayed());
advancedSearchPane.getCancelButton().click();
assertFalse(advancedSearchPane.getVersionInput().isDisplayed());
}
/**
* Tests how core extensions are displayed.
*/
@Test
public void testCoreExtensions()
{
ExtensionAdministrationPage adminPage = ExtensionAdministrationPage.gotoPage().clickCoreExtensionsSection();
// Assert that the core extension repository is selected.
SimpleSearchPane searchBar = adminPage.getSearchBar();
assertEquals("Core extensions", searchBar.getRepositorySelect().getFirstSelectedOption().getText());
ExtensionPane extension = adminPage.getSearchResults().getExtension(RandomUtils.nextInt(20));
assertEquals("core", extension.getStatus());
assertEquals("Provided", extension.getStatusMessage());
assertNull(extension.getInstallButton());
assertNull(extension.getUninstallButton());
assertNull(extension.getUpgradeButton());
assertNull(extension.getDowngradeButton());
// Just test that the button to show the extension details is present.
assertEquals("core", extension.showDetails().getStatus());
}
/**
* Tests the extension repository selector (all, core, installed, local).
*/
@Test
public void testRepositorySelector() throws Exception
{
// Setup the extension.
ExtensionId extensionId = new ExtensionId("alice-xar-extension", "1.3");
TestExtension extension = getRepositoryTestUtils().getTestExtension(extensionId, "xar");
getRepositoryTestUtils().addExtension(extension);
getRepositoryTestUtils().waitUntilReady();
// Check if the section links point to the right repository.
ExtensionAdministrationPage adminPage = ExtensionAdministrationPage.gotoPage().clickAddExtensionsSection();
Select repositorySelect = adminPage.getSearchBar().getRepositorySelect();
assertEquals("All Extensions", repositorySelect.getFirstSelectedOption().getText());
adminPage = adminPage.clickCoreExtensionsSection();
repositorySelect = adminPage.getSearchBar().getRepositorySelect();
assertEquals("Core extensions", repositorySelect.getFirstSelectedOption().getText());
adminPage = adminPage.clickInstalledExtensionsSection();
repositorySelect = adminPage.getSearchBar().getRepositorySelect();
assertEquals("Installed extensions", repositorySelect.getFirstSelectedOption().getText());
// Check that a remote extension appears only in the list of "All Extensions".
SearchResultsPane searchResults = adminPage.getSearchBar().search("alice");
assertNull(searchResults.getExtension(extensionId));
new SimpleSearchPane().getRepositorySelect().selectByVisibleText("All Extensions");
adminPage = new ExtensionAdministrationPage();
adminPage.waitUntilPageIsLoaded();
// The value of the search input must be preserved when we switch the repository.
assertEquals("alice", adminPage.getSearchBar().getSearchInput().getAttribute("value"));
assertNotNull(adminPage.getSearchResults().getExtension(extensionId));
assertNull(new SimpleSearchPane().selectRepository("local").getExtension(extensionId));
// Check that an installed extension appears also in "Installed Extensions" and "Local Extensions".
getExtensionTestUtils().install(extensionId);
adminPage = ExtensionAdministrationPage.gotoPage().clickInstalledExtensionsSection();
searchResults = adminPage.getSearchBar().search("alice");
assertNotNull(searchResults.getExtension(extensionId));
assertNotNull(new SimpleSearchPane().selectRepository("local").getExtension(extensionId));
assertNotNull(new SimpleSearchPane().selectRepository("").getExtension(extensionId));
// Check local extension.
getExtensionTestUtils().uninstall(extensionId.getId(), true);
adminPage = ExtensionAdministrationPage.gotoPage().clickInstalledExtensionsSection();
searchResults = adminPage.getSearchBar().search("alice");
assertNull(searchResults.getExtension(extensionId));
assertNotNull(new SimpleSearchPane().selectRepository("local").getExtension(extensionId));
assertNotNull(new SimpleSearchPane().selectRepository("").getExtension(extensionId));
}
/**
* Tests the extension details (license, web site).
*/
@Test
public void testShowDetails() throws Exception
{
// Setup the extension.
ExtensionId extensionId = new ExtensionId("alice-xar-extension", "1.3");
TestExtension extension = getRepositoryTestUtils().getTestExtension(extensionId, "xar");
extension.setName("Alice Wiki Macro");
extension.setSummary("A **useless** macro");
extension.addAuthor(new DefaultExtensionAuthor("Thomas", null));
extension.addAuthor(new DefaultExtensionAuthor("Marius", null));
extension.addFeature("alice-extension");
extension.addLicense(new ExtensionLicense("My own license", null));
extension.setWebsite("http://www.alice.com");
extension.setScm(new DefaultExtensionScm("https://github.com/xwiki-contrib/alice-xar-extension",
new DefaultExtensionScmConnection("git", "git://github.com/xwiki-contrib/alice-xar-extension.git"),
new DefaultExtensionScmConnection("git", "git:git@github.com:xwiki-contrib/alice-xar-extension.git")));
extension.setIssueManagement(new DefaultExtensionIssueManagement("jira", "http://jira.xwiki.org/browse/ALICE"));
getRepositoryTestUtils().addExtension(extension);
// Search the extension and assert the displayed information.
ExtensionAdministrationPage adminPage = ExtensionAdministrationPage.gotoPage().clickAddExtensionsSection();
ExtensionPane extensionPane =
adminPage.getSearchBar().clickAdvancedSearch().search(extensionId).getExtension(0);
assertEquals("remote", extensionPane.getStatus());
assertNull(extensionPane.getStatusMessage());
assertEquals(extension.getName(), extensionPane.getName());
assertEquals(extensionId.getVersion().getValue(), extensionPane.getVersion());
List<WebElement> authors = extensionPane.getAuthors();
assertEquals(2, authors.size());
assertEquals("Thomas", authors.get(0).getText());
assertEquals("Marius", authors.get(1).getText());
assertEquals(extension.getSummary(), extensionPane.getSummary());
// Check the extension details.
ExtensionDescriptionPane descriptionPane = extensionPane.openDescriptionSection();
assertEquals(extension.getLicenses().iterator().next().getName(), descriptionPane.getLicense());
assertEquals(extension.getId().getId(), descriptionPane.getId());
assertEquals(extension.getFeatures().iterator().next(), descriptionPane.getFeatures().get(0));
assertEquals(extension.getType(), descriptionPane.getType());
WebElement webSiteLink = descriptionPane.getWebSite();
assertEquals(extension.getWebSite().substring("http://".length()), webSiteLink.getText());
assertEquals(extension.getWebSite() + '/', webSiteLink.getAttribute("href"));
// Install the extension to check the details that are specific to installed extensions.
Date beforeInstall = new Date();
descriptionPane = extensionPane.install().confirm().openDescriptionSection();
Date afterInstall = new Date();
List<String> namespaces = descriptionPane.getNamespaces();
assertEquals(1, namespaces.size());
String prefix = "Home, by superadmin on ";
assertTrue(namespaces.get(0).startsWith(prefix));
Date installDate = new SimpleDateFormat("yyyy/MM/dd HH:mm").parse(namespaces.get(0).substring(prefix.length()));
// Ignore the seconds as they are not displayed.
assertTrue(String.format("Install date [%s] should be after [%s].", installDate, beforeInstall),
installDate.getTime() / 60000 >= beforeInstall.getTime() / 60000);
assertTrue(String.format("Install date [%s] should be before [%s].", installDate, afterInstall),
installDate.before(afterInstall));
}
/**
* Tests how extension dependencies are displayed (both direct and backward dependencies).
*/
@Test
public void testDependencies() throws Exception
{
// Setup the extension and its dependencies.
ExtensionId dependencyId = new ExtensionId("bob-xar-extension", "2.5-milestone-2");
TestExtension dependency = getRepositoryTestUtils().getTestExtension(dependencyId, "xar");
dependency.setName("Bob Wiki Macro");
dependency.setSummary("Required by Alice");
getRepositoryTestUtils().addExtension(dependency);
ExtensionId extensionId = new ExtensionId("alice-xar-extension", "1.3");
TestExtension extension = getRepositoryTestUtils().getTestExtension(extensionId, "xar");
extension.addDependency(new DefaultExtensionDependency(dependencyId.getId(), new DefaultVersionConstraint(
dependencyId.getVersion().getValue())));
extension.addDependency(new DefaultExtensionDependency("missing-dependency",
new DefaultVersionConstraint("135")));
extension.addDependency(new DefaultExtensionDependency("org.xwiki.platform:xwiki-platform-sheet-api",
new DefaultVersionConstraint("[3.2,)")));
extension.addDependency(new DefaultExtensionDependency("org.xwiki.commons:xwiki-commons-diff-api",
new DefaultVersionConstraint("2.7")));
extension.addDependency(new DefaultExtensionDependency("org.xwiki.platform:xwiki-platform-display-api",
new DefaultVersionConstraint("100.1")));
getRepositoryTestUtils().addExtension(extension);
// Search the extension and assert the list of dependencies.
ExtensionAdministrationPage adminPage = ExtensionAdministrationPage.gotoPage().clickAddExtensionsSection();
ExtensionPane extensionPane =
adminPage.getSearchBar().clickAdvancedSearch().search(extensionId).getExtension(0);
ExtensionDependenciesPane dependenciesPane = extensionPane.openDependenciesSection();
List<DependencyPane> directDependencies = dependenciesPane.getDirectDependencies();
assertEquals(5, directDependencies.size());
assertEquals(dependency.getName(), directDependencies.get(0).getName());
assertEquals(dependencyId.getVersion().getValue(), directDependencies.get(0).getVersion());
assertEquals("remote", directDependencies.get(0).getStatus());
assertNull(directDependencies.get(0).getStatusMessage());
assertNull(directDependencies.get(1).getLink());
assertEquals("missing-dependency", directDependencies.get(1).getName());
assertEquals("135", directDependencies.get(1).getVersion());
assertEquals("unknown", directDependencies.get(1).getStatus());
assertNull(directDependencies.get(1).getStatusMessage());
assertNotNull(directDependencies.get(2).getLink());
assertEquals("XWiki Platform - Sheet - API", directDependencies.get(2).getName());
assertEquals("[3.2,)", directDependencies.get(2).getVersion());
assertEquals("core", directDependencies.get(2).getStatus());
assertEquals("Provided", directDependencies.get(2).getStatusMessage());
assertNotNull(directDependencies.get(3).getLink());
assertEquals("XWiki Commons - Diff API", directDependencies.get(3).getName());
assertEquals("2.7", directDependencies.get(3).getVersion());
assertEquals("remote-core", directDependencies.get(3).getStatus());
assertTrue(directDependencies.get(3).getStatusMessage().matches("Version [^\\s]+ is provided"));
assertEquals("XWiki Platform - Display API", directDependencies.get(4).getName());
assertEquals("100.1", directDependencies.get(4).getVersion());
assertEquals("remote-core-incompatible", directDependencies.get(4).getStatus());
assertTrue(directDependencies.get(4).getStatusMessage().matches("Incompatible with provided version [^\\s]+"));
assertTrue(dependenciesPane.getBackwardDependencies().isEmpty());
// Follow the link to a dependency.
directDependencies.get(0).getLink().click();
adminPage = new ExtensionAdministrationPage();
extensionPane = adminPage.getSearchResults().getExtension(0);
assertEquals(dependency.getName(), extensionPane.getName());
assertEquals(dependencyId.getVersion().getValue(), extensionPane.getVersion());
assertEquals(dependency.getSummary(), extensionPane.getSummary());
// Check that we are still in the administration.
adminPage.clickInstalledExtensionsSection();
}
/**
* Tests how an extension is installed.
*/
@Test
public void testInstall() throws Exception
{
// Setup the extension and its dependencies.
ExtensionId extensionId = new ExtensionId("alice-xar-extension", "1.3");
TestExtension extension = getRepositoryTestUtils().getTestExtension(extensionId, "xar");
ExtensionId dependencyId = new ExtensionId("bob-xar-extension", "2.5-milestone-2");
getRepositoryTestUtils().addExtension(getRepositoryTestUtils().getTestExtension(dependencyId, "xar"));
extension.addDependency(new DefaultExtensionDependency(dependencyId.getId(), new DefaultVersionConstraint(
dependencyId.getVersion().getValue())));
extension.addDependency(new DefaultExtensionDependency("org.xwiki.platform:xwiki-platform-sheet-api",
new DefaultVersionConstraint("[3.2,)")));
getRepositoryTestUtils().addExtension(extension);
// Search the extension and install it.
ExtensionAdministrationPage adminPage = ExtensionAdministrationPage.gotoPage().clickAddExtensionsSection();
ExtensionPane extensionPane =
adminPage.getSearchBar().clickAdvancedSearch().search(extensionId).getExtension(0);
extensionPane = extensionPane.install();
// Assert the install plan.
List<DependencyPane> installPlan = extensionPane.openProgressSection().getJobPlan();
assertEquals(2, installPlan.size());
assertEquals(dependencyId, installPlan.get(0).getId());
assertEquals(extensionId, installPlan.get(1).getId());
// Finish the install and assert the install log.
List<LogItemPane> log = extensionPane.confirm().openProgressSection().getJobLog();
int logSize = log.size();
assertTrue(logSize > 1);
assertEquals("info", log.get(0).getLevel());
assertEquals("Starting job of type [install] with identifier "
+ "[extension/action/alice-xar-extension/wiki:xwiki]", log.get(0).getMessage());
assertEquals("info", log.get(logSize - 1).getLevel());
assertEquals("Finished job of type [install] with identifier "
+ "[extension/action/alice-xar-extension/wiki:xwiki]", log.get(logSize - 1).getMessage());
// Test that both extensions are usable.
ViewPage viewPage = getUtil().createPage(getTestClassName(), getTestMethodName(), "{{alice/}}\n\n{{bob/}}", "");
String content = viewPage.getContent();
assertTrue(content.contains("Alice says hello!"));
assertTrue(content.contains("Bob says hi!"));
// Check the list of installed extensions.
adminPage = ExtensionAdministrationPage.gotoPage().clickInstalledExtensionsSection();
SearchResultsPane searchResults = adminPage.getSearchBar().search("bob");
assertEquals(1, searchResults.getDisplayedResultsCount());
extensionPane = searchResults.getExtension(0);
assertEquals("installed-dependency", extensionPane.getStatus());
assertEquals("Installed as dependency", extensionPane.getStatusMessage());
assertEquals(dependencyId, extensionPane.getId());
assertNotNull(extensionPane.getUninstallButton());
searchResults = new SimpleSearchPane().search("alice");
assertEquals(1, searchResults.getDisplayedResultsCount());
extensionPane = searchResults.getExtension(0);
assertEquals("installed", extensionPane.getStatus());
assertEquals("Installed", extensionPane.getStatusMessage());
assertEquals(extensionId, extensionPane.getId());
assertNotNull(extensionPane.getUninstallButton());
// Check if the progress log is persisted.
extensionPane = extensionPane.showDetails();
log = extensionPane.openProgressSection().getJobLog();
assertEquals(logSize, log.size());
assertEquals("info", log.get(0).getLevel());
assertEquals("Starting job of type [install] with identifier "
+ "[extension/action/alice-xar-extension/wiki:xwiki]", log.get(0).getMessage());
assertEquals("info", log.get(logSize - 1).getLevel());
assertEquals("Finished job of type [install] with identifier "
+ "[extension/action/alice-xar-extension/wiki:xwiki]", log.get(logSize - 1).getMessage());
// Check if the dependency is properly listed as installed.
List<DependencyPane> dependencies = extensionPane.openDependenciesSection().getDirectDependencies();
assertEquals(2, dependencies.size());
assertEquals(dependencyId, dependencies.get(0).getId());
assertEquals("installed-dependency", dependencies.get(0).getStatus());
assertEquals("Installed as dependency", dependencies.get(0).getStatusMessage());
// Check the backward dependency.
dependencies.get(0).getLink().click();
extensionPane = new ExtensionAdministrationPage().getSearchResults().getExtension(0);
dependencies = extensionPane.openDependenciesSection().getBackwardDependencies();
assertEquals(1, dependencies.size());
assertEquals(extensionId, dependencies.get(0).getId());
assertEquals("installed", dependencies.get(0).getStatus());
assertEquals("Installed", dependencies.get(0).getStatusMessage());
}
/**
* Tests how an extension is uninstalled.
*/
@Test
public void testUninstall() throws Exception
{
// Setup the extension and its dependencies.
ExtensionId dependencyId = new ExtensionId("bob-xar-extension", "2.5-milestone-2");
getRepositoryTestUtils().addExtension(getRepositoryTestUtils().getTestExtension(dependencyId, "xar"));
ExtensionId extensionId = new ExtensionId("alice-xar-extension", "1.3");
TestExtension extension = getRepositoryTestUtils().getTestExtension(extensionId, "xar");
extension.addDependency(new DefaultExtensionDependency(dependencyId.getId(), new DefaultVersionConstraint(
dependencyId.getVersion().getValue())));
getRepositoryTestUtils().addExtension(extension);
// Install the extensions.
getExtensionTestUtils().install(extensionId);
// Check if the installed pages are present.
assertTrue(getUtil().pageExists("ExtensionTest", "Alice"));
assertTrue(getUtil().pageExists("ExtensionTest", "Bob"));
// Uninstall the dependency.
ExtensionAdministrationPage adminPage =
ExtensionAdministrationPage.gotoPage().clickInstalledExtensionsSection();
ExtensionPane extensionPane =
adminPage.getSearchBar().clickAdvancedSearch().search(dependencyId).getExtension(0);
extensionPane = extensionPane.uninstall();
// Check the uninstall plan. Both extensions should be included.
List<DependencyPane> uninstallPlan = extensionPane.openProgressSection().getJobPlan();
assertEquals(2, uninstallPlan.size());
assertEquals(extensionId, uninstallPlan.get(0).getId());
assertEquals("installed", uninstallPlan.get(0).getStatus());
assertEquals("Installed", uninstallPlan.get(0).getStatusMessage());
assertEquals(dependencyId, uninstallPlan.get(1).getId());
assertEquals("installed-dependency", uninstallPlan.get(1).getStatus());
assertEquals("Installed as dependency", uninstallPlan.get(1).getStatusMessage());
// Check the confirmation to delete the unused wiki pages.
extensionPane = extensionPane.confirm();
UnusedPagesPane unusedPages = extensionPane.openProgressSection().getUnusedPages();
assertTrue(unusedPages.contains("ExtensionTest", "Alice"));
assertTrue(unusedPages.contains("ExtensionTest", "Bob"));
// Finish the uninstall and check the log.
extensionPane = extensionPane.confirm();
List<LogItemPane> log = extensionPane.openProgressSection().getJobLog();
assertTrue(log.size() > 2);
assertEquals("info", log.get(2).getLevel());
assertEquals("Resolving extension [bob-xar-extension 2.5-milestone-2] from namespace [Home]", log.get(2)
.getMessage());
assertEquals("info", log.get(log.size() - 1).getLevel());
assertEquals("Finished job of type [uninstall] with identifier "
+ "[extension/action/bob-xar-extension/wiki:xwiki]", log.get(log.size() - 1).getMessage());
// Check if the uninstalled pages have been deleted.
assertFalse(getUtil().pageExists("ExtensionTest", "Alice"));
assertFalse(getUtil().pageExists("ExtensionTest", "Bob"));
// Install both extension again and uninstall only the one with the dependency.
getExtensionTestUtils().install(extensionId);
adminPage = ExtensionAdministrationPage.gotoPage().clickInstalledExtensionsSection();
extensionPane = adminPage.getSearchBar().clickAdvancedSearch().search(extensionId).getExtension(0);
extensionPane = extensionPane.uninstall();
// Check the uninstall plan. Only one extension should be included.
uninstallPlan = extensionPane.openProgressSection().getJobPlan();
assertEquals(1, uninstallPlan.size());
assertEquals(extensionId, uninstallPlan.get(0).getId());
// Check the confirmation to delete the unused wiki pages.
extensionPane = extensionPane.confirm();
unusedPages = extensionPane.openProgressSection().getUnusedPages();
assertTrue(unusedPages.contains("ExtensionTest", "Alice"));
assertFalse(unusedPages.contains("ExtensionTest", "Bob"));
// Finish the uninstall and check the log.
log = extensionPane.confirm().openProgressSection().getJobLog();
assertTrue(log.size() > 2);
assertEquals("info", log.get(2).getLevel());
assertEquals("Resolving extension [alice-xar-extension 1.3] from namespace [Home]", log.get(2).getMessage());
assertEquals("info", log.get(log.size() - 1).getLevel());
assertEquals("Finished job of type [uninstall] with identifier "
+ "[extension/action/alice-xar-extension/wiki:xwiki]", log.get(log.size() - 1).getMessage());
// Check if the uninstalled pages have been deleted.
assertFalse(getUtil().pageExists("ExtensionTest", "Alice"));
assertTrue(getUtil().pageExists("ExtensionTest", "Bob"));
// Check the list of installed extensions. It should contain only the second extension.
adminPage = ExtensionAdministrationPage.gotoPage().clickInstalledExtensionsSection();
SearchResultsPane searchResults = adminPage.getSearchBar().search("alice");
assertEquals(0, searchResults.getDisplayedResultsCount());
assertNotNull(searchResults.getNoResultsMessage());
searchResults = new SimpleSearchPane().search("bob");
assertEquals(1, searchResults.getDisplayedResultsCount());
extensionPane = searchResults.getExtension(0);
assertEquals("installed-dependency", extensionPane.getStatus());
assertEquals(dependencyId, extensionPane.getId());
}
/**
* Tests that an extension can be installed and uninstalled without reloading the extension manager UI.
*/
@Test
public void testInstallAndUninstallWithoutReload() throws Exception
{
// Setup the extension.
ExtensionId extensionId = new ExtensionId("alice-xar-extension", "1.3");
getRepositoryTestUtils().addExtension(getRepositoryTestUtils().getTestExtension(extensionId, "xar"));
// Search the extension to install.
ExtensionAdministrationPage adminPage = ExtensionAdministrationPage.gotoPage().clickAddExtensionsSection();
ExtensionPane extensionPane =
adminPage.getSearchBar().clickAdvancedSearch().search(extensionId).getExtension(0);
// Install and uninstall.
extensionPane = extensionPane.install().confirm().uninstall().confirm().confirm().install();
assertEquals("remote", extensionPane.getStatus());
}
/**
* Tests how an extension is upgraded.
*/
@Test
public void testUpgrade() throws Exception
{
// Setup the extension.
String extensionId = "alice-xar-extension";
String oldVersion = "1.3";
String newVersion = "2.1.4";
TestExtension oldExtension =
getRepositoryTestUtils().getTestExtension(new ExtensionId(extensionId, oldVersion), "xar");
getRepositoryTestUtils().addExtension(oldExtension);
TestExtension newExtension =
getRepositoryTestUtils().getTestExtension(new ExtensionId(extensionId, newVersion), "xar");
getRepositoryTestUtils().attachFile(newExtension);
getRepositoryTestUtils().addVersionObject(newExtension, newVersion,
"attach:" + newExtension.getFile().getName());
// Make sure the old version is installed.
getExtensionTestUtils().install(new ExtensionId(extensionId, oldVersion));
// Upgrade the extension.
ExtensionAdministrationPage adminPage = ExtensionAdministrationPage.gotoPage().clickAddExtensionsSection();
ExtensionPane extensionPane =
adminPage.getSearchBar().clickAdvancedSearch().search(extensionId, newVersion).getExtension(0);
assertEquals("remote-installed", extensionPane.getStatus());
assertEquals("Version 1.3 is installed", extensionPane.getStatusMessage());
extensionPane = extensionPane.upgrade();
// Check the upgrade plan.
List<DependencyPane> upgradePlan = extensionPane.openProgressSection().getJobPlan();
assertEquals(1, upgradePlan.size());
assertEquals(extensionId, upgradePlan.get(0).getName());
assertEquals(newVersion, upgradePlan.get(0).getVersion());
assertEquals("remote-installed", upgradePlan.get(0).getStatus());
assertEquals("Version 1.3 is installed", upgradePlan.get(0).getStatusMessage());
// Finish the upgrade and check the upgrade log.
extensionPane = extensionPane.confirm();
assertEquals("installed", extensionPane.getStatus());
assertEquals("Installed", extensionPane.getStatusMessage());
List<LogItemPane> log = extensionPane.openProgressSection().getJobLog();
assertTrue(log.size() > 2);
assertEquals("info", log.get(2).getLevel());
assertEquals("Resolving extension [alice-xar-extension 2.1.4] on namespace [Home]", log.get(2).getMessage());
assertEquals("info", log.get(log.size() - 1).getLevel());
assertEquals("Finished job of type [install] with identifier "
+ "[extension/action/alice-xar-extension/wiki:xwiki]", log.get(log.size() - 1).getMessage());
// Assert the changes.
ViewPage viewPage = getUtil().gotoPage("ExtensionTest", "Alice");
assertEquals("Alice Wiki Macro (upgraded)", viewPage.getDocumentTitle());
assertTrue(viewPage.getContent().contains("Alice says hi guys!"));
}
/**
* Tests how an extension is upgraded when there is a merge conflict.
*/
@Test
public void testUpgradeWithMergeConflict() throws Exception
{
// Setup the extension.
String extensionId = "alice-xar-extension";
String oldVersion = "1.3";
String newVersion = "2.1.4";
TestExtension oldExtension =
getRepositoryTestUtils().getTestExtension(new ExtensionId(extensionId, oldVersion), "xar");
getRepositoryTestUtils().addExtension(oldExtension);
TestExtension newExtension =
getRepositoryTestUtils().getTestExtension(new ExtensionId(extensionId, newVersion), "xar");
getRepositoryTestUtils().attachFile(newExtension);
getRepositoryTestUtils().addVersionObject(newExtension, newVersion,
"attach:" + newExtension.getFile().getName());
// Make sure the old version is installed.
getExtensionTestUtils().install(new ExtensionId(extensionId, oldVersion));
// Edit the installed version so that we have a merge conflict.
Map<String, String> queryParameters = new HashMap<String, String>();
queryParameters.put("title", "Alice Extension");
queryParameters.put("content", "== Usage ==\n\n{{code language=\"none\"}}\n"
+ "{{alice/}}\n{{/code}}\n\n== Output ==\n\n{{alice/}}");
queryParameters.put("XWiki.WikiMacroClass_0_code", "{{info}}Alice says hello!{{/info}}");
getUtil().gotoPage("ExtensionTest", "Alice", "save", queryParameters);
// Initiate the upgrade process.
ExtensionAdministrationPage adminPage = ExtensionAdministrationPage.gotoPage().clickAddExtensionsSection();
SearchResultsPane searchResults =
adminPage.getSearchBar().clickAdvancedSearch().search(extensionId, newVersion);
ExtensionPane extensionPane = searchResults.getExtension(0);
extensionPane = extensionPane.upgrade().confirm();
// Check the merge conflict UI.
assertEquals("loading", extensionPane.getStatus());
assertNull(extensionPane.getStatusMessage());
ProgressBarPane progressBar = extensionPane.getProgressBar();
assertEquals(83, progressBar.getPercent());
assertEquals("Conflict between [@@ -1,1 +1,1 @@] and [@@ -1,1 +1,1 @@]", progressBar.getMessage());
ExtensionProgressPane progressPane = extensionPane.openProgressSection();
WebElement jobLogLabel = progressPane.getJobLogLabel();
assertEquals("INSTALL LOG".toLowerCase(), jobLogLabel.getText().toLowerCase());
// The job log is collapsed when the job is waiting for user input so we need to expand it before asserting its
// content (otherwise #getText() returns the empty string because the text is not visible).
jobLogLabel.click();
List<LogItemPane> upgradeLog = progressPane.getJobLog();
LogItemPane lastLogItem = upgradeLog.get(upgradeLog.size() - 1);
assertEquals("loading", lastLogItem.getLevel());
assertEquals(progressBar.getMessage(), lastLogItem.getMessage());
MergeConflictPane mergeConflictPane = progressPane.getMergeConflict();
ChangesPane changesPane = mergeConflictPane.getChanges();
assertEquals(Arrays.asList("Page properties", "XWiki.WikiMacroClass[0]"), changesPane.getChangedEntities());
EntityDiff pagePropertiesDiff = changesPane.getEntityDiff("Page properties");
assertEquals(Arrays.asList("Parent", "Content"), pagePropertiesDiff.getPropertyNames());
assertFalse(pagePropertiesDiff.getDiff("Content").isEmpty());
EntityDiff macroDiff = changesPane.getEntityDiff("XWiki.WikiMacroClass[0]");
assertEquals(Arrays.asList("Macro description"), macroDiff.getPropertyNames());
assertEquals(
Arrays.asList("@@ -1,1 +1,1 @@", "-<del>Test</del> macro.", "+<ins>A</ins> <ins>cool </ins>macro."),
macroDiff.getDiff("Macro description"));
mergeConflictPane.getFromVersionSelect().selectByVisibleText("Previous version");
mergeConflictPane.getToVersionSelect().selectByVisibleText("Current version");
mergeConflictPane = mergeConflictPane.clickShowChanges();
changesPane = mergeConflictPane.getChanges();
List<String> expectedDiff = new ArrayList<>();
expectedDiff.add("@@ -1,9 +1,9 @@");
expectedDiff.add("-= Usage =");
expectedDiff.add("+=<ins>=</ins> Usage =<ins>=</ins>");
expectedDiff.add(" ");
expectedDiff.add("-{{code}}");
expectedDiff.add("+{{code<ins> language=\"none\"</ins>}}");
expectedDiff.add(" {{alice/}}");
expectedDiff.add(" {{/code}}");
expectedDiff.add(" ");
expectedDiff.add("-= <del>Res</del>u<del>l</del>t =");
expectedDiff.add("+=<ins>=</ins> <ins>O</ins>ut<ins>put</ins> =<ins>=</ins>");
expectedDiff.add(" ");
expectedDiff.add(" {{alice/}}");
assertEquals(expectedDiff, changesPane.getEntityDiff("Page properties").getDiff("Content"));
assertEquals(1, changesPane.getDiffSummary().toggleObjectsDetails().getModifiedObjects().size());
assertEquals(Arrays.asList("@@ -1,1 +1,1 @@", "-Alice says hello!",
"+<ins>{{info}}</ins>Alice says hello!<ins>{{/info}}</ins>"),
changesPane.getEntityDiff("XWiki.WikiMacroClass[0]").getDiff("Macro code"));
// Finish the merge.
mergeConflictPane.getVersionToKeepSelect().selectByValue("NEXT");
// FIXME: We get the extension pane from the search results because it is reloaded when we compare the versions.
extensionPane = searchResults.getExtension(0).confirm();
assertEquals("installed", extensionPane.getStatus());
assertNull(extensionPane.getProgressBar());
upgradeLog = extensionPane.openProgressSection().getJobLog();
lastLogItem = upgradeLog.get(upgradeLog.size() - 1);
assertEquals("info", lastLogItem.getLevel());
assertEquals("Finished job of type [install] with identifier "
+ "[extension/action/alice-xar-extension/wiki:xwiki]", lastLogItem.getMessage());
// Check the merge result.
ViewPage mergedPage = getUtil().gotoPage("ExtensionTest", "Alice");
assertEquals("Alice Wiki Macro (upgraded)", mergedPage.getDocumentTitle());
}
/**
* Tests how an extension is downgraded.
*/
@Test
public void testDowngrade() throws Exception
{
// Setup the extension.
String extensionId = "alice-xar-extension";
String oldVersion = "1.3";
String newVersion = "2.1.4";
TestExtension oldExtension =
getRepositoryTestUtils().getTestExtension(new ExtensionId(extensionId, oldVersion), "xar");
getRepositoryTestUtils().addExtension(oldExtension);
TestExtension newExtension =
getRepositoryTestUtils().getTestExtension(new ExtensionId(extensionId, newVersion), "xar");
getRepositoryTestUtils().attachFile(newExtension);
getRepositoryTestUtils().addVersionObject(newExtension, newVersion,
"attach:" + newExtension.getFile().getName());
// Make sure the new version is installed.
getExtensionTestUtils().install(new ExtensionId(extensionId, newVersion));
// Downgrade the extension.
ExtensionAdministrationPage adminPage = ExtensionAdministrationPage.gotoPage().clickAddExtensionsSection();
ExtensionPane extensionPane =
adminPage.getSearchBar().clickAdvancedSearch().search(extensionId, oldVersion).getExtension(0);
assertEquals("remote-installed", extensionPane.getStatus());
assertEquals("Version 2.1.4 is installed", extensionPane.getStatusMessage());
extensionPane = extensionPane.downgrade();
// Check the downgrade plan.
List<DependencyPane> downgradePlan = extensionPane.openProgressSection().getJobPlan();
assertEquals(1, downgradePlan.size());
assertEquals(extensionId, downgradePlan.get(0).getName());
assertEquals(oldVersion, downgradePlan.get(0).getVersion());
assertEquals("remote-installed", downgradePlan.get(0).getStatus());
assertEquals("Version 2.1.4 is installed", downgradePlan.get(0).getStatusMessage());
// Finish the downgrade and check the downgrade log.
extensionPane = extensionPane.confirm();
assertEquals("installed", extensionPane.getStatus());
assertEquals("Installed", extensionPane.getStatusMessage());
List<LogItemPane> log = extensionPane.openProgressSection().getJobLog();
assertTrue(log.size() > 2);
assertEquals("info", log.get(2).getLevel());
assertEquals("Resolving extension [alice-xar-extension 1.3] on namespace [Home]", log.get(2).getMessage());
assertEquals("info", log.get(log.size() - 1).getLevel());
assertEquals("Finished job of type [install] with identifier "
+ "[extension/action/alice-xar-extension/wiki:xwiki]", log.get(log.size() - 1).getMessage());
// Assert the changes.
ViewPage viewPage = getUtil().gotoPage("ExtensionTest", "Alice");
assertEquals("Alice Macro", viewPage.getDocumentTitle());
assertTrue(viewPage.getContent().contains("Alice says hello!"));
}
/**
* Tests if a Java component script service is properly installed.
*/
@Test
public void testInstallScriptService() throws Exception
{
// Make sure the script service is not available before the extension is installed.
ViewPage viewPage =
getUtil().createPage(
getTestClassName(),
getTestMethodName(),
"{{velocity}}$services.greeter.greet('world') "
+ "$services.greeter.greet('XWiki', 'default'){{/velocity}}", "");
assertFalse(viewPage.getContent().contains("Hello world! Hello XWiki!"));
// Setup the extension.
ExtensionId extensionId = new ExtensionId("scriptServiceJarExtension", "4.2-milestone-1");
TestExtension extension = getRepositoryTestUtils().getTestExtension(extensionId, "jar");
getRepositoryTestUtils().addExtension(extension);
// Search the extension and install it.
ExtensionAdministrationPage adminPage = ExtensionAdministrationPage.gotoPage().clickAddExtensionsSection();
ExtensionPane extensionPane =
adminPage.getSearchBar().clickAdvancedSearch().search(extensionId).getExtension(0);
extensionPane.install().confirm();
// Check the result.
assertEquals("Hello world! Hello XWiki!", getUtil().gotoPage(getTestClassName(), getTestMethodName())
.getContent());
}
}
|
[misc] Update test.
|
xwiki-platform-core/xwiki-platform-extension/xwiki-platform-extension-test/xwiki-platform-extension-test-tests/src/test/it/org/xwiki/test/ui/extension/ExtensionTest.java
|
[misc] Update test.
|
|
Java
|
apache-2.0
|
0c7b5de6ce54bf0c20a0b83c68703db09ea3a2cb
| 0
|
kirillkrohmal/krohmal,kirillkrohmal/krohmal
|
package ru.job4j.storesql;
import java.sql.*;
import java.util.Collections;
import java.util.List;
public class StoreSQL implements AutoCloseable {
private Config config;
private Connection connect;
public StoreSQL(Config config) {
this.config = config;
connect = config.init();
}
public void generate(int size) {
for (int i = 0; i < size; i++) {
String s1 = "INSERT INTO entry(i) VALUES (?)";
try (PreparedStatement statement = connect.prepareStatement(s1);) {
statement.setString(1, s1);
statement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public String findAll() {
String s1 = "SELECT size FROM entry";
try (PreparedStatement statement = connect.prepareStatement(s1);) {
statement.setString(1, s1);
statement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
return s1;
}
public static void createNewDatabase(String fileName) throws SQLException {
String url = "jdbc:sqlite:C:/sqlite/db/" + fileName;
Connection conn = DriverManager.getConnection(url);
Statement statement = conn.createStatement();
try {
String sql = "CREATE TABLE entry " + "(field INTEGER not NULL)";
statement.executeUpdate(sql);
System.out.println("Table successfully created...");
if (conn != null) {
DatabaseMetaData meta = conn.getMetaData();
System.out.println("The driver name is " + meta.getDriverName());
System.out.println("A new database has been created.");
}
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
if (statement != null) {
statement.close();
}
if (conn != null) {
conn.close();
}
}
}
public List<Entry> load() {
return Collections.EMPTY_LIST;
}
@Override
public void close() throws Exception {
if (connect != null) {
connect.close();
}
}
public static void main(String[] args) {
try {
createNewDatabase("test.db");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
|
chapter_008/src/main/java/ru/job4j/storesql/StoreSQL.java
|
package ru.job4j.storesql;
import java.sql.*;
import java.util.Collections;
import java.util.List;
public class StoreSQL implements AutoCloseable {
private Config config;
private Connection connect;
public StoreSQL(Config config) {
this.config = config;
connect = config.init();
}
public void generate(int size) {
for (int i = 0; i < size; i++) {
String s1 = "INSERT INTO test(i) VALUES (?)";
try (PreparedStatement statement = connect.prepareStatement(s1);) {
statement.setString(1, s1);
statement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public String findAll() {
String s1 = "SELECT size FROM test";
try (PreparedStatement statement = connect.prepareStatement(s1);) {
statement.setString(1, s1);
statement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
return s1;
}
public static void createNewDatabase(String fileName) {
String url = "jdbc:sqlite:C:/sqlite/db/" + fileName;
try (Connection conn = DriverManager.getConnection(url)) {
if (conn != null) {
DatabaseMetaData meta = conn.getMetaData();
System.out.println("The driver name is " + meta.getDriverName());
System.out.println("A new database has been created.");
}
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
public List<Entry> load() {
return Collections.EMPTY_LIST;
}
@Override
public void close() throws Exception {
if (connect != null) {
connect.close();
}
}
public static void main(String[] args) {
createNewDatabase("test.db");
}
}
|
Liquibase Интеграционные тесты. Proxy.[#196964]
|
chapter_008/src/main/java/ru/job4j/storesql/StoreSQL.java
|
Liquibase Интеграционные тесты. Proxy.[#196964]
|
|
Java
|
apache-2.0
|
a3123674e02a320dfbe149e81c089779789ae01e
| 0
|
LordAkkarin/BaseDefense
|
/*
* Copyright (C) 2014 Evil-Co <http://wwww.evil-co.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.evilco.defense.common.tile.generic;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.passive.EntityAnimal;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.tileentity.TileEntity;
import org.evilco.defense.common.tile.network.*;
import org.evilco.defense.util.Location;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
/**
* @author Johannes Donath <johannesd@evil-co.com>
* @copyright Copyright (C) 2014 Evil-Co <http://www.evil-co.org>
*/
public class DefenseStationTileEntity extends TileEntity implements ISurveillanceNetworkHub {
/**
* Indicates whether the entity is active.
*/
protected boolean isActive = true;
/**
* Stores a list of user identifiers which may pass through protected zones.
*/
protected List<UUID> knownUsers = new ArrayList<UUID> ();
/**
* Stores the owner's UUID.
*/
protected UUID owner = null;
/**
* Stores all currently connected clients.
*/
protected List<ISurveillanceNetworkClient> connectedClients = new ArrayList<ISurveillanceNetworkClient> ();
/**
* {@inheritDoc}
*/
@Override
public void connectEntity (ISurveillanceNetworkClient entity) throws SurveillanceEntityConnectionException {
if (!this.connectedClients.contains (entity)) this.connectedClients.add (entity);
}
/**
* {@inheritDoc}
*/
@Override
public void disconnectEntity (ISurveillanceNetworkClient entity) {
this.connectedClients.remove (entity);
}
/**
* Returns a list of known users.
* @return The list.
*/
public List<UUID> getKnownUsers () {
return this.knownUsers;
}
/**
* {@inheritDoc}
*/
@Override
public Location getLocation () {
return (new Location (this.xCoord, this.yCoord, this.zCoord));
}
/**
* {@inheritDoc}
*/
@Override
public UUID getOwner () {
return this.owner;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isActive () {
return this.isActive;
}
/**
* {@inheritDoc}
*/
@Override
public void receiveMessage (ISurveillanceNetworkPacket packet) {
// parse camera packets
if (packet instanceof CameraDetectionPacket) {
// cast packet
CameraDetectionPacket detectionPacket = ((CameraDetectionPacket) packet);
// create alert packet
Entity entity = detectionPacket.getDetectedEntities ().get (0);
DefenseOrderPacket defenseOrderPacket = new DefenseOrderPacket (this, new Location (entity.posX, entity.posY, entity.posZ));
// notify all connected entities
for (ISurveillanceNetworkClient client : this.connectedClients) {
client.receiveMessage (defenseOrderPacket);
}
}
// parse attack orders
if (packet instanceof AttackOrderRequestPacket) {
// cast packet
AttackOrderRequestPacket attackOrderPacket = ((AttackOrderRequestPacket) packet);
// iterate over all possible targets
for (EntityLivingBase entityLiving : attackOrderPacket.getPossibleTargets ()) {
// check for player
if (entityLiving instanceof EntityPlayer) {
// cast to player
EntityPlayer entityPlayer = ((EntityPlayer) entityLiving);
// verify UUID against this known users
if (this.knownUsers.contains (entityPlayer.getPersistentID ())) continue;
}
// skip passive mods
if (entityLiving instanceof EntityAnimal) continue;
// send attack order
AttackOrderPacket attackPacket = new AttackOrderPacket (this, entityLiving);
attackOrderPacket.getSource ().receiveMessage (attackPacket);
}
}
}
/**
* {@inheritDoc}
*/
@Override
public void onChunkUnload () {
super.onChunkUnload ();
// disable hub
this.isActive = false;
}
}
|
src/main/java/org/evilco/defense/common/tile/generic/DefenseStationTileEntity.java
|
/*
* Copyright (C) 2014 Evil-Co <http://wwww.evil-co.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.evilco.defense.common.tile.generic;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.tileentity.TileEntity;
import org.evilco.defense.common.tile.network.*;
import org.evilco.defense.util.Location;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
/**
* @author Johannes Donath <johannesd@evil-co.com>
* @copyright Copyright (C) 2014 Evil-Co <http://www.evil-co.org>
*/
public class DefenseStationTileEntity extends TileEntity implements ISurveillanceNetworkHub {
/**
* Indicates whether the entity is active.
*/
protected boolean isActive = true;
/**
* Stores a list of user identifiers which may pass through protected zones.
*/
protected List<UUID> knownUsers = new ArrayList<UUID> ();
/**
* Stores the owner's UUID.
*/
protected UUID owner = null;
/**
* Stores all currently connected clients.
*/
protected List<ISurveillanceNetworkClient> connectedClients = new ArrayList<ISurveillanceNetworkClient> ();
/**
* {@inheritDoc}
*/
@Override
public void connectEntity (ISurveillanceNetworkClient entity) throws SurveillanceEntityConnectionException {
if (!this.connectedClients.contains (entity)) this.connectedClients.add (entity);
}
/**
* {@inheritDoc}
*/
@Override
public void disconnectEntity (ISurveillanceNetworkClient entity) {
this.connectedClients.remove (entity);
}
/**
* Returns a list of known users.
* @return The list.
*/
public List<UUID> getKnownUsers () {
return this.knownUsers;
}
/**
* {@inheritDoc}
*/
@Override
public Location getLocation () {
return (new Location (this.xCoord, this.yCoord, this.zCoord));
}
/**
* {@inheritDoc}
*/
@Override
public UUID getOwner () {
return this.owner;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isActive () {
return this.isActive;
}
/**
* {@inheritDoc}
*/
@Override
public void receiveMessage (ISurveillanceNetworkPacket packet) {
if (packet instanceof CameraDetectionPacket) {
// cast packet
CameraDetectionPacket detectionPacket = ((CameraDetectionPacket) packet);
// create alert packet
}
}
/**
* {@inheritDoc}
*/
@Override
public void onChunkUnload () {
super.onChunkUnload ();
// disable hub
this.isActive = false;
}
@Override
public void updateEntity () {
super.updateEntity ();
}
}
|
Added support for most defense station related packets.
|
src/main/java/org/evilco/defense/common/tile/generic/DefenseStationTileEntity.java
|
Added support for most defense station related packets.
|
|
Java
|
apache-2.0
|
20baaa1a04585534219ab9a2b7a40ab0a47757f7
| 0
|
krosenvold/AxonFramework,AxonFramework/AxonFramework
|
/*
* Copyright (c) 2018. AxonIQ
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.axoniq.axonhub.client.boot;
import io.axoniq.axonhub.client.AxonHubConfiguration;
import io.axoniq.axonhub.client.PlatformConnectionManager;
import io.axoniq.axonhub.client.query.subscription.EnhancedAxonHubQueryBus;
import io.axoniq.axonhub.client.query.QueryPriorityCalculator;
import org.axonframework.common.transaction.TransactionManager;
import org.axonframework.queryhandling.QueryBus;
import org.axonframework.queryhandling.QueryInvocationErrorHandler;
import org.axonframework.queryhandling.QueryUpdateEmitter;
import org.axonframework.queryhandling.SimpleQueryBus;
import org.axonframework.serialization.Serializer;
import org.axonframework.spring.config.AxonConfiguration;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* Created by Sara Pellegrini on 16/05/2018.
* sara.pellegrini@gmail.com
*/
@Configuration
@ConditionalOnClass(QueryUpdateEmitter.class)
@AutoConfigureBefore(MessagingAutoConfiguration.class)
public class SubscriptionQueryAutoConfiguration {
@Bean
@ConditionalOnMissingBean(QueryBus.class)
public EnhancedAxonHubQueryBus queryBus(PlatformConnectionManager platformConnectionManager, AxonHubConfiguration axonHubConfiguration,
AxonConfiguration axonConfiguration, TransactionManager txManager,
@Qualifier("messageSerializer") Serializer messageSerializer,
Serializer genericSerializer,
QueryPriorityCalculator priorityCalculator, QueryInvocationErrorHandler queryInvocationErrorHandler) {
SimpleQueryBus simpleQueryBus = new SimpleQueryBus(axonConfiguration.messageMonitor(QueryBus.class, "queryBus"),
txManager, queryInvocationErrorHandler);
return new EnhancedAxonHubQueryBus(platformConnectionManager, axonHubConfiguration,
simpleQueryBus, simpleQueryBus,
messageSerializer, genericSerializer, priorityCalculator);
}
}
|
src/main/java/io/axoniq/axonhub/client/boot/SubscriptionQueryAutoConfiguration.java
|
/*
* Copyright (c) 2018. AxonIQ
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.axoniq.axonhub.client.boot;
import io.axoniq.axonhub.client.AxonHubConfiguration;
import io.axoniq.axonhub.client.PlatformConnectionManager;
import io.axoniq.axonhub.client.query.EnhancedAxonHubQueryBus;
import io.axoniq.axonhub.client.query.QueryPriorityCalculator;
import io.axoniq.axonhub.client.query.subscription.AxonHubUpdateEmitter;
import org.axonframework.common.transaction.TransactionManager;
import org.axonframework.queryhandling.QueryBus;
import org.axonframework.queryhandling.QueryInvocationErrorHandler;
import org.axonframework.queryhandling.QueryUpdateEmitter;
import org.axonframework.queryhandling.SimpleQueryBus;
import org.axonframework.serialization.Serializer;
import org.axonframework.spring.config.AxonConfiguration;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* Created by Sara Pellegrini on 16/05/2018.
* sara.pellegrini@gmail.com
*/
@Configuration
@ConditionalOnClass(QueryUpdateEmitter.class)
@AutoConfigureBefore(MessagingAutoConfiguration.class)
public class SubscriptionQueryAutoConfiguration {
@Bean("queryUpdateEmitter")
public QueryUpdateEmitter defaultQueryUpdateEmitter(
PlatformConnectionManager platformConnectionManager,
@Qualifier("messageSerializer") Serializer messageSerializer,
Serializer genericSerializer,
AxonHubConfiguration configuration) {
return new AxonHubUpdateEmitter(platformConnectionManager, messageSerializer, genericSerializer, configuration);
}
@Bean
@ConditionalOnMissingBean(QueryBus.class)
public QueryBus queryBus(PlatformConnectionManager platformConnectionManager, AxonHubConfiguration axonHubConfiguration,
AxonConfiguration axonConfiguration, TransactionManager txManager,
@Qualifier("messageSerializer") Serializer messageSerializer,
Serializer genericSerializer,
QueryPriorityCalculator priorityCalculator, QueryInvocationErrorHandler queryInvocationErrorHandler) {
return new EnhancedAxonHubQueryBus(platformConnectionManager, axonHubConfiguration,
new SimpleQueryBus(axonConfiguration.messageMonitor(QueryBus.class, "queryBus"),
txManager, queryInvocationErrorHandler),
messageSerializer, genericSerializer, priorityCalculator);
}
}
|
#11 Subscription Query - Work In Progress
|
src/main/java/io/axoniq/axonhub/client/boot/SubscriptionQueryAutoConfiguration.java
|
#11 Subscription Query - Work In Progress
|
|
Java
|
apache-2.0
|
cf3f36abed73b9a0602656d54fa1f90eacdb22bc
| 0
|
valfirst/selenium,titusfortner/selenium,joshmgrant/selenium,SeleniumHQ/selenium,SeleniumHQ/selenium,SeleniumHQ/selenium,valfirst/selenium,SeleniumHQ/selenium,valfirst/selenium,titusfortner/selenium,valfirst/selenium,SeleniumHQ/selenium,HtmlUnit/selenium,joshmgrant/selenium,HtmlUnit/selenium,HtmlUnit/selenium,joshmgrant/selenium,HtmlUnit/selenium,joshmgrant/selenium,titusfortner/selenium,SeleniumHQ/selenium,HtmlUnit/selenium,SeleniumHQ/selenium,valfirst/selenium,HtmlUnit/selenium,SeleniumHQ/selenium,joshmgrant/selenium,joshmgrant/selenium,titusfortner/selenium,SeleniumHQ/selenium,HtmlUnit/selenium,titusfortner/selenium,valfirst/selenium,HtmlUnit/selenium,titusfortner/selenium,joshmgrant/selenium,valfirst/selenium,titusfortner/selenium,joshmgrant/selenium,valfirst/selenium,SeleniumHQ/selenium,joshmgrant/selenium,valfirst/selenium,titusfortner/selenium,HtmlUnit/selenium,valfirst/selenium,titusfortner/selenium,titusfortner/selenium,joshmgrant/selenium,valfirst/selenium,HtmlUnit/selenium,titusfortner/selenium,SeleniumHQ/selenium,joshmgrant/selenium
|
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package org.openqa.selenium;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Base64;
/**
* Defines the output type for a screenshot.
*
* @see TakesScreenshot
* @param <T> Type for the screenshot output.
*/
public interface OutputType<T> {
/**
* Obtain the screenshot as base64 data.
*/
OutputType<String> BASE64 = new OutputType<String>() {
@Override
public String convertFromBase64Png(String base64Png) {
return base64Png;
}
@Override
public String convertFromPngBytes(byte[] png) {
return Base64.getEncoder().encodeToString(png);
}
public String toString() {
return "OutputType.BASE64";
}
};
/**
* Obtain the screenshot as raw bytes.
*/
OutputType<byte[]> BYTES = new OutputType<byte[]>() {
@Override
public byte[] convertFromBase64Png(String base64Png) {
return Base64.getMimeDecoder().decode(base64Png);
}
@Override
public byte[] convertFromPngBytes(byte[] png) {
return png;
}
public String toString() {
return "OutputType.BYTES";
}
};
/**
* Obtain the screenshot into a temporary file that will be deleted once the JVM exits. It is up
* to users to make a copy of this file.
*/
OutputType<File> FILE = new OutputType<File>() {
@Override
public File convertFromBase64Png(String base64Png) {
return save(BYTES.convertFromBase64Png(base64Png));
}
@Override
public File convertFromPngBytes(byte[] data) {
return save(data);
}
private File save(byte[] data) {
try {
Path tmpFilePath = Files.createTempFile("screenshot", ".png");
File tmpFile = tmpFilePath.toFile();
tmpFile.deleteOnExit();
Files.write(tmpFilePath, data);
return tmpFile;
} catch (IOException e) {
throw new WebDriverException(e);
}
}
public String toString() {
return "OutputType.FILE";
}
};
/**
* Convert the given base64 png to a requested format.
*
* @param base64Png base64 encoded png.
* @return png encoded into requested format.
*/
T convertFromBase64Png(String base64Png);
/**
* Convert the given png to a requested format.
*
* @param png an array of bytes forming a png file.
* @return png encoded into requested format.
*/
T convertFromPngBytes(byte[] png);
}
|
java/client/src/org/openqa/selenium/OutputType.java
|
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package org.openqa.selenium;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Base64;
/**
* Defines the output type for a screenshot.
*
* @see TakesScreenshot
* @param <T> Type for the screenshot output.
*/
public interface OutputType<T> {
/**
* Obtain the screenshot as base64 data.
*/
OutputType<String> BASE64 = new OutputType<String>() {
@Override
public String convertFromBase64Png(String base64Png) {
return base64Png;
}
@Override
public String convertFromPngBytes(byte[] png) {
return Base64.getEncoder().encodeToString(png);
}
public String toString() {
return "OutputType.BASE64";
}
};
/**
* Obtain the screenshot as raw bytes.
*/
OutputType<byte[]> BYTES = new OutputType<byte[]>() {
@Override
public byte[] convertFromBase64Png(String base64Png) {
return Base64.getMimeDecoder().decode(base64Png);
}
@Override
public byte[] convertFromPngBytes(byte[] png) {
return png;
}
public String toString() {
return "OutputType.BYTES";
}
};
/**
* Obtain the screenshot into a temporary file that will be deleted once the JVM exits. It is up
* to users to make a copy of this file.
*/
OutputType<File> FILE = new OutputType<File>() {
@Override
public File convertFromBase64Png(String base64Png) {
return save(BYTES.convertFromBase64Png(base64Png));
}
@Override
public File convertFromPngBytes(byte[] data) {
return save(data);
}
private File save(byte[] data) {
try {
File tmpFile = File.createTempFile("screenshot", ".png");
tmpFile.deleteOnExit();
try (OutputStream stream = new FileOutputStream(tmpFile)) {
stream.write(data);
return tmpFile;
} catch (IOException e) {
throw new WebDriverException(e);
}
} catch (IOException e) {
throw new WebDriverException(e);
}
}
public String toString() {
return "OutputType.FILE";
}
};
/**
* Convert the given base64 png to a requested format.
*
* @param base64Png base64 encoded png.
* @return png encoded into requested format.
*/
T convertFromBase64Png(String base64Png);
/**
* Convert the given png to a requested format.
*
* @param png an array of bytes forming a png file.
* @return png encoded into requested format.
*/
T convertFromPngBytes(byte[] png);
}
|
[java] Refactoring OutputType.FILE#save (#9309)
Leveraging Java 7 Files class.
|
java/client/src/org/openqa/selenium/OutputType.java
|
[java] Refactoring OutputType.FILE#save (#9309)
|
|
Java
|
apache-2.0
|
bb0550ab95c817301cf1e435abfeaa6c246eb73b
| 0
|
jxblum/spring-boot,htynkn/spring-boot,michael-simons/spring-boot,drumonii/spring-boot,ptahchiev/spring-boot,ilayaperumalg/spring-boot,scottfrederick/spring-boot,vpavic/spring-boot,hello2009chen/spring-boot,drumonii/spring-boot,ptahchiev/spring-boot,vpavic/spring-boot,eddumelendez/spring-boot,michael-simons/spring-boot,tsachev/spring-boot,royclarkson/spring-boot,tsachev/spring-boot,donhuvy/spring-boot,philwebb/spring-boot,hello2009chen/spring-boot,felipeg48/spring-boot,NetoDevel/spring-boot,vpavic/spring-boot,joshiste/spring-boot,royclarkson/spring-boot,spring-projects/spring-boot,mbenson/spring-boot,ilayaperumalg/spring-boot,scottfrederick/spring-boot,dreis2211/spring-boot,dreis2211/spring-boot,chrylis/spring-boot,drumonii/spring-boot,philwebb/spring-boot,mbenson/spring-boot,tiarebalbi/spring-boot,yangdd1205/spring-boot,rweisleder/spring-boot,donhuvy/spring-boot,zhanhb/spring-boot,tsachev/spring-boot,tiarebalbi/spring-boot,tiarebalbi/spring-boot,joshiste/spring-boot,rweisleder/spring-boot,shakuzen/spring-boot,lburgazzoli/spring-boot,eddumelendez/spring-boot,bclozel/spring-boot,mdeinum/spring-boot,NetoDevel/spring-boot,mdeinum/spring-boot,felipeg48/spring-boot,NetoDevel/spring-boot,kdvolder/spring-boot,wilkinsona/spring-boot,wilkinsona/spring-boot,wilkinsona/spring-boot,dreis2211/spring-boot,Buzzardo/spring-boot,joshiste/spring-boot,aahlenst/spring-boot,tiarebalbi/spring-boot,zhanhb/spring-boot,htynkn/spring-boot,shakuzen/spring-boot,eddumelendez/spring-boot,ilayaperumalg/spring-boot,dreis2211/spring-boot,drumonii/spring-boot,chrylis/spring-boot,ptahchiev/spring-boot,royclarkson/spring-boot,ptahchiev/spring-boot,shakuzen/spring-boot,tsachev/spring-boot,tsachev/spring-boot,Buzzardo/spring-boot,htynkn/spring-boot,royclarkson/spring-boot,aahlenst/spring-boot,aahlenst/spring-boot,rweisleder/spring-boot,tiarebalbi/spring-boot,ptahchiev/spring-boot,felipeg48/spring-boot,hello2009chen/spring-boot,wilkinsona/spring-boot,kdvolder/spring-boot,jxblum/spring-boot,chrylis/spring-boot,hello2009chen/spring-boot,michael-simons/spring-boot,vpavic/spring-boot,bclozel/spring-boot,felipeg48/spring-boot,joshiste/spring-boot,yangdd1205/spring-boot,mdeinum/spring-boot,aahlenst/spring-boot,aahlenst/spring-boot,drumonii/spring-boot,chrylis/spring-boot,zhanhb/spring-boot,Buzzardo/spring-boot,kdvolder/spring-boot,scottfrederick/spring-boot,spring-projects/spring-boot,spring-projects/spring-boot,felipeg48/spring-boot,donhuvy/spring-boot,joshiste/spring-boot,eddumelendez/spring-boot,bclozel/spring-boot,spring-projects/spring-boot,royclarkson/spring-boot,spring-projects/spring-boot,philwebb/spring-boot,drumonii/spring-boot,dreis2211/spring-boot,rweisleder/spring-boot,shakuzen/spring-boot,wilkinsona/spring-boot,vpavic/spring-boot,mbenson/spring-boot,tiarebalbi/spring-boot,mbenson/spring-boot,bclozel/spring-boot,chrylis/spring-boot,lburgazzoli/spring-boot,michael-simons/spring-boot,Buzzardo/spring-boot,NetoDevel/spring-boot,tsachev/spring-boot,aahlenst/spring-boot,eddumelendez/spring-boot,philwebb/spring-boot,scottfrederick/spring-boot,lburgazzoli/spring-boot,bclozel/spring-boot,felipeg48/spring-boot,rweisleder/spring-boot,zhanhb/spring-boot,ilayaperumalg/spring-boot,kdvolder/spring-boot,lburgazzoli/spring-boot,mbenson/spring-boot,michael-simons/spring-boot,zhanhb/spring-boot,spring-projects/spring-boot,htynkn/spring-boot,kdvolder/spring-boot,Buzzardo/spring-boot,scottfrederick/spring-boot,kdvolder/spring-boot,ptahchiev/spring-boot,mdeinum/spring-boot,hello2009chen/spring-boot,NetoDevel/spring-boot,ilayaperumalg/spring-boot,zhanhb/spring-boot,jxblum/spring-boot,mbenson/spring-boot,donhuvy/spring-boot,jxblum/spring-boot,eddumelendez/spring-boot,vpavic/spring-boot,yangdd1205/spring-boot,michael-simons/spring-boot,philwebb/spring-boot,Buzzardo/spring-boot,mdeinum/spring-boot,bclozel/spring-boot,chrylis/spring-boot,wilkinsona/spring-boot,dreis2211/spring-boot,joshiste/spring-boot,htynkn/spring-boot,donhuvy/spring-boot,shakuzen/spring-boot,rweisleder/spring-boot,scottfrederick/spring-boot,mdeinum/spring-boot,shakuzen/spring-boot,lburgazzoli/spring-boot,jxblum/spring-boot,philwebb/spring-boot,htynkn/spring-boot,ilayaperumalg/spring-boot,donhuvy/spring-boot,jxblum/spring-boot
|
/*
* Copyright 2012-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.loader.jar;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.net.URL;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.rules.TemporaryFolder;
import org.springframework.boot.loader.TestJarCreator;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link JarURLConnection}.
*
* @author Andy Wilkinson
* @author Phillip Webb
* @author Rostyslav Dudka
*/
public class JarURLConnectionTests {
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder(new File("target"));
@Rule
public ExpectedException thrown = ExpectedException.none();
private File rootJarFile;
private JarFile jarFile;
@Before
public void setup() throws Exception {
this.rootJarFile = this.temporaryFolder.newFile();
TestJarCreator.createTestJar(this.rootJarFile);
this.jarFile = new JarFile(this.rootJarFile);
}
@Test
public void connectionToRootUsingAbsoluteUrl() throws Exception {
URL url = new URL("jar:file:" + getAbsolutePath() + "!/");
assertThat(JarURLConnection.get(url, this.jarFile).getContent())
.isSameAs(this.jarFile);
}
@Test
public void connectionToRootUsingRelativeUrl() throws Exception {
URL url = new URL("jar:file:" + getRelativePath() + "!/");
assertThat(JarURLConnection.get(url, this.jarFile).getContent())
.isSameAs(this.jarFile);
}
@Test
public void connectionToEntryUsingAbsoluteUrl() throws Exception {
URL url = new URL("jar:file:" + getAbsolutePath() + "!/1.dat");
assertThat(JarURLConnection.get(url, this.jarFile).getInputStream())
.hasSameContentAs(new ByteArrayInputStream(new byte[] { 1 }));
}
@Test
public void connectionToEntryUsingRelativeUrl() throws Exception {
URL url = new URL("jar:file:" + getRelativePath() + "!/1.dat");
assertThat(JarURLConnection.get(url, this.jarFile).getInputStream())
.hasSameContentAs(new ByteArrayInputStream(new byte[] { 1 }));
}
@Test
public void connectionToEntryUsingAbsoluteUrlWithFileColonSlashSlashPrefix()
throws Exception {
URL url = new URL("jar:file:/" + getAbsolutePath() + "!/1.dat");
assertThat(JarURLConnection.get(url, this.jarFile).getInputStream())
.hasSameContentAs(new ByteArrayInputStream(new byte[] { 1 }));
}
@Test
public void connectionToEntryUsingAbsoluteUrlForNestedEntry() throws Exception {
URL url = new URL("jar:file:" + getAbsolutePath() + "!/nested.jar!/3.dat");
assertThat(JarURLConnection.get(url, this.jarFile).getInputStream())
.hasSameContentAs(new ByteArrayInputStream(new byte[] { 3 }));
}
@Test
public void connectionToEntryUsingRelativeUrlForNestedEntry() throws Exception {
URL url = new URL("jar:file:" + getRelativePath() + "!/nested.jar!/3.dat");
assertThat(JarURLConnection.get(url, this.jarFile).getInputStream())
.hasSameContentAs(new ByteArrayInputStream(new byte[] { 3 }));
}
@Test
public void connectionToEntryUsingAbsoluteUrlForEntryFromNestedJarFile()
throws Exception {
URL url = new URL("jar:file:" + getAbsolutePath() + "!/nested.jar!/3.dat");
JarFile nested = this.jarFile
.getNestedJarFile(this.jarFile.getEntry("nested.jar"));
assertThat(JarURLConnection.get(url, nested).getInputStream())
.hasSameContentAs(new ByteArrayInputStream(new byte[] { 3 }));
}
@Test
public void connectionToEntryUsingRelativeUrlForEntryFromNestedJarFile()
throws Exception {
URL url = new URL("jar:file:" + getRelativePath() + "!/nested.jar!/3.dat");
JarFile nested = this.jarFile
.getNestedJarFile(this.jarFile.getEntry("nested.jar"));
assertThat(JarURLConnection.get(url, nested).getInputStream())
.hasSameContentAs(new ByteArrayInputStream(new byte[] { 3 }));
}
@Test
public void connectionToEntryInNestedJarFromUrlThatUsesExistingUrlAsContext()
throws Exception {
URL url = new URL(new URL("jar", null, -1,
"file:" + getAbsolutePath() + "!/nested.jar!/", new Handler()), "/3.dat");
JarFile nested = this.jarFile
.getNestedJarFile(this.jarFile.getEntry("nested.jar"));
assertThat(JarURLConnection.get(url, nested).getInputStream())
.hasSameContentAs(new ByteArrayInputStream(new byte[] { 3 }));
}
@Test
public void connectionToEntryWithSpaceNestedEntry() throws Exception {
URL url = new URL("jar:file:" + getRelativePath() + "!/space nested.jar!/3.dat");
assertThat(JarURLConnection.get(url, this.jarFile).getInputStream())
.hasSameContentAs(new ByteArrayInputStream(new byte[] { 3 }));
}
@Test
public void connectionToEntryWithEncodedSpaceNestedEntry() throws Exception {
URL url = new URL(
"jar:file:" + getRelativePath() + "!/space%20nested.jar!/3.dat");
assertThat(JarURLConnection.get(url, this.jarFile).getInputStream())
.hasSameContentAs(new ByteArrayInputStream(new byte[] { 3 }));
}
@Test
public void connectionToEntryUsingWrongAbsoluteUrlForEntryFromNestedJarFile()
throws Exception {
URL url = new URL("jar:file:" + getAbsolutePath() + "!/w.jar!/3.dat");
JarFile nested = this.jarFile
.getNestedJarFile(this.jarFile.getEntry("nested.jar"));
this.thrown.expect(FileNotFoundException.class);
JarURLConnection.get(url, nested).getInputStream();
}
@Test
public void getContentLengthReturnsLengthOfUnderlyingEntry() throws Exception {
URL url = new URL(new URL("jar", null, -1,
"file:" + getAbsolutePath() + "!/nested.jar!/", new Handler()), "/3.dat");
assertThat(url.openConnection().getContentLength()).isEqualTo(1);
}
@Test
public void getContentLengthLongReturnsLengthOfUnderlyingEntry() throws Exception {
URL url = new URL(new URL("jar", null, -1,
"file:" + getAbsolutePath() + "!/nested.jar!/", new Handler()), "/3.dat");
assertThat(url.openConnection().getContentLengthLong()).isEqualTo(1);
}
@Test
public void getLastModifiedReturnsLastModifiedTimeOfJarEntry() throws Exception {
URL url = new URL("jar:file:" + getAbsolutePath() + "!/1.dat");
JarURLConnection connection = JarURLConnection.get(url, this.jarFile);
assertThat(connection.getLastModified())
.isEqualTo(connection.getJarEntry().getTime());
}
private String getAbsolutePath() {
return this.rootJarFile.getAbsolutePath().replace('\\', '/');
}
private String getRelativePath() {
return this.rootJarFile.getPath().replace('\\', '/');
}
}
|
spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/JarURLConnectionTests.java
|
/*
* Copyright 2012-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.loader.jar;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.net.URL;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.rules.TemporaryFolder;
import org.springframework.boot.loader.TestJarCreator;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link JarURLConnection}.
*
* @author Andy Wilkinson
* @author Phillip Webb
* @author Rostyslav Dudka
*/
public class JarURLConnectionTests {
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder(new File("target"));
@Rule
public ExpectedException thrown = ExpectedException.none();
private File rootJarFile;
private JarFile jarFile;
@Before
public void setup() throws Exception {
this.rootJarFile = this.temporaryFolder.newFile();
TestJarCreator.createTestJar(this.rootJarFile);
this.jarFile = new JarFile(this.rootJarFile);
}
@Test
public void connectionToRootUsingAbsoluteUrl() throws Exception {
URL url = new URL("jar:file:" + getAbsolutePath() + "!/");
assertThat(JarURLConnection.get(url, this.jarFile).getContent())
.isSameAs(this.jarFile);
}
@Test
public void connectionToRootUsingRelativeUrl() throws Exception {
URL url = new URL("jar:file:" + getRelativePath() + "!/");
assertThat(JarURLConnection.get(url, this.jarFile).getContent())
.isSameAs(this.jarFile);
}
@Test
public void connectionToEntryUsingAbsoluteUrl() throws Exception {
URL url = new URL("jar:file:" + getAbsolutePath() + "!/1.dat");
assertThat(JarURLConnection.get(url, this.jarFile).getInputStream())
.hasSameContentAs(new ByteArrayInputStream(new byte[] { 1 }));
}
@Test
public void connectionToEntryUsingRelativeUrl() throws Exception {
URL url = new URL("jar:file:" + getRelativePath() + "!/1.dat");
assertThat(JarURLConnection.get(url, this.jarFile).getInputStream())
.hasSameContentAs(new ByteArrayInputStream(new byte[] { 1 }));
}
@Test
public void connectionToEntryUsingAbsoluteUrlWithFileColonSlashSlashPrefix()
throws Exception {
URL url = new URL("jar:file:/" + getAbsolutePath() + "!/1.dat");
assertThat(JarURLConnection.get(url, this.jarFile).getInputStream())
.hasSameContentAs(new ByteArrayInputStream(new byte[] { 1 }));
}
@Test
public void connectionToEntryUsingAbsoluteUrlForNestedEntry() throws Exception {
URL url = new URL("jar:file:" + getAbsolutePath() + "!/nested.jar!/3.dat");
assertThat(JarURLConnection.get(url, this.jarFile).getInputStream())
.hasSameContentAs(new ByteArrayInputStream(new byte[] { 3 }));
}
@Test
public void connectionToEntryUsingRelativeUrlForNestedEntry() throws Exception {
URL url = new URL("jar:file:" + getRelativePath() + "!/nested.jar!/3.dat");
assertThat(JarURLConnection.get(url, this.jarFile).getInputStream())
.hasSameContentAs(new ByteArrayInputStream(new byte[] { 3 }));
}
@Test
public void connectionToEntryUsingAbsoluteUrlForEntryFromNestedJarFile()
throws Exception {
URL url = new URL("jar:file:" + getAbsolutePath() + "!/nested.jar!/3.dat");
JarFile nested = this.jarFile
.getNestedJarFile(this.jarFile.getEntry("nested.jar"));
assertThat(JarURLConnection.get(url, nested).getInputStream())
.hasSameContentAs(new ByteArrayInputStream(new byte[] { 3 }));
}
@Test
public void connectionToEntryUsingRelativeUrlForEntryFromNestedJarFile()
throws Exception {
URL url = new URL("jar:file:" + getRelativePath() + "!/nested.jar!/3.dat");
JarFile nested = this.jarFile
.getNestedJarFile(this.jarFile.getEntry("nested.jar"));
assertThat(JarURLConnection.get(url, nested).getInputStream())
.hasSameContentAs(new ByteArrayInputStream(new byte[] { 3 }));
}
@Test
public void connectionToEntryInNestedJarFromUrlThatUsesExistingUrlAsContext()
throws Exception {
URL url = new URL(new URL("jar", null, -1,
"file:" + getAbsolutePath() + "!/nested.jar!/", new Handler()), "/3.dat");
JarFile nested = this.jarFile
.getNestedJarFile(this.jarFile.getEntry("nested.jar"));
assertThat(JarURLConnection.get(url, nested).getInputStream())
.hasSameContentAs(new ByteArrayInputStream(new byte[] { 3 }));
}
@Test
public void connectionToEntryWithSpaceNestedEntry() throws Exception {
URL url = new URL("jar:file:" + getRelativePath() + "!/space nested.jar!/3.dat");
assertThat(JarURLConnection.get(url, this.jarFile).getInputStream())
.hasSameContentAs(new ByteArrayInputStream(new byte[] { 3 }));
}
@Test
public void connectionToEntryWithEncodedSpaceNestedEntry() throws Exception {
URL url = new URL(
"jar:file:" + getRelativePath() + "!/space%20nested.jar!/3.dat");
assertThat(JarURLConnection.get(url, this.jarFile).getInputStream())
.hasSameContentAs(new ByteArrayInputStream(new byte[] { 3 }));
}
@Test(expected = FileNotFoundException.class)
public void connectionToEntryUsingWrongAbsoluteUrlForEntryFromNestedJarFile()
throws Exception {
URL url = new URL("jar:file:" + getAbsolutePath() + "!/w.jar!/3.dat");
JarFile nested = this.jarFile
.getNestedJarFile(this.jarFile.getEntry("nested.jar"));
JarURLConnection.get(url, nested).getInputStream();
}
@Test
public void getContentLengthReturnsLengthOfUnderlyingEntry() throws Exception {
URL url = new URL(new URL("jar", null, -1,
"file:" + getAbsolutePath() + "!/nested.jar!/", new Handler()), "/3.dat");
assertThat(url.openConnection().getContentLength()).isEqualTo(1);
}
@Test
public void getContentLengthLongReturnsLengthOfUnderlyingEntry() throws Exception {
URL url = new URL(new URL("jar", null, -1,
"file:" + getAbsolutePath() + "!/nested.jar!/", new Handler()), "/3.dat");
assertThat(url.openConnection().getContentLengthLong()).isEqualTo(1);
}
@Test
public void getLastModifiedReturnsLastModifiedTimeOfJarEntry() throws Exception {
URL url = new URL("jar:file:" + getAbsolutePath() + "!/1.dat");
JarURLConnection connection = JarURLConnection.get(url, this.jarFile);
assertThat(connection.getLastModified())
.isEqualTo(connection.getJarEntry().getTime());
}
private String getAbsolutePath() {
return this.rootJarFile.getAbsolutePath().replace('\\', '/');
}
private String getRelativePath() {
return this.rootJarFile.getPath().replace('\\', '/');
}
}
|
Polish
|
spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/JarURLConnectionTests.java
|
Polish
|
|
Java
|
apache-2.0
|
f5d4a7253ca029065195105ab5dceabd3dddbb5d
| 0
|
rawbenny/BroadleafCommerce,passion1014/metaworks_framework,TouK/BroadleafCommerce,macielbombonato/BroadleafCommerce,alextiannus/BroadleafCommerce,shopizer/BroadleafCommerce,cogitoboy/BroadleafCommerce,liqianggao/BroadleafCommerce,zhaorui1/BroadleafCommerce,cloudbearings/BroadleafCommerce,TouK/BroadleafCommerce,cogitoboy/BroadleafCommerce,trombka/blc-tmp,ljshj/BroadleafCommerce,alextiannus/BroadleafCommerce,shopizer/BroadleafCommerce,caosg/BroadleafCommerce,arshadalisoomro/BroadleafCommerce,udayinfy/BroadleafCommerce,caosg/BroadleafCommerce,zhaorui1/BroadleafCommerce,gengzhengtao/BroadleafCommerce,liqianggao/BroadleafCommerce,liqianggao/BroadleafCommerce,lgscofield/BroadleafCommerce,lgscofield/BroadleafCommerce,ljshj/BroadleafCommerce,udayinfy/BroadleafCommerce,trombka/blc-tmp,udayinfy/BroadleafCommerce,zhaorui1/BroadleafCommerce,passion1014/metaworks_framework,cengizhanozcan/BroadleafCommerce,arshadalisoomro/BroadleafCommerce,ljshj/BroadleafCommerce,sanlingdd/broadleaf,trombka/blc-tmp,jiman94/BroadleafCommerce-BroadleafCommerce2014,daniellavoie/BroadleafCommerce,daniellavoie/BroadleafCommerce,TouK/BroadleafCommerce,macielbombonato/BroadleafCommerce,cogitoboy/BroadleafCommerce,passion1014/metaworks_framework,bijukunjummen/BroadleafCommerce,SerPenTeHoK/BroadleafCommerce,wenmangbo/BroadleafCommerce,lgscofield/BroadleafCommerce,sanlingdd/broadleaf,alextiannus/BroadleafCommerce,caosg/BroadleafCommerce,rawbenny/BroadleafCommerce,cengizhanozcan/BroadleafCommerce,macielbombonato/BroadleafCommerce,arshadalisoomro/BroadleafCommerce,wenmangbo/BroadleafCommerce,sitexa/BroadleafCommerce,cloudbearings/BroadleafCommerce,wenmangbo/BroadleafCommerce,gengzhengtao/BroadleafCommerce,sitexa/BroadleafCommerce,daniellavoie/BroadleafCommerce,cloudbearings/BroadleafCommerce,SerPenTeHoK/BroadleafCommerce,shopizer/BroadleafCommerce,jiman94/BroadleafCommerce-BroadleafCommerce2014,SerPenTeHoK/BroadleafCommerce,sitexa/BroadleafCommerce,gengzhengtao/BroadleafCommerce,bijukunjummen/BroadleafCommerce,cengizhanozcan/BroadleafCommerce,rawbenny/BroadleafCommerce,bijukunjummen/BroadleafCommerce
|
/*
* Copyright 2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.broadleafcommerce.core.web.processor;
import org.broadleafcommerce.common.money.Money;
import org.thymeleaf.Arguments;
import org.thymeleaf.dom.Element;
import org.thymeleaf.processor.attr.AbstractTextChildModifierAttrProcessor;
import org.thymeleaf.standard.expression.StandardExpressionProcessor;
/**
* A Thymeleaf processor that renders a Money object according to the currently set locale options.
* For example, when rendering "6.99" in a US locale, the output text would be "$6.99".
* When viewing in France for example, you might see "6,99 (US)$". Alternatively, if currency conversion
* was enabled, you may see "5,59 (euro-symbol)"
*
* @author apazzolini
*/
public class PriceTextDisplayProcessor extends AbstractTextChildModifierAttrProcessor {
/**
* Sets the name of this processor to be used in Thymeleaf template
*/
public PriceTextDisplayProcessor() {
super("price");
}
@Override
public int getPrecedence() {
return 10000;
}
// TODO: Actually make the returned text formatted for the given locale
@Override
protected String getText(Arguments arguments, Element element, String attributeName) {
Money price = (Money) StandardExpressionProcessor.processExpression(arguments, element.getAttributeValue(attributeName));
return "$" + price.getAmount().toString();
}
}
|
core/broadleaf-framework-web/src/main/java/org/broadleafcommerce/core/web/processor/PriceTextDisplayProcessor.java
|
/*
* Copyright 2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.broadleafcommerce.core.web.processor;
import org.broadleafcommerce.common.money.Money;
import org.thymeleaf.Arguments;
import org.thymeleaf.dom.Element;
import org.thymeleaf.processor.attr.AbstractTextChildModifierAttrProcessor;
import org.thymeleaf.standard.expression.StandardExpressionProcessor;
/**
* A Thymeleaf processor that renders a Money object according to the currently set locale options.
* For example, when rendering "6.99" in a US locale, the output text would be "$6.99".
* When viewing in France for example, you might see "6,99 (US)$". Alternatively, if currency conversion
* was enabled, you may see "5,59 €"
*
* @author apazzolini
*/
public class PriceTextDisplayProcessor extends AbstractTextChildModifierAttrProcessor {
/**
* Sets the name of this processor to be used in Thymeleaf template
*/
public PriceTextDisplayProcessor() {
super("price");
}
@Override
public int getPrecedence() {
return 10000;
}
// TODO: Actually make the returned text formatted for the given locale
@Override
protected String getText(Arguments arguments, Element element, String attributeName) {
Money price = (Money) StandardExpressionProcessor.processExpression(arguments, element.getAttributeValue(attributeName));
return "$" + price.getAmount().toString();
}
}
|
Remove Euro symbol from javadoc comment as it was potentially breaking the build
|
core/broadleaf-framework-web/src/main/java/org/broadleafcommerce/core/web/processor/PriceTextDisplayProcessor.java
|
Remove Euro symbol from javadoc comment as it was potentially breaking the build
|
|
Java
|
apache-2.0
|
129b171c11be823860f9621875be5d5fa2ae51fa
| 0
|
logic-ng/LogicNG
|
///////////////////////////////////////////////////////////////////////////
// __ _ _ ________ //
// / / ____ ____ _(_)____/ | / / ____/ //
// / / / __ \/ __ `/ / ___/ |/ / / __ //
// / /___/ /_/ / /_/ / / /__/ /| / /_/ / //
// /_____/\____/\__, /_/\___/_/ |_/\____/ //
// /____/ //
// //
// The Next Generation Logic Library //
// //
///////////////////////////////////////////////////////////////////////////
// //
// Copyright 2015-2017 Christoph Zengler //
// //
// Licensed under the Apache License, Version 2.0 (the "License"); //
// you may not use this file except in compliance with the License. //
// You may obtain a copy of the License at //
// //
// http://www.apache.org/licenses/LICENSE-2.0 //
// //
// Unless required by applicable law or agreed to in writing, software //
// distributed under the License is distributed on an "AS IS" BASIS, //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or //
// implied. See the License for the specific language governing //
// permissions and limitations under the License. //
// //
///////////////////////////////////////////////////////////////////////////
package org.logicng.solvers;
import org.logicng.cardinalityconstraints.CCEncoder;
import org.logicng.cardinalityconstraints.CCIncrementalData;
import org.logicng.collections.LNGBooleanVector;
import org.logicng.collections.LNGIntVector;
import org.logicng.collections.LNGVector;
import org.logicng.datastructures.Assignment;
import org.logicng.datastructures.EncodingResult;
import org.logicng.datastructures.Tristate;
import org.logicng.explanations.unsatcores.UNSATCore;
import org.logicng.explanations.unsatcores.drup.DRUPTrim;
import org.logicng.formulas.CType;
import org.logicng.formulas.FType;
import org.logicng.formulas.Formula;
import org.logicng.formulas.FormulaFactory;
import org.logicng.formulas.Literal;
import org.logicng.formulas.PBConstraint;
import org.logicng.formulas.Variable;
import org.logicng.handlers.ModelEnumerationHandler;
import org.logicng.handlers.SATHandler;
import org.logicng.propositions.Proposition;
import org.logicng.propositions.StandardProposition;
import org.logicng.solvers.sat.GlucoseConfig;
import org.logicng.solvers.sat.GlucoseSyrup;
import org.logicng.solvers.sat.MiniCard;
import org.logicng.solvers.sat.MiniSat2Solver;
import org.logicng.solvers.sat.MiniSatConfig;
import org.logicng.solvers.sat.MiniSatStyleSolver;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import static org.logicng.datastructures.Tristate.TRUE;
import static org.logicng.datastructures.Tristate.UNDEF;
/**
* Wrapper for the MiniSAT-style SAT solvers.
* @version 1.3.1
* @since 1.0
*/
public final class MiniSat extends SATSolver {
private enum SolverStyle {MINISAT, GLUCOSE, MINICARD}
private final MiniSatConfig config;
private final MiniSatStyleSolver solver;
private final CCEncoder ccEncoder;
private final SolverStyle style;
private final LNGIntVector validStates;
private final boolean initialPhase;
private boolean incremental;
private int nextStateId;
/**
* Constructs a new SAT solver instance.
* @param f the formula factory
* @param solverStyle the solver style
* @throws IllegalArgumentException if the solver style is unknown
*/
private MiniSat(final FormulaFactory f, final SolverStyle solverStyle, final MiniSatConfig miniSatConfig,
final GlucoseConfig glucoseConfig) {
super(f);
this.config = miniSatConfig;
this.style = solverStyle;
this.initialPhase = miniSatConfig.initialPhase();
switch (solverStyle) {
case MINISAT:
this.solver = new MiniSat2Solver(miniSatConfig);
break;
case GLUCOSE:
this.solver = new GlucoseSyrup(miniSatConfig, glucoseConfig);
break;
case MINICARD:
this.solver = new MiniCard(miniSatConfig);
break;
default:
throw new IllegalArgumentException("Unknown solver style: " + solverStyle);
}
this.result = UNDEF;
this.incremental = miniSatConfig.incremental();
this.validStates = new LNGIntVector();
this.nextStateId = 0;
this.ccEncoder = new CCEncoder(f);
}
/**
* Returns a new MiniSat solver.
* @param f the formula factory
* @return the solver
*/
public static MiniSat miniSat(final FormulaFactory f) {
return new MiniSat(f, SolverStyle.MINISAT, new MiniSatConfig.Builder().build(), null);
}
/**
* Returns a new MiniSat solver with a given configuration.
* @param f the formula factory
* @param config the configuration
* @return the solver
*/
public static MiniSat miniSat(final FormulaFactory f, final MiniSatConfig config) {
return new MiniSat(f, SolverStyle.MINISAT, config, null);
}
/**
* Returns a new Glucose solver.
* @param f the formula factory
* @return the solver
*/
public static MiniSat glucose(final FormulaFactory f) {
return new MiniSat(f, SolverStyle.GLUCOSE, new MiniSatConfig.Builder().build(), new GlucoseConfig.Builder().build());
}
/**
* Returns a new Glucose solver with a given configuration.
* @param f the formula factory
* @param miniSatConfig the MiniSat configuration
* @param glucoseConfig the Glucose configuration
* @return the solver
*/
public static MiniSat glucose(final FormulaFactory f, final MiniSatConfig miniSatConfig,
final GlucoseConfig glucoseConfig) {
return new MiniSat(f, SolverStyle.GLUCOSE, miniSatConfig, glucoseConfig);
}
/**
* Returns a new MiniCard solver.
* @param f the formula factory
* @return the solver
*/
public static MiniSat miniCard(final FormulaFactory f) {
return new MiniSat(f, SolverStyle.MINICARD, new MiniSatConfig.Builder().build(), null);
}
/**
* Returns a new MiniCard solver with a given configuration.
* @param f the formula factory
* @param config the configuration
* @return the solver
*/
public static MiniSat miniCard(final FormulaFactory f, final MiniSatConfig config) {
return new MiniSat(f, SolverStyle.MINICARD, config, null);
}
@Override
public void add(final Formula formula, Proposition proposition) {
if (formula.type() == FType.PBC) {
final PBConstraint constraint = (PBConstraint) formula;
this.result = UNDEF;
if (constraint.isCC()) {
if (this.style == SolverStyle.MINICARD) {
if (constraint.comparator() == CType.LE)
((MiniCard) this.solver).addAtMost(generateClauseVector(Arrays.asList(constraint.operands())), constraint.rhs());
else if (constraint.comparator() == CType.LT && constraint.rhs() > 3)
((MiniCard) this.solver).addAtMost(generateClauseVector(Arrays.asList(constraint.operands())), constraint.rhs() - 1);
else if (constraint.comparator() == CType.EQ && constraint.rhs() == 1) {
((MiniCard) this.solver).addAtMost(generateClauseVector(Arrays.asList(constraint.operands())), constraint.rhs());
this.solver.addClause(generateClauseVector(Arrays.asList(constraint.operands())), proposition);
} else
this.addClauseSet(constraint.cnf(), proposition);
} else {
final EncodingResult result = EncodingResult.resultForMiniSat(this.f, this);
ccEncoder.encode(constraint, result);
}
} else
this.addClauseSet(constraint.cnf(), proposition);
} else
this.addClauseSet(formula.cnf(), proposition);
}
@Override
public void addWithoutUnknown(final Formula formula) {
final int nVars = this.solver.nVars();
final Assignment restriction = new Assignment(true);
final Map<String, Integer> map = this.solver.name2idx();
for (final Variable var : formula.variables()) {
final Integer index = map.get(var.name());
if (index == null || index >= nVars)
restriction.addLiteral(var.negate());
}
this.add(formula.restrict(restriction));
}
@Override
public CCIncrementalData addIncrementalCC(PBConstraint cc) {
if (!cc.isCC())
throw new IllegalArgumentException("Cannot generate an incremental cardinality constraint on a pseudo-Boolean constraint");
final EncodingResult result = EncodingResult.resultForMiniSat(this.f, this);
return ccEncoder.encodeIncremental(cc, result);
}
@Override
protected void addClause(final Formula formula, final Proposition proposition) {
this.result = UNDEF;
this.solver.addClause(generateClauseVector(formula.literals()), proposition);
}
@Override
protected void addClauseWithRelaxation(Variable relaxationVar, Formula formula) {
this.result = UNDEF;
final SortedSet<Literal> literals = new TreeSet<>(formula.literals());
literals.add(relaxationVar);
this.solver.addClause(generateClauseVector(literals), null);
}
@Override
public Tristate sat(final SATHandler handler) {
if (this.result != UNDEF)
return this.result;
this.result = this.solver.solve(handler);
return result;
}
@Override
public Tristate sat(final SATHandler handler, final Literal literal) {
final LNGIntVector clauseVec = new LNGIntVector(1);
int index = this.solver.idxForName(literal.name());
if (index == -1) {
index = this.solver.newVar(!initialPhase, true);
this.solver.addName(literal.name(), index);
}
int litNum = literal.phase() ? index * 2 : (index * 2) ^ 1;
clauseVec.push(litNum);
this.result = this.solver.solve(handler, clauseVec);
return this.result;
}
@Override
public Tristate sat(final SATHandler handler, final Collection<? extends Literal> assumptions) {
final Set<Literal> assumptionSet = new LinkedHashSet<>(assumptions);
final LNGIntVector assumptionVec = new LNGIntVector(assumptionSet.size());
for (final Literal literal : assumptionSet) {
int index = this.solver.idxForName(literal.name());
if (index == -1) {
index = this.solver.newVar(!initialPhase, true);
this.solver.addName(literal.name(), index);
}
int litNum = literal.phase() ? index * 2 : (index * 2) ^ 1;
assumptionVec.push(litNum);
}
this.result = this.solver.solve(handler, assumptionVec);
return this.result;
}
@Override
public void reset() {
this.solver.reset();
this.result = UNDEF;
}
@Override
public Assignment model(final Collection<Variable> variables) {
if (this.result == UNDEF)
throw new IllegalStateException("Cannot get a model as long as the formula is not solved. Call 'sat' first.");
final LNGIntVector relevantIndices = variables == null ? null : new LNGIntVector(variables.size());
if (relevantIndices != null) {
for (Variable var : variables) {
relevantIndices.push(this.solver.idxForName(var.name()));
}
}
return this.result == TRUE ? this.createAssignment(this.solver.model(), relevantIndices) : null;
}
@Override
public List<Assignment> enumerateAllModels(final Collection<Variable> variables) {
return enumerateAllModels(variables, Collections.<Variable>emptyList());
}
@Override
public List<Assignment> enumerateAllModels(Collection<Variable> variables, Collection<Variable> additionalVariables) {
return enumerateAllModels(variables, additionalVariables, null);
}
@Override
public List<Assignment> enumerateAllModels(final Collection<Variable> literals, final ModelEnumerationHandler handler) {
return enumerateAllModels(literals, Collections.<Variable>emptyList(), handler);
}
@Override
public List<Assignment> enumerateAllModels(Collection<Variable> variables, Collection<Variable> additionalVariables, ModelEnumerationHandler handler) {
List<Assignment> models = new LinkedList<>();
SolverState stateBeforeEnumeration = null;
if (this.style == SolverStyle.MINISAT && incremental)
stateBeforeEnumeration = this.saveState();
boolean proceed = true;
SortedSet<Variable> allVariables = new TreeSet<>();
if (variables == null) {
allVariables = null;
} else {
allVariables.addAll(variables);
allVariables.addAll(additionalVariables);
}
final LNGIntVector relevantIndices = variables == null ? null : new LNGIntVector(variables.size());
LNGIntVector relevantAllIndices = null;
if (relevantIndices != null) {
for (Variable var : variables) {
relevantIndices.push(this.solver.idxForName(var.name()));
}
relevantAllIndices = additionalVariables.isEmpty() ? relevantIndices : new LNGIntVector(allVariables.size());
if (!additionalVariables.isEmpty()) {
for (Variable var : allVariables) {
relevantAllIndices.push(this.solver.idxForName(var.name()));
}
}
}
while (proceed && this.sat((SATHandler) null) == TRUE) {
final LNGBooleanVector modelFromSolver = this.solver.model();
final Assignment model = this.createAssignment(modelFromSolver, relevantAllIndices);
assert model != null;
models.add(model);
proceed = handler == null || handler.foundModel(model);
if (model.size() > 0) {
LNGIntVector blockingClause = generateBlockingClause(modelFromSolver, relevantIndices);
this.solver.addClause(blockingClause, null);
this.result = UNDEF;
} else {
break;
}
}
if (this.style == SolverStyle.MINISAT && incremental)
this.loadState(stateBeforeEnumeration);
return models;
}
/**
* Generates a blocking clause from a given model and a set of relevant variables.
* @param modelFromSolver the current model for which the blocking clause should be generated
* @param relevantVars the indices of the relevant variables. If {@code null} all variables are relevant.
* @return the blocking clause for the given model and relevant variables
*/
private LNGIntVector generateBlockingClause(final LNGBooleanVector modelFromSolver, final LNGIntVector relevantVars) {
final LNGIntVector blockingClause;
if (relevantVars != null) {
blockingClause = new LNGIntVector(relevantVars.size());
for (int i = 0; i < relevantVars.size(); i++) {
final int varIndex = relevantVars.get(i);
final boolean varAssignment = modelFromSolver.get(varIndex);
blockingClause.push(varAssignment ? (varIndex * 2) ^ 1 : varIndex * 2);
}
} else {
blockingClause = new LNGIntVector(modelFromSolver.size());
for (int i = 0; i < modelFromSolver.size(); i++) {
final boolean varAssignment = modelFromSolver.get(i);
blockingClause.push(varAssignment ? (i * 2) ^ 1 : i * 2);
}
}
return blockingClause;
}
@Override
public SolverState saveState() {
final int id = this.nextStateId++;
validStates.push(id);
return new SolverState(id, this.solver.saveState());
}
@Override
public void loadState(final SolverState state) {
int index = -1;
for (int i = validStates.size() - 1; i >= 0 && index == -1; i--)
if (validStates.get(i) == state.id())
index = i;
if (index == -1)
throw new IllegalArgumentException("The given solver state is not valid anymore.");
this.validStates.shrinkTo(index + 1);
this.solver.loadState(state.state());
this.result = UNDEF;
}
@Override
public SortedSet<Variable> knownVariables() {
final SortedSet<Variable> result = new TreeSet<>();
final int nVars = this.solver.nVars();
for (final Map.Entry<String, Integer> entry : this.solver.name2idx().entrySet())
if (entry.getValue() < nVars)
result.add(this.f.variable(entry.getKey()));
return result;
}
@Override
public UNSATCore<Proposition> unsatCore() {
if (!this.config.proofGeneration())
throw new IllegalStateException("Cannot generate an unsat core if proof generation is not turned on");
if (this.result == TRUE)
throw new IllegalStateException("An unsat core can only be generated if the formula is solved and is UNSAT");
if (this.result == Tristate.UNDEF) {
throw new IllegalStateException("Cannot generate an unsat core before the formula was solved.");
}
if (this.underlyingSolver() instanceof MiniCard)
throw new IllegalStateException("Cannot compute an unsat core with MiniCard.");
if (this.underlyingSolver() instanceof GlucoseSyrup && this.config.incremental())
throw new IllegalStateException("Cannot compute an unsat core with Glucose in incremental mode.");
DRUPTrim trimmer = new DRUPTrim();
Map<Formula, Proposition> clause2proposition = new HashMap<>();
final LNGVector<LNGIntVector> clauses = new LNGVector<>(this.underlyingSolver().pgOriginalClauses().size());
for (MiniSatStyleSolver.ProofInformation pi : this.underlyingSolver().pgOriginalClauses()) {
clauses.push(pi.clause());
final Formula clause = getFormulaForVector(pi.clause());
Proposition proposition = pi.proposition();
if (proposition == null)
proposition = new StandardProposition(clause);
clause2proposition.put(clause, proposition);
}
if (containsEmptyClause(clauses)) {
final Proposition emptyClause = clause2proposition.get(f.falsum());
return new UNSATCore<>(Collections.singletonList(emptyClause), true);
}
final DRUPTrim.DRUPResult result = trimmer.compute(clauses, this.underlyingSolver().pgProof());
if (result.trivialUnsat())
return handleTrivialCase();
final LinkedHashSet<Proposition> propositions = new LinkedHashSet<>();
for (LNGIntVector vector : result.unsatCore())
propositions.add(clause2proposition.get(getFormulaForVector(vector)));
return new UNSATCore<>(new ArrayList<>(propositions), false);
}
/**
* Generates a clause vector of a collection of literals.
* @param literals the literals
* @return the clause vector
*/
private LNGIntVector generateClauseVector(final Collection<Literal> literals) {
final LNGIntVector clauseVec = new LNGIntVector(literals.size());
for (Literal lit : literals) {
int index = this.solver.idxForName(lit.name());
if (index == -1) {
index = this.solver.newVar(!initialPhase, true);
this.solver.addName(lit.name(), index);
}
int litNum = lit.phase() ? index * 2 : (index * 2) ^ 1;
clauseVec.push(litNum);
}
return clauseVec;
}
/**
* Creates an assignment from a Boolean vector of the solver.
* @param vec the vector of the solver
* @param relevantIndices the solver's indices of the relevant variables for the model. If {@code null}, all
* variables are relevant.
* @return the assignment
*/
private Assignment createAssignment(final LNGBooleanVector vec, final LNGIntVector relevantIndices) {
final Assignment model = new Assignment();
if (relevantIndices == null) {
for (int i = 0; i < vec.size(); i++) {
model.addLiteral(f.literal(this.solver.nameForIdx(i), vec.get(i)));
}
} else {
for (int i = 0; i < relevantIndices.size(); i++) {
final int index = relevantIndices.get(i);
if (index != -1) {
model.addLiteral(f.literal(this.solver.nameForIdx(index), vec.get(index)));
}
}
}
return model;
}
/**
* Returns the underlying core solver.
* <p>
* ATTENTION: by influencing the underlying solver directly, you can mess things up completely! You should really
* know, what you are doing.
* @return the underlying core solver
*/
public MiniSatStyleSolver underlyingSolver() {
return this.solver;
}
/**
* Returns the initial phase of literals of this solver.
* @return the initial phase of literals of this solver
*/
public boolean initialPhase() {
return this.initialPhase;
}
private UNSATCore<Proposition> handleTrivialCase() {
final LNGVector<MiniSatStyleSolver.ProofInformation> clauses = this.underlyingSolver().pgOriginalClauses();
for (int i = 0; i < clauses.size(); i++)
for (int j = i + 1; j < clauses.size(); j++) {
if (clauses.get(i).clause().size() == 1 && clauses.get(j).clause().size() == 1
&& clauses.get(i).clause().get(0) + clauses.get(j).clause().get(0) == 0) {
LinkedHashSet<Proposition> propositions = new LinkedHashSet<>();
propositions.add(clauses.get(i).proposition());
propositions.add(clauses.get(j).proposition());
return new UNSATCore<>(new ArrayList<>(propositions), false);
}
}
throw new IllegalStateException("Should be a trivial unsat core, but did not found one.");
}
private boolean containsEmptyClause(final LNGVector<LNGIntVector> clauses) {
for (LNGIntVector clause : clauses)
if (clause.empty())
return true;
return false;
}
private Formula getFormulaForVector(LNGIntVector vector) {
final List<Literal> literals = new ArrayList<>(vector.size());
for (int i = 0; i < vector.size(); i++) {
int lit = vector.get(i);
String varName = this.underlyingSolver().nameForIdx(Math.abs(lit) - 1);
literals.add(f.literal(varName, lit > 0));
}
return f.or(literals);
}
@Override
public String toString() {
return String.format("MiniSat{result=%s, incremental=%s}", this.result, this.incremental);
}
}
|
src/main/java/org/logicng/solvers/MiniSat.java
|
///////////////////////////////////////////////////////////////////////////
// __ _ _ ________ //
// / / ____ ____ _(_)____/ | / / ____/ //
// / / / __ \/ __ `/ / ___/ |/ / / __ //
// / /___/ /_/ / /_/ / / /__/ /| / /_/ / //
// /_____/\____/\__, /_/\___/_/ |_/\____/ //
// /____/ //
// //
// The Next Generation Logic Library //
// //
///////////////////////////////////////////////////////////////////////////
// //
// Copyright 2015-2017 Christoph Zengler //
// //
// Licensed under the Apache License, Version 2.0 (the "License"); //
// you may not use this file except in compliance with the License. //
// You may obtain a copy of the License at //
// //
// http://www.apache.org/licenses/LICENSE-2.0 //
// //
// Unless required by applicable law or agreed to in writing, software //
// distributed under the License is distributed on an "AS IS" BASIS, //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or //
// implied. See the License for the specific language governing //
// permissions and limitations under the License. //
// //
///////////////////////////////////////////////////////////////////////////
package org.logicng.solvers;
import org.logicng.cardinalityconstraints.CCEncoder;
import org.logicng.cardinalityconstraints.CCIncrementalData;
import org.logicng.collections.LNGBooleanVector;
import org.logicng.collections.LNGIntVector;
import org.logicng.collections.LNGVector;
import org.logicng.datastructures.Assignment;
import org.logicng.datastructures.EncodingResult;
import org.logicng.datastructures.Tristate;
import org.logicng.explanations.unsatcores.UNSATCore;
import org.logicng.explanations.unsatcores.drup.DRUPTrim;
import org.logicng.formulas.CType;
import org.logicng.formulas.FType;
import org.logicng.formulas.Formula;
import org.logicng.formulas.FormulaFactory;
import org.logicng.formulas.Literal;
import org.logicng.formulas.PBConstraint;
import org.logicng.formulas.Variable;
import org.logicng.handlers.ModelEnumerationHandler;
import org.logicng.handlers.SATHandler;
import org.logicng.propositions.Proposition;
import org.logicng.propositions.StandardProposition;
import org.logicng.solvers.sat.GlucoseConfig;
import org.logicng.solvers.sat.GlucoseSyrup;
import org.logicng.solvers.sat.MiniCard;
import org.logicng.solvers.sat.MiniSat2Solver;
import org.logicng.solvers.sat.MiniSatConfig;
import org.logicng.solvers.sat.MiniSatStyleSolver;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import static org.logicng.datastructures.Tristate.TRUE;
import static org.logicng.datastructures.Tristate.UNDEF;
import static org.logicng.solvers.sat.MiniSatStyleSolver.var;
/**
* Wrapper for the MiniSAT-style SAT solvers.
* @version 1.3
* @since 1.0
*/
public final class MiniSat extends SATSolver {
private enum SolverStyle {MINISAT, GLUCOSE, MINICARD}
private final MiniSatConfig config;
private final MiniSatStyleSolver solver;
private final CCEncoder ccEncoder;
private final SolverStyle style;
private final LNGIntVector validStates;
private final boolean initialPhase;
private boolean incremental;
private int nextStateId;
/**
* Constructs a new SAT solver instance.
* @param f the formula factory
* @param solverStyle the solver style
* @throws IllegalArgumentException if the solver style is unknown
*/
private MiniSat(final FormulaFactory f, final SolverStyle solverStyle, final MiniSatConfig miniSatConfig,
final GlucoseConfig glucoseConfig) {
super(f);
this.config = miniSatConfig;
this.style = solverStyle;
this.initialPhase = miniSatConfig.initialPhase();
switch (solverStyle) {
case MINISAT:
this.solver = new MiniSat2Solver(miniSatConfig);
break;
case GLUCOSE:
this.solver = new GlucoseSyrup(miniSatConfig, glucoseConfig);
break;
case MINICARD:
this.solver = new MiniCard(miniSatConfig);
break;
default:
throw new IllegalArgumentException("Unknown solver style: " + solverStyle);
}
this.result = UNDEF;
this.incremental = miniSatConfig.incremental();
this.validStates = new LNGIntVector();
this.nextStateId = 0;
this.ccEncoder = new CCEncoder(f);
}
/**
* Returns a new MiniSat solver.
* @param f the formula factory
* @return the solver
*/
public static MiniSat miniSat(final FormulaFactory f) {
return new MiniSat(f, SolverStyle.MINISAT, new MiniSatConfig.Builder().build(), null);
}
/**
* Returns a new MiniSat solver with a given configuration.
* @param f the formula factory
* @param config the configuration
* @return the solver
*/
public static MiniSat miniSat(final FormulaFactory f, final MiniSatConfig config) {
return new MiniSat(f, SolverStyle.MINISAT, config, null);
}
/**
* Returns a new Glucose solver.
* @param f the formula factory
* @return the solver
*/
public static MiniSat glucose(final FormulaFactory f) {
return new MiniSat(f, SolverStyle.GLUCOSE, new MiniSatConfig.Builder().build(), new GlucoseConfig.Builder().build());
}
/**
* Returns a new Glucose solver with a given configuration.
* @param f the formula factory
* @param miniSatConfig the MiniSat configuration
* @param glucoseConfig the Glucose configuration
* @return the solver
*/
public static MiniSat glucose(final FormulaFactory f, final MiniSatConfig miniSatConfig,
final GlucoseConfig glucoseConfig) {
return new MiniSat(f, SolverStyle.GLUCOSE, miniSatConfig, glucoseConfig);
}
/**
* Returns a new MiniCard solver.
* @param f the formula factory
* @return the solver
*/
public static MiniSat miniCard(final FormulaFactory f) {
return new MiniSat(f, SolverStyle.MINICARD, new MiniSatConfig.Builder().build(), null);
}
/**
* Returns a new MiniCard solver with a given configuration.
* @param f the formula factory
* @param config the configuration
* @return the solver
*/
public static MiniSat miniCard(final FormulaFactory f, final MiniSatConfig config) {
return new MiniSat(f, SolverStyle.MINICARD, config, null);
}
@Override
public void add(final Formula formula, Proposition proposition) {
if (formula.type() == FType.PBC) {
final PBConstraint constraint = (PBConstraint) formula;
this.result = UNDEF;
if (constraint.isCC()) {
if (this.style == SolverStyle.MINICARD) {
if (constraint.comparator() == CType.LE)
((MiniCard) this.solver).addAtMost(generateClauseVector(Arrays.asList(constraint.operands())), constraint.rhs());
else if (constraint.comparator() == CType.LT && constraint.rhs() > 3)
((MiniCard) this.solver).addAtMost(generateClauseVector(Arrays.asList(constraint.operands())), constraint.rhs() - 1);
else if (constraint.comparator() == CType.EQ && constraint.rhs() == 1) {
((MiniCard) this.solver).addAtMost(generateClauseVector(Arrays.asList(constraint.operands())), constraint.rhs());
this.solver.addClause(generateClauseVector(Arrays.asList(constraint.operands())), proposition);
} else
this.addClauseSet(constraint.cnf(), proposition);
} else {
final EncodingResult result = EncodingResult.resultForMiniSat(this.f, this);
ccEncoder.encode(constraint, result);
}
} else
this.addClauseSet(constraint.cnf(), proposition);
} else
this.addClauseSet(formula.cnf(), proposition);
}
@Override
public void addWithoutUnknown(final Formula formula) {
final int nVars = this.solver.nVars();
final Assignment restriction = new Assignment(true);
final Map<String, Integer> map = this.solver.name2idx();
for (final Variable var : formula.variables()) {
final Integer index = map.get(var.name());
if (index == null || index >= nVars)
restriction.addLiteral(var.negate());
}
this.add(formula.restrict(restriction));
}
@Override
public CCIncrementalData addIncrementalCC(PBConstraint cc) {
if (!cc.isCC())
throw new IllegalArgumentException("Cannot generate an incremental cardinality constraint on a pseudo-Boolean constraint");
final EncodingResult result = EncodingResult.resultForMiniSat(this.f, this);
return ccEncoder.encodeIncremental(cc, result);
}
@Override
protected void addClause(final Formula formula, final Proposition proposition) {
this.result = UNDEF;
this.solver.addClause(generateClauseVector(formula.literals()), proposition);
}
@Override
protected void addClauseWithRelaxation(Variable relaxationVar, Formula formula) {
this.result = UNDEF;
final SortedSet<Literal> literals = new TreeSet<>(formula.literals());
literals.add(relaxationVar);
this.solver.addClause(generateClauseVector(literals), null);
}
@Override
public Tristate sat(final SATHandler handler) {
if (this.result != UNDEF)
return this.result;
this.result = this.solver.solve(handler);
return result;
}
@Override
public Tristate sat(final SATHandler handler, final Literal literal) {
final LNGIntVector clauseVec = new LNGIntVector(1);
int index = this.solver.idxForName(literal.name());
if (index == -1) {
index = this.solver.newVar(!initialPhase, true);
this.solver.addName(literal.name(), index);
}
int litNum = literal.phase() ? index * 2 : (index * 2) ^ 1;
clauseVec.push(litNum);
this.result = this.solver.solve(handler, clauseVec);
return this.result;
}
@Override
public Tristate sat(final SATHandler handler, final Collection<? extends Literal> assumptions) {
final Set<Literal> assumptionSet = new LinkedHashSet<>(assumptions);
final LNGIntVector assumptionVec = new LNGIntVector(assumptionSet.size());
for (final Literal literal : assumptionSet) {
int index = this.solver.idxForName(literal.name());
if (index == -1) {
index = this.solver.newVar(!initialPhase, true);
this.solver.addName(literal.name(), index);
}
int litNum = literal.phase() ? index * 2 : (index * 2) ^ 1;
assumptionVec.push(litNum);
}
this.result = this.solver.solve(handler, assumptionVec);
return this.result;
}
@Override
public void reset() {
this.solver.reset();
this.result = UNDEF;
}
@Override
public Assignment model(final Collection<Variable> variables) {
if (this.result == UNDEF)
throw new IllegalStateException("Cannot get a model as long as the formula is not solved. Call 'sat' first.");
return this.result == TRUE ? this.createAssignment(this.solver.model(), variables) : null;
}
@Override
public List<Assignment> enumerateAllModels(final Collection<Variable> variables) {
return enumerateAllModels(variables, Collections.<Variable>emptyList());
}
@Override
public List<Assignment> enumerateAllModels(Collection<Variable> variables, Collection<Variable> additionalVariables) {
List<Assignment> models = new LinkedList<>();
SolverState stateBeforeEnumeration = null;
if (this.style == SolverStyle.MINISAT && incremental)
stateBeforeEnumeration = this.saveState();
SortedSet<Variable> allVariables = new TreeSet<>();
if (variables == null) {
allVariables = null;
} else {
allVariables.addAll(variables);
allVariables.addAll(additionalVariables);
}
final LNGIntVector relevantVars = variables == null ? null : new LNGIntVector(variables.size()) ;
if (relevantVars != null) {
for (Variable var : variables) {
relevantVars.push(this.solver.idxForName(var.name()));
}
}
while (this.sat((SATHandler) null) == TRUE) {
final LNGBooleanVector modelFromSolver = this.solver.model();
final Assignment model = this.createAssignment(modelFromSolver, allVariables);
assert model != null;
models.add(model);
if (model.size() > 0) {
LNGIntVector blockingClause = generateBlockingClause(modelFromSolver, relevantVars);
this.solver.addClause(blockingClause, null);
this.result = UNDEF;
} else {
break;
}
}
if (this.style == SolverStyle.MINISAT && incremental)
this.loadState(stateBeforeEnumeration);
return models;
}
@Override
public List<Assignment> enumerateAllModels(final Collection<Variable> literals, final ModelEnumerationHandler handler) {
return enumerateAllModels(literals, Collections.<Variable>emptyList(), handler);
}
@Override
public List<Assignment> enumerateAllModels(Collection<Variable> variables, Collection<Variable> additionalVariables, ModelEnumerationHandler handler) {
List<Assignment> models = new LinkedList<>();
SolverState stateBeforeEnumeration = null;
if (this.style == SolverStyle.MINISAT && incremental)
stateBeforeEnumeration = this.saveState();
boolean proceed = true;
SortedSet<Variable> allVariables = new TreeSet<>();
if (variables == null) {
allVariables = null;
} else {
allVariables.addAll(variables);
allVariables.addAll(additionalVariables);
}
final LNGIntVector relevantVars = variables == null ? null : new LNGIntVector(variables.size()) ;
if (relevantVars != null) {
for (Variable var : variables) {
relevantVars.push(this.solver.idxForName(var.name()));
}
}
while (proceed && this.sat((SATHandler) null) == TRUE) {
final LNGBooleanVector modelFromSolver = this.solver.model();
final Assignment model = this.createAssignment(modelFromSolver, allVariables);
assert model != null;
models.add(model);
proceed = handler.foundModel(model);
if (model.size() > 0) {
LNGIntVector blockingClause = generateBlockingClause(modelFromSolver, relevantVars);
this.solver.addClause(blockingClause, null);
this.result = UNDEF;
} else {
break;
}
}
if (this.style == SolverStyle.MINISAT && incremental)
this.loadState(stateBeforeEnumeration);
return models;
}
private LNGIntVector generateBlockingClause(final LNGBooleanVector modelFromSolver, final LNGIntVector relevantVars) {
final LNGIntVector blockingClause;
if (relevantVars != null) {
blockingClause = new LNGIntVector(relevantVars.size());
for (int i = 0; i < relevantVars.size(); i++) {
final int varIndex = relevantVars.get(i);
final boolean varAssignment = modelFromSolver.get(varIndex);
blockingClause.push(varAssignment ? (varIndex * 2) ^ 1 : varIndex * 2);
}
} else {
blockingClause = new LNGIntVector(modelFromSolver.size());
for (int i = 0; i < modelFromSolver.size(); i++) {
final boolean varAssignment = modelFromSolver.get(i);
blockingClause.push(varAssignment ? (i * 2) ^ 1 : i * 2);
}
}
return blockingClause;
}
@Override
public SolverState saveState() {
final int id = this.nextStateId++;
validStates.push(id);
return new SolverState(id, this.solver.saveState());
}
@Override
public void loadState(final SolverState state) {
int index = -1;
for (int i = validStates.size() - 1; i >= 0 && index == -1; i--)
if (validStates.get(i) == state.id())
index = i;
if (index == -1)
throw new IllegalArgumentException("The given solver state is not valid anymore.");
this.validStates.shrinkTo(index + 1);
this.solver.loadState(state.state());
this.result = UNDEF;
}
@Override
public SortedSet<Variable> knownVariables() {
final SortedSet<Variable> result = new TreeSet<>();
final int nVars = this.solver.nVars();
for (final Map.Entry<String, Integer> entry : this.solver.name2idx().entrySet())
if (entry.getValue() < nVars)
result.add(this.f.variable(entry.getKey()));
return result;
}
@Override
public UNSATCore<Proposition> unsatCore() {
if (!this.config.proofGeneration())
throw new IllegalStateException("Cannot generate an unsat core if proof generation is not turned on");
if (this.result == TRUE)
throw new IllegalStateException("An unsat core can only be generated if the formula is solved and is UNSAT");
if (this.result == Tristate.UNDEF) {
throw new IllegalStateException("Cannot generate an unsat core before the formula was solved.");
}
if (this.underlyingSolver() instanceof MiniCard)
throw new IllegalStateException("Cannot compute an unsat core with MiniCard.");
if (this.underlyingSolver() instanceof GlucoseSyrup && this.config.incremental())
throw new IllegalStateException("Cannot compute an unsat core with Glucose in incremental mode.");
DRUPTrim trimmer = new DRUPTrim();
Map<Formula, Proposition> clause2proposition = new HashMap<>();
final LNGVector<LNGIntVector> clauses = new LNGVector<>(this.underlyingSolver().pgOriginalClauses().size());
for (MiniSatStyleSolver.ProofInformation pi : this.underlyingSolver().pgOriginalClauses()) {
clauses.push(pi.clause());
final Formula clause = getFormulaForVector(pi.clause());
Proposition proposition = pi.proposition();
if (proposition == null)
proposition = new StandardProposition(clause);
clause2proposition.put(clause, proposition);
}
if (containsEmptyClause(clauses)) {
final Proposition emptyClause = clause2proposition.get(f.falsum());
return new UNSATCore<>(Collections.singletonList(emptyClause), true);
}
final DRUPTrim.DRUPResult result = trimmer.compute(clauses, this.underlyingSolver().pgProof());
if (result.trivialUnsat())
return handleTrivialCase();
final LinkedHashSet<Proposition> propositions = new LinkedHashSet<>();
for (LNGIntVector vector : result.unsatCore())
propositions.add(clause2proposition.get(getFormulaForVector(vector)));
return new UNSATCore<>(new ArrayList<>(propositions), false);
}
/**
* Generates a clause vector of a collection of literals.
* @param literals the literals
* @return the clause vector
*/
private LNGIntVector generateClauseVector(final Collection<Literal> literals) {
final LNGIntVector clauseVec = new LNGIntVector(literals.size());
for (Literal lit : literals) {
int index = this.solver.idxForName(lit.name());
if (index == -1) {
index = this.solver.newVar(!initialPhase, true);
this.solver.addName(lit.name(), index);
}
int litNum = lit.phase() ? index * 2 : (index * 2) ^ 1;
clauseVec.push(litNum);
}
return clauseVec;
}
/**
* Creates an assignment from a Boolean vector of the solver.
* @param vec the vector of the solver
* @param variables the variables which should appear in the model or {@code null} if all variables should
* appear
* @return the assignment
*/
private Assignment createAssignment(final LNGBooleanVector vec, final Collection<Variable> variables) {
final Assignment model = new Assignment();
for (int i = 0; i < vec.size(); i++) {
final Variable var = this.f.variable(this.solver.nameForIdx(i));
if (vec.get(i)) {
if (variables == null || variables.contains(var))
model.addLiteral(var);
} else if (variables == null || variables.contains(var))
model.addLiteral(var.negate());
}
return model;
}
/**
* Returns the underlying core solver.
* <p>
* ATTENTION: by influencing the underlying solver directly, you can mess things up completely! You should really
* know, what you are doing.
* @return the underlying core solver
*/
public MiniSatStyleSolver underlyingSolver() {
return this.solver;
}
/**
* Returns the initial phase of literals of this solver.
* @return the initial phase of literals of this solver
*/
public boolean initialPhase() {
return this.initialPhase;
}
private UNSATCore<Proposition> handleTrivialCase() {
final LNGVector<MiniSatStyleSolver.ProofInformation> clauses = this.underlyingSolver().pgOriginalClauses();
for (int i = 0; i < clauses.size(); i++)
for (int j = i + 1; j < clauses.size(); j++) {
if (clauses.get(i).clause().size() == 1 && clauses.get(j).clause().size() == 1
&& clauses.get(i).clause().get(0) + clauses.get(j).clause().get(0) == 0) {
LinkedHashSet<Proposition> propositions = new LinkedHashSet<>();
propositions.add(clauses.get(i).proposition());
propositions.add(clauses.get(j).proposition());
return new UNSATCore<>(new ArrayList<>(propositions), false);
}
}
throw new IllegalStateException("Should be a trivial unsat core, but did not found one.");
}
private boolean containsEmptyClause(final LNGVector<LNGIntVector> clauses) {
for (LNGIntVector clause : clauses)
if (clause.empty())
return true;
return false;
}
private Formula getFormulaForVector(LNGIntVector vector) {
final List<Literal> literals = new ArrayList<>(vector.size());
for (int i = 0; i < vector.size(); i++) {
int lit = vector.get(i);
String varName = this.underlyingSolver().nameForIdx(Math.abs(lit) - 1);
literals.add(f.literal(varName, lit > 0));
}
return f.or(literals);
}
@Override
public String toString() {
return String.format("MiniSat{result=%s, incremental=%s}", this.result, this.incremental);
}
}
|
Huge performance boost for MiniSat model enumeration
|
src/main/java/org/logicng/solvers/MiniSat.java
|
Huge performance boost for MiniSat model enumeration
|
|
Java
|
apache-2.0
|
f9ca88209249dd711722a8758922d625d3ac755b
| 0
|
zerodengxinchao/ovirt-engine,zerodengxinchao/ovirt-engine,zerodengxinchao/ovirt-engine,yingyun001/ovirt-engine,walteryang47/ovirt-engine,yingyun001/ovirt-engine,zerodengxinchao/ovirt-engine,OpenUniversity/ovirt-engine,OpenUniversity/ovirt-engine,yapengsong/ovirt-engine,walteryang47/ovirt-engine,OpenUniversity/ovirt-engine,yapengsong/ovirt-engine,yingyun001/ovirt-engine,OpenUniversity/ovirt-engine,yapengsong/ovirt-engine,eayun/ovirt-engine,yapengsong/ovirt-engine,eayun/ovirt-engine,yingyun001/ovirt-engine,eayun/ovirt-engine,OpenUniversity/ovirt-engine,eayun/ovirt-engine,eayun/ovirt-engine,zerodengxinchao/ovirt-engine,walteryang47/ovirt-engine,yingyun001/ovirt-engine,walteryang47/ovirt-engine,yapengsong/ovirt-engine,walteryang47/ovirt-engine
|
package org.ovirt.engine.ui.uicommonweb.models.hosts;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import org.ovirt.engine.core.common.businessentities.VDS;
import org.ovirt.engine.core.common.mode.ApplicationMode;
import org.ovirt.engine.core.common.utils.ObjectUtils;
import org.ovirt.engine.core.compat.Version;
import org.ovirt.engine.ui.uicommonweb.help.HelpTag;
import org.ovirt.engine.ui.uicommonweb.models.EntityModel;
import org.ovirt.engine.ui.uicompat.ConstantsManager;
import org.ovirt.engine.ui.uicompat.PropertyChangedEventArgs;
import org.ovirt.engine.ui.uicompat.UIConstants;
import org.ovirt.engine.ui.uicompat.UIMessages;
@SuppressWarnings("unused")
public class HostHardwareGeneralModel extends EntityModel
{
private static final UIConstants constants = ConstantsManager.getInstance().getConstants();
private static final UIMessages messages = ConstantsManager.getInstance().getMessages();
@Override
public VDS getEntity()
{
return (VDS) super.getEntity();
}
private String hardwareManufacturer;
public String getHardwareManufacturer()
{
return hardwareManufacturer;
}
public void setHardwareManufacturer(String value)
{
if (!ObjectUtils.objectsEqual(hardwareManufacturer, value))
{
hardwareManufacturer = value;
onPropertyChanged(new PropertyChangedEventArgs("manufacturer")); //$NON-NLS-1$
}
}
private String hardwareProductName;
public String getHardwareProductName()
{
return hardwareProductName;
}
public void setHardwareProductName(String value)
{
if (!ObjectUtils.objectsEqual(hardwareProductName, value))
{
hardwareProductName = value;
onPropertyChanged(new PropertyChangedEventArgs("productName")); //$NON-NLS-1$
}
}
private String hardwareSerialNumber;
public String getHardwareSerialNumber()
{
return hardwareSerialNumber;
}
public void setHardwareSerialNumber(String value)
{
if (!ObjectUtils.objectsEqual(hardwareSerialNumber, value))
{
hardwareSerialNumber = value;
onPropertyChanged(new PropertyChangedEventArgs("serialNumber")); //$NON-NLS-1$
}
}
private String hardwareVersion;
public String getHardwareVersion()
{
return hardwareVersion;
}
public void setHardwareVersion(String value)
{
if (!ObjectUtils.objectsEqual(hardwareVersion, value))
{
hardwareVersion = value;
onPropertyChanged(new PropertyChangedEventArgs("hardwareVersion")); //$NON-NLS-1$
}
}
private String hardwareUUID;
public String getHardwareUUID()
{
return hardwareUUID;
}
public void setHardwareUUID(String value)
{
if (!ObjectUtils.objectsEqual(hardwareUUID, value))
{
hardwareUUID = value;
onPropertyChanged(new PropertyChangedEventArgs("uuid")); //$NON-NLS-1$
}
}
private String hardwareFamily;
public String getHardwareFamily()
{
return hardwareFamily;
}
@SuppressWarnings("deprecation")
public void setHardwareFamily(String value)
{
if (!ObjectUtils.objectsEqual(hardwareFamily, value))
{
hardwareFamily = value;
onPropertyChanged(new PropertyChangedEventArgs("family")); //$NON-NLS-1$
}
}
private String cpuType;
public String getCpuType()
{
return cpuType;
}
public void setCpuType(String value)
{
if (!ObjectUtils.objectsEqual(cpuType, value)) {
cpuType = value;
onPropertyChanged(new PropertyChangedEventArgs("CpuType")); //$NON-NLS-1$
}
}
private String cpuModel;
public String getCpuModel()
{
return cpuModel;
}
public void setCpuModel(String value)
{
if (!ObjectUtils.objectsEqual(cpuModel, value)) {
cpuModel = value;
onPropertyChanged(new PropertyChangedEventArgs("CpuModel")); //$NON-NLS-1$
}
}
private Integer numberOfSockets;
public Integer getNumberOfSockets()
{
return numberOfSockets;
}
public void setNumberOfSockets(Integer value)
{
if (numberOfSockets == null && value == null) {
return;
} if (numberOfSockets == null || !numberOfSockets.equals(value)) {
numberOfSockets = value;
onPropertyChanged(new PropertyChangedEventArgs("NumberOfSockets")); //$NON-NLS-1$
}
}
private String coresPerSocket;
public String getCoresPerSocket()
{
return coresPerSocket;
}
public void setCoresPerSocket(String value)
{
if (coresPerSocket == null && value == null) {
return;
} if (coresPerSocket == null || !coresPerSocket.equals(value)) {
coresPerSocket = value;
onPropertyChanged(new PropertyChangedEventArgs("CoresPerSocket")); //$NON-NLS-1$
}
}
private String threadsPerCore;
public String getThreadsPerCore()
{
return threadsPerCore;
}
public void setThreadsPerCore(String value)
{
if (threadsPerCore == null && value == null) {
return;
} if (threadsPerCore == null || !threadsPerCore.equals(value)) {
threadsPerCore = value;
onPropertyChanged(new PropertyChangedEventArgs("ThreadsPerCore")); //$NON-NLS-1$
}
}
public enum HbaDeviceKeys { MODEL_NAME, // Model name field
TYPE, // Device type
WWNN, // WWNN of the NIC
WWNPS // Comma separated list of WWNPs (port ids)
};
private List<EnumMap<HbaDeviceKeys, String>> hbaDevices;
public List<EnumMap<HbaDeviceKeys, String>> getHbaDevices() {
return hbaDevices;
}
public void setHbaDevices(List<EnumMap<HbaDeviceKeys, String>> hbaDevices) {
this.hbaDevices = hbaDevices;
}
public HostHardwareGeneralModel()
{
setTitle(ConstantsManager.getInstance().getConstants().generalTitle());
setHelpTag(HelpTag.hardware);
setHashName("hardware"); //$NON-NLS-1$
setAvailableInModes(ApplicationMode.VirtOnly);
}
@Override
protected void entityPropertyChanged(Object sender, PropertyChangedEventArgs e)
{
super.entityPropertyChanged(sender, e);
}
private void updateProperties()
{
VDS vds = getEntity();
setHardwareManufacturer(vds.getHardwareManufacturer());
setHardwareVersion(vds.getHardwareVersion());
setHardwareProductName(vds.getHardwareProductName());
setHardwareUUID(vds.getHardwareUUID());
setHardwareSerialNumber(vds.getHardwareSerialNumber());
setHardwareFamily(vds.getHardwareFamily());
setCpuType(vds.getCpuName() != null ? vds.getCpuName().getCpuName() : null);
setCpuModel(vds.getCpuModel());
setNumberOfSockets(vds.getCpuSockets());
if (vds.getCpuCores() != null && vds.getCpuSockets() != null
&& vds.getCpuThreads() != null && vds.getCpuSockets() != 0) {
int coresPerSocket = vds.getCpuCores() / vds.getCpuSockets();
String fieldValue = String.valueOf(coresPerSocket);
if (vds.getCountThreadsAsCores()) {
fieldValue = ConstantsManager.getInstance().getMessages()
.threadsAsCoresPerSocket(coresPerSocket, vds.getCpuThreads() / vds.getCpuSockets());
}
setCoresPerSocket(fieldValue);
} else {
setCoresPerSocket(null);
}
if (vds.getVdsGroupCompatibilityVersion() != null
&& Version.v3_2.compareTo(vds.getVdsGroupCompatibilityVersion()) > 0) {
// Members of pre-3.2 clusters don't support SMT; here we act like a 3.1 engine
setThreadsPerCore(constants.unsupported());
} else if (vds.getCpuThreads() == null || vds.getCpuCores() == null || vds.getCpuCores() == 0) {
setThreadsPerCore(constants.unknown());
} else {
Integer threads = vds.getCpuThreads() / vds.getCpuCores();
setThreadsPerCore(messages.commonMessageWithBrackets(threads.toString(), threads > 1 ? constants.smtEnabled()
: constants.smtDisabled()));
}
/* Go through the list of HBA devices and transfer the necessary info
to the GWT host hardware model */
List<EnumMap<HbaDeviceKeys, String>> hbaDevices = new ArrayList<EnumMap<HbaDeviceKeys, String>>();
List<Map<String, String>> fcDevices = vds.getHBAs().get("FC"); //$NON-NLS-1$
if (fcDevices != null) {
for (Map<String, String> device: fcDevices) {
EnumMap<HbaDeviceKeys, String> deviceModel = new EnumMap<HbaDeviceKeys, String>(HbaDeviceKeys.class);
deviceModel.put(HbaDeviceKeys.MODEL_NAME, device.get("model")); //$NON-NLS-1$
deviceModel.put(HbaDeviceKeys.WWNN, device.get("wwnn")); //$NON-NLS-1$
deviceModel.put(HbaDeviceKeys.WWNPS, device.get("wwpn")); //$NON-NLS-1$
deviceModel.put(HbaDeviceKeys.TYPE, "FC"); //$NON-NLS-1$
hbaDevices.add(deviceModel);
}
}
setHbaDevices(hbaDevices);
}
@Override
protected void onEntityChanged()
{
super.onEntityChanged();
if (getEntity() != null)
{
updateProperties();
}
}
}
|
frontend/webadmin/modules/uicommonweb/src/main/java/org/ovirt/engine/ui/uicommonweb/models/hosts/HostHardwareGeneralModel.java
|
package org.ovirt.engine.ui.uicommonweb.models.hosts;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import org.ovirt.engine.core.common.businessentities.VDS;
import org.ovirt.engine.core.common.mode.ApplicationMode;
import org.ovirt.engine.core.common.utils.ObjectUtils;
import org.ovirt.engine.core.compat.Version;
import org.ovirt.engine.ui.uicommonweb.help.HelpTag;
import org.ovirt.engine.ui.uicommonweb.models.EntityModel;
import org.ovirt.engine.ui.uicompat.ConstantsManager;
import org.ovirt.engine.ui.uicompat.PropertyChangedEventArgs;
import org.ovirt.engine.ui.uicompat.UIConstants;
import org.ovirt.engine.ui.uicompat.UIMessages;
@SuppressWarnings("unused")
public class HostHardwareGeneralModel extends EntityModel
{
private static final UIConstants constants = ConstantsManager.getInstance().getConstants();
private static final UIMessages messages = ConstantsManager.getInstance().getMessages();
@Override
public VDS getEntity()
{
return (VDS) super.getEntity();
}
private String hardwareManufacturer;
public String getHardwareManufacturer()
{
return hardwareManufacturer;
}
public void setHardwareManufacturer(String value)
{
if (!ObjectUtils.objectsEqual(hardwareManufacturer, value))
{
hardwareManufacturer = value;
onPropertyChanged(new PropertyChangedEventArgs("manufacturer")); //$NON-NLS-1$
}
}
private String hardwareProductName;
public String getHardwareProductName()
{
return hardwareProductName;
}
public void setHardwareProductName(String value)
{
if (!ObjectUtils.objectsEqual(hardwareProductName, value))
{
hardwareProductName = value;
onPropertyChanged(new PropertyChangedEventArgs("productName")); //$NON-NLS-1$
}
}
private String hardwareSerialNumber;
public String getHardwareSerialNumber()
{
return hardwareSerialNumber;
}
public void setHardwareSerialNumber(String value)
{
if (!ObjectUtils.objectsEqual(hardwareSerialNumber, value))
{
hardwareSerialNumber = value;
onPropertyChanged(new PropertyChangedEventArgs("serialNumber")); //$NON-NLS-1$
}
}
private String hardwareVersion;
public String getHardwareVersion()
{
return hardwareVersion;
}
public void setHardwareVersion(String value)
{
if (!ObjectUtils.objectsEqual(hardwareVersion, value))
{
hardwareVersion = value;
onPropertyChanged(new PropertyChangedEventArgs("hardwareVersion")); //$NON-NLS-1$
}
}
private String hardwareUUID;
public String getHardwareUUID()
{
return hardwareUUID;
}
public void setHardwareUUID(String value)
{
if (!ObjectUtils.objectsEqual(hardwareUUID, value))
{
hardwareUUID = value;
onPropertyChanged(new PropertyChangedEventArgs("uuid")); //$NON-NLS-1$
}
}
private String hardwareFamily;
public String getHardwareFamily()
{
return hardwareFamily;
}
@SuppressWarnings("deprecation")
public void setHardwareFamily(String value)
{
if (!ObjectUtils.objectsEqual(hardwareFamily, value))
{
hardwareFamily = value;
onPropertyChanged(new PropertyChangedEventArgs("family")); //$NON-NLS-1$
}
}
private String cpuType;
public String getCpuType()
{
return cpuType;
}
public void setCpuType(String value)
{
if (!ObjectUtils.objectsEqual(cpuType, value)) {
cpuType = value;
onPropertyChanged(new PropertyChangedEventArgs("CpuType")); //$NON-NLS-1$
}
}
private String cpuModel;
public String getCpuModel()
{
return cpuModel;
}
public void setCpuModel(String value)
{
if (!ObjectUtils.objectsEqual(cpuModel, value)) {
cpuModel = value;
onPropertyChanged(new PropertyChangedEventArgs("CpuModel")); //$NON-NLS-1$
}
}
private Integer numberOfSockets;
public Integer getNumberOfSockets()
{
return numberOfSockets;
}
public void setNumberOfSockets(Integer value)
{
if (numberOfSockets == null && value == null) {
return;
} if (numberOfSockets == null || !numberOfSockets.equals(value)) {
numberOfSockets = value;
onPropertyChanged(new PropertyChangedEventArgs("NumberOfSockets")); //$NON-NLS-1$
}
}
private String coresPerSocket;
public String getCoresPerSocket()
{
return coresPerSocket;
}
public void setCoresPerSocket(String value)
{
if (coresPerSocket == null && value == null) {
return;
} if (coresPerSocket == null || !coresPerSocket.equals(value)) {
coresPerSocket = value;
onPropertyChanged(new PropertyChangedEventArgs("CoresPerSocket")); //$NON-NLS-1$
}
}
private String threadsPerCore;
public String getThreadsPerCore()
{
return threadsPerCore;
}
public void setThreadsPerCore(String value)
{
if (threadsPerCore == null && value == null) {
return;
} if (threadsPerCore == null || !threadsPerCore.equals(value)) {
threadsPerCore = value;
onPropertyChanged(new PropertyChangedEventArgs("ThreadsPerCore")); //$NON-NLS-1$
}
}
public enum HbaDeviceKeys { MODEL_NAME, // Model name field
TYPE, // Device type
WWNN, // WWNN of the NIC
WWNPS // Comma separated list of WWNPs (port ids)
};
private List<EnumMap<HbaDeviceKeys, String>> hbaDevices;
public List<EnumMap<HbaDeviceKeys, String>> getHbaDevices() {
return hbaDevices;
}
public void setHbaDevices(List<EnumMap<HbaDeviceKeys, String>> hbaDevices) {
this.hbaDevices = hbaDevices;
}
public HostHardwareGeneralModel()
{
setTitle(ConstantsManager.getInstance().getConstants().generalTitle());
setHelpTag(HelpTag.hardware);
setHashName("hardware"); //$NON-NLS-1$
setAvailableInModes(ApplicationMode.VirtOnly);
}
@Override
protected void entityPropertyChanged(Object sender, PropertyChangedEventArgs e)
{
super.entityPropertyChanged(sender, e);
}
private void updateProperties()
{
VDS vds = getEntity();
setHardwareManufacturer(vds.getHardwareManufacturer());
setHardwareVersion(vds.getHardwareVersion());
setHardwareProductName(vds.getHardwareProductName());
setHardwareUUID(vds.getHardwareUUID());
setHardwareSerialNumber(vds.getHardwareSerialNumber());
setHardwareFamily(vds.getHardwareFamily());
setCpuType(vds.getCpuName() != null ? vds.getCpuName().getCpuName() : null);
setCpuModel(vds.getCpuModel());
setNumberOfSockets(vds.getCpuSockets());
if (vds.getCpuCores() != null && vds.getCpuSockets() != null
&& vds.getCpuThreads() != null && vds.getCpuSockets() != 0) {
int coresPerSocket = vds.getCpuCores() / vds.getCpuSockets();
String fieldValue = String.valueOf(coresPerSocket);
if (vds.getCountThreadsAsCores()) {
fieldValue = ConstantsManager.getInstance().getMessages()
.threadsAsCoresPerSocket(coresPerSocket, vds.getCpuThreads());
}
setCoresPerSocket(fieldValue);
} else {
setCoresPerSocket(null);
}
if (vds.getVdsGroupCompatibilityVersion() != null
&& Version.v3_2.compareTo(vds.getVdsGroupCompatibilityVersion()) > 0) {
// Members of pre-3.2 clusters don't support SMT; here we act like a 3.1 engine
setThreadsPerCore(constants.unsupported());
} else if (vds.getCpuThreads() == null || vds.getCpuCores() == null || vds.getCpuCores() == 0) {
setThreadsPerCore(constants.unknown());
} else {
Integer threads = vds.getCpuThreads() / vds.getCpuCores();
setThreadsPerCore(messages.commonMessageWithBrackets(threads.toString(), threads > 1 ? constants.smtEnabled()
: constants.smtDisabled()));
}
/* Go through the list of HBA devices and transfer the necessary info
to the GWT host hardware model */
List<EnumMap<HbaDeviceKeys, String>> hbaDevices = new ArrayList<EnumMap<HbaDeviceKeys, String>>();
List<Map<String, String>> fcDevices = vds.getHBAs().get("FC"); //$NON-NLS-1$
if (fcDevices != null) {
for (Map<String, String> device: fcDevices) {
EnumMap<HbaDeviceKeys, String> deviceModel = new EnumMap<HbaDeviceKeys, String>(HbaDeviceKeys.class);
deviceModel.put(HbaDeviceKeys.MODEL_NAME, device.get("model")); //$NON-NLS-1$
deviceModel.put(HbaDeviceKeys.WWNN, device.get("wwnn")); //$NON-NLS-1$
deviceModel.put(HbaDeviceKeys.WWNPS, device.get("wwpn")); //$NON-NLS-1$
deviceModel.put(HbaDeviceKeys.TYPE, "FC"); //$NON-NLS-1$
hbaDevices.add(deviceModel);
}
}
setHbaDevices(hbaDevices);
}
@Override
protected void onEntityChanged()
{
super.onEntityChanged();
if (getEntity() != null)
{
updateProperties();
}
}
}
|
core: more accurate cores(threads) ui representation
in case of 2 cores 2 sockets and cluster-count threads as cores, we want
to show at the host general tab
2(4) which reads 2 cores which is actual 4 for scheduling.
without that fixed it showed the overall count which was 2(8)
Change-Id: I4a2c3563bfd667331a58bf558c1161d4e379c624
Bug-Url: https://bugzilla.redhat.com/show_bug.cgi?id=1169404
Signed-off-by: Roy Golan <713b85d0d8cd34d573c78a20da961d7424e4b81a@redhat.com>
|
frontend/webadmin/modules/uicommonweb/src/main/java/org/ovirt/engine/ui/uicommonweb/models/hosts/HostHardwareGeneralModel.java
|
core: more accurate cores(threads) ui representation
|
|
Java
|
apache-2.0
|
aeae02a1ac7ef4071e890da9fb13dfb45fb5fc0f
| 0
|
asakusafw/asakusafw-compiler,asakusafw/asakusafw-compiler,ashigeru/asakusafw-compiler,ashigeru/asakusafw-compiler,ashigeru/asakusafw-compiler
|
/**
* Copyright 2011-2016 Asakusa Framework Team.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.asakusafw.dag.runtime.data;
import java.io.Closeable;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.text.MessageFormat;
import java.util.AbstractList;
import java.util.Arrays;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.asakusafw.dag.api.common.ObjectCursor;
import com.asakusafw.lang.utils.buffer.nio.NioDataBuffer;
import com.asakusafw.lang.utils.buffer.nio.ResizableNioDataBuffer;
/**
* A {@link ListBuilder} which provides temporary file backed lists.
* @param <T> the element type
* @since 0.4.1
*/
public class SpillListBuilder<T> implements ListBuilder<T> {
private static final int DEFAULT_CACHE_SIZE = 256;
private static final int DEFAULT_BUFFER_SOFT_LIMIT = 4 * 1024 * 1024;
static final Logger LOG = LoggerFactory.getLogger(SpillListBuilder.class);
private Entity<T> entity;
/**
* Creates a new instance.
* @param adapter the data adapter
*/
public SpillListBuilder(DataAdapter<T> adapter) {
this(adapter, DEFAULT_CACHE_SIZE, DEFAULT_BUFFER_SOFT_LIMIT);
}
/**
* Creates a new instance.
* @param adapter the data adapter
* @param cacheSize the number of objects should be cached on Java heap
*/
public SpillListBuilder(DataAdapter<T> adapter, int cacheSize) {
this.entity = new Entity<>(adapter, cacheSize, DEFAULT_BUFFER_SOFT_LIMIT);
}
/**
* Creates a new instance.
* @param adapter the data adapter
* @param cacheSize the number of objects should be cached on Java heap
* @param bufferSoftLimit the buffer size soft limit in bytes
*/
public SpillListBuilder(DataAdapter<T> adapter, int cacheSize, int bufferSoftLimit) {
this.entity = new Entity<>(adapter, cacheSize, bufferSoftLimit);
}
@Override
public List<T> build(ObjectCursor cursor) throws IOException, InterruptedException {
entity.reset(cursor);
return entity;
}
@Override
public void close() throws IOException, InterruptedException {
Arrays.fill(entity.elements, null);
entity.store.close();
}
@SuppressWarnings("unchecked")
private static class Entity<T> extends AbstractList<T> {
final DataAdapter<T> adapter;
final Store<T> store;
final T[] elements;
int currentPageIndex;
int sizeInList;
Entity(DataAdapter<T> adapter, int pageSize, int bufferSoftLimit) {
this.store = new Store<>(bufferSoftLimit);
this.adapter = adapter;
this.elements = (T[]) new Object[pageSize];
this.currentPageIndex = 0;
this.sizeInList = 0;
}
void reset(ObjectCursor cursor) throws IOException, InterruptedException {
store.reset();
DataAdapter<T> da = adapter;
T[] es = this.elements;
int offset = 0;
int pageOffset = 0;
while (cursor.nextObject()) {
if (offset >= es.length) {
// escape into buffer
store.putPage(da, pageOffset, es, offset);
offset = 0;
pageOffset++;
}
T object = (T) cursor.getObject();
T destination = es[offset];
if (destination == null) {
destination = da.create();
es[offset] = destination;
}
da.copy(object, destination);
offset++;
}
if (pageOffset != 0) {
assert offset > 0;
store.putPage(da, pageOffset, es, offset);
}
sizeInList = pageOffset * es.length + offset;
currentPageIndex = pageOffset;
}
@Override
public T get(int index) {
if (index < 0 || index >= sizeInList) {
throw new IndexOutOfBoundsException();
}
int windowSize = elements.length;
int pageIndex = index / windowSize;
int offsetInPage = index % windowSize;
if (currentPageIndex != pageIndex) {
int count = Math.min(sizeInList - pageIndex * windowSize, windowSize);
try {
store.getPage(adapter, pageIndex, elements, count);
} catch (IOException e) {
throw new IllegalStateException(e);
}
currentPageIndex = pageIndex;
}
return elements[offsetInPage];
}
@Override
public int size() {
return sizeInList;
}
}
private static class Store<T> implements Closeable {
private static final int[] EMPTY_INTS = new int[0];
private static final long[] EMPTY_LONGS = new long[0];
private final int bufferSoftLimit;
private Path path;
private FileChannel channel;
private long[] offsets = EMPTY_LONGS;
private long[] fragmentEndOffsets = EMPTY_LONGS;
private int[] fragmentElementCounts = EMPTY_INTS;
private int fragmentTableLimit;
private final ResizableNioDataBuffer buffer = new ResizableNioDataBuffer();
Store(int bufferSoftLimit) {
this.bufferSoftLimit = bufferSoftLimit;
}
void reset() {
this.fragmentTableLimit = 0;
}
void putPage(DataAdapter<T> adapter, int index, T[] elements, int count) throws IOException {
if (path == null) {
path = Files.createTempFile("spill-", ".bin");
if (LOG.isDebugEnabled()) {
LOG.debug("generating list spill: {}", path);
}
channel = FileChannel.open(path,
StandardOpenOption.CREATE, StandardOpenOption.READ, StandardOpenOption.WRITE,
StandardOpenOption.DELETE_ON_CLOSE);
offsets = new long[256];
}
if (index >= offsets.length) {
offsets = Arrays.copyOf(offsets, offsets.length * 2);
}
int fragmentBegin = 0;
long offset = index == 0 ? 0L : offsets[index - 1];
buffer.contents.clear();
for (int i = 0; i < count; i++) {
if (buffer.contents.position() > bufferSoftLimit) {
// write fragment if buffer was exceeded
int fragmentEnd = i;
assert fragmentEnd > fragmentBegin;
offset = putFragment(offset, fragmentEnd - fragmentBegin, buffer.contents);
buffer.contents.clear();
fragmentBegin = fragmentEnd;
}
adapter.write(elements[i], buffer);
}
assert buffer.contents.hasRemaining();
long end = putContents(offset, buffer.contents);
offsets[index] = end;
}
private long putFragment(long begin, int elementCount, ByteBuffer contents) throws IOException {
assert elementCount > 0;
if (fragmentTableLimit >= fragmentEndOffsets.length) {
int size = Math.max(fragmentEndOffsets.length * 2, 256);
fragmentEndOffsets = Arrays.copyOf(fragmentEndOffsets, size);
fragmentElementCounts = Arrays.copyOf(fragmentElementCounts, size);
}
long end = putContents(begin, contents);
fragmentEndOffsets[fragmentTableLimit] = end;
fragmentElementCounts[fragmentTableLimit] = elementCount;
fragmentTableLimit++;
return end;
}
private long putContents(long begin, ByteBuffer contents) throws IOException {
contents.flip();
if (LOG.isTraceEnabled()) {
LOG.trace(String.format("writing page fragment: %s@%,d+%,d", path, begin, contents.remaining())); //$NON-NLS-1$
}
long offset = begin;
while (contents.hasRemaining()) {
offset += channel.write(contents, offset);
}
return offset;
}
void getPage(DataAdapter<T> adapter, int index, T[] elements, int count) throws IOException {
long offset = index == 0 ? 0L : offsets[index - 1];
long end = offsets[index];
long length = end - offset;
ByteBuffer buf = buffer.contents;
if (buf.capacity() >= length) {
readFragment(adapter, offset, end, elements, 0, count);
} else {
getPageFragments(adapter, offset, end, elements, count);
}
}
private void getPageFragments(
DataAdapter<T> adapter,
long begin, long end,
T[] elements, int count) throws IOException {
long fileOffset = begin;
int arrayOffset = 0;
int fIndex = findFragmentsIndex(begin, end);
for (int i = fIndex, n = fragmentTableLimit; i < n; i++) {
long fragmentEnd = fragmentEndOffsets[i];
if (fragmentEnd >= end) {
break;
}
int arrayEnd = arrayOffset + fragmentElementCounts[i];
// reads rest elements
readFragment(adapter, fileOffset, fragmentEnd, elements, arrayOffset, arrayEnd);
fileOffset = fragmentEnd;
arrayOffset = arrayEnd;
}
assert fileOffset < end;
assert arrayOffset < count;
// reads rest elements
readFragment(adapter, fileOffset, end, elements, arrayOffset, count);
}
private int findFragmentsIndex(long begin, long end) {
int fIndex = Arrays.binarySearch(fragmentEndOffsets, 0, fragmentTableLimit, begin);
if (fIndex == fragmentTableLimit || fIndex >= 0) {
throw new IllegalStateException();
}
fIndex = -(fIndex + 1);
assert begin < fragmentEndOffsets[fIndex] && fragmentEndOffsets[fIndex] < end;
return fIndex;
}
private void readFragment(
DataAdapter<T> adapter,
long fileBegin, long fileEnd,
T[] elements, int arrayBegin, int arrayEnd) throws IOException {
ByteBuffer buf = buffer.contents;
int fileSize = (int) (fileEnd - fileBegin);
buf.clear().limit(fileSize);
if (LOG.isTraceEnabled()) {
LOG.trace(String.format("reading page fragment: %s@%,d+%,d", path, fileBegin, buf.remaining())); //$NON-NLS-1$
}
long offset = fileBegin;
while (buf.hasRemaining()) {
int read = channel.read(buf, offset);
if (read < 0) {
throw new IllegalStateException();
}
offset += read;
}
buf.flip();
for (int i = arrayBegin; i < arrayEnd; i++) {
adapter.read(buffer, elements[i]);
}
}
@Override
public void close() throws IOException {
if (channel != null) {
offsets = EMPTY_LONGS;
fragmentEndOffsets = EMPTY_LONGS;
fragmentElementCounts = EMPTY_INTS;
buffer.contents = NioDataBuffer.EMPTY_BUFFER;
channel.close(); // DELETE_ON_CLOSE
if (Files.exists(path) && Files.deleteIfExists(path) == false && Files.exists(path)) {
LOG.warn(MessageFormat.format(
"failed to delete a temporary file: {0}",
path));
}
channel = null;
path = null;
}
}
}
}
|
dag/runtime/runtime/src/main/java/com/asakusafw/dag/runtime/data/SpillListBuilder.java
|
/**
* Copyright 2011-2016 Asakusa Framework Team.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.asakusafw.dag.runtime.data;
import java.io.Closeable;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.text.MessageFormat;
import java.util.AbstractList;
import java.util.Arrays;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.asakusafw.dag.api.common.ObjectCursor;
import com.asakusafw.lang.utils.buffer.nio.NioDataBuffer;
import com.asakusafw.lang.utils.buffer.nio.ResizableNioDataBuffer;
/**
* A {@link ListBuilder} which provides temporary file backed lists.
* @param <T> the element type
* @since 0.4.1
*/
public class SpillListBuilder<T> implements ListBuilder<T> {
private static final int DEFAULT_CACHE_SIZE = 256;
private static final int DEFAULT_BUFFER_SOFT_LIMIT = 4 * 1024 * 1024;
static final Logger LOG = LoggerFactory.getLogger(SpillListBuilder.class);
private Entity<T> entity;
/**
* Creates a new instance.
* @param adapter the data adapter
*/
public SpillListBuilder(DataAdapter<T> adapter) {
this(adapter, DEFAULT_CACHE_SIZE, DEFAULT_BUFFER_SOFT_LIMIT);
}
/**
* Creates a new instance.
* @param adapter the data adapter
* @param cacheSize the number of objects should be cached on Java heap
*/
public SpillListBuilder(DataAdapter<T> adapter, int cacheSize) {
this.entity = new Entity<>(adapter, cacheSize, DEFAULT_BUFFER_SOFT_LIMIT);
}
/**
* Creates a new instance.
* @param adapter the data adapter
* @param cacheSize the number of objects should be cached on Java heap
* @param bufferSoftLimit the buffer size soft limit in bytes
*/
public SpillListBuilder(DataAdapter<T> adapter, int cacheSize, int bufferSoftLimit) {
this.entity = new Entity<>(adapter, cacheSize, bufferSoftLimit);
}
@Override
public List<T> build(ObjectCursor cursor) throws IOException, InterruptedException {
entity.reset(cursor);
return entity;
}
@Override
public void close() throws IOException, InterruptedException {
Arrays.fill(entity.elements, null);
entity.store.close();
}
@SuppressWarnings("unchecked")
private static class Entity<T> extends AbstractList<T> {
final DataAdapter<T> adapter;
final Store<T> store;
final T[] elements;
int currentPageIndex;
int sizeInList;
Entity(DataAdapter<T> adapter, int pageSize, int bufferSoftLimit) {
this.store = new Store<>(bufferSoftLimit);
this.adapter = adapter;
this.elements = (T[]) new Object[pageSize];
this.currentPageIndex = 0;
this.sizeInList = 0;
}
void reset(ObjectCursor cursor) throws IOException, InterruptedException {
store.reset();
DataAdapter<T> da = adapter;
T[] es = this.elements;
int offset = 0;
int pageOffset = 0;
while (cursor.nextObject()) {
if (offset >= es.length) {
// escape into buffer
store.putPage(da, pageOffset, es, offset);
offset = 0;
pageOffset++;
}
T object = (T) cursor.getObject();
T destination = es[offset];
if (destination == null) {
destination = da.create();
es[offset] = destination;
}
da.copy(object, destination);
offset++;
}
if (pageOffset != 0) {
assert offset > 0;
store.putPage(da, pageOffset, es, offset);
}
sizeInList = pageOffset * es.length + offset;
currentPageIndex = pageOffset;
}
@Override
public T get(int index) {
if (index < 0 || index >= sizeInList) {
throw new IndexOutOfBoundsException();
}
int windowSize = elements.length;
int pageIndex = index / windowSize;
int offsetInPage = index % windowSize;
if (currentPageIndex != pageIndex) {
int count = Math.min(sizeInList - pageIndex * windowSize, windowSize);
try {
store.getPage(adapter, pageIndex, elements, count);
} catch (IOException e) {
throw new IllegalStateException(e);
}
currentPageIndex = pageIndex;
}
return elements[offsetInPage];
}
@Override
public int size() {
return sizeInList;
}
}
private static class Store<T> implements Closeable {
private static final int[] EMPTY_INTS = new int[0];
private static final long[] EMPTY_LONGS = new long[0];
private final int bufferSoftLimit;
private Path path;
private FileChannel channel;
private long[] offsets = EMPTY_LONGS;
private long[] fragmentEndOffsets = EMPTY_LONGS;
private int[] fragmentElementCounts = EMPTY_INTS;
private int fragmentTableLimit;
private final ResizableNioDataBuffer buffer = new ResizableNioDataBuffer();
Store(int bufferSoftLimit) {
this.bufferSoftLimit = bufferSoftLimit;
}
void reset() {
this.fragmentTableLimit = 0;
}
void putPage(DataAdapter<T> adapter, int index, T[] elements, int count) throws IOException {
if (path == null) {
path = Files.createTempFile("spill-", ".bin");
if (LOG.isDebugEnabled()) {
LOG.debug("generating list spill: {}", path);
}
channel = FileChannel.open(path,
StandardOpenOption.CREATE, StandardOpenOption.READ, StandardOpenOption.WRITE,
StandardOpenOption.DELETE_ON_CLOSE);
offsets = new long[256];
}
if (index >= offsets.length) {
offsets = Arrays.copyOf(offsets, offsets.length * 2);
}
int fragmentBegin = 0;
long offset = index == 0 ? 0L : offsets[index - 1];
buffer.contents.clear();
for (int i = 0; i < count; i++) {
if (buffer.contents.position() > bufferSoftLimit) {
// write fragment if buffer was exceeded
int fragmentEnd = i;
assert fragmentEnd > fragmentBegin;
offset = putFragment(offset, fragmentEnd - fragmentBegin, buffer.contents);
buffer.contents.clear();
fragmentBegin = fragmentEnd;
}
adapter.write(elements[i], buffer);
}
assert buffer.contents.hasRemaining();
long end = putContents(offset, buffer.contents);
offsets[index] = end;
}
private long putFragment(long begin, int elementCount, ByteBuffer contents) throws IOException {
assert elementCount > 0;
if (fragmentTableLimit >= fragmentEndOffsets.length) {
int size = Math.max(fragmentEndOffsets.length * 2, 256);
fragmentEndOffsets = Arrays.copyOf(fragmentEndOffsets, size);
fragmentElementCounts = Arrays.copyOf(fragmentElementCounts, size);
}
long end = putContents(begin, contents);
fragmentEndOffsets[fragmentTableLimit] = end;
fragmentElementCounts[fragmentTableLimit] = elementCount;
fragmentTableLimit++;
return end;
}
private long putContents(long begin, ByteBuffer contents) throws IOException {
contents.flip();
if (LOG.isTraceEnabled()) {
LOG.trace(String.format("writing page fragment: %s#%,d@%,d+%,d", path, begin, contents.remaining())); //$NON-NLS-1$
}
long offset = begin;
while (contents.hasRemaining()) {
offset += channel.write(contents, offset);
}
return offset;
}
void getPage(DataAdapter<T> adapter, int index, T[] elements, int count) throws IOException {
long offset = index == 0 ? 0L : offsets[index - 1];
long end = offsets[index];
long length = end - offset;
ByteBuffer buf = buffer.contents;
if (buf.capacity() >= length) {
readFragment(adapter, offset, end, elements, 0, count);
} else {
getPageFragments(adapter, offset, end, elements, count);
}
}
private void getPageFragments(
DataAdapter<T> adapter,
long begin, long end,
T[] elements, int count) throws IOException {
long fileOffset = begin;
int arrayOffset = 0;
int fIndex = findFragmentsIndex(begin, end);
for (int i = fIndex, n = fragmentTableLimit; i < n; i++) {
long fragmentEnd = fragmentEndOffsets[i];
if (fragmentEnd >= end) {
break;
}
int arrayEnd = arrayOffset + fragmentElementCounts[i];
// reads rest elements
readFragment(adapter, fileOffset, fragmentEnd, elements, arrayOffset, arrayEnd);
fileOffset = fragmentEnd;
arrayOffset = arrayEnd;
}
assert fileOffset < end;
assert arrayOffset < count;
// reads rest elements
readFragment(adapter, fileOffset, end, elements, arrayOffset, count);
}
private int findFragmentsIndex(long begin, long end) {
int fIndex = Arrays.binarySearch(fragmentEndOffsets, 0, fragmentTableLimit, begin);
if (fIndex == fragmentTableLimit || fIndex >= 0) {
throw new IllegalStateException();
}
fIndex = -(fIndex + 1);
assert begin < fragmentEndOffsets[fIndex] && fragmentEndOffsets[fIndex] < end;
return fIndex;
}
private void readFragment(
DataAdapter<T> adapter,
long fileBegin, long fileEnd,
T[] elements, int arrayBegin, int arrayEnd) throws IOException {
ByteBuffer buf = buffer.contents;
int fileSize = (int) (fileEnd - fileBegin);
buf.clear().limit(fileSize);
if (LOG.isTraceEnabled()) {
LOG.trace(String.format("reading page fragment: %s#%,d@%,d+%,d", path, fileBegin, buf.remaining())); //$NON-NLS-1$
}
long offset = fileBegin;
while (buf.hasRemaining()) {
int read = channel.read(buf, offset);
if (read < 0) {
throw new IllegalStateException();
}
offset += read;
}
buf.flip();
for (int i = arrayBegin; i < arrayEnd; i++) {
adapter.read(buffer, elements[i]);
}
}
@Override
public void close() throws IOException {
if (channel != null) {
offsets = EMPTY_LONGS;
fragmentEndOffsets = EMPTY_LONGS;
fragmentElementCounts = EMPTY_INTS;
buffer.contents = NioDataBuffer.EMPTY_BUFFER;
channel.close(); // DELETE_ON_CLOSE
if (Files.exists(path) && Files.deleteIfExists(path) == false && Files.exists(path)) {
LOG.warn(MessageFormat.format(
"failed to delete a temporary file: {0}",
path));
}
channel = null;
path = null;
}
}
}
}
|
Fix trace log.
|
dag/runtime/runtime/src/main/java/com/asakusafw/dag/runtime/data/SpillListBuilder.java
|
Fix trace log.
|
|
Java
|
apache-2.0
|
9f7a0d1b453d67d23053d99bfe230f4ccaa51a88
| 0
|
elasticjob/elastic-job,elasticjob/elastic-job,elasticjob/elastic-job,elasticjob/elastic-job
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.shardingsphere.elasticjob.lite.console.security;
import com.google.common.base.Splitter;
import com.google.common.hash.Hashing;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* User authentication service.
**/
@Component
@ConfigurationProperties(prefix = "auth")
@Getter
@Setter
public class UserAuthenticationService {
private String rootUsername;
private String rootPassword;
private String guestUsername;
private String guestPassword;
/**
* Check user.
*
* @param authorization authorization
* @param method method
* @return authorization result
*/
public AuthenticationResult checkUser(final String authorization, final String method) {
Map<String, String> authorizationMap = parseAuthorizationMap(authorization);
String username = authorizationMap.get("username");
String realm = authorizationMap.get("realm");
String uri = authorizationMap.get("uri");
String nonce = authorizationMap.get("nonce");
String nc = authorizationMap.get("nc");
String cnonce = authorizationMap.get("cnonce");
String qop = authorizationMap.get("qop");
String response = authorizationMap.get("response");
String password;
AuthenticationResult authenticationResult;
if (rootUsername.equals(username)) {
password = rootPassword;
authenticationResult = new AuthenticationResult(true, false);
} else if (guestUsername.equals(username)) {
password = guestPassword;
authenticationResult = new AuthenticationResult(true, true);
} else {
return new AuthenticationResult(false, false);
}
String hash1 = Hashing.md5().hashBytes((username + ":" + realm + ":" + password).getBytes()).toString();
String hash2 = Hashing.md5().hashBytes((method + ":" + uri).getBytes()).toString();
String exceptResponse = Hashing.md5().hashBytes((hash1 + ":" + nonce + ":" + nc + ":" + cnonce + ":" + qop + ":" + hash2).getBytes()).toString();
if (StringUtils.equals(response, exceptResponse)) {
return authenticationResult;
}
return new AuthenticationResult(false, false);
}
private static Map<String, String> parseAuthorizationMap(final String authority) {
if (StringUtils.isBlank(authority)) {
return Collections.emptyMap();
}
String authorityWithoutPrefix = authority.substring(authority.indexOf(" ") + 1);
List<String> keyValueList = Splitter.on(",").omitEmptyStrings().trimResults().splitToList(authorityWithoutPrefix);
Map<String, String> result = new HashMap<>();
for (String keyValue : keyValueList) {
int index = keyValue.indexOf("=");
if (-1 != index) {
String key = keyValue.substring(0, index);
String value = keyValue.substring(index + 1).replaceAll("\"", "").trim();
result.put(key, value);
}
}
return result;
}
}
|
elasticjob-lite/elasticjob-lite-console/src/main/java/org/apache/shardingsphere/elasticjob/lite/console/security/UserAuthenticationService.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.shardingsphere.elasticjob.lite.console.security;
import com.google.common.base.Splitter;
import com.google.common.hash.Hashing;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* User authentication service.
**/
@Component
@ConfigurationProperties(prefix = "auth")
@Getter
@Setter
public class UserAuthenticationService {
private String rootUsername;
private String rootPassword;
private String guestUsername;
private String guestPassword;
/**
* Check user.
*
* @param authorization authorization
* @param method method
* @return authorization result
*/
public AuthenticationResult checkUser(final String authorization, final String method) {
Map<String, String> authorizationMap = parseAuthorizationMap(authorization);
String username = authorizationMap.get("username");
String realm = authorizationMap.get("realm");
String uri = authorizationMap.get("uri");
String nonce = authorizationMap.get("nonce");
String nc = authorizationMap.get("nc");
String cnonce = authorizationMap.get("cnonce");
String qop = authorizationMap.get("qop");
String response = authorizationMap.get("response");
String password;
AuthenticationResult authenticationResult;
if (rootUsername.equals(username)) {
password = rootPassword;
authenticationResult = new AuthenticationResult(true, false);
} else if (guestUsername.equals(username)) {
password = guestPassword;
authenticationResult = new AuthenticationResult(true, true);
} else {
return new AuthenticationResult(false, false);
}
String hash1 = Hashing.sha256().hashBytes((username + ":" + realm + ":" + password).getBytes()).toString();
String hash2 = Hashing.sha256().hashBytes((method + ":" + uri).getBytes()).toString();
String exceptResponse = Hashing.sha256().hashBytes((hash1 + ":" + nonce + ":" + nc + ":" + cnonce + ":" + qop + ":" + hash2).getBytes()).toString();
if (StringUtils.equals(response, exceptResponse)) {
return authenticationResult;
}
return new AuthenticationResult(false, false);
}
private static Map<String, String> parseAuthorizationMap(final String authority) {
if (StringUtils.isBlank(authority)) {
return Collections.emptyMap();
}
String authorityWithoutPrefix = authority.substring(authority.indexOf(" ") + 1);
List<String> keyValueList = Splitter.on(",").omitEmptyStrings().trimResults().splitToList(authorityWithoutPrefix);
Map<String, String> result = new HashMap<>();
for (String keyValue : keyValueList) {
int index = keyValue.indexOf("=");
if (-1 != index) {
String key = keyValue.substring(0, index);
String value = keyValue.substring(index + 1).replaceAll("\"", "").trim();
result.put(key, value);
}
}
return result;
}
}
|
change console authorization encode from sha256 to md5 (#1156)
|
elasticjob-lite/elasticjob-lite-console/src/main/java/org/apache/shardingsphere/elasticjob/lite/console/security/UserAuthenticationService.java
|
change console authorization encode from sha256 to md5 (#1156)
|
|
Java
|
apache-2.0
|
ce388bf397abe3096487e319f8820aa873255ca1
| 0
|
unidev-polydata/polydata-storage-android
|
/**
* Copyright (c) 2015,2016 Denis O <denis@universal-development.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.unidev.polydata.storage;
import android.content.Context;
import android.content.res.AssetManager;
import android.util.Log;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.unidev.polydata.domain.BasicPoly;
import com.unidev.polydata.domain.BasicPolyList;
import com.unidev.polydata.domain.Poly;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
/**
* Storage backed by assets json files
*/
public class AssetStorage implements PolyStorage {
public static ObjectMapper objectMapper;
static {
objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
}
private BasicPoly meta;
private Map<String, BasicPoly> storage;
/**
* Load poly records from assets
* @param context Application context
* @param filePath Path to file in assets
*/
public void load(Context context, String filePath) {
AssetManager assets = context.getAssets();
InputStream inputStream = null;
try {
inputStream = assets.open(filePath);
PolyStorageDTO polyDTO = objectMapper.readValue(inputStream, PolyStorageDTO.class);
meta = polyDTO.getMeta();
storage = new HashMap<>();
for(BasicPoly poly : polyDTO.getRecords()) {
storage.put(poly._id(), poly);
}
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
public Map<String, BasicPoly> getStorage() {
return storage;
}
@Override
public Poly fetchById(String id) {
return storage.get(id);
}
@Override
public Collection<? extends Poly> list() {
return storage.values();
}
public BasicPoly getMeta() {
return meta;
}
public void setMeta(BasicPoly meta) {
this.meta = meta;
}
}
|
polydata-storage-android-assets/src/main/java/com/unidev/polydata/storage/AssetStorage.java
|
/**
* Copyright (c) 2015,2016 Denis O <denis@universal-development.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.unidev.polydata.storage;
import android.content.Context;
import android.content.res.AssetManager;
import android.util.Log;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.unidev.polydata.domain.BasicPoly;
import com.unidev.polydata.domain.BasicPolyList;
import com.unidev.polydata.domain.Poly;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
/**
* Storage backed by assets json files
*/
public class AssetStorage implements PolyStorage {
public static ObjectMapper objectMapper;
static {
objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
}
private Map<String, BasicPoly> storage;
/**
* Load poly records from assets
* @param context Application context
* @param filePath Path to file in assets
*/
public void load(Context context, String filePath) {
AssetManager assets = context.getAssets();
InputStream inputStream = null;
try {
inputStream = assets.open(filePath);
BasicPolyList basicPolyList = objectMapper.readValue(inputStream, BasicPolyList.class);
storage = new HashMap<>();
for(BasicPoly poly : basicPolyList) {
storage.put(poly._id(), poly);
}
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
public Map<String, BasicPoly> getStorage() {
return storage;
}
@Override
public Poly fetchById(String id) {
return storage.get(id);
}
@Override
public Collection<? extends Poly> list() {
return storage.values();
}
}
|
Poly storage loading through dto instance
|
polydata-storage-android-assets/src/main/java/com/unidev/polydata/storage/AssetStorage.java
|
Poly storage loading through dto instance
|
|
Java
|
apache-2.0
|
52c5c197c9af3b429dc66dc4fcfb289bb08dbc3a
| 0
|
cirg-up/cilib
|
/**
* Copyright (C) 2003 - 2009
* Computational Intelligence Research Group (CIRG@UP)
* Department of Computer Science
* University of Pretoria
* South Africa
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package net.sourceforge.cilib.ec;
import net.sourceforge.cilib.entity.AbstractEntity;
import net.sourceforge.cilib.entity.Entity;
import net.sourceforge.cilib.entity.EntityType;
import net.sourceforge.cilib.math.random.generator.MersenneTwister;
import net.sourceforge.cilib.problem.InferiorFitness;
import net.sourceforge.cilib.problem.OptimisationProblem;
import net.sourceforge.cilib.type.types.Resetable;
import net.sourceforge.cilib.type.types.container.StructuredType;
import net.sourceforge.cilib.type.types.container.Vector;
/**
* @author otter
* Implements the Entity interface. Individual represents entities used within the EC paradigm.
*/
public class Individual extends AbstractEntity {
private static final long serialVersionUID = -578986147850240655L;
/**
* Create an instance of {@linkplain Individual}.
*/
public Individual() {
setCandidateSolution(new Vector());
this.getProperties().put(EntityType.FITNESS, InferiorFitness.instance());
}
/**
* Copy constructor. Creates a copy of the given {@linkplain Individual}.
* @param copy The {@linkplain Individual} to copy.
*/
public Individual(Individual copy) {
super(copy);
}
/**
* {@inheritDoc}
*/
@Override
public Individual getClone() {
return new Individual(this);
}
/**
* {@inheritDoc}
*/
@Override
public boolean equals(Object object) {
if (this == object)
return true;
if ((object == null) || (this.getClass() != object.getClass()))
return false;
Individual other = (Individual) object;
return super.equals(other);
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
int hash = 7;
hash = 31 * hash + super.hashCode();
return hash;
}
/**
* Resets the fitness to <code>InferiorFitness</code>.
*/
public void resetFitness() {
this.getProperties().put(EntityType.FITNESS, InferiorFitness.instance());
}
/**
* {@inheritDoc}
*/
@Override
public void initialise(OptimisationProblem problem) {
// ID initialization is done in the clone method...
// which is always enforced due to the semantics of the performInitialisation methods
MersenneTwister random = new MersenneTwister();
this.setCandidateSolution(problem.getDomain().getBuiltRepresenation().getClone());
this.getCandidateSolution().randomize(random);
this.getProperties().put(EntityType.STRATEGY_PARAMETERS, getCandidateSolution().getClone());
((Resetable) this.getProperties().get(EntityType.STRATEGY_PARAMETERS)).reset();
this.getProperties().put(EntityType.FITNESS, InferiorFitness.instance());
}
/**
* {@inheritDoc}
*/
@Override
public int compareTo(Entity o) {
return this.getFitness().compareTo(o.getFitness());
}
/**
* {@inheritDoc}
*/
@Override
public void setCandidateSolution(StructuredType type) {
super.setCandidateSolution(type);
}
/**
* {@inheritDoc}
*/
@Override
public void calculateFitness() {
this.getProperties().put(EntityType.FITNESS, this.getFitnessCalculator().getFitness(this));
}
/**
* {@inheritDoc}
*/
@Override
public int getDimension() {
return getCandidateSolution().size();
}
/**
* Create a textual representation of the current {@linkplain Individual}. The
* returned {@linkplain String} will contain both the genotypes and penotypes for
* the current {@linkplain Individual}.
* @return The textual representation of this {@linkplain Individual}.
*/
@Override
public String toString() {
StringBuilder str = new StringBuilder();
str.append(getCandidateSolution().toString());
str.append(getProperties().get(EntityType.STRATEGY_PARAMETERS));
return str.toString();
}
/**
* {@inheritDoc}
*/
@Override
public void reinitialise() {
throw new UnsupportedOperationException("Implementation is required for this method");
}
}
|
src/main/java/net/sourceforge/cilib/ec/Individual.java
|
/**
* Copyright (C) 2003 - 2009
* Computational Intelligence Research Group (CIRG@UP)
* Department of Computer Science
* University of Pretoria
* South Africa
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package net.sourceforge.cilib.ec;
import net.sourceforge.cilib.entity.AbstractEntity;
import net.sourceforge.cilib.entity.Entity;
import net.sourceforge.cilib.entity.EntityType;
import net.sourceforge.cilib.math.random.generator.MersenneTwister;
import net.sourceforge.cilib.problem.InferiorFitness;
import net.sourceforge.cilib.problem.OptimisationProblem;
import net.sourceforge.cilib.type.types.Resetable;
import net.sourceforge.cilib.type.types.container.StructuredType;
import net.sourceforge.cilib.type.types.container.Vector;
/**
* @author otter
* Implements the Entity interface. Individual represents entities used within the EC paradigm.
*/
public class Individual extends AbstractEntity {
private static final long serialVersionUID = -578986147850240655L;
protected int dimension;
/**
* Create an instance of {@linkplain Individual}.
*/
public Individual() {
dimension = 0;
setCandidateSolution(new Vector());
this.getProperties().put(EntityType.FITNESS, InferiorFitness.instance());
}
/**
* Copy constructor. Creates a copy of the given {@linkplain Individual}.
* @param copy The {@linkplain Individual} to copy.
*/
public Individual(Individual copy) {
super(copy);
this.dimension = copy.dimension;
}
/**
* {@inheritDoc}
*/
@Override
public Individual getClone() {
return new Individual(this);
}
/**
* {@inheritDoc}
*/
@Override
public boolean equals(Object object) {
if (this == object)
return true;
if ((object == null) || (this.getClass() != object.getClass()))
return false;
Individual other = (Individual) object;
return super.equals(other) &&
(this.dimension == other.dimension);
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
int hash = 7;
hash = 31 * hash + super.hashCode();
hash = 31 * hash + Integer.valueOf(dimension).hashCode();
return hash;
}
/**
* Resets the fitness to <code>InferiorFitness</code>.
*/
public void resetFitness() {
this.getProperties().put(EntityType.FITNESS, InferiorFitness.instance());
}
/**
* {@inheritDoc}
*/
@Override
public void initialise(OptimisationProblem problem) {
// ID initialization is done in the clone method...
// which is always enforced due to the semantics of the performInitialisation methods
MersenneTwister random = new MersenneTwister();
this.setCandidateSolution(problem.getDomain().getBuiltRepresenation().getClone());
this.getCandidateSolution().randomize(random);
this.getProperties().put(EntityType.STRATEGY_PARAMETERS, getCandidateSolution().getClone());
((Resetable) this.getProperties().get(EntityType.STRATEGY_PARAMETERS)).reset();
this.dimension = this.getCandidateSolution().size();
this.getProperties().put(EntityType.FITNESS, InferiorFitness.instance());
}
/**
* {@inheritDoc}
*/
@Override
public int compareTo(Entity o) {
return this.getFitness().compareTo(o.getFitness());
}
/**
* {@inheritDoc}
*/
@Override
public void setCandidateSolution(StructuredType type) {
super.setCandidateSolution(type);
this.dimension = type.size();
}
/**
* {@inheritDoc}
*/
@Override
public void calculateFitness() {
this.getProperties().put(EntityType.FITNESS, this.getFitnessCalculator().getFitness(this));
}
/**
* {@inheritDoc}
*/
@Override
public int getDimension() {
return this.dimension;
}
/**
* Set the current dimension value for the current {@linkplain Individual}.
* @param dim The dimension value to set.
*/
public void setDimension(int dim) {
this.dimension = dim;
}
/**
* Create a textual representation of the current {@linkplain Individual}. The
* returned {@linkplain String} will contain both the genotypes and penotypes for
* the current {@linkplain Individual}.
* @return The textual representation of this {@linkplain Individual}.
*/
@Override
public String toString() {
StringBuilder str = new StringBuilder();
str.append(getCandidateSolution().toString());
str.append(getProperties().get(EntityType.STRATEGY_PARAMETERS));
return str.toString();
}
/**
* {@inheritDoc}
*/
@Override
public void reinitialise() {
throw new UnsupportedOperationException("Implementation is required for this method");
}
}
|
Remove redundant 'dimension'
The dimension variable within the Inidividual was not needed. It has
been removed to avoid unnecessary clutter.
Signed-off-by: Gary Pampara <46654e9f53f0e5c1be5f3914582d375e0aa2156c@gmail.com>
|
src/main/java/net/sourceforge/cilib/ec/Individual.java
|
Remove redundant 'dimension'
|
|
Java
|
apache-2.0
|
8fb98dbfc9a40a0eafb6d18956540948df93a746
| 0
|
MyRobotLab/myrobotlab,MyRobotLab/myrobotlab,MyRobotLab/myrobotlab,MyRobotLab/myrobotlab,MyRobotLab/myrobotlab,MyRobotLab/myrobotlab,MyRobotLab/myrobotlab
|
/*
*
* AdafruitMotorShield
*
* TODO - test with Steppers & Motors - switches on board - interface accepts motor control
*
*/
package org.myrobotlab.service;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import org.myrobotlab.framework.MRLException;
import org.myrobotlab.framework.Service;
import org.myrobotlab.framework.repo.ServiceType;
import org.myrobotlab.logging.Level;
import org.myrobotlab.logging.LoggerFactory;
import org.myrobotlab.logging.Logging;
import org.myrobotlab.logging.LoggingFactory;
import org.myrobotlab.service.Arduino.ServoData;
import org.myrobotlab.service.Arduino.Sketch;
import org.myrobotlab.service.data.Pin;
import org.myrobotlab.service.interfaces.ArduinoShield;
import org.myrobotlab.service.interfaces.ServoController;
import org.slf4j.Logger;
import com.pi4j.io.i2c.I2CBus;
/**
* AdaFruit Motor Shield Controller Service
*
* @author GroG
*
* References : http://www.ladyada.net/make/mshield/use.html
*/
public class Adafruit16CServoDriver extends Service implements ArduinoShield, ServoController {
/** version of the library */
static public final String VERSION = "0.9";
private static final long serialVersionUID = 1L;
// Depending on your servo make, the pulse width min and max may vary, you
// want these to be as small/large as possible without hitting the hard stop
// for max range. You'll have to tweak them as necessary to match the servos
// you have!
//
public final static int SERVOMIN = 150; // this is the 'minimum' pulse
// length count (out of 4096)
public final static int SERVOMAX = 600; // this is the 'maximum' pulse
// length count (out of 4096)
// TODO - Only one I2CControler should be started
transient public Arduino arduino = null;
transient public RasPi raspi = null;
// Used during development to switch between Arduino and RasPi specific code
// Not needed when both use I2CControl interface
public String controler = "Arduino";
HashMap<String, Integer> servoMap = new HashMap<String, Integer>();
// TODO - The commands below should be removed, when a generic i2c interface has been created
public final int AF_BEGIN = 50;
public final int AF_SET_PWM_FREQ = 51;
public final int AF_SET_PWM = 52;
public final int AF_SET_SERVO = 53;
// Variable to ensure that a PWM freqency has been set before starting PWM
private int pwmFreq = 60;
private boolean pwmFreqSet = false;
// Default i2cAddress
public int busAddress = I2CBus.BUS_1;
public int deviceAddress = 0x40;
public String type = "PCA9685";
public transient final static Logger log = LoggerFactory.getLogger(Adafruit16CServoDriver.class.getCanonicalName());
// TODO - Remove this code. It's not needed for code injection any more
/*
public static final String ADAFRUIT_DEFINES = "\n#define AF_SET_PWM 52\n" + "#define AF_BEGIN 50\n" + "#define AF_SET_SERVO 53\n"
+ "#define SERVOMIN 150 // this is the 'minimum' pulse length count (out of 4096)\n"
+ "#define SERVOMAX 600 // this is the 'maximum' pulse length count (out of 4096)\n\n" + "\n\n#include <Wire.h>\n" + "#include <Adafruit_PWMServoDriver.h>\n"
+ "// called this way, it uses the default address 0x40\n" + "Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver();\n" +
"int servoNum = 0; // servoNum is currently active servo";
public static final String ADAFRUIT_SETUP = "\n\n" + " pwm.begin();\n pwm.setPWMFreq(60); // Analog servos run at ~60 Hz updates \n";
public static final String ADAFRUIT_CODE = "\n\n" +
" case AF_SET_PWM:{ \n" + " pwm.setPWM(ioCmd[1], ioCmd[2], ioCmd[3]); \n" + " break;} \n" + " case AF_BEGIN:{ \n"
+ " pwm.begin(); \n" + " break;} \n" + " case AF_SET_SERVO:{ \n"
+ " pwm.setPWM(ioCmd[1], 0, (ioCmd[2] << 8) + ioCmd[3]); \n" + " break; }\n";
*/
HashMap<String, Integer> servoNameToPinMap = new HashMap<String, Integer>();
public static final int PCA9685_MODE1 = 0x00; // Mode 1 register
public static final byte PCA9685_SLEEP = 0x10; // Set sleep mode, before changing prescale value
public static final byte PCA9685_AUTOINCREMENT = 0x20; // Set autoincrement to be able to write more than one byte in sequence
public static final byte PCA9685_PRESCALE = (byte)0xFE; // PreScale register
// Pin PWM addresses 4 bytes repeats for each pin so I only define pin 0
// The rest of the addresses are calculated based on pin numbers
public static final int PCA9685_LED0_ON_L = 0x06; // First LED address Low
public static final int PCA9685_LED0_ON_H = 0x07; // First LED address High
public static final int PCA9685_LED0_OFF_L = 0x08; // First LED address Low
public static final int PCA9685_LED0_OFF_H = 0x08; // First LED address High
public static final int PWM_FREQ = 60; // default frequency for servos
public static final int osc_clock = 25000000; // clock frequency of the internal clock
public static final int precision = 4096; // pwm_precision
/*
public static final int pin = 3; // pin number
public static final int left = 300; // left position
public static final int right = 450; // right position
*/
public static void main(String[] args) {
LoggingFactory.getInstance().configure();
LoggingFactory.getInstance().setLevel(Level.DEBUG);
Adafruit16CServoDriver driver = (Adafruit16CServoDriver) Runtime.start("pwm", "Adafruit16CServoDriver");
}
public Adafruit16CServoDriver(String n) {
super(n);
// Only one should be created
arduino = (Arduino) createPeer("arduino");
raspi = (RasPi) createPeer("raspi");
}
// ----------- AFMotor API End --------------
// attachControllerBoard ??? FIXME FIXME FIXME - should "attach" call
// another's attach?
/**
* an Arduino does not need to know about a shield but a shield must know
* about a Arduino Arduino owns the script, but a Shield needs additional
* support Shields are specific - but plug into a generalized Arduino
* Arduino shields can not be plugged into other uCs
*
* TODO - Program Version & Type injection - with feedback + query to load
*/
@Override
public boolean attach(Arduino arduino) {
if (arduino == null) {
error("can't attach - arduino is invalid");
return false;
}
this.arduino = arduino;
// FIXME - better way to do this might be custom messaging within the
// MRLComm protocol - or re-implementation of the library with MRLComm
// :(
// arduinoName; FIXME - get clear on diction Program Script or Sketch
StringBuffer newProgram = new StringBuffer();
newProgram.append(arduino.getSketch().data);
/*
// modify the program
int insertPoint = newProgram.indexOf(Arduino.VENDOR_DEFINES_BEGIN);
if (insertPoint > 0) {
newProgram.insert(Arduino.VENDOR_DEFINES_BEGIN.length() + insertPoint, ADAFRUIT_DEFINES);
} else {
error("could not find insert point in MRLComm.ino");
// get info back to user
return false;
}
insertPoint = newProgram.indexOf(Arduino.VENDOR_SETUP_BEGIN);
if (insertPoint > 0) {
newProgram.insert(Arduino.VENDOR_SETUP_BEGIN.length() + insertPoint, ADAFRUIT_SETUP);
} else {
error("could not find insert point in MRLComm.ino");
// get info back to user
return false;
}
insertPoint = newProgram.indexOf(Arduino.VENDOR_CODE_BEGIN);
if (insertPoint > 0) {
newProgram.insert(Arduino.VENDOR_CODE_BEGIN.length() + insertPoint, ADAFRUIT_CODE);
} else {
error("could not find insert point in MRLComm.ino");
// get info back to user
return false;
}
*/
// set the program
Sketch sketch = new Sketch("Adafruit16CServoDriver", newProgram.toString());
arduino.setSketch(sketch);
// broadcast the arduino state - ArduinoGUI should subscribe to
// setProgram
broadcastState(); // state has changed let everyone know
arduino.broadcastState();
// servo9.attach(arduinoName, 9); // FIXME ??? - createServo(Integer i)
// servo10.attach(arduinoName, 10);
// error(String.format("couldn't find %s", arduinoName));
return true;
}
// public static final String ADAFRUIT_SCRIPT_TYPE = "#define SCRIPT_TYPE "
// TODO
// FIXME - put in ServoController interface !!!
public boolean attach(Servo servo, Integer pinNumber) {
if (servo == null) {
error("trying to attach null servo");
return false;
}
servo.setController(this);
servoNameToPinMap.put(servo.getName(), pinNumber);
return true;
}
public boolean attach(RasPi raspi) {
if (raspi == null) {
error("can't attach - RasPi is invalid");
return false;
}
this.raspi = raspi;
return true;
}
// VENDOR SPECIFIC LIBRARY METHODS BEGIN /////
// ----------- AF16C API Begin --------------
// TODO The Arduino specific parts should be move to the Arduino service
// The I2CControler methods should be used for both Arduino and RasPi
// The buffer values and the offset and size needs to be changed to correct values.
public void begin() {
if (controler == "Arduino"){
arduino.sendMsg(AF_BEGIN, deviceAddress, 0, 0);
}
else {
byte[] buffer = {PCA9685_MODE1,0x0};
raspi.i2cWrite(busAddress, deviceAddress, buffer, buffer.length);
}
}
public boolean connect(String comPort) {
return arduino.connect(comPort);
}
public Arduino getArduino() {
return arduino;
}
// motor controller api
@Override
public ArrayList<Pin> getPinList() {
ArrayList<Pin> ret = new ArrayList<Pin>();
for (int i = 0; i < 16; ++i) {
Pin p = new Pin();
p.pin = i;
p.type = Pin.PWM_VALUE;
ret.add(p);
}
return ret;
}
@Override
public boolean isAttached() {
return arduino != null;
}
public void setDeviceAddress(Integer DeviceAddress) {
deviceAddress = DeviceAddress;
}
// drive the true PWM. I
public void setPWM(Integer servoNum, Integer pulseWidthOn, Integer pulseWidthOff) {
if (controler == "Arduino"){
arduino.sendMsg(AF_SET_PWM, deviceAddress, servoNum, pulseWidthOn, pulseWidthOff);
}
else {
byte[] buffer = {(byte) (PCA9685_LED0_ON_L + (servoNum * 4)),
(byte)(pulseWidthOn&0xff),(byte)(pulseWidthOn>>8),
(byte)(pulseWidthOff&0xff),(byte)(pulseWidthOff>>8)};
raspi.i2cWrite(busAddress,deviceAddress, buffer, buffer.length);
}
}
public void setPWMFreq(Integer hz) { // Analog servos run at ~60 Hz updates
log.info(String.format("servoPWMFreq %s hz", hz));
if (controler == "Arduino"){
arduino.sendMsg(AF_SET_PWM_FREQ, deviceAddress, hz, 0);
pwmFreqSet = true;
}
else
{
int prescale_value = Math.round(osc_clock / precision / PWM_FREQ) -1;
// Set sleep mode before changing PWM freqency
byte[] buffer1 = {PCA9685_MODE1, PCA9685_SLEEP};
raspi.i2cWrite(busAddress, deviceAddress, buffer1, buffer1.length);
// Wait 1 millisecond until the oscillator has stabilized
try {
Thread.sleep(1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
if (Thread.interrupted()) { // Clears interrupted status!
}
}
// Write the PWM frequency value
byte[] buffer2 = {PCA9685_PRESCALE, (byte) prescale_value};
raspi.i2cWrite(busAddress, deviceAddress, buffer2, buffer2.length );
// Leave sleep mode, set autoincrement to be able to write several bytes in sequence
byte[] buffer3 = {PCA9685_MODE1, PCA9685_AUTOINCREMENT};
raspi.i2cWrite(busAddress, deviceAddress, buffer3, buffer3.length );
// Wait 1 millisecond until the oscillator has stabilized
try {
Thread.sleep(1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
if (Thread.interrupted()) { // Clears interrupted status!
}
}
}
}
public void setServo(Integer servoNum, Integer pulseWidthOff) {
// since pulseWidthOff can be larger than > 256 it needs to be
// sent as 2 bytes
log.info(String.format("setServo %s deviceAddress x%02X pin %s pulse %s", servoNum, deviceAddress, servoNum, pulseWidthOff));
if (controler == "Arduino"){
arduino.sendMsg(AF_SET_SERVO, deviceAddress, servoNum, pulseWidthOff >> 8, pulseWidthOff & 0xFF);
}
else {
byte[] buffer = {(byte) (PCA9685_LED0_OFF_L + (servoNum * 4)),
(byte)(pulseWidthOff&0xff),(byte)(pulseWidthOff>>8)};
raspi.i2cWrite(busAddress, deviceAddress, buffer, buffer.length);
}
}
@Override
public void startService() {
super.startService();
attach(arduino);
arduino.startService();
attach(raspi);
raspi.startService();
// TODO - request myArduino - re connect
}
@Override
public void attach(String name) throws MRLException {
// TODO Auto-generated method stub
}
@Override
public boolean detach(String name) {
// TODO Auto-generated method stub
return false;
}
public synchronized boolean servoAttach(Servo servo, Integer pinNumber) {
if (servo == null) {
error("trying to attach null servo");
return false;
}
servo.setController(this);
servoNameToPinMap.put(servo.getName(), pinNumber);
raspi.createDevice(busAddress, deviceAddress, type);
begin();
return true;
}
@Override
public boolean servoAttach(Servo servo) {
return servoAttach(servo, servo.getPin());
}
@Override
public boolean servoDetach(Servo servo) {
servoNameToPinMap.remove(servo.getName());
return true;
}
@Override
public void servoSweepStart(Servo servo) {
// TODO Auto-generated method stub
}
@Override
public void servoSweepStop(Servo servo) {
// TODO Auto-generated method stub
}
@Override
public void servoWrite(Servo servo) {
if (!pwmFreqSet) {
setPWMFreq(pwmFreq);
}
log.info(String.format("servoWrite %s deviceAddress x%02X pin %s targetOutput %d", servo.getName(), deviceAddress, servo.getPin(), servo.targetOutput));
int pulseWidthOff = SERVOMIN + (int)(servo.targetOutput * (int)((float)SERVOMAX - (float)SERVOMIN) / (float)(180));
setServo(servo.getPin(), pulseWidthOff);
}
@Override
public void servoWriteMicroseconds(Servo servo) {
if (!pwmFreqSet) {
setPWMFreq(pwmFreq);
}
// 1000 ms => 150, 2000 ms => 600
int pulseWidthOff = (int)(servo.uS * 0.45) - 300;
// since pulseWidthOff can be larger than > 256 it needs to be
// sent as 2 bytes
log.info(String.format("servoWriteMicroseconds %s deviceAddress x%02X pin %s pulse %d", servo.getName(), deviceAddress, servo.getPin(), pulseWidthOff));
if (controler == "Arduino"){
arduino.sendMsg(AF_SET_SERVO, deviceAddress, servo.getPin(), pulseWidthOff >> 8, pulseWidthOff & 0xFF);
}
else {
byte[] buffer = {(byte) (PCA9685_LED0_OFF_L + (servo.getPin() * 4)),
(byte)(pulseWidthOff&0xff),(byte)(pulseWidthOff>>8)};
raspi.i2cWrite(busAddress, deviceAddress, buffer, buffer.length);
}
}
@Override
public boolean servoEventsEnabled(Servo servo) {
// TODO Auto-generated method stub
return false;
}
@Override
public void setServoSpeed(Servo servo) {
// TODO Auto-generated method stub
}
/**
* This static method returns all the details of the class without
* it having to be constructed. It has description, categories,
* dependencies, and peer definitions.
*
* @return ServiceType - returns all the data
*
*/
static public ServiceType getMetaData(){
ServiceType meta = new ServiceType(Adafruit16CServoDriver.class.getCanonicalName());
meta.addDescription("Adafruit Motor Shield Service");
meta.addCategory("shield", "motor");
meta.addPeer("arduino", "Arduino", "our Arduino");
meta.addPeer("raspi", "RasPi", "our RasPi");
return meta;
}
}
|
src/org/myrobotlab/service/Adafruit16CServoDriver.java
|
/*
*
* AdafruitMotorShield
*
* TODO - test with Steppers & Motors - switches on board - interface accepts motor control
*
*/
package org.myrobotlab.service;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import org.myrobotlab.framework.MRLException;
import org.myrobotlab.framework.Service;
import org.myrobotlab.framework.repo.ServiceType;
import org.myrobotlab.logging.Level;
import org.myrobotlab.logging.LoggerFactory;
import org.myrobotlab.logging.Logging;
import org.myrobotlab.logging.LoggingFactory;
import org.myrobotlab.service.Arduino.ServoData;
import org.myrobotlab.service.Arduino.Sketch;
import org.myrobotlab.service.data.Pin;
import org.myrobotlab.service.interfaces.ArduinoShield;
import org.myrobotlab.service.interfaces.ServoController;
import org.slf4j.Logger;
import com.pi4j.io.i2c.I2CBus;
/**
* AdaFruit Motor Shield Controller Service
*
* @author GroG
*
* References : http://www.ladyada.net/make/mshield/use.html
*/
public class Adafruit16CServoDriver extends Service implements ArduinoShield, ServoController {
/** version of the library */
static public final String VERSION = "0.9";
private static final long serialVersionUID = 1L;
// Depending on your servo make, the pulse width min and max may vary, you
// want these to be as small/large as possible without hitting the hard stop
// for max range. You'll have to tweak them as necessary to match the servos
// you have!
//
public final static int SERVOMIN = 150; // this is the 'minimum' pulse
// length count (out of 4096)
public final static int SERVOMAX = 600; // this is the 'maximum' pulse
// length count (out of 4096)
// TODO - Only one I2CControler should be started
transient public Arduino arduino = null;
transient public RasPi raspi = null;
// Used during development to switch between Arduino and RasPi specific code
// Not needed when both use I2CControl interface
public String controler = "Arduino";
HashMap<String, Integer> servoMap = new HashMap<String, Integer>();
// TODO - The commands below should be removed, when a generic i2c interface has been created
public final int AF_BEGIN = 50;
public final int AF_SET_PWM_FREQ = 51;
public final int AF_SET_PWM = 52;
public final int AF_SET_SERVO = 53;
// Variable to ensure that a PWM freqency has been set before starting PWM
private int pwmFreq = 60;
private boolean pwmFreqSet = false;
// Default i2cAddress
public int busAddress = I2CBus.BUS_1;
public int deviceAddress = 0x40;
public String type = "PCA9685";
public transient final static Logger log = LoggerFactory.getLogger(Adafruit16CServoDriver.class.getCanonicalName());
// TODO - Remove this code. It's not needed for code injection any more
/*
public static final String ADAFRUIT_DEFINES = "\n#define AF_SET_PWM 52\n" + "#define AF_BEGIN 50\n" + "#define AF_SET_SERVO 53\n"
+ "#define SERVOMIN 150 // this is the 'minimum' pulse length count (out of 4096)\n"
+ "#define SERVOMAX 600 // this is the 'maximum' pulse length count (out of 4096)\n\n" + "\n\n#include <Wire.h>\n" + "#include <Adafruit_PWMServoDriver.h>\n"
+ "// called this way, it uses the default address 0x40\n" + "Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver();\n" +
"int servoNum = 0; // servoNum is currently active servo";
public static final String ADAFRUIT_SETUP = "\n\n" + " pwm.begin();\n pwm.setPWMFreq(60); // Analog servos run at ~60 Hz updates \n";
public static final String ADAFRUIT_CODE = "\n\n" +
" case AF_SET_PWM:{ \n" + " pwm.setPWM(ioCmd[1], ioCmd[2], ioCmd[3]); \n" + " break;} \n" + " case AF_BEGIN:{ \n"
+ " pwm.begin(); \n" + " break;} \n" + " case AF_SET_SERVO:{ \n"
+ " pwm.setPWM(ioCmd[1], 0, (ioCmd[2] << 8) + ioCmd[3]); \n" + " break; }\n";
*/
HashMap<String, Integer> servoNameToPinMap = new HashMap<String, Integer>();
public static final int PCA9685_MODE1 = 0x00; // Mode 1 register
public static final byte PCA9685_SLEEP = 0x10; // Set sleep mode, before changing prescale value
public static final byte PCA9685_AUTOINCREMENT = 0x20; // Set autoincrement to be able to write more than one byte in sequence
public static final byte PCA9685_PRESCALE = (byte)0xFE; // PreScale register
// Pin PWM addresses 4 bytes repeats for each pin so I only define pin 0
// The rest of the addresses are calculated based on pin numbers
public static final int PCA9685_LED0_ON_L = 0x06; // First LED address Low
public static final int PCA9685_LED0_ON_H = 0x07; // First LED address High
public static final int PCA9685_LED0_OFF_L = 0x08; // First LED address Low
public static final int PCA9685_LED0_OFF_H = 0x08; // First LED address High
public static final int PWM_FREQ = 60; // default frequency for servos
public static final int osc_clock = 25000000; // clock frequency of the internal clock
public static final int precision = 4096; // pwm_precision
/*
public static final int pin = 3; // pin number
public static final int left = 300; // left position
public static final int right = 450; // right position
*/
public static void main(String[] args) {
LoggingFactory.getInstance().configure();
LoggingFactory.getInstance().setLevel(Level.DEBUG);
Adafruit16CServoDriver driver = (Adafruit16CServoDriver) Runtime.start("pwm", "Adafruit16CServoDriver");
}
public Adafruit16CServoDriver(String n) {
super(n);
// Only one should be created
arduino = (Arduino) createPeer("arduino");
raspi = (RasPi) createPeer("raspi");
}
// ----------- AFMotor API End --------------
// attachControllerBoard ??? FIXME FIXME FIXME - should "attach" call
// another's attach?
/**
* an Arduino does not need to know about a shield but a shield must know
* about a Arduino Arduino owns the script, but a Shield needs additional
* support Shields are specific - but plug into a generalized Arduino
* Arduino shields can not be plugged into other uCs
*
* TODO - Program Version & Type injection - with feedback + query to load
*/
@Override
public boolean attach(Arduino arduino) {
if (arduino == null) {
error("can't attach - arduino is invalid");
return false;
}
this.arduino = arduino;
// FIXME - better way to do this might be custom messaging within the
// MRLComm protocol - or re-implementation of the library with MRLComm
// :(
// arduinoName; FIXME - get clear on diction Program Script or Sketch
StringBuffer newProgram = new StringBuffer();
newProgram.append(arduino.getSketch().data);
/*
// modify the program
int insertPoint = newProgram.indexOf(Arduino.VENDOR_DEFINES_BEGIN);
if (insertPoint > 0) {
newProgram.insert(Arduino.VENDOR_DEFINES_BEGIN.length() + insertPoint, ADAFRUIT_DEFINES);
} else {
error("could not find insert point in MRLComm.ino");
// get info back to user
return false;
}
insertPoint = newProgram.indexOf(Arduino.VENDOR_SETUP_BEGIN);
if (insertPoint > 0) {
newProgram.insert(Arduino.VENDOR_SETUP_BEGIN.length() + insertPoint, ADAFRUIT_SETUP);
} else {
error("could not find insert point in MRLComm.ino");
// get info back to user
return false;
}
insertPoint = newProgram.indexOf(Arduino.VENDOR_CODE_BEGIN);
if (insertPoint > 0) {
newProgram.insert(Arduino.VENDOR_CODE_BEGIN.length() + insertPoint, ADAFRUIT_CODE);
} else {
error("could not find insert point in MRLComm.ino");
// get info back to user
return false;
}
*/
// set the program
Sketch sketch = new Sketch("Adafruit16CServoDriver", newProgram.toString());
arduino.setSketch(sketch);
// broadcast the arduino state - ArduinoGUI should subscribe to
// setProgram
broadcastState(); // state has changed let everyone know
arduino.broadcastState();
// servo9.attach(arduinoName, 9); // FIXME ??? - createServo(Integer i)
// servo10.attach(arduinoName, 10);
// error(String.format("couldn't find %s", arduinoName));
return true;
}
// public static final String ADAFRUIT_SCRIPT_TYPE = "#define SCRIPT_TYPE "
// TODO
// FIXME - put in ServoController interface !!!
public boolean attach(Servo servo, Integer pinNumber) {
if (servo == null) {
error("trying to attach null servo");
return false;
}
servo.setController(this);
servoNameToPinMap.put(servo.getName(), pinNumber);
return true;
}
public boolean attach(RasPi raspi) {
if (raspi == null) {
error("can't attach - RasPi is invalid");
return false;
}
this.raspi = raspi;
return true;
}
// VENDOR SPECIFIC LIBRARY METHODS BEGIN /////
// ----------- AF16C API Begin --------------
// TODO The Arduino specific parts should be move to the Arduino service
// The I2CControler methods should be used for both Arduino and RasPi
// The buffer values and the offset and size needs to be changed to correct values.
public void begin() {
if (controler == "Arduino"){
arduino.sendMsg(AF_BEGIN, deviceAddress, 0, 0);
}
else {
byte[] buffer = {PCA9685_MODE1,0x0};
raspi.i2cWrite(busAddress, deviceAddress, buffer, buffer.length);
}
}
public boolean connect(String comPort) {
return arduino.connect(comPort);
}
public Arduino getArduino() {
return arduino;
}
// motor controller api
@Override
public ArrayList<Pin> getPinList() {
ArrayList<Pin> ret = new ArrayList<Pin>();
for (int i = 0; i < 16; ++i) {
Pin p = new Pin();
p.pin = i;
p.type = Pin.PWM_VALUE;
ret.add(p);
}
return ret;
}
@Override
public boolean isAttached() {
return arduino != null;
}
public void setDeviceAddress(Integer DeviceAddress) {
deviceAddress = DeviceAddress;
}
// drive the true PWM. I
public void setPWM(Integer servoNum, Integer pulseWidthOn, Integer pulseWidthOff) {
if (controler == "Arduino"){
arduino.sendMsg(AF_SET_PWM, deviceAddress, servoNum, pulseWidthOn, pulseWidthOff);
}
else {
byte[] buffer = {(byte) (PCA9685_LED0_ON_L + (servoNum * 4)),
(byte)(pulseWidthOn&0xff),(byte)(pulseWidthOn>>8),
(byte)(pulseWidthOff&0xff),(byte)(pulseWidthOff>>8)};
raspi.i2cWrite(busAddress,deviceAddress, buffer, buffer.length);
}
}
public void setPWMFreq(Integer hz) { // Analog servos run at ~60 Hz updates
log.info(String.format("servoPWMFreq %s hz", hz));
if (controler == "Arduino"){
arduino.sendMsg(AF_SET_PWM_FREQ, deviceAddress, hz, 0);
}
else
{
int prescale_value = Math.round(osc_clock / precision / PWM_FREQ) -1;
// Set sleep mode before changing PWM freqency
byte[] buffer1 = {PCA9685_MODE1, PCA9685_SLEEP};
raspi.i2cWrite(busAddress, deviceAddress, buffer1, buffer1.length);
// Wait 1 millisecond until the oscillator has stabilized
try {
Thread.sleep(1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
if (Thread.interrupted()) { // Clears interrupted status!
}
}
// Write the PWM frequency value
byte[] buffer2 = {PCA9685_PRESCALE, (byte) prescale_value};
raspi.i2cWrite(busAddress, deviceAddress, buffer2, buffer2.length );
// Leave sleep mode, set autoincrement to be able to write several bytes in sequence
byte[] buffer3 = {PCA9685_MODE1, PCA9685_AUTOINCREMENT};
raspi.i2cWrite(busAddress, deviceAddress, buffer3, buffer3.length );
// Wait 1 millisecond until the oscillator has stabilized
try {
Thread.sleep(1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
if (Thread.interrupted()) { // Clears interrupted status!
}
}
}
}
public void setServo(Integer servoNum, Integer pulseWidthOff) {
// since pulseWidthOff can be larger than > 256 it needs to be
// sent as 2 bytes
log.info(String.format("setServo %s deviceAddress x%02X pin %s pulse %s", servoNum, deviceAddress, servoNum, pulseWidthOff));
if (controler == "Arduino"){
arduino.sendMsg(AF_SET_SERVO, deviceAddress, servoNum, pulseWidthOff >> 8, pulseWidthOff & 0xFF);
}
else {
byte[] buffer = {(byte) (PCA9685_LED0_OFF_L + (servoNum * 4)),
(byte)(pulseWidthOff&0xff),(byte)(pulseWidthOff>>8)};
raspi.i2cWrite(busAddress, deviceAddress, buffer, buffer.length);
}
}
@Override
public void startService() {
super.startService();
attach(arduino);
arduino.startService();
attach(raspi);
raspi.startService();
// TODO - request myArduino - re connect
}
@Override
public void attach(String name) throws MRLException {
// TODO Auto-generated method stub
}
@Override
public boolean detach(String name) {
// TODO Auto-generated method stub
return false;
}
public synchronized boolean servoAttach(Servo servo, Integer pinNumber) {
if (servo == null) {
error("trying to attach null servo");
return false;
}
servo.setController(this);
servoNameToPinMap.put(servo.getName(), pinNumber);
raspi.createDevice(busAddress, deviceAddress, type);
begin();
return true;
}
@Override
public boolean servoAttach(Servo servo) {
return servoAttach(servo, servo.getPin());
}
@Override
public boolean servoDetach(Servo servo) {
servoNameToPinMap.remove(servo.getName());
return true;
}
@Override
public void servoSweepStart(Servo servo) {
// TODO Auto-generated method stub
}
@Override
public void servoSweepStop(Servo servo) {
// TODO Auto-generated method stub
}
@Override
public void servoWrite(Servo servo) {
if (!pwmFreqSet) {
setPWMFreq(pwmFreq);
}
log.info(String.format("servoWrite %s deviceAddress x%02X pin %s targetOutput %d", servo.getName(), deviceAddress, servo.getPin(), servo.targetOutput));
int pulseWidthOff = SERVOMIN + (int)(servo.targetOutput * (int)((float)SERVOMAX - (float)SERVOMIN) / (float)(180));
setServo(servo.getPin(), pulseWidthOff);
}
@Override
public void servoWriteMicroseconds(Servo servo) {
if (!pwmFreqSet) {
setPWMFreq(pwmFreq);
}
// 1000 ms => 150, 2000 ms => 600
int pulseWidthOff = (int)(servo.uS * 0.45) - 300;
// since pulseWidthOff can be larger than > 256 it needs to be
// sent as 2 bytes
log.info(String.format("servoWriteMicroseconds %s deviceAddress x%02X pin %s pulse %d", servo.getName(), deviceAddress, servo.getPin(), pulseWidthOff));
if (controler == "Arduino"){
arduino.sendMsg(AF_SET_SERVO, deviceAddress, servo.getPin(), pulseWidthOff >> 8, pulseWidthOff & 0xFF);
}
else {
byte[] buffer = {(byte) (PCA9685_LED0_OFF_L + (servo.getPin() * 4)),
(byte)(pulseWidthOff&0xff),(byte)(pulseWidthOff>>8)};
raspi.i2cWrite(busAddress, deviceAddress, buffer, buffer.length);
}
}
@Override
public boolean servoEventsEnabled(Servo servo) {
// TODO Auto-generated method stub
return false;
}
@Override
public void setServoSpeed(Servo servo) {
// TODO Auto-generated method stub
}
/**
* This static method returns all the details of the class without
* it having to be constructed. It has description, categories,
* dependencies, and peer definitions.
*
* @return ServiceType - returns all the data
*
*/
static public ServiceType getMetaData(){
ServiceType meta = new ServiceType(Adafruit16CServoDriver.class.getCanonicalName());
meta.addDescription("Adafruit Motor Shield Service");
meta.addCategory("shield", "motor");
meta.addPeer("arduino", "Arduino", "our Arduino");
meta.addPeer("raspi", "RasPi", "our RasPi");
return meta;
}
}
|
Minor change to avoid execting setPWMFreq multiple times
|
src/org/myrobotlab/service/Adafruit16CServoDriver.java
|
Minor change to avoid execting setPWMFreq multiple times
|
|
Java
|
apache-2.0
|
bebe7b46d004568c47b8857ba316c038a74b485e
| 0
|
mikosik/smooth-build,mikosik/smooth-build
|
package org.smoothbuild.lang;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static java.lang.Math.max;
import static java.util.Arrays.stream;
import static org.smoothbuild.lang.base.define.TestingLocation.loc;
import static org.smoothbuild.lang.base.define.TestingModulePath.modulePath;
import java.util.List;
import java.util.Optional;
import org.smoothbuild.lang.base.define.Constructor;
import org.smoothbuild.lang.base.define.Function;
import org.smoothbuild.lang.base.define.Item;
import org.smoothbuild.lang.base.define.Location;
import org.smoothbuild.lang.base.define.RealFunction;
import org.smoothbuild.lang.base.define.Value;
import org.smoothbuild.lang.base.type.ItemSignature;
import org.smoothbuild.lang.base.type.StructType;
import org.smoothbuild.lang.base.type.Type;
import org.smoothbuild.lang.base.type.Types;
import org.smoothbuild.lang.expr.ArrayLiteralExpression;
import org.smoothbuild.lang.expr.BlobLiteralExpression;
import org.smoothbuild.lang.expr.CallExpression;
import org.smoothbuild.lang.expr.Expression;
import org.smoothbuild.lang.expr.FieldReadExpression;
import org.smoothbuild.lang.expr.NativeExpression;
import org.smoothbuild.lang.expr.ParameterReferenceExpression;
import org.smoothbuild.lang.expr.ReferenceExpression;
import org.smoothbuild.lang.expr.StringLiteralExpression;
import com.google.common.collect.ImmutableList;
import okio.ByteString;
public class TestingLang {
public static BlobLiteralExpression blob(int data) {
return blob(1, data);
}
public static BlobLiteralExpression blob(int line, int data) {
return new BlobLiteralExpression(ByteString.of((byte) data), loc(line));
}
public static StringLiteralExpression string(int line, String data) {
return new StringLiteralExpression(data, loc(line));
}
public static ArrayLiteralExpression array(int line, Type elemType, Expression... expressions) {
return new ArrayLiteralExpression(
Types.array(elemType), ImmutableList.copyOf(expressions), loc(line));
}
public static ReferenceExpression reference(int line, Type type, String name) {
return new ReferenceExpression(name, type, loc(line));
}
public static ParameterReferenceExpression parameterRef(Type type, String name) {
return parameterRef(1, type, name);
}
public static ParameterReferenceExpression parameterRef(int line, Type type, String name) {
return new ParameterReferenceExpression(type, name, loc(line));
}
public static FieldReadExpression fieldRead(
int line, ItemSignature field, Expression expression) {
return new FieldReadExpression(field, expression, loc(line));
}
public static CallExpression call(
int line, Type type, Function function, Expression... arguments) {
Location loc = loc(line);
ReferenceExpression reference = new ReferenceExpression(function.name(), function.type(), loc);
var args = stream(arguments).map(Optional::of).collect(toImmutableList());
return new CallExpression(type, reference, args, loc);
}
public static RealFunction function(Type type, String name, Item... parameters) {
return function(1, type, name, "Impl.met", parameters);
}
public static RealFunction function(int line, Type type, String name, String implementedBy,
Item... parameters) {
NativeExpression nativeExpression = new NativeExpression(
implementedBy, true, loc(max(line - 1, 1)));
return function(line, type, name, nativeExpression, parameters);
}
public static RealFunction function(Type type, String name, Expression body, Item... parameters) {
return function(1, type, name, body, parameters);
}
public static RealFunction function(int line, Type type, String name, Expression body,
Item... parameters) {
return new RealFunction(
type, modulePath(), name, ImmutableList.copyOf(parameters), body, loc(line));
}
public static Value value(int line, Type type, String name, String implementedBy) {
NativeExpression nativ = new NativeExpression(implementedBy, true, loc(line -1));
return new Value(type, modulePath(), name, nativ, loc(line));
}
public static Value value(int line, Type type, String name, Expression expression) {
return new Value(type, modulePath(), name, expression, loc(line));
}
public static StructType struct(String name, ItemSignature field) {
return Types.struct(name, List.of(field));
}
public static Constructor constr(int line, Type resultType, String name, Item... parameters) {
return new Constructor(
resultType, modulePath(), name, ImmutableList.copyOf(parameters), loc(line));
}
public static Item parameter(Type type, String name) {
return parameter(type, name, Optional.empty());
}
public static Item parameter(Type type, String name, Expression defaultValue) {
return parameter(type, name, Optional.of(defaultValue));
}
private static Item parameter(Type type, String name,
Optional<Expression> defaultValue) {
return new Item(type, name, defaultValue);
}
public static Item field(Type type, String name) {
return new Item(type, name, Optional.empty());
}
}
|
src/testing/java/org/smoothbuild/lang/TestingLang.java
|
package org.smoothbuild.lang;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static java.lang.Math.max;
import static java.util.Arrays.stream;
import static org.smoothbuild.lang.base.define.TestingLocation.loc;
import static org.smoothbuild.lang.base.define.TestingModulePath.modulePath;
import java.util.List;
import java.util.Optional;
import org.smoothbuild.lang.base.define.Constructor;
import org.smoothbuild.lang.base.define.Function;
import org.smoothbuild.lang.base.define.Item;
import org.smoothbuild.lang.base.define.Location;
import org.smoothbuild.lang.base.define.RealFunction;
import org.smoothbuild.lang.base.define.Value;
import org.smoothbuild.lang.base.type.ItemSignature;
import org.smoothbuild.lang.base.type.StructType;
import org.smoothbuild.lang.base.type.Type;
import org.smoothbuild.lang.base.type.Types;
import org.smoothbuild.lang.expr.ArrayLiteralExpression;
import org.smoothbuild.lang.expr.BlobLiteralExpression;
import org.smoothbuild.lang.expr.CallExpression;
import org.smoothbuild.lang.expr.Expression;
import org.smoothbuild.lang.expr.FieldReadExpression;
import org.smoothbuild.lang.expr.NativeExpression;
import org.smoothbuild.lang.expr.ParameterReferenceExpression;
import org.smoothbuild.lang.expr.ReferenceExpression;
import org.smoothbuild.lang.expr.StringLiteralExpression;
import com.google.common.collect.ImmutableList;
import okio.ByteString;
public class TestingLang {
public static BlobLiteralExpression blob(int data) {
return blob(1, data);
}
public static BlobLiteralExpression blob(int line, int data) {
return new BlobLiteralExpression(ByteString.of((byte) data), loc(line));
}
public static StringLiteralExpression string(int line, String data) {
return new StringLiteralExpression(data, loc(line));
}
public static ArrayLiteralExpression array(int line, Type elemType, Expression... expressions) {
return new ArrayLiteralExpression(
Types.array(elemType), ImmutableList.copyOf(expressions), loc(line));
}
public static ReferenceExpression reference(int line, Type type, String name) {
return new ReferenceExpression(name, type, loc(line));
}
public static ParameterReferenceExpression parameterRef(Type type, String name) {
return parameterRef(1, type, name);
}
public static ParameterReferenceExpression parameterRef(int line, Type type, String name) {
return new ParameterReferenceExpression(type, name, loc(line));
}
public static FieldReadExpression fieldRead(
int line, ItemSignature field, Expression expression) {
return new FieldReadExpression(field, expression, loc(line));
}
public static CallExpression call(Type type, Function function, Expression... arguments) {
return call(1, type, function, arguments);
}
public static CallExpression call(
int line, Type type, Function function, Expression... arguments) {
Location loc = loc(line);
ReferenceExpression reference = new ReferenceExpression(function.name(), function.type(), loc);
var args = stream(arguments).map(Optional::of).collect(toImmutableList());
return new CallExpression(type, reference, args, loc);
}
public static RealFunction function(Type type, String name, Item... parameters) {
return function(1, type, name, "Impl.met", parameters);
}
public static RealFunction function(int line, Type type, String name, String implementedBy,
Item... parameters) {
NativeExpression nativeExpression = new NativeExpression(
implementedBy, true, loc(max(line - 1, 1)));
return function(line, type, name, nativeExpression, parameters);
}
public static RealFunction function(Type type, String name, Expression body, Item... parameters) {
return function(1, type, name, body, parameters);
}
public static RealFunction function(int line, Type type, String name, Expression body,
Item... parameters) {
return new RealFunction(
type, modulePath(), name, ImmutableList.copyOf(parameters), body, loc(line));
}
public static Value value(int line, Type type, String name, String implementedBy) {
NativeExpression nativ = new NativeExpression(implementedBy, true, loc(line -1));
return new Value(type, modulePath(), name, nativ, loc(line));
}
public static Value value(int line, Type type, String name, Expression expression) {
return new Value(type, modulePath(), name, expression, loc(line));
}
public static StructType struct(String name, ItemSignature field) {
return Types.struct(name, List.of(field));
}
public static Constructor constr(int line, Type resultType, String name, Item... parameters) {
return new Constructor(
resultType, modulePath(), name, ImmutableList.copyOf(parameters), loc(line));
}
public static Item parameter(Type type, String name) {
return parameter(type, name, Optional.empty());
}
public static Item parameter(Type type, String name, Expression defaultValue) {
return parameter(type, name, Optional.of(defaultValue));
}
private static Item parameter(Type type, String name,
Optional<Expression> defaultValue) {
return new Item(type, name, defaultValue);
}
public static Item field(Type type, String name) {
return new Item(type, name, Optional.empty());
}
}
|
removed dead code
|
src/testing/java/org/smoothbuild/lang/TestingLang.java
|
removed dead code
|
|
Java
|
apache-2.0
|
637703cccec9b605e40b1ec58f7c0be01ab8706b
| 0
|
jondwillis/ElectricSleep
|
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.androsz.electricsleepbeta.alarmclock;
import android.app.AlertDialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.EditTextPreference;
import android.preference.Preference;
import android.preference.PreferenceScreen;
import android.text.format.DateFormat;
import android.view.View;
import android.widget.Button;
import android.widget.TimePicker;
import android.widget.Toast;
import com.androsz.electricsleepbeta.R;
import com.androsz.electricsleepbeta.preference.HostPreferenceActivity;
/**
* Manages each alarm
*/
public class SetAlarm extends HostPreferenceActivity implements
TimePickerDialog.OnTimeSetListener, Preference.OnPreferenceChangeListener {
// Used to post runnables asynchronously.
// private static final Handler sHandler = new Handler();
/**
* format "Alarm set for 2 days 7 hours and 53 minutes from now"
*/
static String formatToast(final Context context, final long timeInMillis) {
final long delta = timeInMillis - System.currentTimeMillis();
long hours = delta / (1000 * 60 * 60);
final long minutes = delta / (1000 * 60) % 60;
final long days = hours / 24;
hours = hours % 24;
final String daySeq = days == 0 ? "" : days == 1 ? context.getString(R.string.day)
: context.getString(R.string.days, Long.toString(days));
final String minSeq = minutes == 0 ? "" : minutes == 1 ? context.getString(R.string.minute)
: context.getString(R.string.minutes, Long.toString(minutes));
final String hourSeq = hours == 0 ? "" : hours == 1 ? context.getString(R.string.hour)
: context.getString(R.string.hours, Long.toString(hours));
final boolean dispDays = days > 0;
final boolean dispHour = hours > 0;
final boolean dispMinute = minutes > 0;
final int index = (dispDays ? 1 : 0) | (dispHour ? 2 : 0) | (dispMinute ? 4 : 0);
final String[] formats = context.getResources().getStringArray(R.array.alarm_set);
return String.format(formats[index], daySeq, hourSeq, minSeq);
}
/**
* Display a toast that tells the user how long until the alarm goes off.
* This helps prevent "am/pm" mistakes.
*/
static void popAlarmSetToast(final Context context, final int hour, final int minute,
final Alarm.DaysOfWeek daysOfWeek) {
popAlarmSetToast(context, Alarms.calculateAlarm(hour, minute, daysOfWeek).getTimeInMillis());
}
private static void popAlarmSetToast(final Context context, final long timeInMillis) {
final String toastText = formatToast(context, timeInMillis);
final Toast toast = Toast.makeText(context, toastText, Toast.LENGTH_LONG);
ToastMaster.setToast(toast);
toast.show();
}
private AlarmPreference mAlarmPref;
private CheckBoxPreference mEnabledPref;
private int mHour;
private int mId;
private EditTextPreference mLabel;
private int mMinutes;
private Alarm mOriginalAlarm;
private RepeatPreference mRepeatPref;
private boolean mTimePickerCancelled;
private Preference mTimePref;
private CheckBoxPreference mVibratePref;
private void deleteAlarm() {
new AlertDialog.Builder(this).setTitle(getString(R.string.delete_alarm))
.setMessage(getString(R.string.delete_alarm_confirm))
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(final DialogInterface d, final int w) {
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
Alarms.deleteAlarm(SetAlarm.this, mId);
return null;
}
@Override
protected void onPostExecute(Void result) {
finish();
}
}.execute();
}
}).setNegativeButton(android.R.string.cancel, null).show();
}
@Override
protected int getContentAreaLayoutId() {
return R.xml.alarm_prefs;
}
@Override
public void onBackPressed() {
// In the usual case of viewing an alarm, mTimePickerCancelled is
// initialized to false. When creating a new alarm, this value is
// assumed true until the user changes the time.
if (!mTimePickerCancelled) {
new Thread(new Runnable() {
@Override
public void run() {
saveAlarm();
}
}).start();
}
finish();
}
/**
* Set an alarm. Requires an Alarms.ALARM_ID to be passed in as an extra.
* FIXME: Pass an Alarm object like every other Activity.
*/
@Override
protected void onCreate(final Bundle icicle) {
super.onCreate(icicle);
// Override the default content view.
setContentView(R.layout.set_alarm);
// addPreferencesFromResource(R.xml.alarm_prefs);
// Get each preference so we can retrieve the value later.
mLabel = (EditTextPreference) findPreference("label");
mLabel.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(final Preference p, final Object newValue) {
final String val = (String) newValue;
// Set the summary based on the new label.
p.setSummary(val);
if (val != null && !val.equals(mLabel.getText())) {
// Call through to the generic listener.
return SetAlarm.this.onPreferenceChange(p, newValue);
}
return true;
}
});
mEnabledPref = (CheckBoxPreference) findPreference("enabled");
mEnabledPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(final Preference p, final Object newValue) {
// Pop a toast when enabling alarms.
if (!mEnabledPref.isChecked()) {
popAlarmSetToast(SetAlarm.this, mHour, mMinutes, mRepeatPref.getDaysOfWeek());
}
return SetAlarm.this.onPreferenceChange(p, newValue);
}
});
mTimePref = findPreference("time");
mAlarmPref = (AlarmPreference) findPreference("alarm");
mAlarmPref.setOnPreferenceChangeListener(this);
mVibratePref = (CheckBoxPreference) findPreference("vibrate");
mVibratePref.setOnPreferenceChangeListener(this);
mRepeatPref = (RepeatPreference) findPreference("setRepeat");
mRepeatPref.setOnPreferenceChangeListener(this);
final Intent i = getIntent();
mId = i.getIntExtra(Alarms.ALARM_ID, -1);
if (Log.LOGV) {
Log.v("In SetAlarm, alarm id = " + mId);
}
Alarm alarm = null;
if (mId == -1) {
// No alarm id means create a new alarm.
alarm = new Alarm();
} else {
/* load alarm details from database */
alarm = Alarms.getAlarm(getContentResolver(), mId);
// Bad alarm, bail to avoid a NPE.
if (alarm == null) {
finish();
return;
}
}
mOriginalAlarm = alarm;
updatePrefs(mOriginalAlarm);
// We have to do this to get the save/cancel buttons to highlight on
// their own.
getListView().setItemsCanFocus(true);
getListView().setBackgroundColor(Color.BLACK);
//getListView().setCacheColorHint(0);
//getListView().setBackgroundDrawable(
// getResources().getDrawable(R.drawable.gradient_background_vert));
// Attach actions to each button.
Button b = (Button) findViewById(R.id.alarm_save);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View v) {
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
saveAlarm();
return null;
}
@Override
protected void onPostExecute(Void result) {
finish();
}
}.execute();
}
});
final Button revert = (Button) findViewById(R.id.alarm_revert);
revert.setEnabled(false);
revert.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View v) {
final int newId = mId;
updatePrefs(mOriginalAlarm);
// "Revert" on a newly created alarm should delete it.
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
if (mOriginalAlarm.id == -1) {
Alarms.deleteAlarm(SetAlarm.this, newId);
} else {
saveAlarm();
}
return null;
}
@Override
protected void onPostExecute(Void result) {
revert.setEnabled(false);
}
}.execute();
}
});
b = (Button) findViewById(R.id.alarm_delete);
if (mId == -1) {
b.setEnabled(false);
} else {
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View v) {
deleteAlarm();
}
});
}
// The last thing we do is pop the time picker if this is a new alarm.
if (mId == -1) {
// Assume the user hit cancel
mTimePickerCancelled = true;
showTimePicker();
}
}
@Override
public boolean onPreferenceChange(final Preference p, final Object newValue) {
// Asynchronously save the alarm since this method is called _before_
// the value of the preference has changed.
new AsyncTask<Void, Void, Void>() {
@Override
protected void onPreExecute() {
// Editing any preference (except enable) enables the alarm.
if (p != mEnabledPref) {
mEnabledPref.setChecked(true);
}
}
@Override
protected Void doInBackground(Void... params) {
saveAlarm();
return null;
}
@Override
protected void onPostExecute(Void result) {
final Button revert = (Button) findViewById(R.id.alarm_revert);
revert.setEnabled(true);
}
}.execute();
return true;
}
@Override
public boolean onPreferenceTreeClick(final PreferenceScreen preferenceScreen,
final Preference preference) {
if (preference == mTimePref) {
showTimePicker();
}
return super.onPreferenceTreeClick(preferenceScreen, preference);
}
@Override
public void onTimeSet(final TimePicker view, final int hourOfDay, final int minute) {
// onTimeSet is called when the user clicks "Set"
mTimePickerCancelled = false;
mHour = hourOfDay;
mMinutes = minute;
updateTime();
// If the time has been changed, enable the alarm.
mEnabledPref.setChecked(true);
// Save the alarm and pop a toast.
// Enable "Revert" to go back to the original Alarm.
final Button revert = (Button) findViewById(R.id.alarm_revert);
revert.setEnabled(true);
new AsyncTask<Void, Void, Long>() {
@Override
protected Long doInBackground(Void... params) {
return saveAlarm();
}
@Override
protected void onPostExecute(Long result) {
popAlarmSetToast(SetAlarm.this, result);
}
}.execute();
}
private long saveAlarm() {
long time;
final Alarm alarm = new Alarm();
alarm.id = mId;
alarm.enabled = mEnabledPref.isChecked();
alarm.hour = mHour;
alarm.minutes = mMinutes;
alarm.daysOfWeek = mRepeatPref.getDaysOfWeek();
alarm.vibrate = mVibratePref.isChecked();
alarm.label = mLabel.getText();
alarm.alert = mAlarmPref.getAlert();
if (alarm.id == -1) {
time = Alarms.addAlarm(this, alarm);
// addAlarm populates the alarm with the new id. Update mId so that
// changes to other preferences update the new alarm.
mId = alarm.id;
} else {
time = Alarms.setAlarm(this, alarm);
}
return time;
}
private long saveAlarmAndEnableRevert() {
final Button revert = (Button) findViewById(R.id.alarm_revert);
revert.setEnabled(true);
return saveAlarm();
}
private void showTimePicker() {
new TimePickerDialog(this, this, mHour, mMinutes, DateFormat.is24HourFormat(this)).show();
}
private void updatePrefs(final Alarm alarm) {
mId = alarm.id;
mEnabledPref.setChecked(alarm.enabled);
mLabel.setText(alarm.label);
mLabel.setSummary(alarm.label);
mHour = alarm.hour;
mMinutes = alarm.minutes;
mRepeatPref.setDaysOfWeek(alarm.daysOfWeek);
mVibratePref.setChecked(alarm.vibrate);
// Give the alert uri to the preference.
mAlarmPref.setAlert(alarm.alert);
updateTime();
}
private void updateTime() {
if (Log.LOGV) {
Log.v("updateTime " + mId);
}
mTimePref.setSummary(Alarms.formatTime(this, mHour, mMinutes, mRepeatPref.getDaysOfWeek()));
}
@Override
protected int getHeadersResourceId() {
return NO_HEADERS;
}
}
|
src/com/androsz/electricsleepbeta/alarmclock/SetAlarm.java
|
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.androsz.electricsleepbeta.alarmclock;
import android.app.AlertDialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.EditTextPreference;
import android.preference.Preference;
import android.preference.PreferenceScreen;
import android.text.format.DateFormat;
import android.view.View;
import android.widget.Button;
import android.widget.TimePicker;
import android.widget.Toast;
import com.androsz.electricsleepbeta.R;
import com.androsz.electricsleepbeta.preference.HostPreferenceActivity;
/**
* Manages each alarm
*/
public class SetAlarm extends HostPreferenceActivity implements
TimePickerDialog.OnTimeSetListener, Preference.OnPreferenceChangeListener {
// Used to post runnables asynchronously.
// private static final Handler sHandler = new Handler();
/**
* format "Alarm set for 2 days 7 hours and 53 minutes from now"
*/
static String formatToast(final Context context, final long timeInMillis) {
final long delta = timeInMillis - System.currentTimeMillis();
long hours = delta / (1000 * 60 * 60);
final long minutes = delta / (1000 * 60) % 60;
final long days = hours / 24;
hours = hours % 24;
final String daySeq = days == 0 ? "" : days == 1 ? context.getString(R.string.day)
: context.getString(R.string.days, Long.toString(days));
final String minSeq = minutes == 0 ? "" : minutes == 1 ? context.getString(R.string.minute)
: context.getString(R.string.minutes, Long.toString(minutes));
final String hourSeq = hours == 0 ? "" : hours == 1 ? context.getString(R.string.hour)
: context.getString(R.string.hours, Long.toString(hours));
final boolean dispDays = days > 0;
final boolean dispHour = hours > 0;
final boolean dispMinute = minutes > 0;
final int index = (dispDays ? 1 : 0) | (dispHour ? 2 : 0) | (dispMinute ? 4 : 0);
final String[] formats = context.getResources().getStringArray(R.array.alarm_set);
return String.format(formats[index], daySeq, hourSeq, minSeq);
}
/**
* Display a toast that tells the user how long until the alarm goes off.
* This helps prevent "am/pm" mistakes.
*/
static void popAlarmSetToast(final Context context, final int hour, final int minute,
final Alarm.DaysOfWeek daysOfWeek) {
popAlarmSetToast(context, Alarms.calculateAlarm(hour, minute, daysOfWeek).getTimeInMillis());
}
private static void popAlarmSetToast(final Context context, final long timeInMillis) {
final String toastText = formatToast(context, timeInMillis);
final Toast toast = Toast.makeText(context, toastText, Toast.LENGTH_LONG);
ToastMaster.setToast(toast);
toast.show();
}
private AlarmPreference mAlarmPref;
private CheckBoxPreference mEnabledPref;
private int mHour;
private int mId;
private EditTextPreference mLabel;
private int mMinutes;
private Alarm mOriginalAlarm;
private RepeatPreference mRepeatPref;
private boolean mTimePickerCancelled;
private Preference mTimePref;
private CheckBoxPreference mVibratePref;
private void deleteAlarm() {
new AlertDialog.Builder(this).setTitle(getString(R.string.delete_alarm))
.setMessage(getString(R.string.delete_alarm_confirm))
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(final DialogInterface d, final int w) {
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
Alarms.deleteAlarm(SetAlarm.this, mId);
return null;
}
@Override
protected void onPostExecute(Void result) {
finish();
}
}.execute();
}
}).setNegativeButton(android.R.string.cancel, null).show();
}
@Override
protected int getContentAreaLayoutId() {
return R.xml.alarm_prefs;
}
@Override
public void onBackPressed() {
// In the usual case of viewing an alarm, mTimePickerCancelled is
// initialized to false. When creating a new alarm, this value is
// assumed true until the user changes the time.
if (!mTimePickerCancelled) {
new Thread(new Runnable() {
@Override
public void run() {
saveAlarm();
}
}).start();
}
finish();
}
/**
* Set an alarm. Requires an Alarms.ALARM_ID to be passed in as an extra.
* FIXME: Pass an Alarm object like every other Activity.
*/
@Override
protected void onCreate(final Bundle icicle) {
super.onCreate(icicle);
// Override the default content view.
setContentView(R.layout.set_alarm);
// addPreferencesFromResource(R.xml.alarm_prefs);
// Get each preference so we can retrieve the value later.
mLabel = (EditTextPreference) findPreference("label");
mLabel.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(final Preference p, final Object newValue) {
final String val = (String) newValue;
// Set the summary based on the new label.
p.setSummary(val);
if (val != null && !val.equals(mLabel.getText())) {
// Call through to the generic listener.
return SetAlarm.this.onPreferenceChange(p, newValue);
}
return true;
}
});
mEnabledPref = (CheckBoxPreference) findPreference("enabled");
mEnabledPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(final Preference p, final Object newValue) {
// Pop a toast when enabling alarms.
if (!mEnabledPref.isChecked()) {
popAlarmSetToast(SetAlarm.this, mHour, mMinutes, mRepeatPref.getDaysOfWeek());
}
return SetAlarm.this.onPreferenceChange(p, newValue);
}
});
mTimePref = findPreference("time");
mAlarmPref = (AlarmPreference) findPreference("alarm");
mAlarmPref.setOnPreferenceChangeListener(this);
mVibratePref = (CheckBoxPreference) findPreference("vibrate");
mVibratePref.setOnPreferenceChangeListener(this);
mRepeatPref = (RepeatPreference) findPreference("setRepeat");
mRepeatPref.setOnPreferenceChangeListener(this);
final Intent i = getIntent();
mId = i.getIntExtra(Alarms.ALARM_ID, -1);
if (Log.LOGV) {
Log.v("In SetAlarm, alarm id = " + mId);
}
Alarm alarm = null;
if (mId == -1) {
// No alarm id means create a new alarm.
alarm = new Alarm();
} else {
/* load alarm details from database */
alarm = Alarms.getAlarm(getContentResolver(), mId);
// Bad alarm, bail to avoid a NPE.
if (alarm == null) {
finish();
return;
}
}
mOriginalAlarm = alarm;
updatePrefs(mOriginalAlarm);
// We have to do this to get the save/cancel buttons to highlight on
// their own.
getListView().setItemsCanFocus(true);
getListView().setBackgroundColor(Color.BLACK);
//getListView().setCacheColorHint(0);
//getListView().setBackgroundDrawable(
// getResources().getDrawable(R.drawable.gradient_background_vert));
// Attach actions to each button.
Button b = (Button) findViewById(R.id.alarm_save);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View v) {
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
saveAlarm();
return null;
}
@Override
protected void onPostExecute(Void result) {
finish();
}
}.execute();
}
});
final Button revert = (Button) findViewById(R.id.alarm_revert);
revert.setEnabled(false);
revert.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View v) {
final int newId = mId;
updatePrefs(mOriginalAlarm);
// "Revert" on a newly created alarm should delete it.
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
if (mOriginalAlarm.id == -1) {
Alarms.deleteAlarm(SetAlarm.this, newId);
} else {
saveAlarm();
}
return null;
}
@Override
protected void onPostExecute(Void result) {
revert.setEnabled(false);
}
}.execute();
}
});
b = (Button) findViewById(R.id.alarm_delete);
if (mId == -1) {
b.setEnabled(false);
} else {
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View v) {
deleteAlarm();
}
});
}
// The last thing we do is pop the time picker if this is a new alarm.
if (mId == -1) {
// Assume the user hit cancel
mTimePickerCancelled = true;
showTimePicker();
}
}
@Override
public boolean onPreferenceChange(final Preference p, final Object newValue) {
// Asynchronously save the alarm since this method is called _before_
// the value of the preference has changed.
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
// Editing any preference (except enable) enables the alarm.
if (p != mEnabledPref) {
mEnabledPref.setChecked(true);
}
saveAlarm();
return null;
}
@Override
protected void onPostExecute(Void result) {
final Button revert = (Button) findViewById(R.id.alarm_revert);
revert.setEnabled(true);
}
}.execute();
return true;
}
@Override
public boolean onPreferenceTreeClick(final PreferenceScreen preferenceScreen,
final Preference preference) {
if (preference == mTimePref) {
showTimePicker();
}
return super.onPreferenceTreeClick(preferenceScreen, preference);
}
@Override
public void onTimeSet(final TimePicker view, final int hourOfDay, final int minute) {
// onTimeSet is called when the user clicks "Set"
mTimePickerCancelled = false;
mHour = hourOfDay;
mMinutes = minute;
updateTime();
// If the time has been changed, enable the alarm.
mEnabledPref.setChecked(true);
// Save the alarm and pop a toast.
// Enable "Revert" to go back to the original Alarm.
final Button revert = (Button) findViewById(R.id.alarm_revert);
revert.setEnabled(true);
new AsyncTask<Void, Void, Long>() {
@Override
protected Long doInBackground(Void... params) {
return saveAlarm();
}
@Override
protected void onPostExecute(Long result) {
popAlarmSetToast(SetAlarm.this, result);
}
}.execute();
}
private long saveAlarm() {
long time;
final Alarm alarm = new Alarm();
alarm.id = mId;
alarm.enabled = mEnabledPref.isChecked();
alarm.hour = mHour;
alarm.minutes = mMinutes;
alarm.daysOfWeek = mRepeatPref.getDaysOfWeek();
alarm.vibrate = mVibratePref.isChecked();
alarm.label = mLabel.getText();
alarm.alert = mAlarmPref.getAlert();
if (alarm.id == -1) {
time = Alarms.addAlarm(this, alarm);
// addAlarm populates the alarm with the new id. Update mId so that
// changes to other preferences update the new alarm.
mId = alarm.id;
} else {
time = Alarms.setAlarm(this, alarm);
}
return time;
}
private long saveAlarmAndEnableRevert() {
final Button revert = (Button) findViewById(R.id.alarm_revert);
revert.setEnabled(true);
return saveAlarm();
}
private void showTimePicker() {
new TimePickerDialog(this, this, mHour, mMinutes, DateFormat.is24HourFormat(this)).show();
}
private void updatePrefs(final Alarm alarm) {
mId = alarm.id;
mEnabledPref.setChecked(alarm.enabled);
mLabel.setText(alarm.label);
mLabel.setSummary(alarm.label);
mHour = alarm.hour;
mMinutes = alarm.minutes;
mRepeatPref.setDaysOfWeek(alarm.daysOfWeek);
mVibratePref.setChecked(alarm.vibrate);
// Give the alert uri to the preference.
mAlarmPref.setAlert(alarm.alert);
updateTime();
}
private void updateTime() {
if (Log.LOGV) {
Log.v("updateTime " + mId);
}
mTimePref.setSummary(Alarms.formatTime(this, mHour, mMinutes, mRepeatPref.getDaysOfWeek()));
}
@Override
protected int getHeadersResourceId() {
return NO_HEADERS;
}
}
|
No longer modifying a checkbox on a non-UI thread.
|
src/com/androsz/electricsleepbeta/alarmclock/SetAlarm.java
|
No longer modifying a checkbox on a non-UI thread.
|
|
Java
|
apache-2.0
|
8e16312c638fa852da40d0ff4fe67e6e14c0ea8d
| 0
|
lsurvila/AnimatedExpandableListView
|
package com.idunnololz.widgets;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.Log;
import android.util.SparseArray;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.widget.AbsListView;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListAdapter;
import android.widget.ExpandableListView;
import android.view.animation.Transformation;
/**
* This class defines an ExpandableListView which supports animations for
* collapsing and expanding groups.
*/
public class AnimatedExpandableListView extends ExpandableListView {
/*
* A detailed explanation for how this class works:
*
* Animating the ExpandableListView was no easy task. The way that this
* class does it is by exploiting how an ExpandableListView works.
*
* Normally when {@link ExpandableListView#collapseGroup(int)} or
* {@link ExpandableListView#expandGroup(int)} is called, the view toggles
* the flag for a group and calls notifyDataSetChanged to cause the ListView
* to refresh all of it's view. This time however, depending on whether a
* group is expanded or collapsed, certain childViews will either be ignored
* or added to the list.
*
* Knowing this, we can come up with a way to animate our views. For
* instance for group expansion, we tell the adapter to animate the
* children of a certain group. We then expand the group which causes the
* ExpandableListView to refresh all views on screen. The way that
* ExpandableListView does this is by calling getView() in the adapter.
* However since the adapter knows that we are animating a certain group,
* instead of returning the real views for the children of the group being
* animated, it will return a fake dummy view. This dummy view will then
* draw the real child views within it's dispatchDraw function. The reason
* we do this is so that we can animate all of it's children by simply
* animating the dummy view. After we complete the animation, we tell the
* adapter to stop animating the group and call notifyDataSetChanged. Now
* the ExpandableListView is forced to refresh it's views again, except this
* time, it will get the real views for the expanded group.
*
* So, to list it all out, when {@link #expandGroupWithAnimation(int)} is
* called the following happens:
*
* 1. The ExpandableListView tells the adapter to animate a certain group.
* 2. The ExpandableListView calls expandGroup.
* 3. ExpandGroup calls notifyDataSetChanged.
* 4. As an result, getChildView is called for expanding group.
* 5. Since the adapter is in "animating mode", it will return a dummy view.
* 6. This dummy view draws the actual children of the expanding group.
* 7. This dummy view's height is animated from 0 to it's expanded height.
* 8. Once the animation completes, the adapter is notified to stop
* animating the group and notifyDataSetChanged is called again.
* 9. This forces the ExpandableListView to refresh all of it's views again.
* 10.This time when getChildView is called, it will return the actual
* child views.
*
* For animating the collapse of a group is a bit more difficult since we
* can't call collapseGroup from the start as it would just ignore the
* child items, giving up no chance to do any sort of animation. Instead
* what we have to do is play the animation first and call collapseGroup
* after the animation is done.
*
* So, to list it all out, when {@link #collapseGroupWithAnimation(int)} is
* called the following happens:
*
* 1. The ExpandableListView tells the adapter to animate a certain group.
* 2. The ExpandableListView calls notifyDataSetChanged.
* 3. As an result, getChildView is called for expanding group.
* 4. Since the adapter is in "animating mode", it will return a dummy view.
* 5. This dummy view draws the actual children of the expanding group.
* 6. This dummy view's height is animated from it's current height to 0.
* 7. Once the animation completes, the adapter is notified to stop
* animating the group and notifyDataSetChanged is called again.
* 8. collapseGroup is finally called.
* 9. This forces the ExpandableListView to refresh all of it's views again.
* 10.This time when the ListView will not get any of the child views for
* the collapsed group.
*/
private static final String TAG = AnimatedExpandableListAdapter.class.getSimpleName();
/**
* The duration of the expand/collapse animations
*/
private static final int ANIMATION_DURATION = 300;
private AnimatedExpandableListAdapter adapter;
public AnimatedExpandableListView(Context context) {
super(context);
}
public AnimatedExpandableListView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public AnimatedExpandableListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
/**
* @see ExpandableListView#setAdapter(ExpandableListAdapter)
*/
public void setAdapter(ExpandableListAdapter adapter) {
super.setAdapter(adapter);
// Make sure that the adapter extends AnimatedExpandableListAdapter
if(adapter instanceof AnimatedExpandableListAdapter) {
this.adapter = (AnimatedExpandableListAdapter) adapter;
this.adapter.setParent(this);
} else {
throw new ClassCastException(adapter.toString() + " must implement AnimatedExpandableListAdapter");
}
}
/**
* Expands the given group with an animation.
* @param groupPos The position of the group to expand
* @return Returns true if the group was expanded. False if the group was
* already expanded.
*/
public boolean expandGroupWithAnimation(int groupPos) {
int groupFlatPos = getFlatListPosition(getPackedPositionForGroup(groupPos));
if (groupFlatPos != -1) {
int childIndex = groupFlatPos - getFirstVisiblePosition();
if (childIndex < getChildCount()) {
// Get the view for the group is it is on screen...
View v = getChildAt(childIndex);
if (v.getBottom() >= getBottom()) {
// If the user is not going to be able to see the animation
// we just expand the group without an animation.
// This resolves the case where getChildView will not be
// called if the children of the group is not on screen
// We need to notify the adapter that the group was expanded
// without it's knowledge
adapter.notifyGroupExpanded(groupPos);
return expandGroup(groupPos);
}
}
}
// Let the adapter know that we are starting the animation...
adapter.startExpandAnimation(groupPos, 0);
// Finally call expandGroup (note that expandGroup will call
// notifyDataSetChanged so we don't need to)
return expandGroup(groupPos);
}
/**
* Collapses the given group with an animation.
* @param groupPos The position of the group to collapse
* @return Returns true if the group was collapsed. False if the group was
* already collapsed.
*/
public boolean collapseGroupWithAnimation(int groupPos) {
int groupFlatPos = getFlatListPosition(getPackedPositionForGroup(groupPos));
if (groupFlatPos != -1) {
int childIndex = groupFlatPos - getFirstVisiblePosition();
if (childIndex >= 0 && childIndex < getChildCount()) {
// Get the view for the group is it is on screen...
View v = getChildAt(childIndex);
if (v.getBottom() >= getBottom()) {
// If the user is not going to be able to see the animation
// we just collapse the group without an animation.
// This resolves the case where getChildView will not be
// called if the children of the group is not on screen
return collapseGroup(groupPos);
}
} else {
// If the group is offscreen, we can just collapse it without an
// animation...
return collapseGroup(groupPos);
}
}
// Get the position of the firstChild visible from the top of the screen
long packedPos = getExpandableListPosition(getFirstVisiblePosition());
int firstChildPos = getPackedPositionChild(packedPos);
int firstGroupPos = getPackedPositionGroup(packedPos);
// If the first visible view on the screen is a child view AND it's a
// child of the group we are trying to collapse, then set that
// as the first child position of the group... see
// {@link #startCollapseAnimation(int, int)} for why this is necessary
firstChildPos = firstChildPos == -1 || firstGroupPos != groupPos ? 0 : firstChildPos;
// Let the adapter know that we are going to start animating the
// collapse animation.
adapter.startCollapseAnimation(groupPos, firstChildPos);
// Force the listview to refresh it's views
adapter.notifyDataSetChanged();
return isGroupExpanded(groupPos);
}
private int getAnimationDuration() {
return ANIMATION_DURATION;
}
/**
* Used for holding information regarding the group.
*/
private static class GroupInfo {
boolean animating = false;
boolean expanding = false;
int firstChildPosition;
/**
* This variable contains the last known height value of the dummy view.
* We save this information so that if the user collapses a group
* before it fully expands, the collapse animation will start from the
* CURRENT height of the dummy view and not from the full expanded
* height.
*/
int dummyHeight = -1;
}
/**
* A specialized adapter for use with the AnimatedExpandableListView. All
* adapters used with AnimatedExpandableListView MUST extend this class.
*/
public static abstract class AnimatedExpandableListAdapter extends BaseExpandableListAdapter {
private SparseArray<GroupInfo> groupInfo = new SparseArray<GroupInfo>();
private AnimatedExpandableListView parent;
private static final int STATE_IDLE = 0;
private static final int STATE_EXPANDING = 1;
private static final int STATE_COLLAPSING = 2;
private void setParent(AnimatedExpandableListView parent) {
this.parent = parent;
}
public int getRealChildType(int groupPosition, int childPosition) {
return 0;
}
public int getRealChildTypeCount() {
return 1;
}
public abstract View getRealChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent);
public abstract int getRealChildrenCount(int groupPosition);
private GroupInfo getGroupInfo(int groupPosition) {
GroupInfo info = groupInfo.get(groupPosition);
if (info == null) {
info = new GroupInfo();
groupInfo.put(groupPosition, info);
}
return info;
}
public void notifyGroupExpanded(int groupPosition) {
GroupInfo info = getGroupInfo(groupPosition);
info.dummyHeight = -1;
}
private void startExpandAnimation(int groupPosition, int firstChildPosition) {
GroupInfo info = getGroupInfo(groupPosition);
info.animating = true;
info.firstChildPosition = firstChildPosition;
info.expanding = true;
}
private void startCollapseAnimation(int groupPosition, int firstChildPosition) {
GroupInfo info = getGroupInfo(groupPosition);
info.animating = true;
info.firstChildPosition = firstChildPosition;
info.expanding = false;
}
private void stopAnimation(int groupPosition) {
GroupInfo info = getGroupInfo(groupPosition);
info.animating = false;
}
/**
* Override {@link #getRealChildType(int, int)} instead.
*/
@Override
public final int getChildType(int groupPosition, int childPosition) {
GroupInfo info = getGroupInfo(groupPosition);
if (info.animating) {
// If we are animating this group, then all of it's children
// are going to be dummy views which we will say is type 0.
return 0;
} else {
// If we are not animating this group, then we will add 1 to
// the type it has so that no type id conflicts will occur
// unless getRealChildType() returns MAX_INT
return getRealChildType(groupPosition, childPosition) + 1;
}
}
/**
* Override {@link #getRealChildTypeCount()} instead.
*/
@Override
public final int getChildTypeCount() {
// Return 1 more than the childTypeCount to account for DummyView
return getRealChildTypeCount() + 1;
}
/**
* Override {@link #getChildView(int, int, boolean, View, ViewGroup)} instead.
*/
@Override
public final View getChildView(final int groupPosition, int childPosition, boolean isLastChild, View convertView, final ViewGroup parent) {
final GroupInfo info = getGroupInfo(groupPosition);
if (info.animating) {
// If this group is animating, return the a DummyView...
if (convertView instanceof DummyView == false) {
convertView = new DummyView(parent.getContext());
convertView.setLayoutParams(new AbsListView.LayoutParams(LayoutParams.MATCH_PARENT, 0));
}
if (childPosition < info.firstChildPosition) {
// The reason why we do this is to support the collapse
// this group when the group view is not visible but the
// children of this group are. When notifyDataSetChanged
// is called, the ExpandableListView tries to keep the
// list position the same by saving the first visible item
// and jumping back to that item after the views have been
// refreshed. Now the problem is, if a group has 2 items
// and the first visible item is the 2nd child of the group
// and this group is collapsed, then the dummy view will be
// used for the group. But now the group only has 1 item
// which is the dummy view, thus when the ListView is trying
// to restore the scroll position, it will try to jump to
// the second item of the group. But this group no longer
// has a second item, so it is forced to jump to the next
// group. This will cause a very ugly visual glitch. So
// the way that we counteract this is by creating as many
// dummy views as we need to maintain the scroll position
// of the ListView after notifyDataSetChanged has been
// called.
convertView.getLayoutParams().height = 0;
return convertView;
}
final ExpandableListView listView = (ExpandableListView) parent;
final DummyView dummyView = (DummyView) convertView;
// Clear the views that the dummy view draws.
dummyView.clearViews();
// Set the style of the divider
dummyView.setDivider(listView.getDivider(), parent.getMeasuredWidth(), listView.getDividerHeight());
// Make measure specs to measure child views
final int measureSpecW = MeasureSpec.makeMeasureSpec(parent.getWidth(), MeasureSpec.EXACTLY);
final int measureSpecH = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
int totalHeight = 0;
int clipHeight = parent.getHeight();
final int len = getRealChildrenCount(groupPosition);
for (int i = info.firstChildPosition; i < len; i++) {
View childView = getRealChildView(groupPosition, i, (i == len - 1), null, parent);
childView.measure(measureSpecW, measureSpecH);
totalHeight += childView.getMeasuredHeight();
if (totalHeight < clipHeight) {
// we only need to draw enough views to fool the user...
dummyView.addFakeView(childView);
} else {
dummyView.addFakeView(childView);
// if this group has too many views, we don't want to
// calculate the height of everything... just do a light
// approximation and break
int averageHeight = totalHeight / (i + 1);
totalHeight += (len - i - 1) * averageHeight;
break;
}
}
Object o;
int state = (o = dummyView.getTag()) == null ? STATE_IDLE : (Integer) o;
if (info.expanding && state != STATE_EXPANDING) {
ExpandAnimation ani = new ExpandAnimation(dummyView, 0, totalHeight, info);
ani.setDuration(this.parent.getAnimationDuration());
ani.setAnimationListener(new AnimationListener() {
@Override
public void onAnimationEnd(Animation animation) {
stopAnimation(groupPosition);
notifyDataSetChanged();
dummyView.setTag(STATE_IDLE);
}
@Override
public void onAnimationRepeat(Animation animation) {}
@Override
public void onAnimationStart(Animation animation) {}
});
dummyView.startAnimation(ani);
dummyView.setTag(STATE_EXPANDING);
} else if (!info.expanding && state != STATE_COLLAPSING) {
if (info.dummyHeight == -1) {
info.dummyHeight = totalHeight;
}
ExpandAnimation ani = new ExpandAnimation(dummyView, info.dummyHeight, 0, info);
ani.setDuration(this.parent.getAnimationDuration());
ani.setAnimationListener(new AnimationListener() {
@Override
public void onAnimationEnd(Animation animation) {
stopAnimation(groupPosition);
listView.collapseGroup(groupPosition);
notifyDataSetChanged();
info.dummyHeight = -1;
dummyView.setTag(STATE_IDLE);
}
@Override
public void onAnimationRepeat(Animation animation) {}
@Override
public void onAnimationStart(Animation animation) {}
});
dummyView.startAnimation(ani);
dummyView.setTag(STATE_COLLAPSING);
}
return convertView;
} else {
return getRealChildView(groupPosition, childPosition, isLastChild, convertView, parent);
}
}
@Override
public final int getChildrenCount(int groupPosition) {
GroupInfo info = getGroupInfo(groupPosition);
if (info.animating) {
return info.firstChildPosition + 1;
} else {
return getRealChildrenCount(groupPosition);
}
}
}
private static class DummyView extends View {
private List<View> views = new ArrayList<View>();
private Drawable divider;
private int dividerWidth;
private int dividerHeight;
public DummyView(Context context) {
super(context);
}
public void setDivider(Drawable divider, int dividerWidth, int dividerHeight) {
this.divider = divider;
this.dividerWidth = dividerWidth;
this.dividerHeight = dividerHeight;
divider.setBounds(0, 0, dividerWidth, dividerHeight);
}
/**
* Add a view for the DummyView to draw.
* @param childView View to draw
*/
public void addFakeView(View childView) {
childView.layout(0, 0, getWidth(), getHeight());
views.add(childView);
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
final int len = views.size();
for(int i = 0; i < len; i++) {
View v = views.get(i);
v.layout(left, top, right, bottom);
}
}
public void clearViews() {
views.clear();
}
@Override
public void dispatchDraw(Canvas canvas) {
canvas.save();
divider.setBounds(0, 0, dividerWidth, dividerHeight);
final int len = views.size();
for(int i = 0; i < len; i++) {
View v = views.get(i);
v.draw(canvas);
canvas.translate(0, v.getMeasuredHeight());
divider.draw(canvas);
canvas.translate(0, dividerHeight);
}
canvas.restore();
}
}
private static class ExpandAnimation extends Animation {
private int baseHeight;
private int delta;
private View view;
private GroupInfo groupInfo;
private ExpandAnimation(View v, int startHeight, int endHeight, GroupInfo info) {
baseHeight = startHeight;
delta = endHeight - startHeight;
view = v;
groupInfo = info;
view.getLayoutParams().height = startHeight;
view.requestLayout();
}
@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
super.applyTransformation(interpolatedTime, t);
if (interpolatedTime < 1.0f) {
int val = baseHeight + (int) (delta * interpolatedTime);
view.getLayoutParams().height = val;
groupInfo.dummyHeight = val;
view.requestLayout();
} else {
int val = baseHeight + delta;
view.getLayoutParams().height = val;
groupInfo.dummyHeight = val;
view.requestLayout();
}
}
}
}
|
src/com/idunnololz/widgets/AnimatedExpandableListView.java
|
package com.idunnololz.widgets;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.Log;
import android.util.SparseArray;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.widget.AbsListView;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListAdapter;
import android.widget.ExpandableListView;
import android.view.animation.Transformation;
/**
* This class defines an ExpandableListView which supports animations for
* collapsing and expanding groups.
*/
public class AnimatedExpandableListView extends ExpandableListView {
/*
* A detailed explanation for how this class works:
*
* Animating the ExpandableListView was no easy task. The way that this
* class does it is by exploiting how an ExpandableListView works.
*
* Normally when {@link ExpandableListView#collapseGroup(int)} or
* {@link ExpandableListView#expandGroup(int)} is called, the view toggles
* the flag for a group and calls notifyDataSetChanged to cause the ListView
* to refresh all of it's view. This time however, depending on whether a
* group is expanded or collapsed, certain childViews will either be ignored
* or added to the list.
*
* Knowing this, we can come up with a way to animate our views. For
* instance for group expansion, we tell the adapter to animate the
* children of a certain group. We then expand the group which causes the
* ExpandableListView to refresh all views on screen. The way that
* ExpandableListView does this is by calling getView() in the adapter.
* However since the adapter knows that we are animating a certain group,
* instead of returning the real views for the children of the group being
* animated, it will return a fake dummy view. This dummy view will then
* draw the real child views within it's dispatchDraw function. The reason
* we do this is so that we can animate all of it's children by simply
* animating the dummy view. After we complete the animation, we tell the
* adapter to stop animating the group and call notifyDataSetChanged. Now
* the ExpandableListView is forced to refresh it's views again, except this
* time, it will get the real views for the expanded group.
*
* So, to list it all out, when {@link #expandGroupWithAnimation(int)} is
* called the following happens:
*
* 1. The ExpandableListView tells the adapter to animate a certain group.
* 2. The ExpandableListView calls expandGroup.
* 3. ExpandGroup calls notifyDataSetChanged.
* 4. As an result, getChildView is called for expanding group.
* 5. Since the adapter is in "animating mode", it will return a dummy view.
* 6. This dummy view draws the actual children of the expanding group.
* 7. This dummy view's height is animated from 0 to it's expanded height.
* 8. Once the animation completes, the adapter is notified to stop
* animating the group and notifyDataSetChanged is called again.
* 9. This forces the ExpandableListView to refresh all of it's views again.
* 10.This time when getChildView is called, it will return the actual
* child views.
*
* For animating the collapse of a group is a bit more difficult since we
* can't call collapseGroup from the start as it would just ignore the
* child items, giving up no chance to do any sort of animation. Instead
* what we have to do is play the animation first and call collapseGroup
* after the animation is done.
*
* So, to list it all out, when {@link #collapseGroupWithAnimation(int)} is
* called the following happens:
*
* 1. The ExpandableListView tells the adapter to animate a certain group.
* 2. The ExpandableListView calls notifyDataSetChanged.
* 3. As an result, getChildView is called for expanding group.
* 4. Since the adapter is in "animating mode", it will return a dummy view.
* 5. This dummy view draws the actual children of the expanding group.
* 6. This dummy view's height is animated from it's current height to 0.
* 7. Once the animation completes, the adapter is notified to stop
* animating the group and notifyDataSetChanged is called again.
* 8. collapseGroup is finally called.
* 9. This forces the ExpandableListView to refresh all of it's views again.
* 10.This time when the ListView will not get any of the child views for
* the collapsed group.
*/
private static final String TAG = AnimatedExpandableListAdapter.class.getSimpleName();
/**
* The duration of the expand/collapse animations
*/
private static final int ANIMATION_DURATION = 300;
private AnimatedExpandableListAdapter adapter;
public AnimatedExpandableListView(Context context) {
super(context);
}
public AnimatedExpandableListView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public AnimatedExpandableListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
/**
* @see ExpandableListView#setAdapter(ExpandableListAdapter)
*/
public void setAdapter(ExpandableListAdapter adapter) {
super.setAdapter(adapter);
// Make sure that the adapter extends AnimatedExpandableListAdapter
if(adapter instanceof AnimatedExpandableListAdapter) {
this.adapter = (AnimatedExpandableListAdapter) adapter;
this.adapter.setParent(this);
} else {
throw new ClassCastException(adapter.toString() + " must implement AnimatedExpandableListAdapter");
}
}
/**
* Expands the given group with an animation.
* @param groupPos The position of the group to expand
* @return Returns true if the group was expanded. False if the group was
* already expanded.
*/
public boolean expandGroupWithAnimation(int groupPos) {
int groupFlatPos = getFlatListPosition(getPackedPositionForGroup(groupPos));
if (groupFlatPos != -1) {
int childIndex = groupFlatPos - getFirstVisiblePosition();
if (childIndex < getChildCount()) {
// Get the view for the group is it is on screen...
View v = getChildAt(childIndex);
if (v.getBottom() >= getBottom()) {
// If the user is not going to be able to see the animation
// we just expand the group without an animation.
// This resolves the case where getChildView will not be
// called if the children of the group is not on screen
// We need to notify the adapter that the group was expanded
// without it's knowledge
adapter.notifyGroupExpanded(groupPos);
return expandGroup(groupPos);
}
}
}
// Let the adapter know that we are starting the animation...
adapter.startExpandAnimation(groupPos, 0);
// Finally call expandGroup (note that expandGroup will call
// notifyDataSetChanged so we don't need to)
return expandGroup(groupPos);
}
/**
* Collapses the given group with an animation.
* @param groupPos The position of the group to collapse
* @return Returns true if the group was collapsed. False if the group was
* already collapsed.
*/
public boolean collapseGroupWithAnimation(int groupPos) {
int groupFlatPos = getFlatListPosition(getPackedPositionForGroup(groupPos));
if (groupFlatPos != -1) {
int childIndex = groupFlatPos - getFirstVisiblePosition();
if (childIndex >= 0 && childIndex < getChildCount()) {
// Get the view for the group is it is on screen...
View v = getChildAt(childIndex);
if (v.getBottom() >= getBottom()) {
// If the user is not going to be able to see the animation
// we just collapse the group without an animation.
// This resolves the case where getChildView will not be
// called if the children of the group is not on screen
return collapseGroup(groupPos);
}
} else {
// If the group is offscreen, we can just collapse it without an
// animation...
return collapseGroup(groupPos);
}
}
// Get the position of the firstChild visible from the top of the screen
long packedPos = getExpandableListPosition(getFirstVisiblePosition());
int firstChildPos = getPackedPositionChild(packedPos);
int firstGroupPos = getPackedPositionGroup(packedPos);
// If the first visible view on the screen is a child view AND it's a
// child of the group we are trying to collapse, then set that
// as the first child position of the group... see
// {@link #startCollapseAnimation(int, int)} for why this is necessary
firstChildPos = firstChildPos == -1 || firstGroupPos != groupPos ? 0 : firstChildPos;
// Let the adapter know that we are going to start animating the
// collapse animation.
adapter.startCollapseAnimation(groupPos, firstChildPos);
// Force the listview to refresh it's views
adapter.notifyDataSetChanged();
return isGroupExpanded(groupPos);
}
private int getAnimationDuration() {
return ANIMATION_DURATION;
}
/**
* Used for holding information regarding the group.
*/
private static class GroupInfo {
boolean animating = false;
boolean expanding = false;
int firstChildPosition;
/**
* This variable contains the last known height value of the dummy view.
* We save this information so that if the user collapses a group
* before it fully expands, the collapse animation will start from the
* CURRENT height of the dummy view and not from the full expanded
* height.
*/
int dummyHeight = -1;
}
/**
* A specialized adapter for use with the AnimatedExpandableListView. All
* adapters used with AnimatedExpandableListView MUST extend this class.
*/
public static abstract class AnimatedExpandableListAdapter extends BaseExpandableListAdapter {
private SparseArray<GroupInfo> groupInfo = new SparseArray<GroupInfo>();
private AnimatedExpandableListView parent;
private static final int STATE_IDLE = 0;
private static final int STATE_EXPANDING = 1;
private static final int STATE_COLLAPSING = 2;
private void setParent(AnimatedExpandableListView parent) {
this.parent = parent;
}
public int getRealChildType(int groupPosition, int childPosition) {
return 0;
}
public int getRealChildTypeCount() {
return 1;
}
public abstract View getRealChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent);
public abstract int getRealChildrenCount(int groupPosition);
private GroupInfo getGroupInfo(int groupPosition) {
GroupInfo info = groupInfo.get(groupPosition);
if (info == null) {
info = new GroupInfo();
groupInfo.put(groupPosition, info);
}
return info;
}
public void notifyGroupExpanded(int groupPosition) {
GroupInfo info = getGroupInfo(groupPosition);
info.dummyHeight = -1;
}
private void startExpandAnimation(int groupPosition, int firstChildPosition) {
GroupInfo info = getGroupInfo(groupPosition);
info.animating = true;
info.firstChildPosition = firstChildPosition;
info.expanding = true;
}
private void startCollapseAnimation(int groupPosition, int firstChildPosition) {
GroupInfo info = getGroupInfo(groupPosition);
info.animating = true;
info.firstChildPosition = firstChildPosition;
info.expanding = false;
}
private void stopAnimation(int groupPosition) {
GroupInfo info = getGroupInfo(groupPosition);
info.animating = false;
}
/**
* Override {@link #getRealChildType(int, int)} instead.
*/
@Override
public final int getChildType(int groupPosition, int childPosition) {
GroupInfo info = getGroupInfo(groupPosition);
if (info.animating) {
// If we are animating this group, then all of it's children
// are going to be dummy views which we will say is type 0.
return 0;
} else {
// If we are not animating this group, then we will add 1 to
// the type it has so that no type id conflicts will occur
// unless getRealChildType() returns MAX_INT
return getRealChildType(groupPosition, childPosition) + 1;
}
}
/**
* Override {@link #getRealChildTypeCount()} instead.
*/
@Override
public final int getChildTypeCount() {
// Return 1 more than the childTypeCount to account for DummyView
return getRealChildTypeCount() + 1;
}
/**
* Override {@link #getChildView(int, int, boolean, View, ViewGroup)} instead.
*/
@Override
public final View getChildView(final int groupPosition, int childPosition, boolean isLastChild, View convertView, final ViewGroup parent) {
final GroupInfo info = getGroupInfo(groupPosition);
if (info.animating) {
// If this group is animating, return the a DummyView...
if (convertView == null) {
convertView = new DummyView(parent.getContext());
convertView.setLayoutParams(new AbsListView.LayoutParams(LayoutParams.MATCH_PARENT, 0));
}
if (childPosition < info.firstChildPosition) {
// The reason why we do this is to support the collapse
// this group when the group view is not visible but the
// children of this group are. When notifyDataSetChanged
// is called, the ExpandableListView tries to keep the
// list position the same by saving the first visible item
// and jumping back to that item after the views have been
// refreshed. Now the problem is, if a group has 2 items
// and the first visible item is the 2nd child of the group
// and this group is collapsed, then the dummy view will be
// used for the group. But now the group only has 1 item
// which is the dummy view, thus when the ListView is trying
// to restore the scroll position, it will try to jump to
// the second item of the group. But this group no longer
// has a second item, so it is forced to jump to the next
// group. This will cause a very ugly visual glitch. So
// the way that we counteract this is by creating as many
// dummy views as we need to maintain the scroll position
// of the ListView after notifyDataSetChanged has been
// called.
convertView.getLayoutParams().height = 0;
return convertView;
}
final ExpandableListView listView = (ExpandableListView) parent;
final DummyView dummyView = (DummyView) convertView;
// Clear the views that the dummy view draws.
dummyView.clearViews();
// Set the style of the divider
dummyView.setDivider(listView.getDivider(), parent.getMeasuredWidth(), listView.getDividerHeight());
// Make measure specs to measure child views
final int measureSpecW = MeasureSpec.makeMeasureSpec(parent.getWidth(), MeasureSpec.EXACTLY);
final int measureSpecH = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
int totalHeight = 0;
int clipHeight = parent.getHeight();
final int len = getRealChildrenCount(groupPosition);
for (int i = info.firstChildPosition; i < len; i++) {
View childView = getRealChildView(groupPosition, i, (i == len - 1), null, parent);
childView.measure(measureSpecW, measureSpecH);
totalHeight += childView.getMeasuredHeight();
if (totalHeight < clipHeight) {
// we only need to draw enough views to fool the user...
dummyView.addFakeView(childView);
} else {
dummyView.addFakeView(childView);
// if this group has too many views, we don't want to
// calculate the height of everything... just do a light
// approximation and break
int averageHeight = totalHeight / (i + 1);
totalHeight += (len - i - 1) * averageHeight;
break;
}
}
Object o;
int state = (o = dummyView.getTag()) == null ? STATE_IDLE : (Integer) o;
if (info.expanding && state != STATE_EXPANDING) {
ExpandAnimation ani = new ExpandAnimation(dummyView, 0, totalHeight, info);
ani.setDuration(this.parent.getAnimationDuration());
ani.setAnimationListener(new AnimationListener() {
@Override
public void onAnimationEnd(Animation animation) {
stopAnimation(groupPosition);
notifyDataSetChanged();
dummyView.setTag(STATE_IDLE);
}
@Override
public void onAnimationRepeat(Animation animation) {}
@Override
public void onAnimationStart(Animation animation) {}
});
dummyView.startAnimation(ani);
dummyView.setTag(STATE_EXPANDING);
} else if (!info.expanding && state != STATE_COLLAPSING) {
if (info.dummyHeight == -1) {
info.dummyHeight = totalHeight;
}
ExpandAnimation ani = new ExpandAnimation(dummyView, info.dummyHeight, 0, info);
ani.setDuration(this.parent.getAnimationDuration());
ani.setAnimationListener(new AnimationListener() {
@Override
public void onAnimationEnd(Animation animation) {
stopAnimation(groupPosition);
listView.collapseGroup(groupPosition);
notifyDataSetChanged();
info.dummyHeight = -1;
dummyView.setTag(STATE_IDLE);
}
@Override
public void onAnimationRepeat(Animation animation) {}
@Override
public void onAnimationStart(Animation animation) {}
});
dummyView.startAnimation(ani);
dummyView.setTag(STATE_COLLAPSING);
}
return convertView;
} else {
return getRealChildView(groupPosition, childPosition, isLastChild, convertView, parent);
}
}
@Override
public final int getChildrenCount(int groupPosition) {
GroupInfo info = getGroupInfo(groupPosition);
if (info.animating) {
return info.firstChildPosition + 1;
} else {
return getRealChildrenCount(groupPosition);
}
}
}
private static class DummyView extends View {
private List<View> views = new ArrayList<View>();
private Drawable divider;
private int dividerWidth;
private int dividerHeight;
public DummyView(Context context) {
super(context);
}
public void setDivider(Drawable divider, int dividerWidth, int dividerHeight) {
this.divider = divider;
this.dividerWidth = dividerWidth;
this.dividerHeight = dividerHeight;
divider.setBounds(0, 0, dividerWidth, dividerHeight);
}
/**
* Add a view for the DummyView to draw.
* @param childView View to draw
*/
public void addFakeView(View childView) {
childView.layout(0, 0, getWidth(), getHeight());
views.add(childView);
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
final int len = views.size();
for(int i = 0; i < len; i++) {
View v = views.get(i);
v.layout(left, top, right, bottom);
}
}
public void clearViews() {
views.clear();
}
@Override
public void dispatchDraw(Canvas canvas) {
canvas.save();
divider.setBounds(0, 0, dividerWidth, dividerHeight);
final int len = views.size();
for(int i = 0; i < len; i++) {
View v = views.get(i);
v.draw(canvas);
canvas.translate(0, v.getMeasuredHeight());
divider.draw(canvas);
canvas.translate(0, dividerHeight);
}
canvas.restore();
}
}
private static class ExpandAnimation extends Animation {
private int baseHeight;
private int delta;
private View view;
private GroupInfo groupInfo;
private ExpandAnimation(View v, int startHeight, int endHeight, GroupInfo info) {
baseHeight = startHeight;
delta = endHeight - startHeight;
view = v;
groupInfo = info;
view.getLayoutParams().height = startHeight;
view.requestLayout();
}
@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
super.applyTransformation(interpolatedTime, t);
if (interpolatedTime < 1.0f) {
int val = baseHeight + (int) (delta * interpolatedTime);
view.getLayoutParams().height = val;
groupInfo.dummyHeight = val;
view.requestLayout();
} else {
int val = baseHeight + delta;
view.getLayoutParams().height = val;
groupInfo.dummyHeight = val;
view.requestLayout();
}
}
}
}
|
Crash fix. convertView sometimes attempts to reuse a view where it shouldn't
|
src/com/idunnololz/widgets/AnimatedExpandableListView.java
|
Crash fix. convertView sometimes attempts to reuse a view where it shouldn't
|
|
Java
|
apache-2.0
|
75b088bd34c4a61cc4fea68ce89860fec9a7a979
| 0
|
mathemage/h2o-3,spennihana/h2o-3,datachand/h2o-3,h2oai/h2o-dev,mathemage/h2o-3,pchmieli/h2o-3,YzPaul3/h2o-3,madmax983/h2o-3,michalkurka/h2o-3,madmax983/h2o-3,datachand/h2o-3,pchmieli/h2o-3,junwucs/h2o-3,h2oai/h2o-dev,michalkurka/h2o-3,jangorecki/h2o-3,h2oai/h2o-3,pchmieli/h2o-3,kyoren/https-github.com-h2oai-h2o-3,michalkurka/h2o-3,pchmieli/h2o-3,kyoren/https-github.com-h2oai-h2o-3,datachand/h2o-3,brightchen/h2o-3,spennihana/h2o-3,madmax983/h2o-3,h2oai/h2o-3,printedheart/h2o-3,junwucs/h2o-3,h2oai/h2o-dev,pchmieli/h2o-3,printedheart/h2o-3,YzPaul3/h2o-3,h2oai/h2o-dev,printedheart/h2o-3,h2oai/h2o-dev,kyoren/https-github.com-h2oai-h2o-3,h2oai/h2o-3,datachand/h2o-3,YzPaul3/h2o-3,printedheart/h2o-3,brightchen/h2o-3,brightchen/h2o-3,printedheart/h2o-3,brightchen/h2o-3,datachand/h2o-3,madmax983/h2o-3,michalkurka/h2o-3,brightchen/h2o-3,junwucs/h2o-3,spennihana/h2o-3,h2oai/h2o-3,jangorecki/h2o-3,michalkurka/h2o-3,mathemage/h2o-3,jangorecki/h2o-3,michalkurka/h2o-3,spennihana/h2o-3,madmax983/h2o-3,YzPaul3/h2o-3,h2oai/h2o-3,printedheart/h2o-3,spennihana/h2o-3,junwucs/h2o-3,jangorecki/h2o-3,madmax983/h2o-3,jangorecki/h2o-3,h2oai/h2o-3,pchmieli/h2o-3,mathemage/h2o-3,junwucs/h2o-3,kyoren/https-github.com-h2oai-h2o-3,junwucs/h2o-3,printedheart/h2o-3,michalkurka/h2o-3,spennihana/h2o-3,YzPaul3/h2o-3,jangorecki/h2o-3,h2oai/h2o-3,h2oai/h2o-dev,spennihana/h2o-3,brightchen/h2o-3,datachand/h2o-3,brightchen/h2o-3,junwucs/h2o-3,kyoren/https-github.com-h2oai-h2o-3,mathemage/h2o-3,YzPaul3/h2o-3,kyoren/https-github.com-h2oai-h2o-3,madmax983/h2o-3,datachand/h2o-3,h2oai/h2o-dev,kyoren/https-github.com-h2oai-h2o-3,pchmieli/h2o-3,mathemage/h2o-3,YzPaul3/h2o-3,h2oai/h2o-3,jangorecki/h2o-3,mathemage/h2o-3
|
package water.currents;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import water.*;
import water.fvec.Frame;
import water.fvec.Vec;
/** Execute a set of instructions in the context of an H2O cloud.
*
* An Env (environment) object is a classic stack of values used during
* execution of an AST. The stack is hidden in the normal Java execution
* stack and is not explicit.
*
* For efficiency, reference counting is employed to recycle objects already
* in use rather than creating copies upon copies (a la R). When a Frame is
* `pushed` on to the stack, its reference count is incremented by 1. When a
* Frame is `popped` off of the stack, its reference count is decremented by
* 1. When the reference count is 0, the Env instance will dispose of the
* object. All objects live and die by the Env's that create them. That
* means that any object not created by an Env instance shalt not be
* DKV.removed.
*
* Therefore, the Env class is a stack of values + an API for reference counting.
*/
public class Env {
/**
* The refcnt API. Looks like a Stack, because lifetimes are stack-like, but
* just counts refs by unary stack-slot counting.
*/
private final ArrayList<Frame> _refcnt = new ArrayList<>();
private final HashSet<Vec> _globals = new HashSet<>();
public int sp() { return _refcnt.size(); }
public Frame peek(int x) { return _refcnt.get(sp()+x); }
// Deletes dead Frames & forces good stack cleanliness at opcode end.
// One per Opcode implementation.
StackHelp stk() { return new StackHelp(); }
class StackHelp implements AutoCloseable {
final int _sp = sp();
// Push & track. Called on every Val that spans a (nested) exec call.
// Used to track Frames with lifetimes spanning other AST executions.
public Val track(Val v) {
if( v instanceof ValFrame )
_refcnt.add(sp(),((ValFrame)v)._fr);
return v;
}
// If an opcode is returning a Frame, it must call "returning(frame)" to
// track the returned Frame. Otherwise shared input Vecs who's last use is
// in this opcode will get deleted as the opcode exits - even if they are
// shared in the returning output Frame.
private Frame _ret_fr; // Optionally return a Frame on stack scope exit
public <V extends Val> V returning( V fr ) {
if( fr instanceof ValFrame )
_ret_fr = ((ValFrame)fr)._fr;
return fr;
}
// Pop-all and remove dead. If a Frame was not "tracked" above, then if it
// goes dead it will leak on function exit. If a Frame is returned from a
// function and not declared "returning", any Vecs it shares with Frames
// that are dying in this opcode will be deleted out from under it.
@Override public void close() {
Futures fs = null;
int i, sp = sp();
while( sp > _sp ) {
Frame fr = _refcnt.remove(--sp);
for( Vec vec : fr.vecs() ) {
if( _globals.contains(vec) ) continue;
for( i=0; i<_sp; i++ )
if( _refcnt.get(i).find(vec) != -1 )
break;
if( i==_sp && (_ret_fr==null || _ret_fr.find(vec)== -1) ) {
if( fs == null ) fs = new Futures();
vec.remove(fs);
}
}
}
if( fs != null ) fs.blockForPending();
}
}
// Produce "value" semantics for all top-level Frame returns - which means a
// true data copy is made of every top-level Vec return. See if this Vec
// exists in some pre-existing global.
boolean isPreExistingGlobal( Vec vec ) {
return _globals.contains(vec);
}
// ----
// Variable lookup
ASTFun _scope; // Current lexical scope lookup
Val lookup( String id ) {
// Lexically scoped functions first
Val val = _scope==null ? null : _scope.lookup(id);
if( val != null ) return val;
// Now the DKV
Value value = DKV.get(Key.make(id));
if( value != null ) {
if( value.isFrame() ) {
Frame fr = value.get();
assert fr._key.toString().equals(id);
_globals.addAll(Arrays.asList(fr.vecs()));
return new ValFrame(fr);
}
// Only understand Frames right now
throw new IllegalArgumentException("DKV name lookup of "+id+" yielded an instance of type "+value.className()+", but only Frame is supported");
}
// Now the built-ins
AST ast = AST.PRIMS.get(id);
if( ast != null )
return ast instanceof ASTNum ? ast.exec(this) : new ValFun(ast);
throw new IllegalArgumentException("Name lookup of "+id+" failed");
}
/*
* Utility & Cleanup
*/
@Override public String toString() {
String s="{";
for( int i=0, sp=sp(); i < sp; i++ ) s += peek(-sp+i).toString()+",";
return s+"}";
}
// @Override public AutoBuffer write_impl(AutoBuffer ab) {
// // write _refcnt
// ab.put4(_refcnt.size());
// for (Frame v: _refcnt.keySet()) { ab.putStr(v._key.toString()); ab.put4(_refcnt.get(v)._val); }
// return ab;
// }
//
// @Override public Env read_impl(AutoBuffer ab) {
// _stack = new ExecStack();
// _refcnt = new HashMap<>();
// int len = ab.get4();
// for (int i = 0; i < len; ++i)
// _refcnt.put((Frame)DKV.getGet(ab.getStr()), new IcedInt(ab.get4()));
// return this;
// }
}
|
h2o-core/src/main/java/water/currents/Env.java
|
package water.currents;
import java.util.ArrayList;
import java.util.HashSet;
import water.*;
import water.fvec.Frame;
import water.fvec.Vec;
/** Execute a set of instructions in the context of an H2O cloud.
*
* An Env (environment) object is a classic stack of values used during
* execution of an AST. The stack is hidden in the normal Java execution
* stack and is not explicit.
*
* For efficiency, reference counting is employed to recycle objects already
* in use rather than creating copies upon copies (a la R). When a Frame is
* `pushed` on to the stack, its reference count is incremented by 1. When a
* Frame is `popped` off of the stack, its reference count is decremented by
* 1. When the reference count is 0, the Env instance will dispose of the
* object. All objects live and die by the Env's that create them. That
* means that any object not created by an Env instance shalt not be
* DKV.removed.
*
* Therefore, the Env class is a stack of values + an API for reference counting.
*/
public class Env {
/**
* The refcnt API. Looks like a Stack, because lifetimes are stack-like, but
* just counts refs by unary stack-slot counting.
*/
private final ArrayList<Frame> _refcnt = new ArrayList<>();
private final HashSet<Vec> _globals = new HashSet<>();
public int sp() { return _refcnt.size(); }
public Frame peek(int x) { return _refcnt.get(sp()+x); }
// Deletes dead Frames & forces good stack cleanliness at opcode end.
// One per Opcode implementation.
StackHelp stk() { return new StackHelp(); }
class StackHelp implements AutoCloseable {
final int _sp = sp();
// Push & track. Called on every Val that spans a (nested) exec call.
// Used to track Frames with lifetimes spanning other AST executions.
public Val track(Val v) {
if( v instanceof ValFrame )
_refcnt.add(sp(),((ValFrame)v)._fr);
return v;
}
// If an opcode is returning a Frame, it must call "returning(frame)" to
// track the returned Frame. Otherwise shared input Vecs who's last use is
// in this opcode will get deleted as the opcode exits - even if they are
// shared in the returning output Frame.
private Frame _ret_fr; // Optionally return a Frame on stack scope exit
public <V extends Val> V returning( V fr ) {
if( fr instanceof ValFrame )
_ret_fr = ((ValFrame)fr)._fr;
return fr;
}
// Pop-all and remove dead. If a Frame was not "tracked" above, then if it
// goes dead it will leak on function exit. If a Frame is returned from a
// function and not declared "returning", any Vecs it shares with Frames
// that are dying in this opcode will be deleted out from under it.
@Override public void close() {
Futures fs = null;
int i, sp = sp();
while( sp > _sp ) {
Frame fr = _refcnt.remove(--sp);
for( Vec vec : fr.vecs() ) {
if( _globals.contains(vec) ) continue;
for( i=0; i<_sp; i++ )
if( _refcnt.get(i).find(vec) != -1 )
break;
if( i==_sp && (_ret_fr==null || _ret_fr.find(vec)== -1) ) {
if( fs == null ) fs = new Futures();
vec.remove(fs);
}
}
}
if( fs != null ) fs.blockForPending();
}
}
// Produce "value" semantics for all top-level Frame returns - which means a
// true data copy is made of every top-level Vec return. See if this Vec
// exists in some pre-existing global.
boolean isPreExistingGlobal( Vec vec ) {
return _globals.contains(vec);
}
// ----
// Variable lookup
ASTFun _scope; // Current lexical scope lookup
Val lookup( String id ) {
// Lexically scoped functions first
Val val = _scope==null ? null : _scope.lookup(id);
if( val != null ) return val;
// Now the DKV
Value value = DKV.get(Key.make(id));
if( value != null ) {
if( value.isFrame() ) {
Frame fr = value.get();
assert fr._key.toString().equals(id);
for( Vec vec : fr.vecs() ) _globals.add(vec);
return new ValFrame(fr);
}
// Only understand Frames right now
throw new IllegalArgumentException("DKV name lookup of "+id+" yielded an instance of type "+value.className()+", but only Frame is supported");
}
// Now the built-ins
AST ast = AST.PRIMS.get(id);
if( ast != null )
return ast instanceof ASTNum ? ast.exec(this) : new ValFun(ast);
throw new IllegalArgumentException("Name lookup of "+id+" failed");
}
/*
* Utility & Cleanup
*/
@Override public String toString() {
String s="{";
for( int i=0, sp=sp(); i < sp; i++ ) s += peek(-sp+i).toString()+",";
return s+"}";
}
// @Override public AutoBuffer write_impl(AutoBuffer ab) {
// // write _refcnt
// ab.put4(_refcnt.size());
// for (Frame v: _refcnt.keySet()) { ab.putStr(v._key.toString()); ab.put4(_refcnt.get(v)._val); }
// return ab;
// }
//
// @Override public Env read_impl(AutoBuffer ab) {
// _stack = new ExecStack();
// _refcnt = new HashMap<>();
// int len = ab.get4();
// for (int i = 0; i < len; ++i)
// _refcnt.put((Frame)DKV.getGet(ab.getStr()), new IcedInt(ab.get4()));
// return this;
// }
}
|
ideaj warning
|
h2o-core/src/main/java/water/currents/Env.java
|
ideaj warning
|
|
Java
|
apache-2.0
|
70e3b173520de99a0581df4defe67f4d16402485
| 0
|
fabric8io/fabric8-forge,fabric8io/fabric8-forge,fabric8io/fabric8-forge
|
/**
* Copyright 2005-2015 Red Hat, Inc.
* <p/>
* Red Hat licenses this file to you under the Apache License, version
* 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package io.fabric8.forge.camel.commands.project;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.inject.Inject;
import io.fabric8.forge.addon.utils.LineNumberHelper;
import io.fabric8.forge.camel.commands.project.dto.ComponentDto;
import io.fabric8.forge.camel.commands.project.helper.CamelCommandsHelper;
import io.fabric8.forge.camel.commands.project.helper.PoorMansLogger;
import io.fabric8.forge.camel.commands.project.model.InputOptionByGroup;
import org.jboss.forge.addon.convert.Converter;
import org.jboss.forge.addon.parser.java.facets.JavaSourceFacet;
import org.jboss.forge.addon.parser.java.resources.JavaResource;
import org.jboss.forge.addon.projects.Project;
import org.jboss.forge.addon.projects.dependencies.DependencyInstaller;
import org.jboss.forge.addon.projects.facets.ResourcesFacet;
import org.jboss.forge.addon.projects.facets.WebResourcesFacet;
import org.jboss.forge.addon.resource.FileResource;
import org.jboss.forge.addon.ui.context.UIBuilder;
import org.jboss.forge.addon.ui.context.UIContext;
import org.jboss.forge.addon.ui.context.UIExecutionContext;
import org.jboss.forge.addon.ui.context.UINavigationContext;
import org.jboss.forge.addon.ui.input.InputComponent;
import org.jboss.forge.addon.ui.input.InputComponentFactory;
import org.jboss.forge.addon.ui.input.UISelectOne;
import org.jboss.forge.addon.ui.input.ValueChangeListener;
import org.jboss.forge.addon.ui.input.events.ValueChangeEvent;
import org.jboss.forge.addon.ui.metadata.UICommandMetadata;
import org.jboss.forge.addon.ui.metadata.WithAttributes;
import org.jboss.forge.addon.ui.result.NavigationResult;
import org.jboss.forge.addon.ui.result.Result;
import org.jboss.forge.addon.ui.result.Results;
import org.jboss.forge.addon.ui.result.navigation.NavigationResultBuilder;
import org.jboss.forge.addon.ui.util.Categories;
import org.jboss.forge.addon.ui.util.Metadata;
import org.jboss.forge.addon.ui.wizard.UIWizard;
import static io.fabric8.forge.camel.commands.project.helper.CamelCatalogHelper.createComponentDto;
import static io.fabric8.forge.camel.commands.project.helper.CamelCommandsHelper.createUIInputsForCamelComponent;
public class CamelAddEndpointCommand extends AbstractCamelProjectCommand implements UIWizard {
private static final int MAX_OPTIONS = 20;
private static final PoorMansLogger LOG = new PoorMansLogger(false);
@Inject
@WithAttributes(label = "Name", required = true, description = "Name of component to use for the endpoint")
private UISelectOne<ComponentDto> componentName;
@Inject
private InputComponentFactory componentFactory;
@Inject
private DependencyInstaller dependencyInstaller;
@Override
public UICommandMetadata getMetadata(UIContext context) {
return Metadata.forCommand(CamelAddEndpointCommand.class).name(
"Camel: Add Endpoint").category(Categories.create(CATEGORY))
.description("Add Camel endpoint to the current file");
}
@Override
public boolean isEnabled(UIContext context) {
boolean answer = super.isEnabled(context);
if (answer) {
// we are only enabled if there is a file open in the editor and we have a cursor position
int pos = getCurrentCursorPosition(context);
answer = pos > -1;
}
return answer;
}
@Override
public void initializeUI(UIBuilder builder) throws Exception {
Map<Object, Object> attributeMap = builder.getUIContext().getAttributeMap();
attributeMap.remove("navigationResult");
Project project = getSelectedProject(builder.getUIContext());
String selectedFile = getSelectedFile(builder.getUIContext());
final String currentFile = asRelativeFile(builder.getUIContext(), selectedFile);
attributeMap.put("currentFile", currentFile);
boolean xmlFile = currentFile != null && currentFile.endsWith(".xml");
// determine if the current cursor position is in a route where we should be either consumer or producer only
AtomicBoolean consumerOnly = new AtomicBoolean();
AtomicBoolean producerOnly = new AtomicBoolean();
determineConsumerAndProducerOnly(consumerOnly, producerOnly, builder.getUIContext(), xmlFile, currentFile);
attributeMap.put("consumerOnly", Boolean.toString(consumerOnly.get()));
attributeMap.put("producerOnly", Boolean.toString(producerOnly.get()));
// filter the list of components based on consumer and producer only
componentName.setValueChoices(CamelCommandsHelper.createComponentDtoValues(project, getCamelCatalog(), null, false, consumerOnly.get(), producerOnly.get()));
// include converter from string->dto
componentName.setValueConverter(new Converter<String, ComponentDto>() {
@Override
public ComponentDto convert(String text) {
return createComponentDto(getCamelCatalog(), text);
}
});
// show note about the chosen component
componentName.addValueChangeListener(new ValueChangeListener() {
@Override
public void valueChanged(ValueChangeEvent event) {
ComponentDto component = (ComponentDto) event.getNewValue();
if (component != null) {
String description = component.getDescription();
componentName.setNote(description != null ? description : "");
} else {
componentName.setNote("");
}
}
});
builder.add(componentName);
}
@Override
public NavigationResult next(UINavigationContext context) throws Exception {
Map<Object, Object> attributeMap = context.getUIContext().getAttributeMap();
ComponentDto component = componentName.getValue();
String camelComponentName = component.getScheme();
// must be same component name and endpoint type to allow reusing existing navigation result
String previous = (String) attributeMap.get("componentName");
if (previous != null && previous.equals(camelComponentName)) {
NavigationResult navigationResult = (NavigationResult) attributeMap.get("navigationResult");
if (navigationResult != null) {
return navigationResult;
}
}
attributeMap.put("componentName", camelComponentName);
String currentFile = (String) attributeMap.get("currentFile");
boolean xmlFile = currentFile != null && currentFile.endsWith(".xml");
attributeMap.put("mode", "add");
if (xmlFile) {
attributeMap.put("xml", currentFile);
attributeMap.put("kind", "xml");
} else {
attributeMap.put("routeBuilder", currentFile);
attributeMap.put("kind", "java");
}
int pos = getCurrentCursorPosition(context.getUIContext());
attributeMap.put("cursorPosition", pos);
// producer vs consumer only
boolean consumerOnly = "true".equals(attributeMap.get("consumerOnly"));
boolean producerOnly = "true".equals(attributeMap.get("producerOnly"));
// we need to figure out how many options there is so we can as many steps we need
UIContext ui = context.getUIContext();
List<InputOptionByGroup> groups = createUIInputsForCamelComponent(camelComponentName, null, MAX_OPTIONS, consumerOnly, producerOnly,
getCamelCatalog(), componentFactory, converterFactory, ui);
// need all inputs in a list as well
List<InputComponent> allInputs = new ArrayList<>();
for (InputOptionByGroup group : groups) {
allInputs.addAll(group.getInputs());
}
NavigationResultBuilder builder = Results.navigationBuilder();
int pages = groups.size();
for (int i = 0; i < pages; i++) {
boolean last = i == pages - 1;
InputOptionByGroup current = groups.get(i);
ConfigureEndpointPropertiesStep step = new ConfigureEndpointPropertiesStep(projectFactory, dependencyInstaller, getCamelCatalog(),
camelComponentName, current.getGroup(), allInputs, current.getInputs(), last, i, pages);
builder.add(step);
}
NavigationResult navigationResult = builder.build();
attributeMap.put("navigationResult", navigationResult);
return navigationResult;
}
@Override
public Result execute(UIExecutionContext context) throws Exception {
return null;
}
private void determineConsumerAndProducerOnly(AtomicBoolean consumerOnly, AtomicBoolean producerOnly,
UIContext context, boolean xmlFile, String currentFile) {
Project project = getSelectedProject(context);
final int cursorLineNumber = getCurrentCursorLine(context);
if (cursorLineNumber == -1) {
// cannot find the cursor
return;
}
// we can be both kind lets try to see if we can figure out if the current position is in a Camel route
// where we use EIPs so we can know if its a from/pollEnrich = consumer, and if not = producer)
if (xmlFile) {
ResourcesFacet facet = project.getFacet(ResourcesFacet.class);
WebResourcesFacet webResourcesFacet = null;
if (project.hasFacet(WebResourcesFacet.class)) {
webResourcesFacet = project.getFacet(WebResourcesFacet.class);
}
FileResource file = facet != null ? facet.getResource(currentFile) : null;
if (file == null || !file.exists()) {
file = webResourcesFacet != null ? webResourcesFacet.getWebResource(currentFile) : null;
}
try {
if (file != null && file.exists() && cursorLineNumber > 0) {
// read all the lines
List<String> lines = LineNumberHelper.readLines(file.getResourceInputStream());
// the list is 0-based, and line number is 1-based
String line = lines.get(cursorLineNumber - 1);
LOG.info("Line " + line);
if (line != null) {
if (line.contains("<from") || line.contains("<pollEnrich")) {
// only from and poll enrich is consumer based
consumerOnly.set(true);
} else if (!line.contains("<endpoint")) {
// assume producer unless its a generic endpoint
producerOnly.set(true);
}
}
}
} catch (Exception e) {
// ignore
}
} else {
// java code
JavaSourceFacet facet = project.getFacet(JavaSourceFacet.class);
JavaResource file = facet.getJavaResource(currentFile);
try {
if (file != null && file.exists() && cursorLineNumber > 0) {
// read all the lines
List<String> lines = LineNumberHelper.readLines(file.getResourceInputStream());
// the list is 0-based, and line number is 1-based
String line = lines.get(cursorLineNumber - 1);
LOG.info("Line " + line);
if (line != null) {
if (line.contains("from(") || line.contains("pollEnrich(")) {
// only from and poll enrich is consumer based
consumerOnly.set(true);
} else if (!line.contains("endpoint(")) {
// assume producer unless its a generic endpoint
producerOnly.set(true);
}
}
}
} catch (Exception e) {
// ignore
}
}
}
}
|
addons/camel/src/main/java/io/fabric8/forge/camel/commands/project/CamelAddEndpointCommand.java
|
/**
* Copyright 2005-2015 Red Hat, Inc.
* <p/>
* Red Hat licenses this file to you under the Apache License, version
* 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package io.fabric8.forge.camel.commands.project;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.inject.Inject;
import io.fabric8.forge.addon.utils.LineNumberHelper;
import io.fabric8.forge.camel.commands.project.dto.ComponentDto;
import io.fabric8.forge.camel.commands.project.helper.CamelCommandsHelper;
import io.fabric8.forge.camel.commands.project.helper.PoorMansLogger;
import io.fabric8.forge.camel.commands.project.model.InputOptionByGroup;
import org.jboss.forge.addon.convert.Converter;
import org.jboss.forge.addon.parser.java.facets.JavaSourceFacet;
import org.jboss.forge.addon.parser.java.resources.JavaResource;
import org.jboss.forge.addon.projects.Project;
import org.jboss.forge.addon.projects.dependencies.DependencyInstaller;
import org.jboss.forge.addon.projects.facets.ResourcesFacet;
import org.jboss.forge.addon.projects.facets.WebResourcesFacet;
import org.jboss.forge.addon.resource.FileResource;
import org.jboss.forge.addon.ui.context.UIBuilder;
import org.jboss.forge.addon.ui.context.UIContext;
import org.jboss.forge.addon.ui.context.UIExecutionContext;
import org.jboss.forge.addon.ui.context.UINavigationContext;
import org.jboss.forge.addon.ui.input.InputComponent;
import org.jboss.forge.addon.ui.input.InputComponentFactory;
import org.jboss.forge.addon.ui.input.UISelectOne;
import org.jboss.forge.addon.ui.input.ValueChangeListener;
import org.jboss.forge.addon.ui.input.events.ValueChangeEvent;
import org.jboss.forge.addon.ui.metadata.UICommandMetadata;
import org.jboss.forge.addon.ui.metadata.WithAttributes;
import org.jboss.forge.addon.ui.result.NavigationResult;
import org.jboss.forge.addon.ui.result.Result;
import org.jboss.forge.addon.ui.result.Results;
import org.jboss.forge.addon.ui.result.navigation.NavigationResultBuilder;
import org.jboss.forge.addon.ui.util.Categories;
import org.jboss.forge.addon.ui.util.Metadata;
import org.jboss.forge.addon.ui.wizard.UIWizard;
import static io.fabric8.forge.camel.commands.project.helper.CamelCatalogHelper.createComponentDto;
import static io.fabric8.forge.camel.commands.project.helper.CamelCommandsHelper.createUIInputsForCamelComponent;
public class CamelAddEndpointCommand extends AbstractCamelProjectCommand implements UIWizard {
private static final int MAX_OPTIONS = 20;
private static final PoorMansLogger LOG = new PoorMansLogger(false);
@Inject
@WithAttributes(label = "Filter", required = false, description = "To filter components")
private UISelectOne<String> componentNameFilter;
@Inject
@WithAttributes(label = "Name", required = true, description = "Name of component to use for the endpoint")
private UISelectOne<ComponentDto> componentName;
@Inject
private InputComponentFactory componentFactory;
@Inject
private DependencyInstaller dependencyInstaller;
@Override
public UICommandMetadata getMetadata(UIContext context) {
return Metadata.forCommand(CamelAddEndpointCommand.class).name(
"Camel: Add Endpoint").category(Categories.create(CATEGORY))
.description("Add Camel endpoint to the current file");
}
@Override
public boolean isEnabled(UIContext context) {
boolean answer = super.isEnabled(context);
if (answer) {
// we are only enabled if there is a file open in the editor and we have a cursor position
int pos = getCurrentCursorPosition(context);
answer = pos > -1;
}
return answer;
}
@Override
public void initializeUI(UIBuilder builder) throws Exception {
Map<Object, Object> attributeMap = builder.getUIContext().getAttributeMap();
attributeMap.remove("navigationResult");
Project project = getSelectedProject(builder.getUIContext());
String selectedFile = getSelectedFile(builder.getUIContext());
final String currentFile = asRelativeFile(builder.getUIContext(), selectedFile);
attributeMap.put("currentFile", currentFile);
boolean xmlFile = currentFile != null && currentFile.endsWith(".xml");
// determine if the current cursor position is in a route where we should be either consumer or producer only
AtomicBoolean consumerOnly = new AtomicBoolean();
AtomicBoolean producerOnly = new AtomicBoolean();
determineConsumerAndProducerOnly(consumerOnly, producerOnly, builder.getUIContext(), xmlFile, currentFile);
attributeMap.put("consumerOnly", Boolean.toString(consumerOnly.get()));
attributeMap.put("producerOnly", Boolean.toString(producerOnly.get()));
// filter the list of components based on consumer and producer only
componentNameFilter.setValueChoices(CamelCommandsHelper.createComponentLabelValues(project, getCamelCatalog()));
componentNameFilter.setDefaultValue("<all>");
componentName.setValueChoices(CamelCommandsHelper.createComponentDtoValues(project, getCamelCatalog(),
componentNameFilter, false, consumerOnly.get(), producerOnly.get()));
// include converter from string->dto
componentName.setValueConverter(new Converter<String, ComponentDto>() {
@Override
public ComponentDto convert(String text) {
return createComponentDto(getCamelCatalog(), text);
}
});
// show note about the chosen component
componentName.addValueChangeListener(new ValueChangeListener() {
@Override
public void valueChanged(ValueChangeEvent event) {
ComponentDto component = (ComponentDto) event.getNewValue();
if (component != null) {
String description = component.getDescription();
componentName.setNote(description != null ? description : "");
} else {
componentName.setNote("");
}
}
});
builder.add(componentNameFilter).add(componentName);
}
@Override
public NavigationResult next(UINavigationContext context) throws Exception {
Map<Object, Object> attributeMap = context.getUIContext().getAttributeMap();
ComponentDto component = componentName.getValue();
String camelComponentName = component.getScheme();
// must be same component name and endpoint type to allow reusing existing navigation result
String previous = (String) attributeMap.get("componentName");
if (previous != null && previous.equals(camelComponentName)) {
NavigationResult navigationResult = (NavigationResult) attributeMap.get("navigationResult");
if (navigationResult != null) {
return navigationResult;
}
}
attributeMap.put("componentName", camelComponentName);
String currentFile = (String) attributeMap.get("currentFile");
boolean xmlFile = currentFile != null && currentFile.endsWith(".xml");
attributeMap.put("mode", "add");
if (xmlFile) {
attributeMap.put("xml", currentFile);
attributeMap.put("kind", "xml");
} else {
attributeMap.put("routeBuilder", currentFile);
attributeMap.put("kind", "java");
}
int pos = getCurrentCursorPosition(context.getUIContext());
attributeMap.put("cursorPosition", pos);
// producer vs consumer only
boolean consumerOnly = "true".equals(attributeMap.get("consumerOnly"));
boolean producerOnly = "true".equals(attributeMap.get("producerOnly"));
// we need to figure out how many options there is so we can as many steps we need
UIContext ui = context.getUIContext();
List<InputOptionByGroup> groups = createUIInputsForCamelComponent(camelComponentName, null, MAX_OPTIONS, consumerOnly, producerOnly,
getCamelCatalog(), componentFactory, converterFactory, ui);
// need all inputs in a list as well
List<InputComponent> allInputs = new ArrayList<>();
for (InputOptionByGroup group : groups) {
allInputs.addAll(group.getInputs());
}
NavigationResultBuilder builder = Results.navigationBuilder();
int pages = groups.size();
for (int i = 0; i < pages; i++) {
boolean last = i == pages - 1;
InputOptionByGroup current = groups.get(i);
ConfigureEndpointPropertiesStep step = new ConfigureEndpointPropertiesStep(projectFactory, dependencyInstaller, getCamelCatalog(),
camelComponentName, current.getGroup(), allInputs, current.getInputs(), last, i, pages);
builder.add(step);
}
NavigationResult navigationResult = builder.build();
attributeMap.put("navigationResult", navigationResult);
return navigationResult;
}
@Override
public Result execute(UIExecutionContext context) throws Exception {
return null;
}
private void determineConsumerAndProducerOnly(AtomicBoolean consumerOnly, AtomicBoolean producerOnly,
UIContext context, boolean xmlFile, String currentFile) {
Project project = getSelectedProject(context);
final int cursorLineNumber = getCurrentCursorLine(context);
if (cursorLineNumber == -1) {
// cannot find the cursor
return;
}
// we can be both kind lets try to see if we can figure out if the current position is in a Camel route
// where we use EIPs so we can know if its a from/pollEnrich = consumer, and if not = producer)
if (xmlFile) {
ResourcesFacet facet = project.getFacet(ResourcesFacet.class);
WebResourcesFacet webResourcesFacet = null;
if (project.hasFacet(WebResourcesFacet.class)) {
webResourcesFacet = project.getFacet(WebResourcesFacet.class);
}
FileResource file = facet != null ? facet.getResource(currentFile) : null;
if (file == null || !file.exists()) {
file = webResourcesFacet != null ? webResourcesFacet.getWebResource(currentFile) : null;
}
try {
if (file != null && file.exists() && cursorLineNumber > 0) {
// read all the lines
List<String> lines = LineNumberHelper.readLines(file.getResourceInputStream());
// the list is 0-based, and line number is 1-based
String line = lines.get(cursorLineNumber - 1);
LOG.info("Line " + line);
if (line != null) {
if (line.contains("<from") || line.contains("<pollEnrich")) {
// only from and poll enrich is consumer based
consumerOnly.set(true);
} else if (!line.contains("<endpoint")) {
// assume producer unless its a generic endpoint
producerOnly.set(true);
}
}
}
} catch (Exception e) {
// ignore
}
} else {
// java code
JavaSourceFacet facet = project.getFacet(JavaSourceFacet.class);
JavaResource file = facet.getJavaResource(currentFile);
try {
if (file != null && file.exists() && cursorLineNumber > 0) {
// read all the lines
List<String> lines = LineNumberHelper.readLines(file.getResourceInputStream());
// the list is 0-based, and line number is 1-based
String line = lines.get(cursorLineNumber - 1);
LOG.info("Line " + line);
if (line != null) {
if (line.contains("from(") || line.contains("pollEnrich(")) {
// only from and poll enrich is consumer based
consumerOnly.set(true);
} else if (!line.contains("endpoint(")) {
// assume producer unless its a generic endpoint
producerOnly.set(true);
}
}
}
} catch (Exception e) {
// ignore
}
}
}
}
|
Camel catalog - No need for component filter on add endpoint.
|
addons/camel/src/main/java/io/fabric8/forge/camel/commands/project/CamelAddEndpointCommand.java
|
Camel catalog - No need for component filter on add endpoint.
|
|
Java
|
apache-2.0
|
b3a7888e8a78d8182bff48c6c7fbeb28491f4319
| 0
|
apache/camel,christophd/camel,onders86/camel,apache/camel,pax95/camel,kevinearls/camel,DariusX/camel,apache/camel,tdiesler/camel,cunningt/camel,tadayosi/camel,sverkera/camel,zregvart/camel,pmoerenhout/camel,cunningt/camel,CodeSmell/camel,tadayosi/camel,kevinearls/camel,apache/camel,gnodet/camel,kevinearls/camel,mcollovati/camel,tadayosi/camel,kevinearls/camel,gnodet/camel,tadayosi/camel,nikhilvibhav/camel,pax95/camel,pax95/camel,gnodet/camel,pax95/camel,nicolaferraro/camel,davidkarlsen/camel,punkhorn/camel-upstream,onders86/camel,ullgren/camel,alvinkwekel/camel,pax95/camel,davidkarlsen/camel,mcollovati/camel,tdiesler/camel,apache/camel,sverkera/camel,DariusX/camel,davidkarlsen/camel,alvinkwekel/camel,zregvart/camel,ullgren/camel,nikhilvibhav/camel,objectiser/camel,davidkarlsen/camel,kevinearls/camel,punkhorn/camel-upstream,christophd/camel,cunningt/camel,nicolaferraro/camel,onders86/camel,zregvart/camel,gnodet/camel,alvinkwekel/camel,nikhilvibhav/camel,pax95/camel,sverkera/camel,CodeSmell/camel,tdiesler/camel,sverkera/camel,objectiser/camel,nicolaferraro/camel,pmoerenhout/camel,pmoerenhout/camel,CodeSmell/camel,zregvart/camel,adessaigne/camel,nicolaferraro/camel,ullgren/camel,tdiesler/camel,tdiesler/camel,christophd/camel,christophd/camel,adessaigne/camel,onders86/camel,ullgren/camel,pmoerenhout/camel,tadayosi/camel,onders86/camel,punkhorn/camel-upstream,christophd/camel,punkhorn/camel-upstream,adessaigne/camel,sverkera/camel,cunningt/camel,DariusX/camel,mcollovati/camel,pmoerenhout/camel,apache/camel,cunningt/camel,kevinearls/camel,Fabryprog/camel,cunningt/camel,adessaigne/camel,Fabryprog/camel,DariusX/camel,adessaigne/camel,CodeSmell/camel,objectiser/camel,pmoerenhout/camel,objectiser/camel,gnodet/camel,onders86/camel,nikhilvibhav/camel,adessaigne/camel,christophd/camel,tadayosi/camel,mcollovati/camel,Fabryprog/camel,tdiesler/camel,alvinkwekel/camel,Fabryprog/camel,sverkera/camel
|
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.component.servlet;
import java.net.URI;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import org.apache.camel.CamelContext;
import org.apache.camel.Consumer;
import org.apache.camel.Endpoint;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.http.common.HttpBinding;
import org.apache.camel.http.common.HttpCommonComponent;
import org.apache.camel.http.common.HttpConsumer;
import org.apache.camel.spi.HeaderFilterStrategy;
import org.apache.camel.spi.Metadata;
import org.apache.camel.spi.RestApiConsumerFactory;
import org.apache.camel.spi.RestConfiguration;
import org.apache.camel.spi.RestConsumerFactory;
import org.apache.camel.util.FileUtil;
import org.apache.camel.util.ObjectHelper;
import org.apache.camel.util.URISupport;
import org.apache.camel.util.UnsafeUriCharactersEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ServletComponent extends HttpCommonComponent implements RestConsumerFactory, RestApiConsumerFactory {
private static final Logger LOG = LoggerFactory.getLogger(ServletComponent.class);
@Metadata(label = "consumer", defaultValue = "CamelServlet", description = "Default name of servlet to use. The default name is CamelServlet.")
private String servletName = "CamelServlet";
@Metadata(label = "consumer,advanced", description = "To use a custom org.apache.camel.component.servlet.HttpRegistry.")
private HttpRegistry httpRegistry;
@Metadata(label = "consumer,advanced", description = "Whether to automatic bind multipart/form-data as attachments on the Camel Exchange}."
+ " The options attachmentMultipartBinding=true and disableStreamCache=false cannot work together."
+ " Remove disableStreamCache to use AttachmentMultipartBinding."
+ " This is turn off by default as this may require servlet specific configuration to enable this when using Servlet's.")
private boolean attachmentMultipartBinding;
@Metadata(label = "consumer,advanced", description = "Whitelist of accepted filename extensions for accepting uploaded files."
+ " Multiple extensions can be separated by comma, such as txt,xml.")
private String fileNameExtWhitelist;
public ServletComponent() {
super(ServletEndpoint.class);
}
public ServletComponent(Class<? extends ServletEndpoint> endpointClass) {
super(endpointClass);
}
@Override
protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception {
// must extract well known parameters before we create the endpoint
Boolean throwExceptionOnFailure = getAndRemoveParameter(parameters, "throwExceptionOnFailure", Boolean.class);
Boolean transferException = getAndRemoveParameter(parameters, "transferException", Boolean.class);
Boolean bridgeEndpoint = getAndRemoveParameter(parameters, "bridgeEndpoint", Boolean.class);
HttpBinding binding = resolveAndRemoveReferenceParameter(parameters, "httpBinding", HttpBinding.class);
Boolean matchOnUriPrefix = getAndRemoveParameter(parameters, "matchOnUriPrefix", Boolean.class);
String servletName = getAndRemoveParameter(parameters, "servletName", String.class, getServletName());
String httpMethodRestrict = getAndRemoveParameter(parameters, "httpMethodRestrict", String.class);
HeaderFilterStrategy headerFilterStrategy = resolveAndRemoveReferenceParameter(parameters, "headerFilterStrategy", HeaderFilterStrategy.class);
Boolean async = getAndRemoveParameter(parameters, "async", Boolean.class);
Boolean attachmentMultipartBinding = getAndRemoveParameter(parameters, "attachmentMultipartBinding", Boolean.class);
Boolean disableStreamCache = getAndRemoveParameter(parameters, "disableStreamCache", Boolean.class);
if (lenientContextPath()) {
// the uri must have a leading slash for the context-path matching to work with servlet, and it can be something people
// forget to add and then the servlet consumer cannot match the context-path as would have been expected
String scheme = ObjectHelper.before(uri, ":");
String after = ObjectHelper.after(uri, ":");
// rebuild uri to have exactly one leading slash
while (after.startsWith("/")) {
after = after.substring(1);
}
after = "/" + after;
uri = scheme + ":" + after;
}
// restructure uri to be based on the parameters left as we dont want to include the Camel internal options
URI httpUri = URISupport.createRemainingURI(new URI(UnsafeUriCharactersEncoder.encodeHttpURI(uri)), parameters);
ServletEndpoint endpoint = createServletEndpoint(uri, this, httpUri);
endpoint.setServletName(servletName);
endpoint.setFileNameExtWhitelist(fileNameExtWhitelist);
if (async != null) {
endpoint.setAsync(async);
}
if (headerFilterStrategy != null) {
endpoint.setHeaderFilterStrategy(headerFilterStrategy);
} else {
setEndpointHeaderFilterStrategy(endpoint);
}
// prefer to use endpoint configured over component configured
if (binding == null) {
// fallback to component configured
binding = getHttpBinding();
}
if (binding != null) {
endpoint.setBinding(binding);
}
// should we use an exception for failed error codes?
if (throwExceptionOnFailure != null) {
endpoint.setThrowExceptionOnFailure(throwExceptionOnFailure);
}
// should we transfer exception as serialized object
if (transferException != null) {
endpoint.setTransferException(transferException);
}
if (bridgeEndpoint != null) {
endpoint.setBridgeEndpoint(bridgeEndpoint);
}
if (matchOnUriPrefix != null) {
endpoint.setMatchOnUriPrefix(matchOnUriPrefix);
}
if (httpMethodRestrict != null) {
endpoint.setHttpMethodRestrict(httpMethodRestrict);
}
if (attachmentMultipartBinding != null) {
endpoint.setAttachmentMultipartBinding(attachmentMultipartBinding);
} else {
endpoint.setAttachmentMultipartBinding(isAttachmentMultipartBinding());
}
if (disableStreamCache != null) {
endpoint.setDisableStreamCache(disableStreamCache);
}
// turn off stream caching if in attachment mode
if (endpoint.isAttachmentMultipartBinding()) {
if (disableStreamCache == null) {
// disableStreamCache not explicit configured so we can automatic change it
LOG.info("Disabling stream caching as attachmentMultipartBinding is enabled");
endpoint.setDisableStreamCache(true);
} else if (!disableStreamCache) {
throw new IllegalArgumentException("The options attachmentMultipartBinding=true and disableStreamCache=false cannot work together."
+ " Remove disableStreamCache to use AttachmentMultipartBinding");
}
}
setProperties(endpoint, parameters);
return endpoint;
}
/**
* Whether defining the context-path is lenient and do not require an exact leading slash.
*/
protected boolean lenientContextPath() {
return true;
}
/**
* Strategy to create the servlet endpoint.
*/
protected ServletEndpoint createServletEndpoint(String endpointUri, ServletComponent component, URI httpUri) throws Exception {
return new ServletEndpoint(endpointUri, component, httpUri);
}
@Override
public void connect(HttpConsumer consumer) throws Exception {
ServletConsumer sc = (ServletConsumer) consumer;
String name = sc.getEndpoint().getServletName();
HttpRegistry registry = httpRegistry;
if (registry == null) {
registry = DefaultHttpRegistry.getHttpRegistry(name);
}
registry.register(consumer);
}
@Override
public void disconnect(HttpConsumer consumer) throws Exception {
ServletConsumer sc = (ServletConsumer) consumer;
String name = sc.getEndpoint().getServletName();
HttpRegistry registry = httpRegistry;
if (registry == null) {
registry = DefaultHttpRegistry.getHttpRegistry(name);
}
registry.unregister(consumer);
}
public String getServletName() {
return servletName;
}
/**
* Default name of servlet to use. The default name is CamelServlet.
*/
public void setServletName(String servletName) {
this.servletName = servletName;
}
public HttpRegistry getHttpRegistry() {
return httpRegistry;
}
/**
* To use a custom org.apache.camel.component.servlet.HttpRegistry.
*/
public void setHttpRegistry(HttpRegistry httpRegistry) {
this.httpRegistry = httpRegistry;
}
public boolean isAttachmentMultipartBinding() {
return attachmentMultipartBinding;
}
/**
* Whether to automatic bind multipart/form-data as attachments on the Camel {@link Exchange}.
* <p/>
* The options attachmentMultipartBinding=true and disableStreamCache=false cannot work together.
* Remove disableStreamCache to use AttachmentMultipartBinding.
* <p/>
* This is turn off by default as this may require servlet specific configuration to enable this when using Servlet's.
*/
public void setAttachmentMultipartBinding(boolean attachmentMultipartBinding) {
this.attachmentMultipartBinding = attachmentMultipartBinding;
}
public String getFileNameExtWhitelist() {
return fileNameExtWhitelist;
}
/**
* Whitelist of accepted filename extensions for accepting uploaded files.
* <p/>
* Multiple extensions can be separated by comma, such as txt,xml.
*/
public void setFileNameExtWhitelist(String fileNameExtWhitelist) {
this.fileNameExtWhitelist = fileNameExtWhitelist;
}
@Override
public Consumer createConsumer(CamelContext camelContext, Processor processor, String verb, String basePath, String uriTemplate,
String consumes, String produces, RestConfiguration configuration, Map<String, Object> parameters) throws Exception {
return doCreateConsumer(camelContext, processor, verb, basePath, uriTemplate, consumes, produces, configuration, parameters, false);
}
@Override
public Consumer createApiConsumer(CamelContext camelContext, Processor processor, String contextPath,
RestConfiguration configuration, Map<String, Object> parameters) throws Exception {
// reuse the createConsumer method we already have. The api need to use GET and match on uri prefix
return doCreateConsumer(camelContext, processor, "GET", contextPath, null, null, null, configuration, parameters, true);
}
Consumer doCreateConsumer(CamelContext camelContext, Processor processor, String verb, String basePath, String uriTemplate,
String consumes, String produces, RestConfiguration configuration, Map<String, Object> parameters, boolean api) throws Exception {
String path = basePath;
if (uriTemplate != null) {
// make sure to avoid double slashes
if (uriTemplate.startsWith("/")) {
path = path + uriTemplate;
} else {
path = path + "/" + uriTemplate;
}
}
path = FileUtil.stripLeadingSeparator(path);
// if no explicit port/host configured, then use port from rest configuration
RestConfiguration config = configuration;
if (config == null) {
config = camelContext.getRestConfiguration("servlet", true);
}
Map<String, Object> map = new HashMap<>();
// build query string, and append any endpoint configuration properties
if (config.getComponent() == null || config.getComponent().equals("servlet")) {
// setup endpoint options
if (config.getEndpointProperties() != null && !config.getEndpointProperties().isEmpty()) {
map.putAll(config.getEndpointProperties());
}
}
boolean cors = config.isEnableCORS();
if (cors) {
// allow HTTP Options as we want to handle CORS in rest-dsl
map.put("optionsEnabled", "true");
}
// do not append with context-path as the servlet path should be without context-path
String query = URISupport.createQueryString(map);
String url;
if (api) {
url = "servlet:///%s?matchOnUriPrefix=true&httpMethodRestrict=%s";
} else {
url = "servlet:///%s?httpMethodRestrict=%s";
}
// must use upper case for restrict
String restrict = verb.toUpperCase(Locale.US);
if (cors) {
restrict += ",OPTIONS";
}
// get the endpoint
url = String.format(url, path, restrict);
if (!query.isEmpty()) {
url = url + "&" + query;
}
ServletEndpoint endpoint = camelContext.getEndpoint(url, ServletEndpoint.class);
setProperties(camelContext, endpoint, parameters);
if (!map.containsKey("httpBinding")) {
// use the rest binding, if not using a custom http binding
HttpBinding binding = new ServletRestHttpBinding();
binding.setHeaderFilterStrategy(endpoint.getHeaderFilterStrategy());
binding.setTransferException(endpoint.isTransferException());
binding.setEagerCheckContentAvailable(endpoint.isEagerCheckContentAvailable());
endpoint.setHttpBinding(binding);
}
// configure consumer properties
Consumer consumer = endpoint.createConsumer(processor);
if (config.getConsumerProperties() != null && !config.getConsumerProperties().isEmpty()) {
setProperties(camelContext, consumer, config.getConsumerProperties());
}
return consumer;
}
@Override
protected void doStart() throws Exception {
super.doStart();
RestConfiguration config = getCamelContext().getRestConfiguration("servlet", true);
// configure additional options on jetty configuration
if (config.getComponentProperties() != null && !config.getComponentProperties().isEmpty()) {
setProperties(this, config.getComponentProperties());
}
}
}
|
components/camel-servlet/src/main/java/org/apache/camel/component/servlet/ServletComponent.java
|
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.component.servlet;
import java.net.URI;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import org.apache.camel.CamelContext;
import org.apache.camel.Consumer;
import org.apache.camel.Endpoint;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.http.common.HttpBinding;
import org.apache.camel.http.common.HttpCommonComponent;
import org.apache.camel.http.common.HttpConsumer;
import org.apache.camel.spi.HeaderFilterStrategy;
import org.apache.camel.spi.Metadata;
import org.apache.camel.spi.RestApiConsumerFactory;
import org.apache.camel.spi.RestConfiguration;
import org.apache.camel.spi.RestConsumerFactory;
import org.apache.camel.util.FileUtil;
import org.apache.camel.util.ObjectHelper;
import org.apache.camel.util.URISupport;
import org.apache.camel.util.UnsafeUriCharactersEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ServletComponent extends HttpCommonComponent implements RestConsumerFactory, RestApiConsumerFactory {
private static final Logger LOG = LoggerFactory.getLogger(ServletComponent.class);
@Metadata(label = "consumer", defaultValue = "CamelServlet", description = "Default name of servlet to use. The default name is CamelServlet.")
private String servletName = "CamelServlet";
@Metadata(label = "consumer,advanced", description = "To use a custom org.apache.camel.component.servlet.HttpRegistry.")
private HttpRegistry httpRegistry;
@Metadata(label = "consumer,advanced", description = "Whether to automatic bind multipart/form-data as attachments on the Camel Exchange}."
+ " The options attachmentMultipartBinding=true and disableStreamCache=false cannot work together."
+ " Remove disableStreamCache to use AttachmentMultipartBinding."
+ " This is turn off by default as this may require servlet specific configuration to enable this when using Servlet's.")
private boolean attachmentMultipartBinding;
@Metadata(label = "consumer,advanced", description = "Whitelist of accepted filename extensions for accepting uploaded files."
+ " Multiple extensions can be separated by comma, such as txt,xml.")
private String fileNameExtWhitelist;
public ServletComponent() {
super(ServletEndpoint.class);
}
public ServletComponent(Class<? extends ServletEndpoint> endpointClass) {
super(endpointClass);
}
@Override
protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception {
// must extract well known parameters before we create the endpoint
Boolean throwExceptionOnFailure = getAndRemoveParameter(parameters, "throwExceptionOnFailure", Boolean.class);
Boolean transferException = getAndRemoveParameter(parameters, "transferException", Boolean.class);
Boolean bridgeEndpoint = getAndRemoveParameter(parameters, "bridgeEndpoint", Boolean.class);
HttpBinding binding = resolveAndRemoveReferenceParameter(parameters, "httpBinding", HttpBinding.class);
Boolean matchOnUriPrefix = getAndRemoveParameter(parameters, "matchOnUriPrefix", Boolean.class);
String servletName = getAndRemoveParameter(parameters, "servletName", String.class, getServletName());
String httpMethodRestrict = getAndRemoveParameter(parameters, "httpMethodRestrict", String.class);
HeaderFilterStrategy headerFilterStrategy = resolveAndRemoveReferenceParameter(parameters, "headerFilterStrategy", HeaderFilterStrategy.class);
Boolean async = getAndRemoveParameter(parameters, "async", Boolean.class);
Boolean attachmentMultipartBinding = getAndRemoveParameter(parameters, "attachmentMultipartBinding", Boolean.class);
Boolean disableStreamCache = getAndRemoveParameter(parameters, "disableStreamCache", Boolean.class);
if (lenientContextPath()) {
// the uri must have a leading slash for the context-path matching to work with servlet, and it can be something people
// forget to add and then the servlet consumer cannot match the context-path as would have been expected
String scheme = ObjectHelper.before(uri, ":");
String after = ObjectHelper.after(uri, ":");
// rebuild uri to have exactly one leading slash
while (after.startsWith("/")) {
after = after.substring(1);
}
after = "/" + after;
uri = scheme + ":" + after;
}
// restructure uri to be based on the parameters left as we dont want to include the Camel internal options
URI httpUri = URISupport.createRemainingURI(new URI(UnsafeUriCharactersEncoder.encodeHttpURI(uri)), parameters);
ServletEndpoint endpoint = createServletEndpoint(uri, this, httpUri);
endpoint.setServletName(servletName);
endpoint.setFileNameExtWhitelist(fileNameExtWhitelist);
if (async != null) {
endpoint.setAsync(async);
}
if (headerFilterStrategy != null) {
endpoint.setHeaderFilterStrategy(headerFilterStrategy);
} else {
setEndpointHeaderFilterStrategy(endpoint);
}
// prefer to use endpoint configured over component configured
if (binding == null) {
// fallback to component configured
binding = getHttpBinding();
}
if (binding != null) {
endpoint.setBinding(binding);
}
// should we use an exception for failed error codes?
if (throwExceptionOnFailure != null) {
endpoint.setThrowExceptionOnFailure(throwExceptionOnFailure);
}
// should we transfer exception as serialized object
if (transferException != null) {
endpoint.setTransferException(transferException);
}
if (bridgeEndpoint != null) {
endpoint.setBridgeEndpoint(bridgeEndpoint);
}
if (matchOnUriPrefix != null) {
endpoint.setMatchOnUriPrefix(matchOnUriPrefix);
}
if (httpMethodRestrict != null) {
endpoint.setHttpMethodRestrict(httpMethodRestrict);
}
if (attachmentMultipartBinding != null) {
endpoint.setAttachmentMultipartBinding(attachmentMultipartBinding);
} else {
endpoint.setAttachmentMultipartBinding(isAttachmentMultipartBinding());
}
if (disableStreamCache != null) {
endpoint.setDisableStreamCache(disableStreamCache);
}
// turn off stream caching if in attachment mode
if (endpoint.isAttachmentMultipartBinding()) {
if (disableStreamCache == null) {
// disableStreamCache not explicit configured so we can automatic change it
LOG.info("Disabling stream caching as attachmentMultipartBinding is enabled");
endpoint.setDisableStreamCache(true);
} else if (!disableStreamCache) {
throw new IllegalArgumentException("The options attachmentMultipartBinding=true and disableStreamCache=false cannot work together."
+ " Remove disableStreamCache to use AttachmentMultipartBinding");
}
}
setProperties(endpoint, parameters);
return endpoint;
}
/**
* Whether defining the context-path is lenient and do not require an exact leading slash.
*/
protected boolean lenientContextPath() {
return true;
}
/**
* Strategy to create the servlet endpoint.
*/
protected ServletEndpoint createServletEndpoint(String endpointUri, ServletComponent component, URI httpUri) throws Exception {
return new ServletEndpoint(endpointUri, component, httpUri);
}
@Override
public void connect(HttpConsumer consumer) throws Exception {
ServletConsumer sc = (ServletConsumer) consumer;
String name = sc.getEndpoint().getServletName();
HttpRegistry registry = httpRegistry;
if (registry == null) {
registry = DefaultHttpRegistry.getHttpRegistry(name);
}
registry.register(consumer);
}
@Override
public void disconnect(HttpConsumer consumer) throws Exception {
ServletConsumer sc = (ServletConsumer) consumer;
String name = sc.getEndpoint().getServletName();
HttpRegistry registry = httpRegistry;
if (registry == null) {
registry = DefaultHttpRegistry.getHttpRegistry(name);
}
registry.unregister(consumer);
}
public String getServletName() {
return servletName;
}
/**
* Default name of servlet to use. The default name is CamelServlet.
*/
public void setServletName(String servletName) {
this.servletName = servletName;
}
public HttpRegistry getHttpRegistry() {
return httpRegistry;
}
/**
* To use a custom org.apache.camel.component.servlet.HttpRegistry.
*/
public void setHttpRegistry(HttpRegistry httpRegistry) {
this.httpRegistry = httpRegistry;
}
public boolean isAttachmentMultipartBinding() {
return attachmentMultipartBinding;
}
/**
* Whether to automatic bind multipart/form-data as attachments on the Camel {@link Exchange}.
* <p/>
* The options attachmentMultipartBinding=true and disableStreamCache=false cannot work together.
* Remove disableStreamCache to use AttachmentMultipartBinding.
* <p/>
* This is turn off by default as this may require servlet specific configuration to enable this when using Servlet's.
*/
public void setAttachmentMultipartBinding(boolean attachmentMultipartBinding) {
this.attachmentMultipartBinding = attachmentMultipartBinding;
}
public String getFileNameExtWhitelist() {
return fileNameExtWhitelist;
}
/**
* Whitelist of accepted filename extensions for accepting uploaded files.
* <p/>
* Multiple extensions can be separated by comma, such as txt,xml.
*/
public void setFileNameExtWhitelist(String fileNameExtWhitelist) {
this.fileNameExtWhitelist = fileNameExtWhitelist;
}
@Override
public Consumer createConsumer(CamelContext camelContext, Processor processor, String verb, String basePath, String uriTemplate,
String consumes, String produces, RestConfiguration configuration, Map<String, Object> parameters) throws Exception {
return doCreateConsumer(camelContext, processor, verb, basePath, uriTemplate, consumes, produces, configuration, parameters, false);
}
@Override
public Consumer createApiConsumer(CamelContext camelContext, Processor processor, String contextPath,
RestConfiguration configuration, Map<String, Object> parameters) throws Exception {
// reuse the createConsumer method we already have. The api need to use GET and match on uri prefix
return doCreateConsumer(camelContext, processor, "GET", contextPath, null, null, null, configuration, parameters, true);
}
Consumer doCreateConsumer(CamelContext camelContext, Processor processor, String verb, String basePath, String uriTemplate,
String consumes, String produces, RestConfiguration configuration, Map<String, Object> parameters, boolean api) throws Exception {
String path = basePath;
if (uriTemplate != null) {
// make sure to avoid double slashes
if (uriTemplate.startsWith("/")) {
path = path + uriTemplate;
} else {
path = path + "/" + uriTemplate;
}
}
path = FileUtil.stripLeadingSeparator(path);
// if no explicit port/host configured, then use port from rest configuration
RestConfiguration config = configuration;
if (config == null) {
config = camelContext.getRestConfiguration("servlet", true);
}
Map<String, Object> map = new HashMap<>();
// build query string, and append any endpoint configuration properties
if (config.getComponent() == null || config.getComponent().equals("servlet")) {
// setup endpoint options
if (config.getEndpointProperties() != null && !config.getEndpointProperties().isEmpty()) {
map.putAll(config.getEndpointProperties());
}
}
boolean cors = config.isEnableCORS();
if (cors) {
// allow HTTP Options as we want to handle CORS in rest-dsl
map.put("optionsEnabled", "true");
}
// do not append with context-path as the servlet path should be without context-path
String query = URISupport.createQueryString(map);
String url;
if (api) {
url = "servlet:///%s?matchOnUriPrefix=true&httpMethodRestrict=%s";
} else {
url = "servlet:///%s?httpMethodRestrict=%s";
}
// must use upper case for restrict
String restrict = verb.toUpperCase(Locale.US);
if (cors) {
restrict += ",OPTIONS";
}
// get the endpoint
url = String.format(url, path, restrict);
if (!query.isEmpty()) {
url = url + "&" + query;
}
ServletEndpoint endpoint = camelContext.getEndpoint(url, ServletEndpoint.class);
setProperties(camelContext, endpoint, parameters);
if (!map.containsKey("httpBindingRef")) {
// use the rest binding, if not using a custom http binding
HttpBinding binding = new ServletRestHttpBinding();
binding.setHeaderFilterStrategy(endpoint.getHeaderFilterStrategy());
binding.setTransferException(endpoint.isTransferException());
binding.setEagerCheckContentAvailable(endpoint.isEagerCheckContentAvailable());
endpoint.setHttpBinding(binding);
}
// configure consumer properties
Consumer consumer = endpoint.createConsumer(processor);
if (config.getConsumerProperties() != null && !config.getConsumerProperties().isEmpty()) {
setProperties(camelContext, consumer, config.getConsumerProperties());
}
return consumer;
}
@Override
protected void doStart() throws Exception {
super.doStart();
RestConfiguration config = getCamelContext().getRestConfiguration("servlet", true);
// configure additional options on jetty configuration
if (config.getComponentProperties() != null && !config.getComponentProperties().isEmpty()) {
setProperties(this, config.getComponentProperties());
}
}
}
|
CAMEL-12785: ServletComponent ignores HttpBinding
|
components/camel-servlet/src/main/java/org/apache/camel/component/servlet/ServletComponent.java
|
CAMEL-12785: ServletComponent ignores HttpBinding
|
|
Java
|
bsd-3-clause
|
7f4dd34d322947992eea5b0591515b03dd736534
| 0
|
NCIP/cadsr-grid-dataservice,NCIP/cadsr-grid-dataservice
|
import gov.nih.nci.cagrid.cqlquery.CQLQuery;
import gov.nih.nci.cagrid.data.client.DataServiceClient;
import java.util.Iterator;
import gov.nih.nci.cagrid.common.Utils;
import gov.nih.nci.cagrid.cqlresultset.CQLQueryResults;
import gov.nih.nci.cagrid.data.utilities.CQLQueryResultsIterator;
import java.io.File;
import java.io.FilenameFilter;
public class CadsrDataServiceTest {
private String serviceUrl;
private String queryDirectory;
public CadsrDataServiceTest(String serviceUrl, String queryDirectory) {
this.serviceUrl = serviceUrl;
this.queryDirectory = queryDirectory;
}
private void performQuery() {
try {
// initialize the generic data service client
DataServiceClient client = new DataServiceClient(serviceUrl);
String[] filenames = new File(queryDirectory).list(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith(".xml");
}
});
if(filenames == null)
filenames = new String[0];
if(filenames.length == 0) {
System.out.println("No query files. Exiting");
System.exit(0);
}
for(String queryFilename : filenames) {
// deserialize the CQL query
CQLQuery query = (CQLQuery) Utils.deserializeDocument(queryDirectory + "/" + queryFilename, CQLQuery.class);
// execute the query on the data service
System.out.println("Querying file: " + queryFilename);
long l = new java.util.Date().getTime();
CQLQueryResults results = client.query(query);
l = (new java.util.Date().getTime() - l);
System.out.println("Time to run Query : " + l + " ms");
// create a results iterator
System.out.println("Iterating");
Iterator iter = new CQLQueryResultsIterator(results, true);
// iterate and print XML
System.out.println("-- RESULT --");
int i = 0;
while (iter.hasNext()) {
String value = (String) iter.next();
System.out.println(value);
System.out.print("+");
i++;
}
System.out.println("Nb of results: " + i);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* @param args
*/
public static void main(String[] args) {
if (args.length != 2) {
System.err.println("USAGE: <serviceUrl> <queryDirectory>");
System.exit(1);
}
CadsrDataServiceTest runner = new CadsrDataServiceTest(args[0], args[1]);
runner.performQuery();
}
}
|
test/src/CadsrDataServiceTest.java
|
import gov.nih.nci.cagrid.cqlquery.CQLQuery;
import gov.nih.nci.cagrid.data.client.DataServiceClient;
import java.util.Iterator;
import gov.nih.nci.cagrid.common.Utils;
import gov.nih.nci.cagrid.cqlresultset.CQLQueryResults;
import gov.nih.nci.cagrid.data.utilities.CQLQueryResultsIterator;
import java.io.File;
import java.io.FilenameFilter;
public class CadsrDataServiceTest {
private String serviceUrl;
private String queryDirectory;
public CadsrDataServiceTest(String serviceUrl, String queryDirectory) {
this.serviceUrl = serviceUrl;
this.queryDirectory = queryDirectory;
}
private void performQuery() {
try {
// initialize the generic data service client
DataServiceClient client = new DataServiceClient(serviceUrl);
String[] filenames = new File(queryDirectory).list(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith(".xml");
}
});
if(filenames == null)
filenames = new String[0];
if(filenames.length == 0) {
System.out.println("No query files. Exiting");
System.exit(0);
}
for(String queryFilename : filenames) {
// deserialize the CQL query
CQLQuery query = (CQLQuery) Utils.deserializeDocument(queryDirectory + "/" + queryFilename, CQLQuery.class);
// execute the query on the data service
System.out.println("Querying file: " + queryFilename);
long l = new java.util.Date().getTime();
CQLQueryResults results = client.query(query);
l = (new java.util.Date().getTime() - l);
System.out.println("Time to run Query : " + l + " ms");
// create a results iterator
System.out.println("Iterating");
Iterator iter = new CQLQueryResultsIterator(results, true);
// iterate and print XML
System.out.println("-- RESULT --");
while (iter.hasNext()) {
String value = (String) iter.next();
// System.out.println(value);
System.out.print("+");
}
System.out.println("");
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* @param args
*/
public static void main(String[] args) {
if (args.length != 2) {
System.err.println("USAGE: <serviceUrl> <queryDirectory>");
System.exit(1);
}
CadsrDataServiceTest runner = new CadsrDataServiceTest(args[0], args[1]);
runner.performQuery();
}
}
|
iterate over files
SVN-Revision: 29
|
test/src/CadsrDataServiceTest.java
|
iterate over files
|
|
Java
|
mit
|
17a683ae8318ea47542aa2f31ba44584b1c547ca
| 0
|
hazendaz/oshi,dbwiddis/oshi,jmazzitelli/oshi,pilhuhn/oshi,kamenitxan/oshi,cqse/oshi
|
/**
* Copyright (c) Daniel Doubrovkine, 2010 dblock[at]dblock[dot]org All Rights
* Reserved Eclipse Public License (EPLv1) http://oshi.codeplex.com/license
*/
package oshi;
import org.junit.Test;
import static org.junit.Assert.*;
import oshi.hardware.HardwareAbstractionLayer;
import oshi.hardware.Memory;
import oshi.hardware.Processor;
import oshi.software.os.OperatingSystem;
import oshi.software.os.OperatingSystemVersion;
import oshi.util.FormatUtil;
/**
* @author dblock[at]dblock[dot]org
*/
public class SystemInfoTest {
@Test
public void testGetVersion() {
SystemInfo si = new SystemInfo();
OperatingSystem os = si.getOperatingSystem();
assertNotNull(os);
OperatingSystemVersion version = os.getVersion();
assertNotNull(version);
assertTrue(os.toString().length() > 0);
}
@Test
public void testGetProcessors() {
SystemInfo si = new SystemInfo();
HardwareAbstractionLayer hal = si.getHardware();
assertTrue(hal.getProcessors().length > 0);
}
@Test
public void testGetMemory() {
SystemInfo si = new SystemInfo();
HardwareAbstractionLayer hal = si.getHardware();
Memory memory = hal.getMemory();
assertNotNull(memory);
assertTrue(memory.getTotal() > 0);
assertTrue(memory.getAvailable() >= 0);
assertTrue(memory.getAvailable() <= memory.getTotal());
}
@Test
public void testCpuLoad() {
SystemInfo si = new SystemInfo();
HardwareAbstractionLayer hal = si.getHardware();
assertTrue(hal.getProcessorLoad() >= 0 && hal.getProcessorLoad() <= 100);
}
public static void main(String[] args) {
SystemInfo si = new SystemInfo();
// software
// software: operating system
OperatingSystem os = si.getOperatingSystem();
System.out.println(os);
// hardware
HardwareAbstractionLayer hal = si.getHardware();
// hardware: processors
System.out.println(hal.getProcessors().length + " CPU(s):");
for (Processor cpu : hal.getProcessors()) {
System.out.println(" " + cpu);
}
// hardware: memory
System.out.println("Memory: "
+ FormatUtil.formatBytes(hal.getMemory().getAvailable()) + "/"
+ FormatUtil.formatBytes(hal.getMemory().getTotal()));
System.out.println("CPU load: " + hal.getProcessorLoad() + "%");
}
}
|
src/test/java/oshi/SystemInfoTest.java
|
/**
* Copyright (c) Daniel Doubrovkine, 2010 dblock[at]dblock[dot]org All Rights
* Reserved Eclipse Public License (EPLv1) http://oshi.codeplex.com/license
*/
package oshi;
import org.junit.Test;
import static org.junit.Assert.*;
import oshi.hardware.HardwareAbstractionLayer;
import oshi.hardware.Memory;
import oshi.hardware.Processor;
import oshi.software.os.OperatingSystem;
import oshi.software.os.OperatingSystemVersion;
import oshi.util.FormatUtil;
/**
* @author dblock[at]dblock[dot]org
*/
public class SystemInfoTest {
@Test
public void testGetVersion() {
SystemInfo si = new SystemInfo();
OperatingSystem os = si.getOperatingSystem();
assertNotNull(os);
OperatingSystemVersion version = os.getVersion();
assertNotNull(version);
assertTrue(os.toString().length() > 0);
}
@Test
public void testGetProcessors() {
SystemInfo si = new SystemInfo();
HardwareAbstractionLayer hal = si.getHardware();
assertTrue(hal.getProcessors().length > 0);
}
@Test
public void testGetMemory() {
SystemInfo si = new SystemInfo();
HardwareAbstractionLayer hal = si.getHardware();
Memory memory = hal.getMemory();
assertNotNull(memory);
assertTrue(memory.getTotal() > 0);
assertTrue(memory.getAvailable() >= 0);
assertTrue(memory.getAvailable() <= memory.getTotal());
}
@Test
public void testCpuLoad() {
SystemInfo si = new SystemInfo();
HardwareAbstractionLayer hal = si.getHardware();
assertTrue(hal.getProcessorLoad() >= 0 && hal.getProcessorLoad() <= 100);
}
public static void main(String[] args) {
SystemInfo si = new SystemInfo();
// software
// software: operating system
OperatingSystem os = si.getOperatingSystem();
System.out.println(os);
// hardware
HardwareAbstractionLayer hal = si.getHardware();
// hardware: processors
System.out.println(hal.getProcessors().length + " CPU(s):");
for (Processor cpu : hal.getProcessors()) {
System.out.println(" " + cpu);
}
// hardware: memory
System.out.println("Memory: "
+ FormatUtil.formatBytes(hal.getMemory().getAvailable()) + "/"
+ FormatUtil.formatBytes(hal.getMemory().getTotal()));
hal.getProcessors()[0].getVendor();
System.out.println("CPU load: " + hal.getProcessorLoad() + "%");
}
}
|
no message
|
src/test/java/oshi/SystemInfoTest.java
|
no message
|
|
Java
|
mit
|
188d487405aab4e9c315aea820d5a403af3b006d
| 0
|
handschuh/Slight-backup
|
/**
* Copyright (c) 2011 Stefan Handschuh
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
package de.shandschuh.slightbackup.exporter;
import java.io.IOException;
import java.io.Writer;
import android.database.Cursor;
import de.shandschuh.slightbackup.BackupActivity;
import de.shandschuh.slightbackup.R;
import de.shandschuh.slightbackup.Strings;
public class MessageExporter extends SimpleExporter {
public static final int ID = 3;
public static final int NAMEID = R.string.messages;
private int bodyPosition;
public MessageExporter(ExportTask exportTask) {
super(Strings.TAG_MESSAGE, Strings.SMS_FIELDS, BackupActivity.SMS_URI, true, "1 order by date", exportTask);
bodyPosition = -1;
}
@Override
public void addText(Cursor cursor, Writer writer) throws IOException {
if (bodyPosition == -1) {
bodyPosition = cursor.getColumnIndex(Strings.BODY);
}
writer.write(cursor.getString(bodyPosition).replace("&", "&").replace("<", "<").replace(">", ">"));
}
@Override
public boolean checkFieldNames(String[] availableFieldNames, String[] neededFieldNames) {
return super.checkFieldNames(availableFieldNames, neededFieldNames)
&& Strings.indexOf(availableFieldNames, Strings.BODY) > -1;
}
@Override
public String getContentName() {
return Strings.MESSAGES;
}
@Override
public int getId() {
return ID;
}
@Override
public int getTranslatedContentName() {
return NAMEID;
}
}
|
src/de/shandschuh/slightbackup/exporter/MessageExporter.java
|
/**
* Copyright (c) 2011 Stefan Handschuh
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
package de.shandschuh.slightbackup.exporter;
import java.io.IOException;
import java.io.Writer;
import android.database.Cursor;
import de.shandschuh.slightbackup.BackupActivity;
import de.shandschuh.slightbackup.R;
import de.shandschuh.slightbackup.Strings;
public class MessageExporter extends SimpleExporter {
public static final int ID = 3;
public static final int NAMEID = R.string.messages;
private int bodyPosition;
public MessageExporter(ExportTask exportTask) {
super(Strings.TAG_MESSAGE, Strings.SMS_FIELDS, BackupActivity.SMS_URI, true, exportTask);
bodyPosition = -1;
}
@Override
public void addText(Cursor cursor, Writer writer) throws IOException {
if (bodyPosition == -1) {
bodyPosition = cursor.getColumnIndex(Strings.BODY);
}
writer.write(cursor.getString(bodyPosition).replace("&", "&").replace("<", "<").replace(">", ">"));
}
@Override
public boolean checkFieldNames(String[] availableFieldNames, String[] neededFieldNames) {
return super.checkFieldNames(availableFieldNames, neededFieldNames)
&& Strings.indexOf(availableFieldNames, Strings.BODY) > -1;
}
@Override
public String getContentName() {
return Strings.MESSAGES;
}
@Override
public int getId() {
return ID;
}
@Override
public int getTranslatedContentName() {
return NAMEID;
}
}
|
Adds sorting to message exporter.
|
src/de/shandschuh/slightbackup/exporter/MessageExporter.java
|
Adds sorting to message exporter.
|
|
Java
|
mit
|
132ce97680aeb931e963a31a872506b6eb8ba672
| 0
|
IngSW-unipv/GoldRush
|
/*
* Code used in the "Software Engineering" course.
*
* Copyright 2017 by Claudio Cusano (claudio.cusano@unipv.it)
* Dept of Electrical, Computer and Biomedical Engineering,
* University of Pavia.
*/
package goldrush;
/**
*
* @author cl427490
*/
public class ZobeerMohammad extends GoldDigger{
int day;
int scelta = 0;
int revPass;
int[] punti = {0,0,0,0,0,0};
public ZobeerMohammad() {
day=0;
}
@Override
public int chooseDiggingSite(int[] distances) {
//in collaborazione
return new AndreaRossi().chooseDiggingSite(distances);
}
public void dailyOutcome(int revenue, int[] distances, int[] diggers) {
}
}
|
GoldRush/src/goldrush/ZobeerMohammad.java
|
/*
* Code used in the "Software Engineering" course.
*
* Copyright 2017 by Claudio Cusano (claudio.cusano@unipv.it)
* Dept of Electrical, Computer and Biomedical Engineering,
* University of Pavia.
*/
package goldrush;
/**
*
* @author cl427490
*/
public class ZobeerMohammad extends GoldDigger{
int day;
int scelta = 0;
int revPass;
int[] punti = {0,0,0,0,0,0};
public ZobeerMohammad() {
day=0;
}
@Override
public int chooseDiggingSite(int[] distances) {
//in collaborazione
return new AndreaRossi().chooseDiggingSite(distances);
}
public void dailyOutcome(int revenue, int[] distances, int[] diggers) {
}
}
|
finito di Mohammad Zubeer
|
GoldRush/src/goldrush/ZobeerMohammad.java
|
finito di Mohammad Zubeer
|
|
Java
|
mit
|
0fa8951b401e473d30f8a98d64a95a264fcaeb52
| 0
|
jbosboom/streamjit,jbosboom/streamjit
|
package edu.mit.streamjit.impl.distributed.node;
import java.io.EOFException;
import java.io.IOException;
import edu.mit.streamjit.impl.distributed.common.Command;
import edu.mit.streamjit.impl.distributed.common.Connection;
import edu.mit.streamjit.impl.distributed.common.ConnectionFactory;
import edu.mit.streamjit.impl.distributed.common.GlobalConstants;
import edu.mit.streamjit.impl.distributed.common.Ipv4Validator;
import edu.mit.streamjit.impl.distributed.common.MessageElement;
import edu.mit.streamjit.impl.distributed.common.MessageVisitor;
import edu.mit.streamjit.impl.distributed.common.MessageVisitorImpl;
import edu.mit.streamjit.impl.distributed.runtimer.Controller;
/**
* In StreamJit's jargon "Stream node" means a computing node that runs part or
* full a streamJit application. </p> Here, the class StreamNode is a
* StreamJit's run timer for each distributed node. So StreamNode is singleton
* pattern as there can be only one StreamNode instance per computing node. Once
* it got connected with the {@link Controller}, it will keep on listening and
* processing the commands from the Controller. Controller can issue the
* {@link Command} EXIT to stop the streamNode.
*
* @author Sumanan sumanan@mit.edu
* @since May 10, 2013
*/
public class StreamNode extends Thread {
/**
* Lets keep this as package public (default) for the moment.
*/
Connection controllerConnection;
private int myNodeID = -1; // TODO: consider move or remove this from
// StreamNode class. If so, this class will be
// more handy.
private MessageVisitor mv;
private BlobsManager blobsManager;
private boolean run; // As we assume that all controller communication and
// the MessageElement processing is managed by
// single
// thread,
// no need to make this variable thread safe.
private static StreamNode myinstance;
/**
* Thread safe way of Singleton pattern.
*/
public static StreamNode getInstance(Connection connection) {
if (myinstance == null) {
synchronized (StreamNode.class) {
if (myinstance == null)
myinstance = new StreamNode(connection);
}
}
return myinstance;
}
/**
* {@link StreamNode} is Singleton pattern in order to ensure one instance
* per JVM..
*/
private StreamNode(Connection connection) {
super("Stream Node");
this.controllerConnection = connection;
this.mv = new MessageVisitorImpl(new SNAppStatusProcessorImpl(),
new SNCommandProcessorImpl(this), new SNErrorProcessorImpl(),
new SNRequestProcessorImpl(this), new SNCfgStringProcessorImpl(
this), new SNDrainProcessorImpl(this),
new SNNodeInfoProcessorImpl());
this.run = true;
}
public void run() {
while (run) {
try {
MessageElement me = controllerConnection.readObject();
me.accept(mv);
} catch (ClassNotFoundException e) {
// No way. Just ignore.
} catch (EOFException e) {
// Other side closed
run = false;
} catch (IOException e) {
e.printStackTrace();
// TODO: Need to decide what to do here. May be we can re try
// couple of time in a time interval before aborting the
// execution.
run = false;
}
}
try {
this.controllerConnection.closeConnection();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public int getNodeID() {
return myNodeID;
}
public void setNodeID(int nodeID) {
this.myNodeID = nodeID;
System.out.println("I have got my node ID: " + this.myNodeID);
Thread.currentThread().setName(this.tostString());
}
/**
* @return the blobsManager
*/
public BlobsManager getBlobsManager() {
return blobsManager;
}
/**
* @param blobsManager
* the blobsManager to set
*/
public void setBlobsManager(BlobsManager blobsManager) {
this.blobsManager = blobsManager;
}
public void exit() {
this.run = false;
}
public String tostString() {
return "StreamNode-" + myNodeID;
}
/**
* @param args
*/
public static void main(String[] args) {
String ipAddress;
int portNo = 0;
switch (args.length) {
case 1 :
ipAddress = args[0];
portNo = GlobalConstants.PORTNO;
break;
case 2 :
ipAddress = args[0];
try {
portNo = Integer.parseInt(args[1]);
} catch (NumberFormatException ex) {
System.err.println("Invalid port No...");
System.err.println("Please verify the second argument.");
System.exit(0);
}
break;
default :
ipAddress = "127.0.0.1";
portNo = GlobalConstants.PORTNO;
}
if (!Ipv4Validator.getInstance().isValid(ipAddress)) {
System.err.println("Invalid IP address...");
System.err.println("Please verify the first argument.");
System.exit(0);
}
if (portNo < 1024) {
System.err
.println("Wellknown port number has been used. Please consider avoid using it");
} else if (portNo > 65535) {
System.err.println("Invalid port no...");
System.exit(0);
}
Connection tcpConnection;
try {
tcpConnection = ConnectionFactory.getConnection(ipAddress, portNo);
new StreamNode(tcpConnection).run();
} catch (IOException e) {
e.printStackTrace();
System.out
.println("Creating connection with the controller failed.");
}
}
}
|
src/edu/mit/streamjit/impl/distributed/node/StreamNode.java
|
package edu.mit.streamjit.impl.distributed.node;
import java.io.EOFException;
import java.io.IOException;
import edu.mit.streamjit.impl.distributed.common.Command;
import edu.mit.streamjit.impl.distributed.common.Connection;
import edu.mit.streamjit.impl.distributed.common.ConnectionFactory;
import edu.mit.streamjit.impl.distributed.common.GlobalConstants;
import edu.mit.streamjit.impl.distributed.common.Ipv4Validator;
import edu.mit.streamjit.impl.distributed.common.MessageElement;
import edu.mit.streamjit.impl.distributed.common.MessageVisitor;
import edu.mit.streamjit.impl.distributed.common.MessageVisitorImpl;
import edu.mit.streamjit.impl.distributed.runtimer.Controller;
/**
* In StreamJit's jargon "Stream node" means a computing node that runs part or
* full a streamJit application. </p> Here, the class StreamNode is a
* StreamJit's run timer for each distributed node. So StreamNode is singleton
* pattern as there can be only one StreamNode instance per computing node. Once
* it got connected with the {@link Controller}, it will keep on listening and
* processing the commands from the Controller. Controller can issue the
* {@link Command} EXIT to stop the streamNode.
*
* @author Sumanan sumanan@mit.edu
* @since May 10, 2013
*/
public class StreamNode extends Thread {
/**
* Lets keep this as package public (default) for the moment.
*/
Connection controllerConnection;
private int myNodeID = -1; // TODO: consider move or remove this from
// StreamNode class. If so, this class will be
// more handy.
private MessageVisitor mv;
private BlobsManager blobsManager;
private boolean run; // As we assume that all controller communication and
// the MessageElement processing is managed by
// single
// thread,
// no need to make this variable thread safe.
private static StreamNode myinstance;
/**
* Thread safe way of Singleton pattern.
*/
public static StreamNode getInstance(Connection connection) {
if (myinstance == null) {
synchronized (StreamNode.class) {
if (myinstance == null)
myinstance = new StreamNode(connection);
}
}
return myinstance;
}
/**
* {@link StreamNode} is Singleton pattern in order to ensure one instance
* per JVM..
*/
private StreamNode(Connection connection) {
super("Stream Node");
this.controllerConnection = connection;
this.mv = new MessageVisitorImpl(new SNAppStatusProcessorImpl(),
new SNCommandProcessorImpl(this), new SNErrorProcessorImpl(),
new SNRequestProcessorImpl(this), new SNCfgStringProcessorImpl(
this), new SNDrainProcessorImpl(this),
new SNNodeInfoProcessorImpl());
this.run = true;
}
public void run() {
while (run) {
try {
MessageElement me = controllerConnection.readObject();
me.accept(mv);
} catch (ClassNotFoundException e) {
// No way. Just ignore.
} catch (EOFException e) {
// Other side closed
run = false;
} catch (IOException e) {
e.printStackTrace();
// TODO: Need to decide what to do here. May be we can re try
// couple of time in a time interval before aborting the
// execution.
run = false;
}
}
try {
this.controllerConnection.closeConnection();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public int getNodeID() {
return myNodeID;
}
public void setNodeID(int nodeID) {
this.myNodeID = nodeID;
System.out.println("I have got my node ID: " + this.myNodeID);
Thread.currentThread().setName(this.tostString());
}
/**
* @return the blobsManager
*/
public BlobsManager getBlobsManager() {
return blobsManager;
}
/**
* @param blobsManager
* the blobsManager to set
*/
public void setBlobsManager(BlobsManager blobsManager) {
this.blobsManager = blobsManager;
}
public void exit() {
this.run = false;
}
public String tostString() {
return "StreamNode-" + myNodeID;
}
/**
* @param args
*/
public static void main(String[] args) {
String ipAddress;
int portNo = 0;
switch (args.length) {
case 1 :
ipAddress = args[0];
portNo = GlobalConstants.PORTNO;
break;
case 2 :
ipAddress = args[0];
try {
portNo = Integer.parseInt(args[1]);
} catch (NumberFormatException ex) {
System.err.println("Invalid port No...");
System.err.println("Please verify the second argument.");
System.exit(0);
}
break;
default :
ipAddress = "127.0.0.1";
portNo = GlobalConstants.PORTNO;
}
if (!Ipv4Validator.getInstance().isValid(ipAddress)) {
System.err.println("Invalid IP address...");
System.err.println("Please verify the first argument.");
System.exit(0);
}
if (portNo < 1024) {
System.err
.println("Wellknown port number has been used. Please consider avoid using it");
} else if (portNo > 65535) {
System.err.println("Invalid port no...");
System.exit(0);
}
ConnectionFactory cf = new ConnectionFactory();
Connection tcpConnection;
try {
tcpConnection = cf.getConnection(ipAddress, portNo);
new StreamNode(tcpConnection).run();
} catch (IOException e) {
e.printStackTrace();
System.out
.println("Creating connection with the controller failed.");
}
}
}
|
Static methods are called by referring the class
|
src/edu/mit/streamjit/impl/distributed/node/StreamNode.java
|
Static methods are called by referring the class
|
|
Java
|
mit
|
a1e2d98a09a205b7745b8094d79e9f1bfc6fde29
| 0
|
RTLSponge/SpongeCommon,DDoS/SpongeCommon,SpongePowered/SpongeCommon,modwizcode/SpongeCommon,kenzierocks/SpongeCommon,JBYoshi/SpongeCommon,ryantheleach/SpongeCommon,sanman00/SpongeCommon,Grinch/SpongeCommon,SpongePowered/Sponge,RTLSponge/SpongeCommon,SpongePowered/Sponge,sanman00/SpongeCommon,SpongePowered/Sponge,Grinch/SpongeCommon,modwizcode/SpongeCommon,SpongePowered/SpongeCommon,clienthax/SpongeCommon,kenzierocks/SpongeCommon,DDoS/SpongeCommon,clienthax/SpongeCommon,ryantheleach/SpongeCommon,JBYoshi/SpongeCommon
|
/*
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.common.event;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import net.minecraft.block.Block;
import net.minecraft.block.BlockLiquid;
import net.minecraft.block.state.IBlockState;
import net.minecraft.crash.CrashReport;
import net.minecraft.crash.CrashReportCategory;
import net.minecraft.entity.EntityHanging;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.effect.EntityLightningBolt;
import net.minecraft.entity.effect.EntityWeatherEffect;
import net.minecraft.entity.item.EntityArmorStand;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.item.EntityItemFrame;
import net.minecraft.entity.item.EntityTNTPrimed;
import net.minecraft.entity.passive.EntityTameable;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.entity.projectile.EntityFishHook;
import net.minecraft.entity.projectile.EntityThrowable;
import net.minecraft.init.Blocks;
import net.minecraft.inventory.Slot;
import net.minecraft.network.Packet;
import net.minecraft.network.play.client.C01PacketChatMessage;
import net.minecraft.network.play.client.C03PacketPlayer;
import net.minecraft.network.play.client.C07PacketPlayerDigging;
import net.minecraft.network.play.client.C08PacketPlayerBlockPlacement;
import net.minecraft.network.play.client.C0EPacketClickWindow;
import net.minecraft.network.play.client.C10PacketCreativeInventoryAction;
import net.minecraft.network.play.server.S23PacketBlockChange;
import net.minecraft.network.play.server.S2FPacketSetSlot;
import net.minecraft.stats.StatList;
import net.minecraft.util.BlockPos;
import net.minecraft.util.DamageSource;
import net.minecraft.util.EntityDamageSource;
import net.minecraft.util.MathHelper;
import net.minecraft.util.ReportedException;
import net.minecraft.world.chunk.EmptyChunk;
import org.spongepowered.api.block.BlockSnapshot;
import org.spongepowered.api.block.tileentity.TileEntity;
import org.spongepowered.api.data.Transaction;
import org.spongepowered.api.entity.Entity;
import org.spongepowered.api.entity.EntitySnapshot;
import org.spongepowered.api.entity.Item;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.entity.living.player.User;
import org.spongepowered.api.event.SpongeEventFactory;
import org.spongepowered.api.event.action.LightningEvent;
import org.spongepowered.api.event.block.ChangeBlockEvent;
import org.spongepowered.api.event.cause.Cause;
import org.spongepowered.api.event.cause.NamedCause;
import org.spongepowered.api.event.cause.entity.damage.source.IndirectEntityDamageSource;
import org.spongepowered.api.event.cause.entity.spawn.EntitySpawnCause;
import org.spongepowered.api.event.cause.entity.spawn.SpawnCause;
import org.spongepowered.api.event.cause.entity.spawn.SpawnType;
import org.spongepowered.api.event.cause.entity.spawn.SpawnTypes;
import org.spongepowered.api.event.entity.DestructEntityEvent;
import org.spongepowered.api.event.entity.SpawnEntityEvent;
import org.spongepowered.api.event.item.inventory.DropItemEvent;
import org.spongepowered.api.event.message.MessageEvent;
import org.spongepowered.api.text.channel.MessageChannel;
import org.spongepowered.api.world.World;
import org.spongepowered.common.SpongeImpl;
import org.spongepowered.common.SpongeImplHooks;
import org.spongepowered.common.block.SpongeBlockSnapshot;
import org.spongepowered.common.data.util.NbtDataUtil;
import org.spongepowered.common.entity.PlayerTracker;
import org.spongepowered.common.interfaces.IMixinChunk;
import org.spongepowered.common.interfaces.entity.IMixinEntity;
import org.spongepowered.common.interfaces.entity.IMixinEntityLightningBolt;
import org.spongepowered.common.interfaces.world.IMixinWorld;
import org.spongepowered.common.util.SpongeHooks;
import org.spongepowered.common.util.StaticMixinHelper;
import org.spongepowered.common.util.VecHelper;
import org.spongepowered.common.world.CaptureType;
import org.spongepowered.common.world.SpongeProxyBlockAccess;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Optional;
import java.util.Random;
import javax.annotation.Nullable;
public final class CauseTracker {
private final net.minecraft.world.World targetWorld;
private boolean processingCaptureCause = false;
private boolean processingBlockRandomTicks = false;
private boolean captureEntitySpawns = true;
private boolean captureBlockDecay = false;
private boolean captureTerrainGen = false;
private boolean captureBlocks = false;
private boolean captureCommand = false;
private boolean restoringBlocks = false;
private boolean spawningDeathDrops = false;
private List<Entity> capturedEntities = new ArrayList<>();
private List<Entity> capturedEntityItems = new ArrayList<>();
@Nullable private BlockSnapshot currentTickBlock;
@Nullable private Entity currentTickEntity;
@Nullable private TileEntity currentTickTileEntity;
@Nullable private Cause pluginCause;
private List<BlockSnapshot> capturedSpongeBlockSnapshots = new ArrayList<>();
private List<Transaction<BlockSnapshot>> invalidTransactions = new ArrayList<>();
private boolean worldSpawnerRunning;
private boolean chunkSpawnerRunning;
public CauseTracker(net.minecraft.world.World targetWorld) {
this.targetWorld = targetWorld;
}
public World getWorld() {
return (World) this.targetWorld;
}
public net.minecraft.world.World getMinecraftWorld() {
return this.targetWorld;
}
public IMixinWorld getMixinWorld() {
return (IMixinWorld) this.targetWorld;
}
public boolean isProcessingCaptureCause() {
return this.processingCaptureCause;
}
public void setProcessingCaptureCause(boolean processingCaptureCause) {
this.processingCaptureCause = processingCaptureCause;
}
public boolean isProcessingBlockRandomTicks() {
return this.processingBlockRandomTicks;
}
public void setProcessingBlockRandomTicks(boolean processingBlockRandomTicks) {
this.processingBlockRandomTicks = processingBlockRandomTicks;
}
public boolean isCaptureEntitySpawns() {
return this.captureEntitySpawns;
}
public void setCaptureEntitySpawns(boolean captureEntitySpawns) {
this.captureEntitySpawns = captureEntitySpawns;
}
public boolean isCaptureBlockDecay() {
return this.captureBlockDecay;
}
public void setCapturingBlockDecay(boolean captureBlockDecay) {
this.captureBlockDecay = captureBlockDecay;
}
public boolean isCapturingTerrainGen() {
return this.captureTerrainGen;
}
public void setCapturingTerrainGen(boolean captureTerrainGen) {
this.captureTerrainGen = captureTerrainGen;
}
public boolean isCapturingBlocks() {
return this.captureBlocks;
}
public void setCaptureBlocks(boolean captureBlocks) {
this.captureBlocks = captureBlocks;
}
public boolean isCaptureCommand() {
return this.captureCommand;
}
public void setCapturingCommand(boolean captureCommand) {
this.captureCommand = captureCommand;
}
public boolean isRestoringBlocks() {
return this.restoringBlocks;
}
public void setRestoringBlocks(boolean restoringBlocks) {
this.restoringBlocks = restoringBlocks;
}
public boolean isSpawningDeathDrops() {
return this.spawningDeathDrops;
}
public void setSpawningDeathDrops(boolean spawningDeathDrops) {
this.spawningDeathDrops = spawningDeathDrops;
}
public List<Entity> getCapturedEntities() {
return this.capturedEntities;
}
public List<Entity> getCapturedEntityItems() {
return this.capturedEntityItems;
}
public boolean hasTickingBlock() {
return this.currentTickBlock != null;
}
public Optional<BlockSnapshot> getCurrentTickBlock() {
return Optional.ofNullable(this.currentTickBlock);
}
public void setCurrentTickBlock(@Nullable BlockSnapshot currentTickBlock) {
this.currentTickBlock = currentTickBlock;
}
public boolean hasTickingEntity() {
return this.currentTickEntity != null;
}
public Optional<Entity> getCurrentTickEntity() {
return Optional.ofNullable(this.currentTickEntity);
}
public void setCurrentTickEntity(@Nullable Entity currentTickEntity) {
this.currentTickEntity = currentTickEntity;
}
public boolean hasTickingTileEntity() {
return this.currentTickTileEntity != null;
}
public Optional<TileEntity> getCurrentTickTileEntity() {
return Optional.ofNullable(this.currentTickTileEntity);
}
public void setCurrentTickTileEntity(TileEntity currentTickTileEntity) {
this.currentTickTileEntity = currentTickTileEntity;
}
public List<BlockSnapshot> getCapturedSpongeBlockSnapshots() {
return this.capturedSpongeBlockSnapshots;
}
public List<Transaction<BlockSnapshot>> getInvalidTransactions() {
return this.invalidTransactions;
}
public void setInvalidTransactions(List<Transaction<BlockSnapshot>> invalidTransactions) {
this.invalidTransactions = invalidTransactions;
}
public boolean isWorldSpawnerRunning() {
return this.worldSpawnerRunning;
}
public void setWorldSpawnerRunning(boolean worldSpawnerRunning) {
this.worldSpawnerRunning = worldSpawnerRunning;
}
public boolean isChunkSpawnerRunning() {
return this.chunkSpawnerRunning;
}
public void setChunkSpawnerRunning(boolean chunkSpawnerRunning) {
this.chunkSpawnerRunning = chunkSpawnerRunning;
}
public Optional<Cause> getPluginCause() {
return Optional.ofNullable(this.pluginCause);
}
public void setPluginCause(@Nullable Cause pluginCause) {
this.pluginCause = pluginCause;
}
public boolean hasPluginCause() {
return this.pluginCause != null;
}
public void handleEntitySpawns(Cause cause) {
Iterator<Entity> iter = this.capturedEntities.iterator();
ImmutableList.Builder<EntitySnapshot> entitySnapshotBuilder = new ImmutableList.Builder<>();
while (iter.hasNext()) {
Entity currentEntity = iter.next();
if (this.invalidTransactions != null) {
// check to see if this spawn is invalid and if so, remove
boolean invalid = false;
for (Transaction<BlockSnapshot> blockSnapshot : this.invalidTransactions) {
if (blockSnapshot.getOriginal().getLocation().get().getBlockPosition().equals(currentEntity.getLocation().getBlockPosition())) {
invalid = true;
iter.remove();
break;
}
}
if (invalid) {
continue;
}
}
if (cause.first(User.class).isPresent()) {
// store user UUID with entity to track later
User user = cause.first(User.class).get();
((IMixinEntity) currentEntity).trackEntityUniqueId(NbtDataUtil.SPONGE_ENTITY_CREATOR, user.getUniqueId());
} else if (cause.first(Entity.class).isPresent()) {
IMixinEntity spongeEntity = (IMixinEntity) cause.first(Entity.class).get();
Optional<User> owner = spongeEntity.getTrackedPlayer(NbtDataUtil.SPONGE_ENTITY_CREATOR);
if (owner.isPresent() && !cause.containsNamed(NamedCause.OWNER)) {
cause = cause.with(NamedCause.of(NamedCause.OWNER, owner.get()));
((IMixinEntity) currentEntity).trackEntityUniqueId(NbtDataUtil.SPONGE_ENTITY_CREATOR, owner.get().getUniqueId());
}
}
entitySnapshotBuilder.add(currentEntity.createSnapshot());
}
List<EntitySnapshot> entitySnapshots = entitySnapshotBuilder.build();
if (entitySnapshots.isEmpty()) {
return;
}
SpawnEntityEvent event;
if (this.worldSpawnerRunning) {
event = SpongeEventFactory.createSpawnEntityEventSpawner(cause, this.capturedEntities, entitySnapshots, this.getWorld());
} else if (this.chunkSpawnerRunning) {
event = SpongeEventFactory.createSpawnEntityEventChunkLoad(cause, this.capturedEntities, entitySnapshots, this.getWorld());
} else {
List<NamedCause> namedCauses = new ArrayList<>();
for (Map.Entry<String, Object> entry : cause.getNamedCauses().entrySet()) {
if (entry.getKey().equalsIgnoreCase(NamedCause.SOURCE)) {
if (!(entry.getValue() instanceof SpawnCause)) {
namedCauses.add(NamedCause.source(SpawnCause.builder().type(SpawnTypes.CUSTOM).build()));
} else {
namedCauses.add(NamedCause.source(entry.getValue()));
}
} else {
namedCauses.add(NamedCause.of(entry.getKey(), entry.getValue()));
}
}
cause = Cause.of(namedCauses);
event = SpongeEventFactory.createSpawnEntityEvent(cause, this.capturedEntities, entitySnapshotBuilder.build(), this.getWorld());
}
boolean wasProcessing = this.processingCaptureCause;
this.processingCaptureCause = false;
if (!(SpongeImpl.postEvent(event))) {
Iterator<Entity> iterator = event.getEntities().iterator();
while (iterator.hasNext()) {
Entity entity = iterator.next();
if (entity.isRemoved()) { // Entity removed in an event handler
iterator.remove();
continue;
}
net.minecraft.entity.Entity nmsEntity = (net.minecraft.entity.Entity) entity;
if (nmsEntity instanceof EntityWeatherEffect) {
addWeatherEffect(nmsEntity, cause);
} else {
int x = MathHelper.floor_double(nmsEntity.posX / 16.0D);
int z = MathHelper.floor_double(nmsEntity.posZ / 16.0D);
this.getMinecraftWorld().getChunkFromChunkCoords(x, z).addEntity(nmsEntity);
this.getMinecraftWorld().loadedEntityList.add(nmsEntity);
this.getMixinWorld().onSpongeEntityAdded(nmsEntity);
SpongeHooks.logEntitySpawn(cause, nmsEntity);
}
iterator.remove();
}
} else {
this.capturedEntities.clear();
}
this.processingCaptureCause = wasProcessing;
}
public void handlePostTickCaptures(Cause cause) {
if (this.getMinecraftWorld().isRemote || this.restoringBlocks || this.spawningDeathDrops || cause == null) {
return;
} else if (this.capturedEntities.size() == 0 && this.capturedEntityItems.size() == 0 && this.capturedSpongeBlockSnapshots.size() == 0
&& StaticMixinHelper.packetPlayer == null) {
return; // nothing was captured, return
}
EntityPlayerMP player = StaticMixinHelper.packetPlayer;
Packet<?> packetIn = StaticMixinHelper.processingPacket;
// Attempt to find a Player cause if we do not have one
if (!cause.first(User.class).isPresent() && !(this.capturedSpongeBlockSnapshots.size() > 0
&& ((SpongeBlockSnapshot) this.capturedSpongeBlockSnapshots.get(0)).captureType
== CaptureType.DECAY)) {
if ((cause.first(BlockSnapshot.class).isPresent() || cause.first(TileEntity.class).isPresent())) {
// Check for player at pos of first transaction
Optional<BlockSnapshot> snapshot = cause.first(BlockSnapshot.class);
Optional<TileEntity> te = cause.first(TileEntity.class);
BlockPos pos = null;
if (snapshot.isPresent()) {
pos = VecHelper.toBlockPos(snapshot.get().getPosition());
} else {
pos = ((net.minecraft.tileentity.TileEntity) te.get()).getPos();
}
net.minecraft.world.chunk.Chunk chunk = this.getMinecraftWorld().getChunkFromBlockCoords(pos);
if (chunk != null) {
IMixinChunk spongeChunk = (IMixinChunk) chunk;
Optional<User> owner = spongeChunk.getBlockOwner(pos);
Optional<User> notifier = spongeChunk.getBlockNotifier(pos);
if (notifier.isPresent() && !cause.containsNamed(NamedCause.NOTIFIER)) {
cause = cause.with(NamedCause.notifier(notifier.get()));
}
if (owner.isPresent() && !cause.containsNamed(NamedCause.OWNER)) {
cause = cause.with(NamedCause.owner(owner.get()));
}
}
} else if (cause.first(Entity.class).isPresent()) {
Entity entity = cause.first(Entity.class).get();
if (entity instanceof EntityTameable) {
EntityTameable tameable = (EntityTameable) entity;
if (tameable.getOwner() != null && !cause.containsNamed(NamedCause.OWNER)) {
cause = cause.with(NamedCause.owner(tameable.getOwner()));
}
} else {
Optional<User> owner = ((IMixinEntity) entity).getTrackedPlayer(NbtDataUtil.SPONGE_ENTITY_CREATOR);
if (owner.isPresent() && !cause.contains(NamedCause.OWNER)) {
cause = cause.with(NamedCause.owner(owner.get()));
}
}
}
}
// Handle Block Captures
handleBlockCaptures(cause);
// Handle Player Toss
if (player != null && packetIn instanceof C07PacketPlayerDigging) {
C07PacketPlayerDigging digPacket = (C07PacketPlayerDigging) packetIn;
if (digPacket.getStatus() == C07PacketPlayerDigging.Action.DROP_ITEM) {
StaticMixinHelper.destructItemDrop = false;
}
}
// Handle Player kill commands
if (player != null && packetIn instanceof C01PacketChatMessage) {
C01PacketChatMessage chatPacket = (C01PacketChatMessage) packetIn;
if (chatPacket.getMessage().contains("kill")) {
if (!cause.contains(player)) {
cause = cause.with(NamedCause.of("Player", player));
}
StaticMixinHelper.destructItemDrop = true;
}
}
// Inventory Events
if (player != null && player.getHealth() > 0 && StaticMixinHelper.lastOpenContainer != null) {
if (packetIn instanceof C10PacketCreativeInventoryAction && !StaticMixinHelper.ignoreCreativeInventoryPacket) {
SpongeCommonEventFactory.handleCreativeClickInventoryEvent(Cause.of(NamedCause.source(player)), player,
(C10PacketCreativeInventoryAction) packetIn);
} else {
SpongeCommonEventFactory.handleInteractInventoryOpenCloseEvent(Cause.of(NamedCause.source(player)), player, packetIn);
if (packetIn instanceof C0EPacketClickWindow) {
SpongeCommonEventFactory.handleClickInteractInventoryEvent(Cause.of(NamedCause.source(player)), player,
(C0EPacketClickWindow) packetIn);
}
}
}
// Handle Entity captures
if (this.capturedEntityItems.size() > 0) {
if (StaticMixinHelper.dropCause != null) {
cause = StaticMixinHelper.dropCause;
StaticMixinHelper.destructItemDrop = true;
}
handleDroppedItems(cause);
}
if (this.capturedEntities.size() > 0) {
handleEntitySpawns(cause);
}
StaticMixinHelper.dropCause = null;
StaticMixinHelper.destructItemDrop = false;
this.invalidTransactions.clear();
}
public void handleDroppedItems(Cause cause) {
Iterator<Entity> iter = this.capturedEntityItems.iterator();
ImmutableList.Builder<EntitySnapshot> entitySnapshotBuilder = new ImmutableList.Builder<>();
while (iter.hasNext()) {
Entity currentEntity = iter.next();
if (this.invalidTransactions != null) {
// check to see if this drop is invalid and if so, remove
boolean invalid = false;
for (Transaction<BlockSnapshot> blockSnapshot : this.invalidTransactions) {
if (blockSnapshot.getOriginal().getLocation().get().getBlockPosition().equals(currentEntity.getLocation().getBlockPosition())) {
invalid = true;
iter.remove();
break;
}
}
if (invalid) {
continue;
}
}
if (cause.first(User.class).isPresent()) {
// store user UUID with entity to track later
User user = cause.first(User.class).get();
((IMixinEntity) currentEntity).trackEntityUniqueId(NbtDataUtil.SPONGE_ENTITY_CREATOR, user.getUniqueId());
} else if (cause.first(Entity.class).isPresent()) {
IMixinEntity spongeEntity = (IMixinEntity) cause.first(Entity.class).get();
Optional<User> owner = spongeEntity.getTrackedPlayer(NbtDataUtil.SPONGE_ENTITY_CREATOR);
if (owner.isPresent()) {
if (!cause.containsNamed(NamedCause.OWNER)) {
cause = cause.with(NamedCause.of(NamedCause.OWNER, owner.get()));
}
((IMixinEntity) currentEntity).trackEntityUniqueId(NbtDataUtil.SPONGE_ENTITY_CREATOR, owner.get().getUniqueId());
}
if (spongeEntity instanceof EntityLivingBase) {
DamageSource lastDamageSource = spongeEntity.getLastDamageSource();
if (lastDamageSource != null && !cause.contains(lastDamageSource)) {
if (!cause.containsNamed("Attacker")) {
cause = cause.with(NamedCause.of("Attacker", lastDamageSource));
}
}
}
}
entitySnapshotBuilder.add(currentEntity.createSnapshot());
}
List<EntitySnapshot> entitySnapshots = entitySnapshotBuilder.build();
if (entitySnapshots.isEmpty()) {
return;
}
DropItemEvent event = null;
if (StaticMixinHelper.destructItemDrop) {
if (!(cause.root() instanceof SpawnCause)) {
// determine spawn cause
Cause.Builder builder = null;
if (cause.root() instanceof Entity) {
DamageSource damageSource = SpongeHooks.getEntityDamageSource((net.minecraft.entity.Entity) cause.root());
builder = Cause.source(EntitySpawnCause.builder().entity((Entity) cause.root()).type(SpawnTypes.DROPPED_ITEM).build());
if (damageSource != null) {
builder = builder.named(NamedCause.of("LastDamageSource", damageSource));
}
} else {
builder = Cause.source(SpawnCause.builder().type(SpawnTypes.DROPPED_ITEM).build());
}
Cause spawnCause = builder.build();
if (cause.root() == StaticMixinHelper.packetPlayer) {
cause = spawnCause.merge(Cause.of(NamedCause.owner(StaticMixinHelper.packetPlayer)));
} else {
cause = spawnCause.merge(cause);
}
}
event = SpongeEventFactory.createDropItemEventDestruct(cause, this.capturedEntityItems, entitySnapshots, this.getWorld());
} else {
Cause.Builder builder = null;
if (cause.root() instanceof Entity) {
builder = Cause.source(EntitySpawnCause.builder().entity((Entity) cause.root()).type(SpawnTypes.DROPPED_ITEM).build());
} else {
builder = Cause.source(SpawnCause.builder().type(SpawnTypes.DROPPED_ITEM).build());
}
Cause spawnCause = builder.build();
if (cause.root() == StaticMixinHelper.packetPlayer) {
cause = spawnCause.merge(Cause.of(NamedCause.owner(StaticMixinHelper.packetPlayer)));
} else {
cause = spawnCause.merge(cause);
}
event = SpongeEventFactory.createDropItemEventDispense(cause, this.capturedEntityItems, entitySnapshots, this.getWorld());
}
if (!(SpongeImpl.postEvent(event))) {
// Handle player deaths
for (Player causePlayer : cause.allOf(Player.class)) {
EntityPlayerMP playermp = (EntityPlayerMP) causePlayer;
if (playermp.getHealth() <= 0 || playermp.isDead) {
if (!playermp.worldObj.getGameRules().getBoolean("keepInventory")) {
playermp.inventory.clear();
} else {
// don't drop anything if keepInventory is enabled
this.capturedEntityItems.clear();
}
}
}
Iterator<Entity> iterator =
event instanceof DropItemEvent.Destruct ? ((DropItemEvent.Destruct) event).getEntities().iterator()
: ((DropItemEvent.Dispense) event).getEntities().iterator();
while (iterator.hasNext()) {
Entity entity = iterator.next();
if (entity.isRemoved()) { // Entity removed in an event handler
iterator.remove();
continue;
}
net.minecraft.entity.Entity nmsEntity = (net.minecraft.entity.Entity) entity;
int x = MathHelper.floor_double(nmsEntity.posX / 16.0D);
int z = MathHelper.floor_double(nmsEntity.posZ / 16.0D);
this.getMinecraftWorld().getChunkFromChunkCoords(x, z).addEntity(nmsEntity);
this.getMinecraftWorld().loadedEntityList.add(nmsEntity);
this.getMixinWorld().onSpongeEntityAdded(nmsEntity);
SpongeHooks.logEntitySpawn(cause, nmsEntity);
iterator.remove();
}
} else {
sendItemChangeToPlayer(StaticMixinHelper.packetPlayer);
this.capturedEntityItems.clear();
}
}
private boolean addWeatherEffect(net.minecraft.entity.Entity entity, Cause cause) {
if (entity instanceof EntityLightningBolt) {
LightningEvent.Pre event = SpongeEventFactory.createLightningEventPre(((IMixinEntityLightningBolt) entity).getCause());
SpongeImpl.postEvent(event);
if (!event.isCancelled()) {
return getMinecraftWorld().addWeatherEffect(entity);
}
} else {
return getMinecraftWorld().addWeatherEffect(entity);
}
return false;
}
public void handleBlockCaptures(Cause cause) {
EntityPlayerMP player = StaticMixinHelper.packetPlayer;
Packet<?> packetIn = StaticMixinHelper.processingPacket;
ImmutableList<Transaction<BlockSnapshot>> blockBreakTransactions = null;
ImmutableList<Transaction<BlockSnapshot>> blockModifyTransactions = null;
ImmutableList<Transaction<BlockSnapshot>> blockPlaceTransactions = null;
ImmutableList<Transaction<BlockSnapshot>> blockDecayTransactions = null;
ImmutableList<Transaction<BlockSnapshot>> blockMultiTransactions = null;
ImmutableList.Builder<Transaction<BlockSnapshot>> breakBuilder = new ImmutableList.Builder<>();
ImmutableList.Builder<Transaction<BlockSnapshot>> placeBuilder = new ImmutableList.Builder<>();
ImmutableList.Builder<Transaction<BlockSnapshot>> decayBuilder = new ImmutableList.Builder<>();
ImmutableList.Builder<Transaction<BlockSnapshot>> modifyBuilder = new ImmutableList.Builder<>();
ImmutableList.Builder<Transaction<BlockSnapshot>> multiBuilder = new ImmutableList.Builder<>();
ChangeBlockEvent.Break breakEvent = null;
ChangeBlockEvent.Modify modifyEvent = null;
ChangeBlockEvent.Place placeEvent = null;
List<ChangeBlockEvent> blockEvents = new ArrayList<>();
Iterator<BlockSnapshot> iterator = this.capturedSpongeBlockSnapshots.iterator();
while (iterator.hasNext()) {
SpongeBlockSnapshot blockSnapshot = (SpongeBlockSnapshot) iterator.next();
CaptureType captureType = blockSnapshot.captureType;
BlockPos pos = VecHelper.toBlockPos(blockSnapshot.getPosition());
IBlockState currentState = this.getMinecraftWorld().getBlockState(pos);
Transaction<BlockSnapshot> transaction = new Transaction<>(blockSnapshot, this.getMixinWorld().createSpongeBlockSnapshot(currentState, currentState.getBlock()
.getActualState(currentState, this.getMinecraftWorld(), pos), pos, 0));
if (captureType == CaptureType.BREAK) {
breakBuilder.add(transaction);
} else if (captureType == CaptureType.DECAY) {
decayBuilder.add(transaction);
} else if (captureType == CaptureType.PLACE) {
placeBuilder.add(transaction);
} else if (captureType == CaptureType.MODIFY) {
modifyBuilder.add(transaction);
}
multiBuilder.add(transaction);
iterator.remove();
}
blockBreakTransactions = breakBuilder.build();
blockDecayTransactions = decayBuilder.build();
blockModifyTransactions = modifyBuilder.build();
blockPlaceTransactions = placeBuilder.build();
blockMultiTransactions = multiBuilder.build();
ChangeBlockEvent changeBlockEvent;
if (blockBreakTransactions.size() > 0) {
changeBlockEvent = SpongeEventFactory.createChangeBlockEventBreak(cause, this.getWorld(), blockBreakTransactions);
SpongeImpl.postEvent(changeBlockEvent);
breakEvent = (ChangeBlockEvent.Break) changeBlockEvent;
blockEvents.add(changeBlockEvent);
}
if (blockModifyTransactions.size() > 0) {
changeBlockEvent = SpongeEventFactory.createChangeBlockEventModify(cause, this.getWorld(), blockModifyTransactions);
SpongeImpl.postEvent(changeBlockEvent);
modifyEvent = (ChangeBlockEvent.Modify) changeBlockEvent;
blockEvents.add(changeBlockEvent);
}
if (blockPlaceTransactions.size() > 0) {
changeBlockEvent = SpongeEventFactory.createChangeBlockEventPlace(cause, this.getWorld(), blockPlaceTransactions);
SpongeImpl.postEvent(changeBlockEvent);
placeEvent = (ChangeBlockEvent.Place) changeBlockEvent;
blockEvents.add(changeBlockEvent);
}
if (blockEvents.size() > 1) {
if (breakEvent != null) {
int count = cause.allOf(ChangeBlockEvent.Break.class).size();
String namedCause = "BreakEvent" + (count != 0 ? count : "");
cause = cause.with(NamedCause.of(namedCause, breakEvent));
}
if (modifyEvent != null) {
int count = cause.allOf(ChangeBlockEvent.Modify.class).size();
String namedCause = "ModifyEvent" + (count != 0 ? count : "");
cause = cause.with(NamedCause.of(namedCause, modifyEvent));
}
if (placeEvent != null) {
int count = cause.allOf(ChangeBlockEvent.Place.class).size();
String namedCause = "PlaceEvent" + (count != 0 ? count : "");
cause = cause.with(NamedCause.of(namedCause, placeEvent));
}
changeBlockEvent = SpongeEventFactory.createChangeBlockEventPost(cause, this.getWorld(), blockMultiTransactions);
SpongeImpl.postEvent(changeBlockEvent);
if (changeBlockEvent.isCancelled()) {
// Restore original blocks
ListIterator<Transaction<BlockSnapshot>>
listIterator =
changeBlockEvent.getTransactions().listIterator(changeBlockEvent.getTransactions().size());
processList(listIterator);
if (player != null) {
CaptureType captureType = null;
if (packetIn instanceof C08PacketPlayerBlockPlacement) {
captureType = CaptureType.PLACE;
} else if (packetIn instanceof C07PacketPlayerDigging) {
captureType = CaptureType.BREAK;
}
if (captureType != null) {
handlePostPlayerBlockEvent(captureType, changeBlockEvent.getTransactions());
}
}
// clear entity list and return to avoid spawning items
this.capturedEntities.clear();
this.capturedEntityItems.clear();
return;
}
}
if (blockDecayTransactions.size() > 0) {
changeBlockEvent = SpongeEventFactory.createChangeBlockEventDecay(cause, this.getWorld(), blockDecayTransactions);
SpongeImpl.postEvent(changeBlockEvent);
blockEvents.add(changeBlockEvent);
}
for (ChangeBlockEvent blockEvent : blockEvents) {
CaptureType captureType = null;
if (blockEvent instanceof ChangeBlockEvent.Break) {
captureType = CaptureType.BREAK;
} else if (blockEvent instanceof ChangeBlockEvent.Decay) {
captureType = CaptureType.DECAY;
} else if (blockEvent instanceof ChangeBlockEvent.Modify) {
captureType = CaptureType.MODIFY;
} else if (blockEvent instanceof ChangeBlockEvent.Place) {
captureType = CaptureType.PLACE;
}
C08PacketPlayerBlockPlacement packet = null;
if (packetIn instanceof C08PacketPlayerBlockPlacement) {
packet = (C08PacketPlayerBlockPlacement) packetIn;
}
if (blockEvent.isCancelled()) {
// Restore original blocks
ListIterator<Transaction<BlockSnapshot>>
listIterator =
blockEvent.getTransactions().listIterator(blockEvent.getTransactions().size());
processList(listIterator);
handlePostPlayerBlockEvent(captureType, blockEvent.getTransactions());
// clear entity list and return to avoid spawning items
this.capturedEntities.clear();
this.capturedEntityItems.clear();
return;
} else {
for (Transaction<BlockSnapshot> transaction : blockEvent.getTransactions()) {
if (!transaction.isValid()) {
this.invalidTransactions.add(transaction);
} else {
if (captureType == CaptureType.BREAK && !(transaction.getOriginal().getState().getType() instanceof BlockLiquid) && cause.first(User.class).isPresent()) {
BlockPos pos = VecHelper.toBlockPos(transaction.getOriginal().getPosition());
for (EntityHanging hanging : SpongeHooks.findHangingEntities(this.getMinecraftWorld(), pos)) {
if (hanging != null) {
if (hanging instanceof EntityItemFrame) {
EntityItemFrame itemFrame = (EntityItemFrame) hanging;
net.minecraft.entity.Entity dropCause = null;
if (cause.root() instanceof net.minecraft.entity.Entity) {
dropCause = (net.minecraft.entity.Entity) cause.root();
}
itemFrame.dropItemOrSelf(dropCause, true);
itemFrame.setDead();
}
}
}
}
if (captureType == CaptureType.PLACE && player != null && packetIn instanceof C08PacketPlayerBlockPlacement) {
BlockPos pos = VecHelper.toBlockPos(transaction.getFinal().getPosition());
IMixinChunk spongeChunk = (IMixinChunk) this.getMinecraftWorld().getChunkFromBlockCoords(pos);
spongeChunk.addTrackedBlockPosition((net.minecraft.block.Block) transaction.getFinal().getState().getType(), pos,
(User) player, PlayerTracker.Type.OWNER);
spongeChunk.addTrackedBlockPosition((net.minecraft.block.Block) transaction.getFinal().getState().getType(), pos,
(User) player, PlayerTracker.Type.NOTIFIER);
}
}
}
if (this.invalidTransactions.size() > 0) {
for (Transaction<BlockSnapshot> transaction : Lists.reverse(this.invalidTransactions)) {
this.restoringBlocks = true;
transaction.getOriginal().restore(true, false);
this.restoringBlocks = false;
}
handlePostPlayerBlockEvent(captureType, this.invalidTransactions);
}
if (this.capturedEntityItems.size() > 0 && blockEvents.get(0) == breakEvent) {
StaticMixinHelper.destructItemDrop = true;
}
this.markAndNotifyBlockPost(blockEvent.getTransactions(), captureType, cause);
if (captureType == CaptureType.PLACE && player != null && packet != null && packet.getStack() != null) {
player.addStat(StatList.objectUseStats[net.minecraft.item.Item.getIdFromItem(packet.getStack().getItem())], 1);
}
}
}
}
private void handlePostPlayerBlockEvent(CaptureType captureType, List<Transaction<BlockSnapshot>> transactions) {
if (StaticMixinHelper.packetPlayer == null) {
return;
}
if (captureType == CaptureType.BREAK) {
// Let the client know the blocks still exist
for (Transaction<BlockSnapshot> transaction : transactions) {
BlockSnapshot snapshot = transaction.getOriginal();
BlockPos pos = VecHelper.toBlockPos(snapshot.getPosition());
StaticMixinHelper.packetPlayer.playerNetServerHandler.sendPacket(new S23PacketBlockChange(this.getMinecraftWorld(), pos));
// Update any tile entity data for this block
net.minecraft.tileentity.TileEntity tileentity = this.getMinecraftWorld().getTileEntity(pos);
if (tileentity != null) {
Packet<?> pkt = tileentity.getDescriptionPacket();
if (pkt != null) {
StaticMixinHelper.packetPlayer.playerNetServerHandler.sendPacket(pkt);
}
}
}
}
sendItemChangeToPlayer(StaticMixinHelper.packetPlayer);
}
public void handleNonLivingEntityDestruct(net.minecraft.entity.Entity entityIn) {
if (entityIn.isDead && (!(entityIn instanceof EntityLivingBase) || entityIn instanceof EntityArmorStand)) {
MessageChannel originalChannel = MessageChannel.TO_NONE;
IMixinEntity spongeEntity = (IMixinEntity) entityIn;
Cause cause = spongeEntity.getNonLivingDestructCause();;
if (cause == null) {
cause = Cause.of(NamedCause.source(this));
}
if (cause.root() instanceof EntityDamageSource) {
EntityDamageSource entityDamageSource = (EntityDamageSource) cause.root();
if (entityDamageSource.getSourceOfDamage() instanceof Player) {
originalChannel = ((Player) entityDamageSource.getSourceOfDamage()).getMessageChannel();
} else if (entityDamageSource instanceof IndirectEntityDamageSource) {
IndirectEntityDamageSource indirectDamageSource = (IndirectEntityDamageSource) entityDamageSource;
if (indirectDamageSource.getIndirectSource() instanceof Player) {
originalChannel = ((Player) indirectDamageSource.getIndirectSource()).getMessageChannel();
}
}
} else if (cause.root() instanceof Player) {
originalChannel = ((Player) cause.root()).getMessageChannel();
}
DestructEntityEvent event = SpongeEventFactory.createDestructEntityEvent(
cause, originalChannel, Optional.of(originalChannel), new MessageEvent.MessageFormatter(),
(Entity) entityIn, true
);
SpongeImpl.getGame().getEventManager().post(event);
if (!event.isMessageCancelled()) {
event.getChannel().ifPresent(channel -> channel.send(entityIn, event.getMessage()));
}
}
}
private void sendItemChangeToPlayer(EntityPlayerMP player) {
if (StaticMixinHelper.prePacketProcessItem == null) {
return;
}
// handle revert
player.isChangingQuantityOnly = true;
player.inventory.mainInventory[player.inventory.currentItem] = StaticMixinHelper.prePacketProcessItem;
Slot slot = player.openContainer.getSlotFromInventory(player.inventory, player.inventory.currentItem);
player.openContainer.detectAndSendChanges();
player.isChangingQuantityOnly = false;
// force client itemstack update if place event was cancelled
player.playerNetServerHandler.sendPacket(new S2FPacketSetSlot(player.openContainer.windowId, slot.slotNumber,
StaticMixinHelper.prePacketProcessItem));
}
private void processList(ListIterator<Transaction<BlockSnapshot>> listIterator) {
while (listIterator.hasPrevious()) {
Transaction<BlockSnapshot> transaction = listIterator.previous();
this.restoringBlocks = true;
transaction.getOriginal().restore(true, false);
this.restoringBlocks = false;
}
}
public boolean processSpawnEntity(Entity entity, Cause cause) {
checkNotNull(entity, "Entity cannot be null!");
checkNotNull(cause, "Cause cannot be null!");
// Very first thing - fire events that are from entity construction
if (((IMixinEntity) entity).isInConstructPhase()) {
((IMixinEntity) entity).firePostConstructEvents();
}
net.minecraft.entity.Entity entityIn = (net.minecraft.entity.Entity) entity;
// do not drop any items while restoring blocksnapshots. Prevents dupes
if (!this.getMinecraftWorld().isRemote && (entityIn == null || (entityIn instanceof net.minecraft.entity.item.EntityItem && this.restoringBlocks))) {
return false;
}
int i = MathHelper.floor_double(entityIn.posX / 16.0D);
int j = MathHelper.floor_double(entityIn.posZ / 16.0D);
boolean flag = entityIn.forceSpawn;
List<NamedCause> namedCauses = new ArrayList<>();
for (Map.Entry<String, Object> entry : cause.getNamedCauses().entrySet()) {
if (entry.getKey().equals(NamedCause.SOURCE)) {
if (!(entry.getValue() instanceof SpawnCause)) {
SpawnType type;
if (entity instanceof EntityItem) {
type = SpawnTypes.DROPPED_ITEM;
} else {
type = SpawnTypes.CUSTOM;
}
namedCauses.add(NamedCause.source(SpawnCause.builder().type(type).build()));
} else {
namedCauses.add(NamedCause.source(entry.getValue()));
}
} else {
namedCauses.add(NamedCause.of(entry.getKey(), entry.getValue()));
}
}
cause = Cause.of(namedCauses);
if (entityIn instanceof EntityPlayer) {
flag = true;
} else if (entityIn instanceof EntityLightningBolt) {
((IMixinEntityLightningBolt) entityIn).setCause(cause);
}
if (!flag && !this.getMinecraftWorld().isChunkLoaded(i, j, true)) {
return false;
} else {
if (entityIn instanceof EntityPlayer) {
EntityPlayer entityplayer = (EntityPlayer) entityIn;
net.minecraft.world.World world = this.targetWorld;
world.playerEntities.add(entityplayer);
world.updateAllPlayersSleepingFlag();
}
if (this.getMinecraftWorld().isRemote || flag || this.spawningDeathDrops) {
if (SpongeImpl.postEvent(SpongeEventFactory.createSpawnEntityEventCustom(cause, Lists.newArrayList(entity),
Lists.newArrayList(entity.createSnapshot()), getWorld())) && !flag) {
return false;
}
this.getMinecraftWorld().getChunkFromChunkCoords(i, j).addEntity(entityIn);
this.getMinecraftWorld().loadedEntityList.add(entityIn);
this.getMixinWorld().onSpongeEntityAdded(entityIn);
return true;
}
if (!flag && this.processingCaptureCause && !this.captureTerrainGen) {
if (this.currentTickBlock != null) {
BlockPos sourcePos = VecHelper.toBlockPos(this.currentTickBlock.getPosition());
Block targetBlock = getMinecraftWorld().getBlockState(entityIn.getPosition()).getBlock();
SpongeHooks
.tryToTrackBlockAndEntity(this.getMinecraftWorld(), this.currentTickBlock, entityIn, sourcePos, targetBlock, entityIn.getPosition(),
PlayerTracker.Type.NOTIFIER);
}
if (this.currentTickEntity != null) {
Optional<User> creator = ((IMixinEntity) this.currentTickEntity).getTrackedPlayer(NbtDataUtil.SPONGE_ENTITY_CREATOR);
if (creator.isPresent()) { // transfer user to next entity. This occurs with falling blocks that change into items
((IMixinEntity) entityIn).trackEntityUniqueId(NbtDataUtil.SPONGE_ENTITY_CREATOR, creator.get().getUniqueId());
}
}
if (entityIn instanceof EntityItem) {
this.capturedEntityItems.add((Item) entityIn);
} else {
this.capturedEntities.add((Entity) entityIn);
}
return true;
} else { // Custom
if (entityIn instanceof EntityFishHook && ((EntityFishHook) entityIn).angler == null) {
// TODO MixinEntityFishHook.setShooter makes angler null
// sometimes, but that will cause NPE when ticking
return false;
}
EntityLivingBase specialCause = null;
String causeName = "";
// Special case for throwables
if (!(entityIn instanceof EntityPlayer) && entityIn instanceof EntityThrowable) {
EntityThrowable throwable = (EntityThrowable) entityIn;
specialCause = throwable.getThrower();
if (specialCause != null) {
causeName = NamedCause.THROWER;
if (specialCause instanceof Player) {
Player player = (Player) specialCause;
((IMixinEntity) entityIn).trackEntityUniqueId(NbtDataUtil.SPONGE_ENTITY_CREATOR, player.getUniqueId());
}
}
}
// Special case for TNT
else if (!(entityIn instanceof EntityPlayer) && entityIn instanceof EntityTNTPrimed) {
EntityTNTPrimed tntEntity = (EntityTNTPrimed) entityIn;
specialCause = tntEntity.getTntPlacedBy();
causeName = NamedCause.IGNITER;
if (specialCause instanceof Player) {
Player player = (Player) specialCause;
((IMixinEntity) entityIn).trackEntityUniqueId(NbtDataUtil.SPONGE_ENTITY_CREATOR, player.getUniqueId());
}
}
// Special case for Tameables
else if (!(entityIn instanceof EntityPlayer) && entityIn instanceof EntityTameable) {
EntityTameable tameable = (EntityTameable) entityIn;
if (tameable.getOwner() != null) {
specialCause = tameable.getOwner();
causeName = NamedCause.OWNER;
}
}
if (specialCause != null && !cause.containsNamed(causeName)) {
cause = cause.with(NamedCause.of(causeName, specialCause));
}
org.spongepowered.api.event.Event event = null;
List<Entity> entitiesToSpawn = Lists.newArrayList(entity);
ImmutableList<EntitySnapshot> entitySnapshots = ImmutableList.of(entity.createSnapshot());
if (entityIn instanceof EntityItem) {
event = SpongeEventFactory.createDropItemEventCustom(cause, entitiesToSpawn, entitySnapshots, this.getWorld());
} else {
event = SpongeEventFactory.createSpawnEntityEventCustom(cause, entitiesToSpawn, entitySnapshots, this.getWorld());
}
boolean cancelled = SpongeImpl.postEvent(event);
if (!cancelled && !entity.isRemoved()) {
if (entityIn instanceof EntityWeatherEffect) {
return addWeatherEffect(entityIn, cause);
}
this.getMinecraftWorld().getChunkFromChunkCoords(i, j).addEntity(entityIn);
this.getMinecraftWorld().loadedEntityList.add(entityIn);
this.getMixinWorld().onSpongeEntityAdded(entityIn);
return true;
}
return false;
}
}
}
public void randomTickBlock(Block block, BlockPos pos, IBlockState state, Random random) {
this.processingCaptureCause = true;
this.processingBlockRandomTicks = true;
this.currentTickBlock = this.getMixinWorld().createSpongeBlockSnapshot(state, state.getBlock().getActualState(state, this.getMinecraftWorld(), pos), pos, 0);
block.randomTick(this.getMinecraftWorld(), pos, state, random);
this.handlePostTickCaptures(Cause.of(NamedCause.source(this.currentTickBlock)));
this.currentTickBlock = null;
this.processingCaptureCause = false;
this.processingBlockRandomTicks = false;
}
public void updateTickBlock(Block block, BlockPos pos, IBlockState state, Random rand) {
this.processingCaptureCause = true;
this.currentTickBlock = this.getMixinWorld().createSpongeBlockSnapshot(state, state.getBlock().getActualState(state, this.getMinecraftWorld(), pos), pos, 0);
block.updateTick(this.getMinecraftWorld(), pos, state, rand);
this.handlePostTickCaptures(Cause.of(NamedCause.source(this.currentTickBlock)));
this.currentTickBlock = null;
this.processingCaptureCause = false;
}
public void notifyBlockOfStateChange(BlockPos notifyPos, final Block sourceBlock, BlockPos sourcePos) {
if (!this.getMinecraftWorld().isRemote) {
IBlockState iblockstate = this.getMinecraftWorld().getBlockState(notifyPos);
if (iblockstate == Blocks.air.getDefaultState()) {
iblockstate.getBlock().onNeighborBlockChange(this.getMinecraftWorld(), notifyPos, iblockstate, sourceBlock);
return;
}
try {
if (!this.getMinecraftWorld().isRemote) {
if (StaticMixinHelper.packetPlayer != null) {
IMixinChunk spongeChunk = (IMixinChunk) this.getMinecraftWorld().getChunkFromBlockCoords(notifyPos);
if (!(spongeChunk instanceof EmptyChunk)) {
spongeChunk.addTrackedBlockPosition(iblockstate.getBlock(), notifyPos, (User) StaticMixinHelper.packetPlayer,
PlayerTracker.Type.NOTIFIER);
}
} else {
Object source = null;
if (this.hasTickingBlock()) {
source = this.getCurrentTickBlock().get();
sourcePos = VecHelper.toBlockPos(this.getCurrentTickBlock().get().getPosition());
} else if (this.hasTickingTileEntity()) {
source = this.getCurrentTickTileEntity().get();
sourcePos = ((net.minecraft.tileentity.TileEntity) this.getCurrentTickTileEntity().get()).getPos();
} else if (this.hasTickingEntity()) { // Falling Blocks
IMixinEntity spongeEntity = (IMixinEntity) this.getCurrentTickEntity().get();
sourcePos = ((net.minecraft.entity.Entity) this.getCurrentTickEntity().get()).getPosition();
Optional<User> owner = spongeEntity.getTrackedPlayer(NbtDataUtil.SPONGE_ENTITY_CREATOR);
Optional<User> notifier = spongeEntity.getTrackedPlayer(NbtDataUtil.SPONGE_ENTITY_NOTIFIER);
if (notifier.isPresent()) {
IMixinChunk spongeChunk = (IMixinChunk) this.getMinecraftWorld().getChunkFromBlockCoords(notifyPos);
spongeChunk.addTrackedBlockPosition(iblockstate.getBlock(), notifyPos, notifier.get(), PlayerTracker.Type.NOTIFIER);
} else if (owner.isPresent()) {
IMixinChunk spongeChunk = (IMixinChunk) this.getMinecraftWorld().getChunkFromBlockCoords(notifyPos);
spongeChunk.addTrackedBlockPosition(iblockstate.getBlock(), notifyPos, owner.get(), PlayerTracker.Type.NOTIFIER);
}
}
if (source != null) {
SpongeHooks.tryToTrackBlock(this.getMinecraftWorld(), source, sourcePos, iblockstate.getBlock(), notifyPos,
PlayerTracker.Type.NOTIFIER);
}
}
}
iblockstate.getBlock().onNeighborBlockChange(this.getMinecraftWorld(), notifyPos, iblockstate, sourceBlock);
} catch (Throwable throwable) {
CrashReport crashreport = CrashReport.makeCrashReport(throwable, "Exception while updating neighbours");
CrashReportCategory crashreportcategory = crashreport.makeCategory("Block being updated");
// TODO
/*crashreportcategory.addCrashSectionCallable("Source block type", new Callable()
{
public String call() {
try {
return String.format("ID #%d (%s // %s)", new Object[] {Integer.valueOf(Block.getIdFromBlock(blockIn)), blockIn.getUnlocalizedName(), blockIn.getClass().getCanonicalName()});
} catch (Throwable throwable1) {
return "ID #" + Block.getIdFromBlock(blockIn);
}
}
});*/
CrashReportCategory.addBlockInfo(crashreportcategory, notifyPos, iblockstate);
throw new ReportedException(crashreport);
}
}
}
public void markAndNotifyBlockPost(List<Transaction<BlockSnapshot>> transactions, CaptureType type, Cause cause) {
// We have to use a proxy so that our pending changes are notified such that any accessors from block
// classes do not fail on getting the incorrect block state from the IBlockAccess
SpongeProxyBlockAccess proxyBlockAccess = new SpongeProxyBlockAccess(this.getMinecraftWorld(), transactions);
for (Transaction<BlockSnapshot> transaction : transactions) {
if (!transaction.isValid()) {
continue; // Don't use invalidated block transactions during notifications, these only need to be restored
}
// Handle custom replacements
if (transaction.getCustom().isPresent()) {
this.setRestoringBlocks(true);
transaction.getFinal().restore(true, false);
this.setRestoringBlocks(false);
}
SpongeBlockSnapshot oldBlockSnapshot = (SpongeBlockSnapshot) transaction.getOriginal();
SpongeBlockSnapshot newBlockSnapshot = (SpongeBlockSnapshot) transaction.getFinal();
SpongeHooks.logBlockAction(cause, this.getMinecraftWorld(), type, transaction);
int updateFlag = oldBlockSnapshot.getUpdateFlag();
BlockPos pos = VecHelper.toBlockPos(oldBlockSnapshot.getPosition());
IBlockState originalState = (IBlockState) oldBlockSnapshot.getState();
IBlockState newState = (IBlockState) newBlockSnapshot.getState();
BlockSnapshot currentTickingBlock = this.getCurrentTickBlock().orElse(null);
// Containers get placed automatically
if (originalState.getBlock() != newState.getBlock() && !SpongeImplHooks.blockHasTileEntity(newState.getBlock(), newState)) {
this.setCurrentTickBlock(this.getMixinWorld().createSpongeBlockSnapshot(newState,
newState.getBlock().getActualState(newState, proxyBlockAccess, pos), pos, updateFlag));
newState.getBlock().onBlockAdded(this.getMinecraftWorld(), pos, newState);
if (shouldChainCause(cause)) {
cause = cause.merge(Cause.of(NamedCause.source(this.currentTickBlock)));
}
}
proxyBlockAccess.proceed();
this.getMixinWorld().markAndNotifyNeighbors(pos, null, originalState, newState, updateFlag);
// Handle any additional captures during notify
// This is to ensure new captures do not leak into next tick with wrong cause
if (this.getCapturedSpongeBlockSnapshots().size() > 0 && this.pluginCause == null) {
this.handlePostTickCaptures(cause);
}
this.setCurrentTickBlock(currentTickingBlock);
}
}
private boolean shouldChainCause(Cause cause) {
return !this.isCapturingTerrainGen() && !this.isWorldSpawnerRunning() && !this.isChunkSpawnerRunning()
&& !this.isProcessingBlockRandomTicks() && !this.isCaptureCommand() && this.hasTickingBlock() && this.pluginCause == null
&& !cause.contains(this.getCurrentTickBlock().get()) && !(StaticMixinHelper.processingPacket instanceof C03PacketPlayer);
}
}
|
src/main/java/org/spongepowered/common/event/CauseTracker.java
|
/*
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.common.event;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import net.minecraft.block.Block;
import net.minecraft.block.BlockLiquid;
import net.minecraft.block.state.IBlockState;
import net.minecraft.crash.CrashReport;
import net.minecraft.crash.CrashReportCategory;
import net.minecraft.entity.EntityHanging;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.effect.EntityLightningBolt;
import net.minecraft.entity.effect.EntityWeatherEffect;
import net.minecraft.entity.item.EntityArmorStand;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.item.EntityItemFrame;
import net.minecraft.entity.item.EntityTNTPrimed;
import net.minecraft.entity.passive.EntityTameable;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.entity.projectile.EntityFishHook;
import net.minecraft.entity.projectile.EntityThrowable;
import net.minecraft.init.Blocks;
import net.minecraft.inventory.Slot;
import net.minecraft.network.Packet;
import net.minecraft.network.play.client.C01PacketChatMessage;
import net.minecraft.network.play.client.C03PacketPlayer;
import net.minecraft.network.play.client.C07PacketPlayerDigging;
import net.minecraft.network.play.client.C08PacketPlayerBlockPlacement;
import net.minecraft.network.play.client.C0EPacketClickWindow;
import net.minecraft.network.play.client.C10PacketCreativeInventoryAction;
import net.minecraft.network.play.server.S23PacketBlockChange;
import net.minecraft.network.play.server.S2FPacketSetSlot;
import net.minecraft.stats.StatList;
import net.minecraft.util.BlockPos;
import net.minecraft.util.DamageSource;
import net.minecraft.util.EntityDamageSource;
import net.minecraft.util.MathHelper;
import net.minecraft.util.ReportedException;
import net.minecraft.world.chunk.EmptyChunk;
import org.spongepowered.api.block.BlockSnapshot;
import org.spongepowered.api.block.tileentity.TileEntity;
import org.spongepowered.api.data.Transaction;
import org.spongepowered.api.entity.Entity;
import org.spongepowered.api.entity.EntitySnapshot;
import org.spongepowered.api.entity.Item;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.entity.living.player.User;
import org.spongepowered.api.event.SpongeEventFactory;
import org.spongepowered.api.event.action.LightningEvent;
import org.spongepowered.api.event.block.ChangeBlockEvent;
import org.spongepowered.api.event.cause.Cause;
import org.spongepowered.api.event.cause.NamedCause;
import org.spongepowered.api.event.cause.entity.damage.source.IndirectEntityDamageSource;
import org.spongepowered.api.event.cause.entity.spawn.EntitySpawnCause;
import org.spongepowered.api.event.cause.entity.spawn.SpawnCause;
import org.spongepowered.api.event.cause.entity.spawn.SpawnType;
import org.spongepowered.api.event.cause.entity.spawn.SpawnTypes;
import org.spongepowered.api.event.entity.DestructEntityEvent;
import org.spongepowered.api.event.entity.SpawnEntityEvent;
import org.spongepowered.api.event.item.inventory.DropItemEvent;
import org.spongepowered.api.event.message.MessageEvent;
import org.spongepowered.api.text.channel.MessageChannel;
import org.spongepowered.api.world.World;
import org.spongepowered.common.SpongeImpl;
import org.spongepowered.common.SpongeImplHooks;
import org.spongepowered.common.block.SpongeBlockSnapshot;
import org.spongepowered.common.data.util.NbtDataUtil;
import org.spongepowered.common.entity.PlayerTracker;
import org.spongepowered.common.interfaces.IMixinChunk;
import org.spongepowered.common.interfaces.entity.IMixinEntity;
import org.spongepowered.common.interfaces.entity.IMixinEntityLightningBolt;
import org.spongepowered.common.interfaces.world.IMixinWorld;
import org.spongepowered.common.util.SpongeHooks;
import org.spongepowered.common.util.StaticMixinHelper;
import org.spongepowered.common.util.VecHelper;
import org.spongepowered.common.world.CaptureType;
import org.spongepowered.common.world.SpongeProxyBlockAccess;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Optional;
import java.util.Random;
import javax.annotation.Nullable;
public final class CauseTracker {
private final net.minecraft.world.World targetWorld;
private boolean processingCaptureCause = false;
private boolean processingBlockRandomTicks = false;
private boolean captureEntitySpawns = true;
private boolean captureBlockDecay = false;
private boolean captureTerrainGen = false;
private boolean captureBlocks = false;
private boolean captureCommand = false;
private boolean restoringBlocks = false;
private boolean spawningDeathDrops = false;
private List<Entity> capturedEntities = new ArrayList<>();
private List<Entity> capturedEntityItems = new ArrayList<>();
@Nullable private BlockSnapshot currentTickBlock;
@Nullable private Entity currentTickEntity;
@Nullable private TileEntity currentTickTileEntity;
@Nullable private Cause pluginCause;
private List<BlockSnapshot> capturedSpongeBlockSnapshots = new ArrayList<>();
private List<Transaction<BlockSnapshot>> invalidTransactions = new ArrayList<>();
private boolean worldSpawnerRunning;
private boolean chunkSpawnerRunning;
public CauseTracker(net.minecraft.world.World targetWorld) {
this.targetWorld = targetWorld;
}
public World getWorld() {
return (World) this.targetWorld;
}
public net.minecraft.world.World getMinecraftWorld() {
return this.targetWorld;
}
public IMixinWorld getMixinWorld() {
return (IMixinWorld) this.targetWorld;
}
public boolean isProcessingCaptureCause() {
return this.processingCaptureCause;
}
public void setProcessingCaptureCause(boolean processingCaptureCause) {
this.processingCaptureCause = processingCaptureCause;
}
public boolean isProcessingBlockRandomTicks() {
return this.processingBlockRandomTicks;
}
public void setProcessingBlockRandomTicks(boolean processingBlockRandomTicks) {
this.processingBlockRandomTicks = processingBlockRandomTicks;
}
public boolean isCaptureEntitySpawns() {
return this.captureEntitySpawns;
}
public void setCaptureEntitySpawns(boolean captureEntitySpawns) {
this.captureEntitySpawns = captureEntitySpawns;
}
public boolean isCaptureBlockDecay() {
return this.captureBlockDecay;
}
public void setCapturingBlockDecay(boolean captureBlockDecay) {
this.captureBlockDecay = captureBlockDecay;
}
public boolean isCapturingTerrainGen() {
return this.captureTerrainGen;
}
public void setCapturingTerrainGen(boolean captureTerrainGen) {
this.captureTerrainGen = captureTerrainGen;
}
public boolean isCapturingBlocks() {
return this.captureBlocks;
}
public void setCaptureBlocks(boolean captureBlocks) {
this.captureBlocks = captureBlocks;
}
public boolean isCaptureCommand() {
return this.captureCommand;
}
public void setCapturingCommand(boolean captureCommand) {
this.captureCommand = captureCommand;
}
public boolean isRestoringBlocks() {
return this.restoringBlocks;
}
public void setRestoringBlocks(boolean restoringBlocks) {
this.restoringBlocks = restoringBlocks;
}
public boolean isSpawningDeathDrops() {
return this.spawningDeathDrops;
}
public void setSpawningDeathDrops(boolean spawningDeathDrops) {
this.spawningDeathDrops = spawningDeathDrops;
}
public List<Entity> getCapturedEntities() {
return this.capturedEntities;
}
public List<Entity> getCapturedEntityItems() {
return this.capturedEntityItems;
}
public boolean hasTickingBlock() {
return this.currentTickBlock != null;
}
public Optional<BlockSnapshot> getCurrentTickBlock() {
return Optional.ofNullable(this.currentTickBlock);
}
public void setCurrentTickBlock(@Nullable BlockSnapshot currentTickBlock) {
this.currentTickBlock = currentTickBlock;
}
public boolean hasTickingEntity() {
return this.currentTickEntity != null;
}
public Optional<Entity> getCurrentTickEntity() {
return Optional.ofNullable(this.currentTickEntity);
}
public void setCurrentTickEntity(@Nullable Entity currentTickEntity) {
this.currentTickEntity = currentTickEntity;
}
public boolean hasTickingTileEntity() {
return this.currentTickTileEntity != null;
}
public Optional<TileEntity> getCurrentTickTileEntity() {
return Optional.ofNullable(this.currentTickTileEntity);
}
public void setCurrentTickTileEntity(TileEntity currentTickTileEntity) {
this.currentTickTileEntity = currentTickTileEntity;
}
public List<BlockSnapshot> getCapturedSpongeBlockSnapshots() {
return this.capturedSpongeBlockSnapshots;
}
public List<Transaction<BlockSnapshot>> getInvalidTransactions() {
return this.invalidTransactions;
}
public void setInvalidTransactions(List<Transaction<BlockSnapshot>> invalidTransactions) {
this.invalidTransactions = invalidTransactions;
}
public boolean isWorldSpawnerRunning() {
return this.worldSpawnerRunning;
}
public void setWorldSpawnerRunning(boolean worldSpawnerRunning) {
this.worldSpawnerRunning = worldSpawnerRunning;
}
public boolean isChunkSpawnerRunning() {
return this.chunkSpawnerRunning;
}
public void setChunkSpawnerRunning(boolean chunkSpawnerRunning) {
this.chunkSpawnerRunning = chunkSpawnerRunning;
}
public Optional<Cause> getPluginCause() {
return Optional.ofNullable(this.pluginCause);
}
public void setPluginCause(@Nullable Cause pluginCause) {
this.pluginCause = pluginCause;
}
public boolean hasPluginCause() {
return this.pluginCause != null;
}
public void handleEntitySpawns(Cause cause) {
Iterator<Entity> iter = this.capturedEntities.iterator();
ImmutableList.Builder<EntitySnapshot> entitySnapshotBuilder = new ImmutableList.Builder<>();
while (iter.hasNext()) {
Entity currentEntity = iter.next();
if (this.invalidTransactions != null) {
// check to see if this spawn is invalid and if so, remove
boolean invalid = false;
for (Transaction<BlockSnapshot> blockSnapshot : this.invalidTransactions) {
if (blockSnapshot.getOriginal().getLocation().get().getBlockPosition().equals(currentEntity.getLocation().getBlockPosition())) {
invalid = true;
iter.remove();
break;
}
}
if (invalid) {
continue;
}
}
if (cause.first(User.class).isPresent()) {
// store user UUID with entity to track later
User user = cause.first(User.class).get();
((IMixinEntity) currentEntity).trackEntityUniqueId(NbtDataUtil.SPONGE_ENTITY_CREATOR, user.getUniqueId());
} else if (cause.first(Entity.class).isPresent()) {
IMixinEntity spongeEntity = (IMixinEntity) cause.first(Entity.class).get();
Optional<User> owner = spongeEntity.getTrackedPlayer(NbtDataUtil.SPONGE_ENTITY_CREATOR);
if (owner.isPresent() && !cause.containsNamed(NamedCause.OWNER)) {
cause = cause.with(NamedCause.of(NamedCause.OWNER, owner.get()));
((IMixinEntity) currentEntity).trackEntityUniqueId(NbtDataUtil.SPONGE_ENTITY_CREATOR, owner.get().getUniqueId());
}
}
entitySnapshotBuilder.add(currentEntity.createSnapshot());
}
List<EntitySnapshot> entitySnapshots = entitySnapshotBuilder.build();
if (entitySnapshots.isEmpty()) {
return;
}
SpawnEntityEvent event;
if (this.worldSpawnerRunning) {
event = SpongeEventFactory.createSpawnEntityEventSpawner(cause, this.capturedEntities, entitySnapshots, this.getWorld());
} else if (this.chunkSpawnerRunning) {
event = SpongeEventFactory.createSpawnEntityEventChunkLoad(cause, this.capturedEntities, entitySnapshots, this.getWorld());
} else {
List<NamedCause> namedCauses = new ArrayList<>();
for (Map.Entry<String, Object> entry : cause.getNamedCauses().entrySet()) {
if (entry.getKey().equalsIgnoreCase(NamedCause.SOURCE)) {
if (!(entry.getValue() instanceof SpawnCause)) {
namedCauses.add(NamedCause.source(SpawnCause.builder().type(SpawnTypes.CUSTOM).build()));
} else {
namedCauses.add(NamedCause.source(entry.getValue()));
}
} else {
namedCauses.add(NamedCause.of(entry.getKey(), entry.getValue()));
}
}
cause = Cause.of(namedCauses);
event = SpongeEventFactory.createSpawnEntityEvent(cause, this.capturedEntities, entitySnapshotBuilder.build(), this.getWorld());
}
if (!(SpongeImpl.postEvent(event))) {
Iterator<Entity> iterator = event.getEntities().iterator();
while (iterator.hasNext()) {
Entity entity = iterator.next();
if (entity.isRemoved()) { // Entity removed in an event handler
iterator.remove();
continue;
}
net.minecraft.entity.Entity nmsEntity = (net.minecraft.entity.Entity) entity;
if (nmsEntity instanceof EntityWeatherEffect) {
addWeatherEffect(nmsEntity, cause);
} else {
int x = MathHelper.floor_double(nmsEntity.posX / 16.0D);
int z = MathHelper.floor_double(nmsEntity.posZ / 16.0D);
this.getMinecraftWorld().getChunkFromChunkCoords(x, z).addEntity(nmsEntity);
this.getMinecraftWorld().loadedEntityList.add(nmsEntity);
this.getMixinWorld().onSpongeEntityAdded(nmsEntity);
SpongeHooks.logEntitySpawn(cause, nmsEntity);
}
iterator.remove();
}
} else {
this.capturedEntities.clear();
}
}
public void handlePostTickCaptures(Cause cause) {
if (this.getMinecraftWorld().isRemote || this.restoringBlocks || this.spawningDeathDrops || cause == null) {
return;
} else if (this.capturedEntities.size() == 0 && this.capturedEntityItems.size() == 0 && this.capturedSpongeBlockSnapshots.size() == 0
&& StaticMixinHelper.packetPlayer == null) {
return; // nothing was captured, return
}
EntityPlayerMP player = StaticMixinHelper.packetPlayer;
Packet<?> packetIn = StaticMixinHelper.processingPacket;
// Attempt to find a Player cause if we do not have one
if (!cause.first(User.class).isPresent() && !(this.capturedSpongeBlockSnapshots.size() > 0
&& ((SpongeBlockSnapshot) this.capturedSpongeBlockSnapshots.get(0)).captureType
== CaptureType.DECAY)) {
if ((cause.first(BlockSnapshot.class).isPresent() || cause.first(TileEntity.class).isPresent())) {
// Check for player at pos of first transaction
Optional<BlockSnapshot> snapshot = cause.first(BlockSnapshot.class);
Optional<TileEntity> te = cause.first(TileEntity.class);
BlockPos pos = null;
if (snapshot.isPresent()) {
pos = VecHelper.toBlockPos(snapshot.get().getPosition());
} else {
pos = ((net.minecraft.tileentity.TileEntity) te.get()).getPos();
}
net.minecraft.world.chunk.Chunk chunk = this.getMinecraftWorld().getChunkFromBlockCoords(pos);
if (chunk != null) {
IMixinChunk spongeChunk = (IMixinChunk) chunk;
Optional<User> owner = spongeChunk.getBlockOwner(pos);
Optional<User> notifier = spongeChunk.getBlockNotifier(pos);
if (notifier.isPresent() && !cause.containsNamed(NamedCause.NOTIFIER)) {
cause = cause.with(NamedCause.notifier(notifier.get()));
}
if (owner.isPresent() && !cause.containsNamed(NamedCause.OWNER)) {
cause = cause.with(NamedCause.owner(owner.get()));
}
}
} else if (cause.first(Entity.class).isPresent()) {
Entity entity = cause.first(Entity.class).get();
if (entity instanceof EntityTameable) {
EntityTameable tameable = (EntityTameable) entity;
if (tameable.getOwner() != null && !cause.containsNamed(NamedCause.OWNER)) {
cause = cause.with(NamedCause.owner(tameable.getOwner()));
}
} else {
Optional<User> owner = ((IMixinEntity) entity).getTrackedPlayer(NbtDataUtil.SPONGE_ENTITY_CREATOR);
if (owner.isPresent() && !cause.contains(NamedCause.OWNER)) {
cause = cause.with(NamedCause.owner(owner.get()));
}
}
}
}
// Handle Block Captures
handleBlockCaptures(cause);
// Handle Player Toss
if (player != null && packetIn instanceof C07PacketPlayerDigging) {
C07PacketPlayerDigging digPacket = (C07PacketPlayerDigging) packetIn;
if (digPacket.getStatus() == C07PacketPlayerDigging.Action.DROP_ITEM) {
StaticMixinHelper.destructItemDrop = false;
}
}
// Handle Player kill commands
if (player != null && packetIn instanceof C01PacketChatMessage) {
C01PacketChatMessage chatPacket = (C01PacketChatMessage) packetIn;
if (chatPacket.getMessage().contains("kill")) {
if (!cause.contains(player)) {
cause = cause.with(NamedCause.of("Player", player));
}
StaticMixinHelper.destructItemDrop = true;
}
}
// Inventory Events
if (player != null && player.getHealth() > 0 && StaticMixinHelper.lastOpenContainer != null) {
if (packetIn instanceof C10PacketCreativeInventoryAction && !StaticMixinHelper.ignoreCreativeInventoryPacket) {
SpongeCommonEventFactory.handleCreativeClickInventoryEvent(Cause.of(NamedCause.source(player)), player,
(C10PacketCreativeInventoryAction) packetIn);
} else {
SpongeCommonEventFactory.handleInteractInventoryOpenCloseEvent(Cause.of(NamedCause.source(player)), player, packetIn);
if (packetIn instanceof C0EPacketClickWindow) {
SpongeCommonEventFactory.handleClickInteractInventoryEvent(Cause.of(NamedCause.source(player)), player,
(C0EPacketClickWindow) packetIn);
}
}
}
// Handle Entity captures
if (this.capturedEntityItems.size() > 0) {
if (StaticMixinHelper.dropCause != null) {
cause = StaticMixinHelper.dropCause;
StaticMixinHelper.destructItemDrop = true;
}
handleDroppedItems(cause);
}
if (this.capturedEntities.size() > 0) {
handleEntitySpawns(cause);
}
StaticMixinHelper.dropCause = null;
StaticMixinHelper.destructItemDrop = false;
this.invalidTransactions.clear();
}
public void handleDroppedItems(Cause cause) {
Iterator<Entity> iter = this.capturedEntityItems.iterator();
ImmutableList.Builder<EntitySnapshot> entitySnapshotBuilder = new ImmutableList.Builder<>();
while (iter.hasNext()) {
Entity currentEntity = iter.next();
if (this.invalidTransactions != null) {
// check to see if this drop is invalid and if so, remove
boolean invalid = false;
for (Transaction<BlockSnapshot> blockSnapshot : this.invalidTransactions) {
if (blockSnapshot.getOriginal().getLocation().get().getBlockPosition().equals(currentEntity.getLocation().getBlockPosition())) {
invalid = true;
iter.remove();
break;
}
}
if (invalid) {
continue;
}
}
if (cause.first(User.class).isPresent()) {
// store user UUID with entity to track later
User user = cause.first(User.class).get();
((IMixinEntity) currentEntity).trackEntityUniqueId(NbtDataUtil.SPONGE_ENTITY_CREATOR, user.getUniqueId());
} else if (cause.first(Entity.class).isPresent()) {
IMixinEntity spongeEntity = (IMixinEntity) cause.first(Entity.class).get();
Optional<User> owner = spongeEntity.getTrackedPlayer(NbtDataUtil.SPONGE_ENTITY_CREATOR);
if (owner.isPresent()) {
if (!cause.containsNamed(NamedCause.OWNER)) {
cause = cause.with(NamedCause.of(NamedCause.OWNER, owner.get()));
}
((IMixinEntity) currentEntity).trackEntityUniqueId(NbtDataUtil.SPONGE_ENTITY_CREATOR, owner.get().getUniqueId());
}
if (spongeEntity instanceof EntityLivingBase) {
DamageSource lastDamageSource = spongeEntity.getLastDamageSource();
if (lastDamageSource != null && !cause.contains(lastDamageSource)) {
if (!cause.containsNamed("Attacker")) {
cause = cause.with(NamedCause.of("Attacker", lastDamageSource));
}
}
}
}
entitySnapshotBuilder.add(currentEntity.createSnapshot());
}
List<EntitySnapshot> entitySnapshots = entitySnapshotBuilder.build();
if (entitySnapshots.isEmpty()) {
return;
}
DropItemEvent event = null;
if (StaticMixinHelper.destructItemDrop) {
if (!(cause.root() instanceof SpawnCause)) {
// determine spawn cause
Cause.Builder builder = null;
if (cause.root() instanceof Entity) {
DamageSource damageSource = SpongeHooks.getEntityDamageSource((net.minecraft.entity.Entity) cause.root());
builder = Cause.source(EntitySpawnCause.builder().entity((Entity) cause.root()).type(SpawnTypes.DROPPED_ITEM).build());
if (damageSource != null) {
builder = builder.named(NamedCause.of("LastDamageSource", damageSource));
}
} else {
builder = Cause.source(SpawnCause.builder().type(SpawnTypes.DROPPED_ITEM).build());
}
Cause spawnCause = builder.build();
if (cause.root() == StaticMixinHelper.packetPlayer) {
cause = spawnCause.merge(Cause.of(NamedCause.owner(StaticMixinHelper.packetPlayer)));
} else {
cause = spawnCause.merge(cause);
}
}
event = SpongeEventFactory.createDropItemEventDestruct(cause, this.capturedEntityItems, entitySnapshots, this.getWorld());
} else {
Cause.Builder builder = null;
if (cause.root() instanceof Entity) {
builder = Cause.source(EntitySpawnCause.builder().entity((Entity) cause.root()).type(SpawnTypes.DROPPED_ITEM).build());
} else {
builder = Cause.source(SpawnCause.builder().type(SpawnTypes.DROPPED_ITEM).build());
}
Cause spawnCause = builder.build();
if (cause.root() == StaticMixinHelper.packetPlayer) {
cause = spawnCause.merge(Cause.of(NamedCause.owner(StaticMixinHelper.packetPlayer)));
} else {
cause = spawnCause.merge(cause);
}
event = SpongeEventFactory.createDropItemEventDispense(cause, this.capturedEntityItems, entitySnapshots, this.getWorld());
}
if (!(SpongeImpl.postEvent(event))) {
// Handle player deaths
for (Player causePlayer : cause.allOf(Player.class)) {
EntityPlayerMP playermp = (EntityPlayerMP) causePlayer;
if (playermp.getHealth() <= 0 || playermp.isDead) {
if (!playermp.worldObj.getGameRules().getBoolean("keepInventory")) {
playermp.inventory.clear();
} else {
// don't drop anything if keepInventory is enabled
this.capturedEntityItems.clear();
}
}
}
Iterator<Entity> iterator =
event instanceof DropItemEvent.Destruct ? ((DropItemEvent.Destruct) event).getEntities().iterator()
: ((DropItemEvent.Dispense) event).getEntities().iterator();
while (iterator.hasNext()) {
Entity entity = iterator.next();
if (entity.isRemoved()) { // Entity removed in an event handler
iterator.remove();
continue;
}
net.minecraft.entity.Entity nmsEntity = (net.minecraft.entity.Entity) entity;
int x = MathHelper.floor_double(nmsEntity.posX / 16.0D);
int z = MathHelper.floor_double(nmsEntity.posZ / 16.0D);
this.getMinecraftWorld().getChunkFromChunkCoords(x, z).addEntity(nmsEntity);
this.getMinecraftWorld().loadedEntityList.add(nmsEntity);
this.getMixinWorld().onSpongeEntityAdded(nmsEntity);
SpongeHooks.logEntitySpawn(cause, nmsEntity);
iterator.remove();
}
} else {
sendItemChangeToPlayer(StaticMixinHelper.packetPlayer);
this.capturedEntityItems.clear();
}
}
private boolean addWeatherEffect(net.minecraft.entity.Entity entity, Cause cause) {
if (entity instanceof EntityLightningBolt) {
LightningEvent.Pre event = SpongeEventFactory.createLightningEventPre(((IMixinEntityLightningBolt) entity).getCause());
SpongeImpl.postEvent(event);
if (!event.isCancelled()) {
return getMinecraftWorld().addWeatherEffect(entity);
}
} else {
return getMinecraftWorld().addWeatherEffect(entity);
}
return false;
}
public void handleBlockCaptures(Cause cause) {
EntityPlayerMP player = StaticMixinHelper.packetPlayer;
Packet<?> packetIn = StaticMixinHelper.processingPacket;
ImmutableList<Transaction<BlockSnapshot>> blockBreakTransactions = null;
ImmutableList<Transaction<BlockSnapshot>> blockModifyTransactions = null;
ImmutableList<Transaction<BlockSnapshot>> blockPlaceTransactions = null;
ImmutableList<Transaction<BlockSnapshot>> blockDecayTransactions = null;
ImmutableList<Transaction<BlockSnapshot>> blockMultiTransactions = null;
ImmutableList.Builder<Transaction<BlockSnapshot>> breakBuilder = new ImmutableList.Builder<>();
ImmutableList.Builder<Transaction<BlockSnapshot>> placeBuilder = new ImmutableList.Builder<>();
ImmutableList.Builder<Transaction<BlockSnapshot>> decayBuilder = new ImmutableList.Builder<>();
ImmutableList.Builder<Transaction<BlockSnapshot>> modifyBuilder = new ImmutableList.Builder<>();
ImmutableList.Builder<Transaction<BlockSnapshot>> multiBuilder = new ImmutableList.Builder<>();
ChangeBlockEvent.Break breakEvent = null;
ChangeBlockEvent.Modify modifyEvent = null;
ChangeBlockEvent.Place placeEvent = null;
List<ChangeBlockEvent> blockEvents = new ArrayList<>();
Iterator<BlockSnapshot> iterator = this.capturedSpongeBlockSnapshots.iterator();
while (iterator.hasNext()) {
SpongeBlockSnapshot blockSnapshot = (SpongeBlockSnapshot) iterator.next();
CaptureType captureType = blockSnapshot.captureType;
BlockPos pos = VecHelper.toBlockPos(blockSnapshot.getPosition());
IBlockState currentState = this.getMinecraftWorld().getBlockState(pos);
Transaction<BlockSnapshot> transaction = new Transaction<>(blockSnapshot, this.getMixinWorld().createSpongeBlockSnapshot(currentState, currentState.getBlock()
.getActualState(currentState, this.getMinecraftWorld(), pos), pos, 0));
if (captureType == CaptureType.BREAK) {
breakBuilder.add(transaction);
} else if (captureType == CaptureType.DECAY) {
decayBuilder.add(transaction);
} else if (captureType == CaptureType.PLACE) {
placeBuilder.add(transaction);
} else if (captureType == CaptureType.MODIFY) {
modifyBuilder.add(transaction);
}
multiBuilder.add(transaction);
iterator.remove();
}
blockBreakTransactions = breakBuilder.build();
blockDecayTransactions = decayBuilder.build();
blockModifyTransactions = modifyBuilder.build();
blockPlaceTransactions = placeBuilder.build();
blockMultiTransactions = multiBuilder.build();
ChangeBlockEvent changeBlockEvent;
if (blockBreakTransactions.size() > 0) {
changeBlockEvent = SpongeEventFactory.createChangeBlockEventBreak(cause, this.getWorld(), blockBreakTransactions);
SpongeImpl.postEvent(changeBlockEvent);
breakEvent = (ChangeBlockEvent.Break) changeBlockEvent;
blockEvents.add(changeBlockEvent);
}
if (blockModifyTransactions.size() > 0) {
changeBlockEvent = SpongeEventFactory.createChangeBlockEventModify(cause, this.getWorld(), blockModifyTransactions);
SpongeImpl.postEvent(changeBlockEvent);
modifyEvent = (ChangeBlockEvent.Modify) changeBlockEvent;
blockEvents.add(changeBlockEvent);
}
if (blockPlaceTransactions.size() > 0) {
changeBlockEvent = SpongeEventFactory.createChangeBlockEventPlace(cause, this.getWorld(), blockPlaceTransactions);
SpongeImpl.postEvent(changeBlockEvent);
placeEvent = (ChangeBlockEvent.Place) changeBlockEvent;
blockEvents.add(changeBlockEvent);
}
if (blockEvents.size() > 1) {
if (breakEvent != null) {
int count = cause.allOf(ChangeBlockEvent.Break.class).size();
String namedCause = "BreakEvent" + (count != 0 ? count : "");
cause = cause.with(NamedCause.of(namedCause, breakEvent));
}
if (modifyEvent != null) {
int count = cause.allOf(ChangeBlockEvent.Modify.class).size();
String namedCause = "ModifyEvent" + (count != 0 ? count : "");
cause = cause.with(NamedCause.of(namedCause, modifyEvent));
}
if (placeEvent != null) {
int count = cause.allOf(ChangeBlockEvent.Place.class).size();
String namedCause = "PlaceEvent" + (count != 0 ? count : "");
cause = cause.with(NamedCause.of(namedCause, placeEvent));
}
changeBlockEvent = SpongeEventFactory.createChangeBlockEventPost(cause, this.getWorld(), blockMultiTransactions);
SpongeImpl.postEvent(changeBlockEvent);
if (changeBlockEvent.isCancelled()) {
// Restore original blocks
ListIterator<Transaction<BlockSnapshot>>
listIterator =
changeBlockEvent.getTransactions().listIterator(changeBlockEvent.getTransactions().size());
processList(listIterator);
if (player != null) {
CaptureType captureType = null;
if (packetIn instanceof C08PacketPlayerBlockPlacement) {
captureType = CaptureType.PLACE;
} else if (packetIn instanceof C07PacketPlayerDigging) {
captureType = CaptureType.BREAK;
}
if (captureType != null) {
handlePostPlayerBlockEvent(captureType, changeBlockEvent.getTransactions());
}
}
// clear entity list and return to avoid spawning items
this.capturedEntities.clear();
this.capturedEntityItems.clear();
return;
}
}
if (blockDecayTransactions.size() > 0) {
changeBlockEvent = SpongeEventFactory.createChangeBlockEventDecay(cause, this.getWorld(), blockDecayTransactions);
SpongeImpl.postEvent(changeBlockEvent);
blockEvents.add(changeBlockEvent);
}
for (ChangeBlockEvent blockEvent : blockEvents) {
CaptureType captureType = null;
if (blockEvent instanceof ChangeBlockEvent.Break) {
captureType = CaptureType.BREAK;
} else if (blockEvent instanceof ChangeBlockEvent.Decay) {
captureType = CaptureType.DECAY;
} else if (blockEvent instanceof ChangeBlockEvent.Modify) {
captureType = CaptureType.MODIFY;
} else if (blockEvent instanceof ChangeBlockEvent.Place) {
captureType = CaptureType.PLACE;
}
C08PacketPlayerBlockPlacement packet = null;
if (packetIn instanceof C08PacketPlayerBlockPlacement) {
packet = (C08PacketPlayerBlockPlacement) packetIn;
}
if (blockEvent.isCancelled()) {
// Restore original blocks
ListIterator<Transaction<BlockSnapshot>>
listIterator =
blockEvent.getTransactions().listIterator(blockEvent.getTransactions().size());
processList(listIterator);
handlePostPlayerBlockEvent(captureType, blockEvent.getTransactions());
// clear entity list and return to avoid spawning items
this.capturedEntities.clear();
this.capturedEntityItems.clear();
return;
} else {
for (Transaction<BlockSnapshot> transaction : blockEvent.getTransactions()) {
if (!transaction.isValid()) {
this.invalidTransactions.add(transaction);
} else {
if (captureType == CaptureType.BREAK && !(transaction.getOriginal().getState().getType() instanceof BlockLiquid) && cause.first(User.class).isPresent()) {
BlockPos pos = VecHelper.toBlockPos(transaction.getOriginal().getPosition());
for (EntityHanging hanging : SpongeHooks.findHangingEntities(this.getMinecraftWorld(), pos)) {
if (hanging != null) {
if (hanging instanceof EntityItemFrame) {
EntityItemFrame itemFrame = (EntityItemFrame) hanging;
net.minecraft.entity.Entity dropCause = null;
if (cause.root() instanceof net.minecraft.entity.Entity) {
dropCause = (net.minecraft.entity.Entity) cause.root();
}
itemFrame.dropItemOrSelf(dropCause, true);
itemFrame.setDead();
}
}
}
}
if (captureType == CaptureType.PLACE && player != null && packetIn instanceof C08PacketPlayerBlockPlacement) {
BlockPos pos = VecHelper.toBlockPos(transaction.getFinal().getPosition());
IMixinChunk spongeChunk = (IMixinChunk) this.getMinecraftWorld().getChunkFromBlockCoords(pos);
spongeChunk.addTrackedBlockPosition((net.minecraft.block.Block) transaction.getFinal().getState().getType(), pos,
(User) player, PlayerTracker.Type.OWNER);
spongeChunk.addTrackedBlockPosition((net.minecraft.block.Block) transaction.getFinal().getState().getType(), pos,
(User) player, PlayerTracker.Type.NOTIFIER);
}
}
}
if (this.invalidTransactions.size() > 0) {
for (Transaction<BlockSnapshot> transaction : Lists.reverse(this.invalidTransactions)) {
this.restoringBlocks = true;
transaction.getOriginal().restore(true, false);
this.restoringBlocks = false;
}
handlePostPlayerBlockEvent(captureType, this.invalidTransactions);
}
if (this.capturedEntityItems.size() > 0 && blockEvents.get(0) == breakEvent) {
StaticMixinHelper.destructItemDrop = true;
}
this.markAndNotifyBlockPost(blockEvent.getTransactions(), captureType, cause);
if (captureType == CaptureType.PLACE && player != null && packet != null && packet.getStack() != null) {
player.addStat(StatList.objectUseStats[net.minecraft.item.Item.getIdFromItem(packet.getStack().getItem())], 1);
}
}
}
}
private void handlePostPlayerBlockEvent(CaptureType captureType, List<Transaction<BlockSnapshot>> transactions) {
if (StaticMixinHelper.packetPlayer == null) {
return;
}
if (captureType == CaptureType.BREAK) {
// Let the client know the blocks still exist
for (Transaction<BlockSnapshot> transaction : transactions) {
BlockSnapshot snapshot = transaction.getOriginal();
BlockPos pos = VecHelper.toBlockPos(snapshot.getPosition());
StaticMixinHelper.packetPlayer.playerNetServerHandler.sendPacket(new S23PacketBlockChange(this.getMinecraftWorld(), pos));
// Update any tile entity data for this block
net.minecraft.tileentity.TileEntity tileentity = this.getMinecraftWorld().getTileEntity(pos);
if (tileentity != null) {
Packet<?> pkt = tileentity.getDescriptionPacket();
if (pkt != null) {
StaticMixinHelper.packetPlayer.playerNetServerHandler.sendPacket(pkt);
}
}
}
}
sendItemChangeToPlayer(StaticMixinHelper.packetPlayer);
}
public void handleNonLivingEntityDestruct(net.minecraft.entity.Entity entityIn) {
if (entityIn.isDead && (!(entityIn instanceof EntityLivingBase) || entityIn instanceof EntityArmorStand)) {
MessageChannel originalChannel = MessageChannel.TO_NONE;
IMixinEntity spongeEntity = (IMixinEntity) entityIn;
Cause cause = spongeEntity.getNonLivingDestructCause();;
if (cause == null) {
cause = Cause.of(NamedCause.source(this));
}
if (cause.root() instanceof EntityDamageSource) {
EntityDamageSource entityDamageSource = (EntityDamageSource) cause.root();
if (entityDamageSource.getSourceOfDamage() instanceof Player) {
originalChannel = ((Player) entityDamageSource.getSourceOfDamage()).getMessageChannel();
} else if (entityDamageSource instanceof IndirectEntityDamageSource) {
IndirectEntityDamageSource indirectDamageSource = (IndirectEntityDamageSource) entityDamageSource;
if (indirectDamageSource.getIndirectSource() instanceof Player) {
originalChannel = ((Player) indirectDamageSource.getIndirectSource()).getMessageChannel();
}
}
} else if (cause.root() instanceof Player) {
originalChannel = ((Player) cause.root()).getMessageChannel();
}
DestructEntityEvent event = SpongeEventFactory.createDestructEntityEvent(
cause, originalChannel, Optional.of(originalChannel), new MessageEvent.MessageFormatter(),
(Entity) entityIn, true
);
SpongeImpl.getGame().getEventManager().post(event);
if (!event.isMessageCancelled()) {
event.getChannel().ifPresent(channel -> channel.send(entityIn, event.getMessage()));
}
}
}
private void sendItemChangeToPlayer(EntityPlayerMP player) {
if (StaticMixinHelper.prePacketProcessItem == null) {
return;
}
// handle revert
player.isChangingQuantityOnly = true;
player.inventory.mainInventory[player.inventory.currentItem] = StaticMixinHelper.prePacketProcessItem;
Slot slot = player.openContainer.getSlotFromInventory(player.inventory, player.inventory.currentItem);
player.openContainer.detectAndSendChanges();
player.isChangingQuantityOnly = false;
// force client itemstack update if place event was cancelled
player.playerNetServerHandler.sendPacket(new S2FPacketSetSlot(player.openContainer.windowId, slot.slotNumber,
StaticMixinHelper.prePacketProcessItem));
}
private void processList(ListIterator<Transaction<BlockSnapshot>> listIterator) {
while (listIterator.hasPrevious()) {
Transaction<BlockSnapshot> transaction = listIterator.previous();
this.restoringBlocks = true;
transaction.getOriginal().restore(true, false);
this.restoringBlocks = false;
}
}
public boolean processSpawnEntity(Entity entity, Cause cause) {
checkNotNull(entity, "Entity cannot be null!");
checkNotNull(cause, "Cause cannot be null!");
// Very first thing - fire events that are from entity construction
if (((IMixinEntity) entity).isInConstructPhase()) {
((IMixinEntity) entity).firePostConstructEvents();
}
net.minecraft.entity.Entity entityIn = (net.minecraft.entity.Entity) entity;
// do not drop any items while restoring blocksnapshots. Prevents dupes
if (!this.getMinecraftWorld().isRemote && (entityIn == null || (entityIn instanceof net.minecraft.entity.item.EntityItem && this.restoringBlocks))) {
return false;
}
int i = MathHelper.floor_double(entityIn.posX / 16.0D);
int j = MathHelper.floor_double(entityIn.posZ / 16.0D);
boolean flag = entityIn.forceSpawn;
List<NamedCause> namedCauses = new ArrayList<>();
for (Map.Entry<String, Object> entry : cause.getNamedCauses().entrySet()) {
if (entry.getKey().equals(NamedCause.SOURCE)) {
if (!(entry.getValue() instanceof SpawnCause)) {
SpawnType type;
if (entity instanceof EntityItem) {
type = SpawnTypes.DROPPED_ITEM;
} else {
type = SpawnTypes.CUSTOM;
}
namedCauses.add(NamedCause.source(SpawnCause.builder().type(type).build()));
} else {
namedCauses.add(NamedCause.source(entry.getValue()));
}
} else {
namedCauses.add(NamedCause.of(entry.getKey(), entry.getValue()));
}
}
cause = Cause.of(namedCauses);
if (entityIn instanceof EntityPlayer) {
flag = true;
} else if (entityIn instanceof EntityLightningBolt) {
((IMixinEntityLightningBolt) entityIn).setCause(cause);
}
if (!flag && !this.getMinecraftWorld().isChunkLoaded(i, j, true)) {
return false;
} else {
if (entityIn instanceof EntityPlayer) {
EntityPlayer entityplayer = (EntityPlayer) entityIn;
net.minecraft.world.World world = this.targetWorld;
world.playerEntities.add(entityplayer);
world.updateAllPlayersSleepingFlag();
}
if (this.getMinecraftWorld().isRemote || flag || this.spawningDeathDrops) {
if (SpongeImpl.postEvent(SpongeEventFactory.createSpawnEntityEventCustom(cause, Lists.newArrayList(entity),
Lists.newArrayList(entity.createSnapshot()), getWorld())) && !flag) {
return false;
}
this.getMinecraftWorld().getChunkFromChunkCoords(i, j).addEntity(entityIn);
this.getMinecraftWorld().loadedEntityList.add(entityIn);
this.getMixinWorld().onSpongeEntityAdded(entityIn);
return true;
}
if (!flag && this.processingCaptureCause && !this.captureTerrainGen) {
if (this.currentTickBlock != null) {
BlockPos sourcePos = VecHelper.toBlockPos(this.currentTickBlock.getPosition());
Block targetBlock = getMinecraftWorld().getBlockState(entityIn.getPosition()).getBlock();
SpongeHooks
.tryToTrackBlockAndEntity(this.getMinecraftWorld(), this.currentTickBlock, entityIn, sourcePos, targetBlock, entityIn.getPosition(),
PlayerTracker.Type.NOTIFIER);
}
if (this.currentTickEntity != null) {
Optional<User> creator = ((IMixinEntity) this.currentTickEntity).getTrackedPlayer(NbtDataUtil.SPONGE_ENTITY_CREATOR);
if (creator.isPresent()) { // transfer user to next entity. This occurs with falling blocks that change into items
((IMixinEntity) entityIn).trackEntityUniqueId(NbtDataUtil.SPONGE_ENTITY_CREATOR, creator.get().getUniqueId());
}
}
if (entityIn instanceof EntityItem) {
this.capturedEntityItems.add((Item) entityIn);
} else {
this.capturedEntities.add((Entity) entityIn);
}
return true;
} else { // Custom
if (entityIn instanceof EntityFishHook && ((EntityFishHook) entityIn).angler == null) {
// TODO MixinEntityFishHook.setShooter makes angler null
// sometimes, but that will cause NPE when ticking
return false;
}
EntityLivingBase specialCause = null;
String causeName = "";
// Special case for throwables
if (!(entityIn instanceof EntityPlayer) && entityIn instanceof EntityThrowable) {
EntityThrowable throwable = (EntityThrowable) entityIn;
specialCause = throwable.getThrower();
if (specialCause != null) {
causeName = NamedCause.THROWER;
if (specialCause instanceof Player) {
Player player = (Player) specialCause;
((IMixinEntity) entityIn).trackEntityUniqueId(NbtDataUtil.SPONGE_ENTITY_CREATOR, player.getUniqueId());
}
}
}
// Special case for TNT
else if (!(entityIn instanceof EntityPlayer) && entityIn instanceof EntityTNTPrimed) {
EntityTNTPrimed tntEntity = (EntityTNTPrimed) entityIn;
specialCause = tntEntity.getTntPlacedBy();
causeName = NamedCause.IGNITER;
if (specialCause instanceof Player) {
Player player = (Player) specialCause;
((IMixinEntity) entityIn).trackEntityUniqueId(NbtDataUtil.SPONGE_ENTITY_CREATOR, player.getUniqueId());
}
}
// Special case for Tameables
else if (!(entityIn instanceof EntityPlayer) && entityIn instanceof EntityTameable) {
EntityTameable tameable = (EntityTameable) entityIn;
if (tameable.getOwner() != null) {
specialCause = tameable.getOwner();
causeName = NamedCause.OWNER;
}
}
if (specialCause != null && !cause.containsNamed(causeName)) {
cause = cause.with(NamedCause.of(causeName, specialCause));
}
org.spongepowered.api.event.Event event = null;
ImmutableList.Builder<EntitySnapshot> entitySnapshotBuilder = new ImmutableList.Builder<>();
entitySnapshotBuilder.add(((Entity) entityIn).createSnapshot());
if (entityIn instanceof EntityItem) {
this.capturedEntityItems.add((Item) entityIn);
event = SpongeEventFactory.createDropItemEventCustom(cause, this.capturedEntityItems,
entitySnapshotBuilder.build(), this.getWorld());
} else {
this.capturedEntities.add((Entity) entityIn);
event = SpongeEventFactory.createSpawnEntityEventCustom(cause, this.capturedEntities,
entitySnapshotBuilder.build(), this.getWorld());
}
boolean cancelled = SpongeImpl.postEvent(event);
if (entityIn instanceof EntityItem) {
this.capturedEntityItems.remove(entityIn);
} else {
this.capturedEntities.remove(entityIn);
}
if (!cancelled && !entity.isRemoved()) {
if (entityIn instanceof EntityWeatherEffect) {
return addWeatherEffect(entityIn, cause);
}
this.getMinecraftWorld().getChunkFromChunkCoords(i, j).addEntity(entityIn);
this.getMinecraftWorld().loadedEntityList.add(entityIn);
this.getMixinWorld().onSpongeEntityAdded(entityIn);
return true;
}
return false;
}
}
}
public void randomTickBlock(Block block, BlockPos pos, IBlockState state, Random random) {
this.processingCaptureCause = true;
this.processingBlockRandomTicks = true;
this.currentTickBlock = this.getMixinWorld().createSpongeBlockSnapshot(state, state.getBlock().getActualState(state, this.getMinecraftWorld(), pos), pos, 0);
block.randomTick(this.getMinecraftWorld(), pos, state, random);
this.handlePostTickCaptures(Cause.of(NamedCause.source(this.currentTickBlock)));
this.currentTickBlock = null;
this.processingCaptureCause = false;
this.processingBlockRandomTicks = false;
}
public void updateTickBlock(Block block, BlockPos pos, IBlockState state, Random rand) {
this.processingCaptureCause = true;
this.currentTickBlock = this.getMixinWorld().createSpongeBlockSnapshot(state, state.getBlock().getActualState(state, this.getMinecraftWorld(), pos), pos, 0);
block.updateTick(this.getMinecraftWorld(), pos, state, rand);
this.handlePostTickCaptures(Cause.of(NamedCause.source(this.currentTickBlock)));
this.currentTickBlock = null;
this.processingCaptureCause = false;
}
public void notifyBlockOfStateChange(BlockPos notifyPos, final Block sourceBlock, BlockPos sourcePos) {
if (!this.getMinecraftWorld().isRemote) {
IBlockState iblockstate = this.getMinecraftWorld().getBlockState(notifyPos);
if (iblockstate == Blocks.air.getDefaultState()) {
iblockstate.getBlock().onNeighborBlockChange(this.getMinecraftWorld(), notifyPos, iblockstate, sourceBlock);
return;
}
try {
if (!this.getMinecraftWorld().isRemote) {
if (StaticMixinHelper.packetPlayer != null) {
IMixinChunk spongeChunk = (IMixinChunk) this.getMinecraftWorld().getChunkFromBlockCoords(notifyPos);
if (!(spongeChunk instanceof EmptyChunk)) {
spongeChunk.addTrackedBlockPosition(iblockstate.getBlock(), notifyPos, (User) StaticMixinHelper.packetPlayer,
PlayerTracker.Type.NOTIFIER);
}
} else {
Object source = null;
if (this.hasTickingBlock()) {
source = this.getCurrentTickBlock().get();
sourcePos = VecHelper.toBlockPos(this.getCurrentTickBlock().get().getPosition());
} else if (this.hasTickingTileEntity()) {
source = this.getCurrentTickTileEntity().get();
sourcePos = ((net.minecraft.tileentity.TileEntity) this.getCurrentTickTileEntity().get()).getPos();
} else if (this.hasTickingEntity()) { // Falling Blocks
IMixinEntity spongeEntity = (IMixinEntity) this.getCurrentTickEntity().get();
sourcePos = ((net.minecraft.entity.Entity) this.getCurrentTickEntity().get()).getPosition();
Optional<User> owner = spongeEntity.getTrackedPlayer(NbtDataUtil.SPONGE_ENTITY_CREATOR);
Optional<User> notifier = spongeEntity.getTrackedPlayer(NbtDataUtil.SPONGE_ENTITY_NOTIFIER);
if (notifier.isPresent()) {
IMixinChunk spongeChunk = (IMixinChunk) this.getMinecraftWorld().getChunkFromBlockCoords(notifyPos);
spongeChunk.addTrackedBlockPosition(iblockstate.getBlock(), notifyPos, notifier.get(), PlayerTracker.Type.NOTIFIER);
} else if (owner.isPresent()) {
IMixinChunk spongeChunk = (IMixinChunk) this.getMinecraftWorld().getChunkFromBlockCoords(notifyPos);
spongeChunk.addTrackedBlockPosition(iblockstate.getBlock(), notifyPos, owner.get(), PlayerTracker.Type.NOTIFIER);
}
}
if (source != null) {
SpongeHooks.tryToTrackBlock(this.getMinecraftWorld(), source, sourcePos, iblockstate.getBlock(), notifyPos,
PlayerTracker.Type.NOTIFIER);
}
}
}
iblockstate.getBlock().onNeighborBlockChange(this.getMinecraftWorld(), notifyPos, iblockstate, sourceBlock);
} catch (Throwable throwable) {
CrashReport crashreport = CrashReport.makeCrashReport(throwable, "Exception while updating neighbours");
CrashReportCategory crashreportcategory = crashreport.makeCategory("Block being updated");
// TODO
/*crashreportcategory.addCrashSectionCallable("Source block type", new Callable()
{
public String call() {
try {
return String.format("ID #%d (%s // %s)", new Object[] {Integer.valueOf(Block.getIdFromBlock(blockIn)), blockIn.getUnlocalizedName(), blockIn.getClass().getCanonicalName()});
} catch (Throwable throwable1) {
return "ID #" + Block.getIdFromBlock(blockIn);
}
}
});*/
CrashReportCategory.addBlockInfo(crashreportcategory, notifyPos, iblockstate);
throw new ReportedException(crashreport);
}
}
}
public void markAndNotifyBlockPost(List<Transaction<BlockSnapshot>> transactions, CaptureType type, Cause cause) {
// We have to use a proxy so that our pending changes are notified such that any accessors from block
// classes do not fail on getting the incorrect block state from the IBlockAccess
SpongeProxyBlockAccess proxyBlockAccess = new SpongeProxyBlockAccess(this.getMinecraftWorld(), transactions);
for (Transaction<BlockSnapshot> transaction : transactions) {
if (!transaction.isValid()) {
continue; // Don't use invalidated block transactions during notifications, these only need to be restored
}
// Handle custom replacements
if (transaction.getCustom().isPresent()) {
this.setRestoringBlocks(true);
transaction.getFinal().restore(true, false);
this.setRestoringBlocks(false);
}
SpongeBlockSnapshot oldBlockSnapshot = (SpongeBlockSnapshot) transaction.getOriginal();
SpongeBlockSnapshot newBlockSnapshot = (SpongeBlockSnapshot) transaction.getFinal();
SpongeHooks.logBlockAction(cause, this.getMinecraftWorld(), type, transaction);
int updateFlag = oldBlockSnapshot.getUpdateFlag();
BlockPos pos = VecHelper.toBlockPos(oldBlockSnapshot.getPosition());
IBlockState originalState = (IBlockState) oldBlockSnapshot.getState();
IBlockState newState = (IBlockState) newBlockSnapshot.getState();
BlockSnapshot currentTickingBlock = this.getCurrentTickBlock().orElse(null);
// Containers get placed automatically
if (originalState.getBlock() != newState.getBlock() && !SpongeImplHooks.blockHasTileEntity(newState.getBlock(), newState)) {
this.setCurrentTickBlock(this.getMixinWorld().createSpongeBlockSnapshot(newState,
newState.getBlock().getActualState(newState, proxyBlockAccess, pos), pos, updateFlag));
newState.getBlock().onBlockAdded(this.getMinecraftWorld(), pos, newState);
if (shouldChainCause(cause)) {
cause = cause.merge(Cause.of(NamedCause.source(this.currentTickBlock)));
}
}
proxyBlockAccess.proceed();
this.getMixinWorld().markAndNotifyNeighbors(pos, null, originalState, newState, updateFlag);
// Handle any additional captures during notify
// This is to ensure new captures do not leak into next tick with wrong cause
if (this.getCapturedSpongeBlockSnapshots().size() > 0 && this.pluginCause == null) {
this.handlePostTickCaptures(cause);
}
this.setCurrentTickBlock(currentTickingBlock);
}
}
private boolean shouldChainCause(Cause cause) {
return !this.isCapturingTerrainGen() && !this.isWorldSpawnerRunning() && !this.isChunkSpawnerRunning()
&& !this.isProcessingBlockRandomTicks() && !this.isCaptureCommand() && this.hasTickingBlock() && this.pluginCause == null
&& !cause.contains(this.getCurrentTickBlock().get()) && !(StaticMixinHelper.processingPacket instanceof C03PacketPlayer);
}
}
|
Fix infinate capture when spawning entities on a spawn entity event
Fixes SpongePowered/SpongeForge#620
|
src/main/java/org/spongepowered/common/event/CauseTracker.java
|
Fix infinate capture when spawning entities on a spawn entity event
|
|
Java
|
epl-1.0
|
89f53bba0bfd4e4d7ff58565a5cedfc8c06e0e0b
| 0
|
rohitmohan96/ceylon-ide-eclipse,rohitmohan96/ceylon-ide-eclipse
|
package com.redhat.ceylon.eclipse.core.debug;
import java.util.Arrays;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.debug.core.DebugException;
import org.eclipse.debug.core.model.IDebugElement;
import org.eclipse.debug.core.model.IDebugTarget;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.Signature;
import org.eclipse.jdt.debug.core.IJavaStackFrame;
import com.redhat.ceylon.compiler.typechecker.context.PhasedUnit;
import com.redhat.ceylon.compiler.typechecker.context.PhasedUnits;
import com.redhat.ceylon.compiler.typechecker.model.Declaration;
import com.redhat.ceylon.compiler.typechecker.model.Module;
import com.redhat.ceylon.eclipse.core.builder.CeylonBuilder;
import com.redhat.ceylon.eclipse.core.model.JDTModule;
import com.redhat.ceylon.eclipse.core.typechecker.CrossProjectPhasedUnit;
import com.redhat.ceylon.eclipse.util.JavaSearch;
import com.sun.jdi.ClassNotLoadedException;
import com.sun.jdi.Location;
import com.sun.jdi.Method;
public class DebugUtils {
static IProject getProject(IDebugElement debugElement) {
IDebugTarget target = debugElement.getDebugTarget();
if (target instanceof CeylonJDIDebugTarget) {
return ((CeylonJDIDebugTarget) target).getProject();
}
return null;
}
public static IMethod getStackFrameMethod(IJavaStackFrame frame) {
IProject project = getProject(frame);
IJavaProject javaProject = JavaCore.create(project);
try {
IType declaringType = javaProject.findType(frame.getReferenceType().getName());
if (declaringType != null) {
for (IMethod method : declaringType.getMethods()) {
if (method.getElementName().equals(frame.getMethodName()) ||
frame.isConstructor() && method.isConstructor()) {
String[] methodParameterTypes = new String[method.getParameterTypes().length];
int i = 0;
for (String signature : method.getParameterTypes()) {
methodParameterTypes[i++] = Signature.toString(signature);
}
if (Arrays.equals(methodParameterTypes, frame.getArgumentTypeNames().toArray())) {
return method;
}
}
}
}
} catch (CoreException e) {
e.printStackTrace();
}
return null;
}
public static PhasedUnit getStackFramePhasedUnit(IJavaStackFrame frame) {
IProject project = getProject(frame);
try {
PhasedUnits projectPhasedUnits = CeylonBuilder.getProjectPhasedUnits(project);
if (projectPhasedUnits != null) {
PhasedUnit phasedUnit = null;
phasedUnit = projectPhasedUnits.getPhasedUnitFromRelativePath(frame.getSourcePath());
if (phasedUnit != null) {
return phasedUnit;
}
}
for (Module module : CeylonBuilder.getProjectExternalModules(project)) {
if (module instanceof JDTModule) {
JDTModule jdtModule = (JDTModule) module;
if (jdtModule.isCeylonArchive()) {
PhasedUnit phasedUnit = jdtModule.getPhasedUnitFromRelativePath(frame.getSourcePath());
if (phasedUnit != null) {
if (phasedUnit instanceof CrossProjectPhasedUnit) {
phasedUnit = ((CrossProjectPhasedUnit) phasedUnit).getOriginalProjectPhasedUnit();
}
return phasedUnit;
}
}
}
}
} catch (DebugException e) {
e.printStackTrace();
}
return null;
}
public static Declaration getStackFrameCeylonDeclaration(IJavaStackFrame frame) {
IMethod method = getStackFrameMethod(frame);
PhasedUnit unit = getStackFramePhasedUnit(frame);
if (method != null && unit != null) {
return JavaSearch.toCeylonDeclaration(method, Arrays.asList(unit));
}
return null;
}
public static boolean isCeylonFrame(IJavaStackFrame frame) {
try {
if (frame.getSourceName() != null &&
frame.getSourceName().endsWith(".ceylon")) {
return true;
}
} catch (DebugException e) {
e.printStackTrace();
}
return false;
}
public static boolean isMethodFilteredForCeylon(Method method) {
Location location = method.location();
String declaringTypeName = location.declaringType().name();
if (declaringTypeName.equals("ceylon.language.Boolean")) {
return true;
}
if (declaringTypeName.equals("ceylon.language.Integer")
&& ( method.name().equals("instance") ||
method.name().equals("longValue") ||
method.isConstructor())) {
return true;
}
if (declaringTypeName.equals("ceylon.language.Float")
&& ( method.name().equals("instance") ||
method.name().equals("doubleValue") ||
method.isConstructor())) {
return true;
}
if (declaringTypeName.equals("ceylon.language.Byte")
&& ( method.name().equals("instance") ||
method.name().equals("byteValue") ||
method.isConstructor())) {
return true;
}
if (declaringTypeName.equals("ceylon.language.String")
&& ( method.name().equals("instance") ||
method.name().equals("toString") ||
( method.isConstructor()
&& method.argumentTypeNames().size() == 1
&& "java.lang.String".equals(method.argumentTypeNames().get(0))))) {
return true;
}
if (declaringTypeName.startsWith("ceylon.language.impl.Base")) {
return true;
}
if (declaringTypeName.endsWith("$impl") &&
method.isConstructor()) {
return true;
}
if (declaringTypeName.startsWith("com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor")) {
return true;
}
if (method.name().equals("$getType$")) {
return true;
}
try {
if (method.isStatic() &&
method.name().equals("get_") &&
method.argumentTypeNames().isEmpty() &&
method.returnType().name().equals(method.declaringType().name())) {
return true;
}
} catch (ClassNotLoadedException e) {
}
return false;
}
}
|
plugins/com.redhat.ceylon.eclipse.ui/src/com/redhat/ceylon/eclipse/core/debug/DebugUtils.java
|
package com.redhat.ceylon.eclipse.core.debug;
import java.util.Arrays;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.debug.core.DebugException;
import org.eclipse.debug.core.model.IDebugElement;
import org.eclipse.debug.core.model.IDebugTarget;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.Signature;
import org.eclipse.jdt.debug.core.IJavaStackFrame;
import com.redhat.ceylon.compiler.typechecker.context.PhasedUnit;
import com.redhat.ceylon.compiler.typechecker.context.PhasedUnits;
import com.redhat.ceylon.compiler.typechecker.model.Declaration;
import com.redhat.ceylon.compiler.typechecker.model.Module;
import com.redhat.ceylon.eclipse.core.builder.CeylonBuilder;
import com.redhat.ceylon.eclipse.core.model.JDTModule;
import com.redhat.ceylon.eclipse.core.typechecker.CrossProjectPhasedUnit;
import com.redhat.ceylon.eclipse.util.JavaSearch;
import com.sun.jdi.Location;
import com.sun.jdi.Method;
public class DebugUtils {
static IProject getProject(IDebugElement debugElement) {
IDebugTarget target = debugElement.getDebugTarget();
if (target instanceof CeylonJDIDebugTarget) {
return ((CeylonJDIDebugTarget) target).getProject();
}
return null;
}
public static IMethod getStackFrameMethod(IJavaStackFrame frame) {
IProject project = getProject(frame);
IJavaProject javaProject = JavaCore.create(project);
try {
IType declaringType = javaProject.findType(frame.getDeclaringTypeName());
if (declaringType != null) {
for (IMethod method : declaringType.getMethods()) {
if (method.getElementName().equals(frame.getMethodName()) ||
frame.isConstructor() && method.isConstructor()) {
String[] methodParameterTypes = new String[method.getParameterTypes().length];
int i = 0;
for (String signature : method.getParameterTypes()) {
methodParameterTypes[i++] = Signature.toString(signature);
}
if (Arrays.equals(methodParameterTypes, frame.getArgumentTypeNames().toArray())) {
return method;
}
}
}
}
} catch (CoreException e) {
e.printStackTrace();
}
return null;
}
public static PhasedUnit getStackFramePhasedUnit(IJavaStackFrame frame) {
IProject project = getProject(frame);
try {
PhasedUnits projectPhasedUnits = CeylonBuilder.getProjectPhasedUnits(project);
if (projectPhasedUnits != null) {
PhasedUnit phasedUnit = null;
phasedUnit = projectPhasedUnits.getPhasedUnitFromRelativePath(frame.getSourcePath());
if (phasedUnit != null) {
return phasedUnit;
}
}
for (Module module : CeylonBuilder.getProjectExternalModules(project)) {
if (module instanceof JDTModule) {
JDTModule jdtModule = (JDTModule) module;
if (jdtModule.isCeylonArchive()) {
PhasedUnit phasedUnit = jdtModule.getPhasedUnitFromRelativePath(frame.getSourcePath());
if (phasedUnit != null) {
if (phasedUnit instanceof CrossProjectPhasedUnit) {
phasedUnit = ((CrossProjectPhasedUnit) phasedUnit).getOriginalProjectPhasedUnit();
}
return phasedUnit;
}
}
}
}
} catch (DebugException e) {
e.printStackTrace();
}
return null;
}
public static Declaration getStackFrameCeylonDeclaration(IJavaStackFrame frame) {
IMethod method = getStackFrameMethod(frame);
PhasedUnit unit = getStackFramePhasedUnit(frame);
if (method != null && unit != null) {
return JavaSearch.toCeylonDeclaration(method, Arrays.asList(unit));
}
return null;
}
public static boolean isCeylonFrame(IJavaStackFrame frame) {
try {
if (frame.getSourceName() != null &&
frame.getSourceName().endsWith(".ceylon")) {
return true;
}
} catch (DebugException e) {
e.printStackTrace();
}
return false;
}
public static boolean isMethodFilteredForCeylon(Method method) {
Location location = method.location();
String declaringTypeName = location.declaringType().name();
if (declaringTypeName.equals("ceylon.language.Boolean")) {
return true;
}
if (declaringTypeName.equals("ceylon.language.Integer")
&& ( method.name().equals("instance") ||
method.name().equals("longValue") ||
method.isConstructor())) {
return true;
}
if (declaringTypeName.equals("ceylon.language.Float")
&& ( method.name().equals("instance") ||
method.name().equals("doubleValue") ||
method.isConstructor())) {
return true;
}
if (declaringTypeName.equals("ceylon.language.Byte")
&& ( method.name().equals("instance") ||
method.name().equals("byteValue") ||
method.isConstructor())) {
return true;
}
if (declaringTypeName.equals("ceylon.language.String")
&& ( method.name().equals("instance") ||
( method.isConstructor()
&& method.argumentTypeNames().size() == 1
&& "java.lang.String".equals(method.argumentTypeNames().get(0))))) {
return true;
}
if (declaringTypeName.startsWith("com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor")) {
return true;
}
if (method.name().equals("$getType$")) {
return true;
}
return false;
}
}
|
Enhanced Step filtering
|
plugins/com.redhat.ceylon.eclipse.ui/src/com/redhat/ceylon/eclipse/core/debug/DebugUtils.java
|
Enhanced Step filtering
|
|
Java
|
epl-1.0
|
97508c5f55126c09cd19f7b1693d77189404c879
| 0
|
css-iter/cs-studio,css-iter/cs-studio,css-iter/cs-studio,ControlSystemStudio/cs-studio,ESSICS/cs-studio,ControlSystemStudio/cs-studio,css-iter/cs-studio,css-iter/cs-studio,ESSICS/cs-studio,ESSICS/cs-studio,ControlSystemStudio/cs-studio,ControlSystemStudio/cs-studio,css-iter/cs-studio,ControlSystemStudio/cs-studio,css-iter/cs-studio,ESSICS/cs-studio,ESSICS/cs-studio,ControlSystemStudio/cs-studio,ESSICS/cs-studio,ESSICS/cs-studio
|
/*******************************************************************************
* Copyright (c) 2010 Oak Ridge National Laboratory.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
******************************************************************************/
package org.csstudio.opibuilder.visualparts;
import org.csstudio.ui.util.CustomMediaFactory;
import org.csstudio.ui.util.SWTConstants;
import org.eclipse.draw2d.AbstractBorder;
import org.eclipse.draw2d.AbstractLabeledBorder;
import org.eclipse.draw2d.GroupBoxBorder;
import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.LineBorder;
import org.eclipse.draw2d.SchemeBorder;
import org.eclipse.draw2d.SchemeBorder.Scheme;
import org.eclipse.draw2d.TitleBarBorder;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.RGB;
/**The factory to create borders for {@link IFigure}
* @author Xihui Chen
*
*/
public class BorderFactory {
public static AbstractBorder createBorder(BorderStyle style, int width, RGB rgbColor,
String text){
Color color = CustomMediaFactory.getInstance().getColor(rgbColor);
switch (style) {
case LINE:
return createLineBorder(SWTConstants.LINE_SOLID, width, color);
case RAISED:
return createSchemeBorder(SchemeBorder.SCHEMES.RAISED);
case LOWERED:
return createSchemeBorder(SchemeBorder.SCHEMES.LOWERED);
case ETCHED:
return createSchemeBorder(SchemeBorder.SCHEMES.ETCHED);
case RIDGED:
return createSchemeBorder(SchemeBorder.SCHEMES.RIDGED);
case BUTTON_RAISED:
return createSchemeBorder(SchemeBorder.SCHEMES.BUTTON_CONTRAST);
case BUTTON_PRESSED:
return createSchemeBorder(SchemeBorder.SCHEMES.BUTTON_PRESSED);
case DASH_DOT:
return createLineBorder(SWTConstants.LINE_DASHDOT, width, color);
case DASHED:
return createLineBorder(SWTConstants.LINE_DASH, width, color);
case DOTTED:
return createLineBorder(SWTConstants.LINE_DOT, width, color);
case DASH_DOT_DOT:
return createLineBorder(SWTConstants.LINE_DASHDOTDOT, width, color);
case GROUP_BOX:
return createGroupBoxBorder(text, color);
case TITLE_BAR:
return createTitleBarBorder(text, color);
case NONE:
default:
return null;
}
}
/**
* Creates a LineBorder.
*
* @return AbstractBorder The requested Border
*/
private static AbstractBorder createLineBorder(int style, int width, Color color) {
if (width>0) {
LineBorder border = new VersatileLineBorder(color, width, style);
return border;
}
return null;
}
/**
* Creates a SchemeBorder.
* @param scheme the scheme for the {@link SchemeBorder}
* @return AbstractBorder The requested Border
*/
private static AbstractBorder createSchemeBorder(final Scheme scheme) {
SchemeBorder border = new SchemeBorder(scheme);
return border;
}
private static AbstractBorder createGroupBoxBorder(String text, Color textColor) {
AbstractLabeledBorder border = new GroupBoxBorder(text);
border.setTextColor(textColor);
return border;
}
private static AbstractBorder createTitleBarBorder(String text, Color color) {
WidgetFrameBorder border = new WidgetFrameBorder(text);
((TitleBarBorder)border.getInnerBorder()).setBackgroundColor(color);
return border;
}
}
|
applications/plugins/org.csstudio.opibuilder/src/org/csstudio/opibuilder/visualparts/BorderFactory.java
|
/*******************************************************************************
* Copyright (c) 2010 Oak Ridge National Laboratory.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
******************************************************************************/
package org.csstudio.opibuilder.visualparts;
import org.csstudio.ui.util.CustomMediaFactory;
import org.csstudio.ui.util.SWTConstants;
import org.eclipse.draw2d.AbstractBorder;
import org.eclipse.draw2d.AbstractLabeledBorder;
import org.eclipse.draw2d.GroupBoxBorder;
import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.LineBorder;
import org.eclipse.draw2d.SchemeBorder;
import org.eclipse.draw2d.SchemeBorder.Scheme;
import org.eclipse.draw2d.TitleBarBorder;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.RGB;
/**The factory to create borders for {@link IFigure}
* @author Xihui Chen
*
*/
public class BorderFactory {
public static AbstractBorder createBorder(BorderStyle style, int width, RGB rgbColor,
String text){
Color color = CustomMediaFactory.getInstance().getColor(rgbColor);
switch (style) {
case LINE:
return createLineBorder(SWTConstants.LINE_SOLID, width, color);
case RAISED:
return createSchemeBorder(SchemeBorder.SCHEMES.RAISED);
case LOWERED:
return createSchemeBorder(SchemeBorder.SCHEMES.LOWERED);
case ETCHED:
return createSchemeBorder(SchemeBorder.SCHEMES.ETCHED);
case RIDGED:
return createSchemeBorder(SchemeBorder.SCHEMES.RIDGED);
case BUTTON_RAISED:
return createSchemeBorder(SchemeBorder.SCHEMES.BUTTON_CONTRAST);
case BUTTON_PRESSED:
return createSchemeBorder(SchemeBorder.SCHEMES.BUTTON_PRESSED);
case DASH_DOT:
return createLineBorder(SWTConstants.LINE_DASHDOT, width, color);
case DASHED:
return createLineBorder(SWTConstants.LINE_DASH, width, color);
case DOTTED:
return createLineBorder(SWTConstants.LINE_DOT, width, color);
case DASH_DOT_DOT:
return createLineBorder(SWTConstants.LINE_DASHDOTDOT, width, color);
case GROUP_BOX:
return createGroupBoxBorder(text);
case TITLE_BAR:
return createTitleBarBorder(text, color);
case NONE:
default:
return null;
}
}
/**
* Creates a LineBorder.
*
* @return AbstractBorder The requested Border
*/
private static AbstractBorder createLineBorder(int style, int width, Color color) {
if (width>0) {
LineBorder border = new VersatileLineBorder(color, width, style);
return border;
}
return null;
}
/**
* Creates a SchemeBorder.
* @param scheme the scheme for the {@link SchemeBorder}
* @return AbstractBorder The requested Border
*/
private static AbstractBorder createSchemeBorder(final Scheme scheme) {
SchemeBorder border = new SchemeBorder(scheme);
return border;
}
private static AbstractBorder createGroupBoxBorder(String text) {
AbstractLabeledBorder border = new GroupBoxBorder(text);
return border;
}
private static AbstractBorder createTitleBarBorder(String text, Color color) {
WidgetFrameBorder border = new WidgetFrameBorder(text);
((TitleBarBorder)border.getInnerBorder()).setBackgroundColor(color);
return border;
}
}
|
BOY: use border color as the text color on Group Box Style Border.
|
applications/plugins/org.csstudio.opibuilder/src/org/csstudio/opibuilder/visualparts/BorderFactory.java
|
BOY: use border color as the text color on Group Box Style Border.
|
|
Java
|
mpl-2.0
|
6539a341065409704be161154bbd656413d1e949
| 0
|
PharmGKB/PharmCAT,PharmGKB/PharmCAT,PharmGKB/PharmCAT
|
package org.pharmgkb.pharmcat.haplotype;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.annotation.Nonnull;
import org.apache.commons.lang3.ObjectUtils;
/**
* Object to hold information about varaints from the tsv file.
*
* @author nate
*
*/
public class Variant implements Comparable<Variant> {
private String CHROM;
private String GeneName;
private int POS;
private String GenePOS;
private ArrayList<String> HGVSg = new ArrayList<>();
private ArrayList<String> cDNA = new ArrayList<>();
private ArrayList<String> ProteinEffect = new ArrayList<>();
private ArrayList<String> ALTs = new ArrayList<>();
private String REF;
private String rsID;
/**
* @param _CHROM
* @param _GeneName
* @param _cDNA
*/
public Variant(String _CHROM, String _GeneName,String _cDNA){
CHROM = _CHROM;
GeneName = _GeneName;
if (_cDNA.contains(";")){
String [] fields = _cDNA.split(";");
for (int i = 0; i < fields.length; i++){
cDNA.add(fields[i].trim());
}
}else{
cDNA.add(_cDNA);
}
}
/**
* @param _CHROM
* @param _GeneName
*/
public Variant(String _CHROM, String _GeneName){
CHROM = _CHROM;
GeneName = _GeneName;
}
/**
* @return
*/
public String getCHROM(){
return CHROM;
}
/**
* @return
*/
public String getGeneName(){
return GeneName;
}
/**
* @param _cDNA
*/
public void set_cDNA(String _cDNA){
if (_cDNA.contains(";")){
String [] fields = _cDNA.split(";");
for (int i = 0; i < fields.length; i++){
cDNA.add(fields[i].trim());
}
}else{
cDNA.add(_cDNA);
}
}
/**
* @param _ProteingEffect
*/
public void addProteingEffect(String _ProteingEffect){
if (_ProteingEffect.contains(";")){
String [] fields = _ProteingEffect.split(";");
for (int i = 0; i < fields.length; i++){
ProteinEffect.add(fields[i].trim());
}
}else{
ProteinEffect.add(_ProteingEffect);
}
}
/**
* @param _HGVSg
*/
public void addHGVSg(String _HGVSg){
if (_HGVSg.contains(";")){
String [] fields = _HGVSg.split(";");
for (int i = 0; i < fields.length; i++){
HGVSg.add(fields[i].trim());
}
}else{
HGVSg.add(_HGVSg);
}
}
public String getHGVSg(){
return HGVSg.toString();
}
/**
* @param _HGVSg
* @return
*/
private int getStartPOS(String _HGVSg){
Pattern p = Pattern.compile("(\\d+)");
Matcher m = p.matcher(_HGVSg);
//System.out.println(_HGVSg);
if(m.find()){
return Integer.parseInt(m.group(1));
}
else {return -1;}
}
/**
* @return
*/
public boolean setStartPOS(){
if (HGVSg.isEmpty()){
return false;
}else{
POS = getStartPOS(HGVSg.get(0));
return true;
}
}
/**
* @return
*/
public int getPOS(){
return POS;
}
/**
* @param _POS
*/
public void setPOS(String _POS){
POS = Integer.parseInt(_POS);
}
/**
* @return
*/
public String getGenePOS(){
return GenePOS;
}
/**
* @param _GenePOS
*/
public void setGenePOS(String _GenePOS){
GenePOS = _GenePOS;
}
/**
* @return
*/
public String getREF(){
return REF;
}
/**
* @param _REF
*/
public void setREF(String _REF){
REF = (_REF);
}
/**
* @return
*/
public String get_rsID(){
return rsID;
}
/**
* @param _rsID
*/
public void set_rsID(String _rsID){
rsID = (_rsID);
}
/**
* @param _ALT
*/
public void addALT(String _ALT){
ALTs.add(_ALT);
}
/**
* @return
*/
public ArrayList<String> getALTs(){
return ALTs;
}
@Override
public int compareTo(@Nonnull Variant o) {
int rez = ObjectUtils.compare(CHROM, o.CHROM);
if (rez != 0) {
return rez;
}
rez = ObjectUtils.compare(POS, o.POS);
if (rez != 0) {
return rez;
}
return ObjectUtils.compare(GeneName, o.GeneName);
}
}
|
src/main/java/org/pharmgkb/pharmcat/haplotype/Variant.java
|
package org.pharmgkb.pharmcat.haplotype;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.annotation.Nonnull;
import org.apache.commons.lang3.ObjectUtils;
/**
* Object to hold information about varaints from the tsv file.
*
* @author nate
*
*/
public class Variant implements Comparable<Variant> {
private String CHROM;
private String GeneName;
private int POS;
private String GenePOS;
private ArrayList<String> HGVSg = new ArrayList<>();
private ArrayList<String> cDNA = new ArrayList<>();
private ArrayList<String> ProteinEffect = new ArrayList<>();
private ArrayList<String> ALTs = new ArrayList<>();
private String REF;
private String rsID;
/**
* @param _CHROM
* @param _GeneName
* @param _cDNA
*/
public Variant(String _CHROM, String _GeneName,String _cDNA){
CHROM = _CHROM;
GeneName = _GeneName;
if (_cDNA.contains(";")){
String [] fields = _cDNA.split(";");
for (int i = 0; i < fields.length; i++){
cDNA.add(fields[i].trim());
}
}else{
cDNA.add(_cDNA);
}
}
/**
* @param _CHROM
* @param _GeneName
*/
public Variant(String _CHROM, String _GeneName){
CHROM = _CHROM;
GeneName = _GeneName;
}
/**
* @return
*/
public String getCHROM(){
return CHROM;
}
/**
* @return
*/
public String getGeneName(){
return GeneName;
}
/**
* @param _cDNA
*/
public void set_cDNA(String _cDNA){
if (_cDNA.contains(";")){
String [] fields = _cDNA.split(";");
for (int i = 0; i < fields.length; i++){
cDNA.add(fields[i].trim());
}
}else{
cDNA.add(_cDNA);
}
}
/**
* @param _ProteingEffect
*/
public void addProteingEffect(String _ProteingEffect){
if (_ProteingEffect.contains(";")){
String [] fields = _ProteingEffect.split(";");
for (int i = 0; i < fields.length; i++){
ProteinEffect.add(fields[i].trim());
}
}else{
ProteinEffect.add(_ProteingEffect);
}
}
/**
* @param _HGVSg
*/
public void addHGVSg(String _HGVSg){
if (_HGVSg.contains(";")){
String [] fields = _HGVSg.split(";");
for (int i = 0; i < fields.length; i++){
HGVSg.add(fields[i].trim());
}
}else{
HGVSg.add(_HGVSg);
}
}
public String getHGVSg(){
return HGVSg.toString();
}
/**
* @param _HGVSg
* @return
*/
private int getStartPOS(String _HGVSg){
Pattern p = Pattern.compile("(\\d+)");
Matcher m = p.matcher(_HGVSg);
//System.out.println(_HGVSg);
if(m.find()){
System.out.println(m.group(1));
return Integer.parseInt(m.group(1));
}
else {return -1;}
}
/**
* @return
*/
public boolean setStartPOS(){
if (HGVSg.isEmpty()){
return false;
}else{
POS = getStartPOS(HGVSg.get(0));
return true;
}
}
/**
* @param _POS
*/
public void setPOS(String _POS){
POS = Integer.parseInt(_POS);
}
/**
* @return
*/
public int getPOS(){
return POS;
}
/**
* @param _GenePOS
*/
public void setGenePOS(String _GenePOS){
GenePOS = _GenePOS;
}
/**
* @return
*/
public String getGenePOS(){
return GenePOS;
}
/**
* @param _REF
*/
public void setREF(String _REF){
REF = (_REF);
}
/**
* @return
*/
public String getREF(){
return REF;
}
/**
* @param _rsID
*/
public void set_rsID(String _rsID){
rsID = (_rsID);
}
/**
* @return
*/
public String get_rsID(){
return rsID;
}
/**
* @param _ALT
*/
public void addALT(String _ALT){
ALTs.add(_ALT);
}
/**
* @return
*/
public ArrayList<String> getALTs(){
return ALTs;
}
@Override
public int compareTo(@Nonnull Variant o) {
int rez = ObjectUtils.compare(CHROM, o.CHROM);
if (rez != 0) {
return rez;
}
rez = ObjectUtils.compare(POS, o.POS);
if (rez != 0) {
return rez;
}
return ObjectUtils.compare(GeneName, o.GeneName);
}
}
|
Remove System.out.println.
|
src/main/java/org/pharmgkb/pharmcat/haplotype/Variant.java
|
Remove System.out.println.
|
|
Java
|
agpl-3.0
|
3b5f316b31dc8c66b44a57e098536158bffb0a1e
| 0
|
quikkian-ua-devops/kfs,UniversityOfHawaii/kfs,ua-eas/kfs,kkronenb/kfs,kuali/kfs,UniversityOfHawaii/kfs,ua-eas/kfs,kuali/kfs,kuali/kfs,ua-eas/kfs,bhutchinson/kfs,UniversityOfHawaii/kfs,smith750/kfs,quikkian-ua-devops/will-financials,quikkian-ua-devops/kfs,ua-eas/kfs-devops-automation-fork,kkronenb/kfs,kkronenb/kfs,quikkian-ua-devops/will-financials,smith750/kfs,ua-eas/kfs-devops-automation-fork,smith750/kfs,quikkian-ua-devops/will-financials,quikkian-ua-devops/will-financials,kkronenb/kfs,ua-eas/kfs,ua-eas/kfs-devops-automation-fork,ua-eas/kfs-devops-automation-fork,quikkian-ua-devops/kfs,UniversityOfHawaii/kfs,smith750/kfs,bhutchinson/kfs,ua-eas/kfs,bhutchinson/kfs,kuali/kfs,kuali/kfs,quikkian-ua-devops/will-financials,quikkian-ua-devops/kfs,quikkian-ua-devops/kfs,quikkian-ua-devops/kfs,quikkian-ua-devops/will-financials,UniversityOfHawaii/kfs,ua-eas/kfs-devops-automation-fork,bhutchinson/kfs
|
/*
* Copyright 2011 The Kuali Foundation.
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl2.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kuali.kfs.sys.context;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.kuali.kfs.sys.ConfigureContext;
import org.kuali.kfs.sys.FinancialSystemModuleConfiguration;
import org.kuali.kfs.sys.batch.JobDescriptor;
import org.kuali.kfs.sys.batch.TriggerDescriptor;
import org.kuali.kfs.sys.batch.dataaccess.FiscalYearMaker;
import org.kuali.kfs.sys.batch.dataaccess.impl.FiscalYearMakerImpl;
import org.kuali.kfs.sys.service.impl.KfsModuleServiceImpl;
import org.kuali.rice.kns.dao.PlatformAwareDao;
import org.kuali.rice.kns.dao.impl.PlatformAwareDaoBaseOjb;
import org.kuali.rice.kns.dao.jdbc.PlatformAwareDaoBaseJdbc;
import org.kuali.rice.kns.lookup.KualiLookupableImpl;
import org.kuali.rice.kns.lookup.LookupableHelperService;
import org.kuali.rice.kns.service.ModuleService;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.config.BeanDefinition;
@ConfigureContext
public class SpringConfigurationConsistencyCheckTest extends KualiTestBase {
public void testAllLookupablesArePrototypes() throws Exception {
List<String> failingBeans = new ArrayList<String>();
Map<String,KualiLookupableImpl> beans = SpringContext.getBeansOfType(KualiLookupableImpl.class);
Map<String,KualiLookupableImpl> beans2 = SpringContext.getBeansOfType(KualiLookupableImpl.class);
for ( String beanName : beans.keySet() ) {
if ( ProxyUtils.getTargetIfProxied( beans.get(beanName) ).equals(ProxyUtils.getTargetIfProxied( beans2.get(beanName) )) ) {
failingBeans.add( "\n *** " + beanName + " is a singleton and should not be." );
}
}
assertEquals( "Beans Failing Non-Singleton check: " + failingBeans, 0, failingBeans.size() );
}
public void testAllLookupableHelperServicesArePrototypes() throws Exception {
List<String> failingBeans = new ArrayList<String>();
Map<String,LookupableHelperService> beans = SpringContext.getBeansOfType(LookupableHelperService.class);
Map<String,LookupableHelperService> beans2 = SpringContext.getBeansOfType(LookupableHelperService.class);
for ( String beanName : beans.keySet() ) {
if ( ProxyUtils.getTargetIfProxied( beans.get(beanName) ).equals(ProxyUtils.getTargetIfProxied( beans2.get(beanName) )) ) {
failingBeans.add( "\n *** " + beanName + " is a singleton and should not be." );
}
}
assertEquals( "Beans Failing Non-Singleton check: " + failingBeans, 0, failingBeans.size() );
}
public void testJobBeansReferencedInModuleDefinitions() throws Exception {
// get all Job beans
Map<String,JobDescriptor> jobs = SpringContext.getBeansOfType(JobDescriptor.class);
Map<String,ModuleService> moduleServices = SpringContext.getBeansOfType(ModuleService.class);
assertFalse( "Jobs list must not be empty", jobs.isEmpty() );
assertFalse( "Module list must not be empty", moduleServices.isEmpty() );
// build a list of all job names
Set<String> jobNamesInBeans = jobs.keySet();
Set<String> jobNamesInModules = new HashSet<String>();
for ( ModuleService m : moduleServices.values() ) {
jobNamesInModules.addAll( m.getModuleConfiguration().getJobNames() );
}
Set<String> beansNotReferencedInModules = new HashSet<String>( jobNamesInBeans );
beansNotReferencedInModules.removeAll(jobNamesInModules);
Set<String> moduleJobsWithNoBeans = new HashSet<String>( jobNamesInModules );
moduleJobsWithNoBeans.removeAll(jobNamesInBeans);
assertEquals( "All of the job definitions must be referenced in the module definitions.", Collections.emptySet(), beansNotReferencedInModules );
assertEquals( "All of the jobs in the module definitions must be defined in the Spring context.", Collections.emptySet(), moduleJobsWithNoBeans );
}
public void testTriggerBeansReferencedInModuleDefinitions() throws Exception {
// get all Job beans
Map<String,TriggerDescriptor> triggers = SpringContext.getBeansOfType(TriggerDescriptor.class);
Map<String,ModuleService> moduleServices = SpringContext.getBeansOfType(ModuleService.class);
assertFalse( "Jobs list must not be empty", triggers.isEmpty() );
assertFalse( "Module list must not be empty", moduleServices.isEmpty() );
// build a list of all job names
Set<String> triggerNamesInBeans = triggers.keySet();
Set<String> triggerNamesInModules = new HashSet<String>();
for ( ModuleService m : moduleServices.values() ) {
triggerNamesInModules.addAll( m.getModuleConfiguration().getTriggerNames() );
}
Set<String> beansNotReferencedInModules = new HashSet<String>( triggerNamesInBeans );
beansNotReferencedInModules.removeAll(triggerNamesInModules);
Set<String> moduleTriggersWithNoBeans = new HashSet<String>( triggerNamesInModules );
moduleTriggersWithNoBeans.removeAll(triggerNamesInBeans);
assertEquals( "All of the trigger definitions must be referenced in the module definitions.", Collections.emptySet(), beansNotReferencedInModules );
assertEquals( "All of the triggers in the module definitions must be defined in the Spring context.", Collections.emptySet(), moduleTriggersWithNoBeans );
}
// FY makers referenced in module definitions
public void testFiscalYearMakerBeansReferencedInModuleDefinitions() throws Exception {
// get all Job beans
Map<String,FiscalYearMakerImpl> fiscalYearMakers = SpringContext.getBeansOfType(FiscalYearMakerImpl.class);
Map<String,KfsModuleServiceImpl> moduleServices = SpringContext.getBeansOfType(KfsModuleServiceImpl.class);
assertFalse( "FiscalYearMaker list must not be empty", fiscalYearMakers.isEmpty() );
assertFalse( "Module list must not be empty", moduleServices.isEmpty() );
// build a list of all job names
Set<FiscalYearMakerImpl> fiscalYearMakerNamesInBeans = new HashSet<FiscalYearMakerImpl>();
for ( FiscalYearMakerImpl fym : fiscalYearMakers.values() ) {
fiscalYearMakerNamesInBeans.add( (FiscalYearMakerImpl)ProxyUtils.getTargetIfProxied(fym) );
}
Set<FiscalYearMakerImpl> fiscalYearMakerNamesInModules = new HashSet<FiscalYearMakerImpl>();
for ( KfsModuleServiceImpl m : moduleServices.values() ) {
for ( FiscalYearMaker fym : ((FinancialSystemModuleConfiguration)m.getModuleConfiguration()).getFiscalYearMakers() ) {
fiscalYearMakerNamesInModules.add( (FiscalYearMakerImpl)ProxyUtils.getTargetIfProxied(fym) );
}
}
Set<FiscalYearMakerImpl> beansNotReferencedInModules = new HashSet<FiscalYearMakerImpl>( fiscalYearMakerNamesInBeans );
beansNotReferencedInModules.removeAll(fiscalYearMakerNamesInModules);
Set<FiscalYearMakerImpl> moduleFiscalYearMakersWithNoBeans = new HashSet<FiscalYearMakerImpl>( fiscalYearMakerNamesInModules );
moduleFiscalYearMakersWithNoBeans.removeAll(fiscalYearMakerNamesInBeans);
assertEquals( "All of the FiscalYearMaker definitions must be referenced in the module definitions.", Collections.emptySet(), beansNotReferencedInModules );
assertEquals( "All of the FiscalYearMakers in the module definitions must be defined in the Spring context.", Collections.emptySet(), moduleFiscalYearMakersWithNoBeans );
}
public void testParentBeansShouldBeAbstract() {
List<String> failingBeanNames = new ArrayList<String>();
for ( String beanName : SpringContext.applicationContext.getBeanDefinitionNames() ) {
BeanDefinition beanDef = SpringContext.applicationContext.getBeanFactory().getBeanDefinition(beanName);
if ( beanName.endsWith("-parentBean") && !beanDef.isAbstract() ) {
failingBeanNames.add(beanName + " : " + beanDef.getResourceDescription()+"\n");
}
}
assertEquals( "The following parent beans are not defined as abstract:\n" + failingBeanNames, 0, failingBeanNames.size() );
}
public void testServicesShouldHaveParentBeans() {
List<String> failingBeanNames = new ArrayList<String>();
for ( String beanName : SpringContext.applicationContext.getBeanDefinitionNames() ) {
// skip testing mock beans
if ( StringUtils.containsIgnoreCase(beanName, "mock") ) {
continue;
}
BeanDefinition beanDef = SpringContext.applicationContext.getBeanFactory().getBeanDefinition(beanName);
if ( beanName.endsWith("Service") && !beanDef.isAbstract() ) {
String serviceClass = beanDef.getBeanClassName();
// skip Rice classes
if ( serviceClass != null && serviceClass.startsWith("org.kuali.rice") ) {
continue;
}
try {
BeanDefinition parentBean = SpringContext.applicationContext.getBeanFactory().getBeanDefinition(beanName + "-parentBean");
String parentClass = parentBean.getBeanClassName();
// skip Rice classes
if ( parentClass != null && parentClass.startsWith("org.kuali.rice") ) {
continue;
}
} catch ( NoSuchBeanDefinitionException ex ) {
failingBeanNames.add(beanName + " : " + beanDef.getResourceDescription()+"\n");
}
}
}
assertEquals( "The following service beans do not have \"-parentBean\"s:\n" + failingBeanNames, 0, failingBeanNames.size() );
}
// DAOs should extend from the xxxx class
public void testDAOsShouldBeDAOs() throws Exception {
List<String> failingBeanNames = new ArrayList<String>();
for ( String beanName : SpringContext.applicationContext.getBeanDefinitionNames() ) {
BeanDefinition beanDef = SpringContext.applicationContext.getBeanFactory().getBeanDefinition(beanName);
if ( !beanDef.isAbstract() ) {
Object service = TestUtils.getUnproxiedService(beanName);
if ( beanName.endsWith("Dao")
&& !service.getClass().getName().endsWith( "Proxy" )
&& !service.getClass().getName().startsWith( "org.kuali.rice" ) ) {
if ( !(service instanceof PlatformAwareDao) ) {
failingBeanNames.add( " *** FAIL: " + beanName + " does not implement PlatformAwareDao (is " + service.getClass().getName() + ")\n" + " : " + beanDef.getResourceDescription() + "\n" );
}
if ( !(service instanceof PlatformAwareDaoBaseOjb)
&& !(service instanceof PlatformAwareDaoBaseJdbc)) {
failingBeanNames.add( " *** FAIL: " + beanName + " does not extend PlatformAwareDaoBaseOjb/Jdbc (is " + service.getClass().getName() + ")\n" + " : " + beanDef.getResourceDescription() + "\n" );
}
}
}
}
for ( Map.Entry<String,PlatformAwareDao> dao : SpringContext.getBeansOfType(PlatformAwareDao.class).entrySet() ) {
Object service = ProxyUtils.getTargetIfProxied(dao.getValue());
if ( !dao.getKey().endsWith("Dao" )
&& !service.getClass().getName().startsWith( "org.kuali.rice" )
&& !FiscalYearMakerImpl.class.isAssignableFrom(service.getClass())) {
failingBeanNames.add( " *** FAIL: Bean " + dao.getKey() + " implements PlatformAwareDao (" + service.getClass().getName() + ") but its name does not end in 'Dao'\n");
}
}
assertEquals( "The following problems were detected in the DAO definitions:\n" + failingBeanNames, 0, failingBeanNames.size() );
}
}
|
test/unit/src/org/kuali/kfs/sys/context/SpringConfigurationConsistencyCheckTest.java
|
/*
* Copyright 2011 The Kuali Foundation.
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl2.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kuali.kfs.sys.context;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.kuali.kfs.sys.ConfigureContext;
import org.kuali.kfs.sys.FinancialSystemModuleConfiguration;
import org.kuali.kfs.sys.batch.JobDescriptor;
import org.kuali.kfs.sys.batch.TriggerDescriptor;
import org.kuali.kfs.sys.batch.dataaccess.FiscalYearMaker;
import org.kuali.kfs.sys.batch.dataaccess.impl.FiscalYearMakerImpl;
import org.kuali.kfs.sys.service.impl.KfsModuleServiceImpl;
import org.kuali.rice.kns.dao.PlatformAwareDao;
import org.kuali.rice.kns.dao.impl.PlatformAwareDaoBaseOjb;
import org.kuali.rice.kns.dao.jdbc.PlatformAwareDaoBaseJdbc;
import org.kuali.rice.kns.lookup.KualiLookupableImpl;
import org.kuali.rice.kns.lookup.LookupableHelperService;
import org.kuali.rice.kns.service.ModuleService;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.config.BeanDefinition;
@ConfigureContext
public class SpringConfigurationConsistencyCheckTest extends KualiTestBase {
public void testAllLookupablesArePrototypes() throws Exception {
List<String> failingBeans = new ArrayList<String>();
Map<String,KualiLookupableImpl> beans = SpringContext.getBeansOfType(KualiLookupableImpl.class);
Map<String,KualiLookupableImpl> beans2 = SpringContext.getBeansOfType(KualiLookupableImpl.class);
for ( String beanName : beans.keySet() ) {
if ( ProxyUtils.getTargetIfProxied( beans.get(beanName) ).equals(ProxyUtils.getTargetIfProxied( beans2.get(beanName) )) ) {
failingBeans.add( "\n *** " + beanName + " is a singleton and should not be." );
}
}
assertEquals( "Beans Failing Non-Singleton check: " + failingBeans, 0, failingBeans.size() );
}
public void testAllLookupableHelperServicesArePrototypes() throws Exception {
List<String> failingBeans = new ArrayList<String>();
Map<String,LookupableHelperService> beans = SpringContext.getBeansOfType(LookupableHelperService.class);
Map<String,LookupableHelperService> beans2 = SpringContext.getBeansOfType(LookupableHelperService.class);
for ( String beanName : beans.keySet() ) {
if ( ProxyUtils.getTargetIfProxied( beans.get(beanName) ).equals(ProxyUtils.getTargetIfProxied( beans2.get(beanName) )) ) {
failingBeans.add( "\n *** " + beanName + " is a singleton and should not be." );
}
}
assertEquals( "Beans Failing Non-Singleton check: " + failingBeans, 0, failingBeans.size() );
}
public void testJobBeansReferencedInModuleDefinitions() throws Exception {
// get all Job beans
Map<String,JobDescriptor> jobs = SpringContext.getBeansOfType(JobDescriptor.class);
Map<String,ModuleService> moduleServices = SpringContext.getBeansOfType(ModuleService.class);
assertFalse( "Jobs list must not be empty", jobs.isEmpty() );
assertFalse( "Module list must not be empty", moduleServices.isEmpty() );
// build a list of all job names
Set<String> jobNamesInBeans = jobs.keySet();
Set<String> jobNamesInModules = new HashSet<String>();
for ( ModuleService m : moduleServices.values() ) {
jobNamesInModules.addAll( m.getModuleConfiguration().getJobNames() );
}
Set<String> beansNotReferencedInModules = new HashSet<String>( jobNamesInBeans );
beansNotReferencedInModules.removeAll(jobNamesInModules);
Set<String> moduleJobsWithNoBeans = new HashSet<String>( jobNamesInModules );
moduleJobsWithNoBeans.removeAll(jobNamesInBeans);
assertEquals( "All of the job definitions must be referenced in the module definitions.", Collections.emptySet(), beansNotReferencedInModules );
assertEquals( "All of the jobs in the module definitions must be defined in the Spring context.", Collections.emptySet(), moduleJobsWithNoBeans );
}
public void testTriggerBeansReferencedInModuleDefinitions() throws Exception {
// get all Job beans
Map<String,TriggerDescriptor> triggers = SpringContext.getBeansOfType(TriggerDescriptor.class);
Map<String,ModuleService> moduleServices = SpringContext.getBeansOfType(ModuleService.class);
assertFalse( "Jobs list must not be empty", triggers.isEmpty() );
assertFalse( "Module list must not be empty", moduleServices.isEmpty() );
// build a list of all job names
Set<String> triggerNamesInBeans = triggers.keySet();
Set<String> triggerNamesInModules = new HashSet<String>();
for ( ModuleService m : moduleServices.values() ) {
triggerNamesInModules.addAll( m.getModuleConfiguration().getTriggerNames() );
}
Set<String> beansNotReferencedInModules = new HashSet<String>( triggerNamesInBeans );
beansNotReferencedInModules.removeAll(triggerNamesInModules);
Set<String> moduleTriggersWithNoBeans = new HashSet<String>( triggerNamesInModules );
moduleTriggersWithNoBeans.removeAll(triggerNamesInBeans);
assertEquals( "All of the trigger definitions must be referenced in the module definitions.", Collections.emptySet(), beansNotReferencedInModules );
assertEquals( "All of the triggers in the module definitions must be defined in the Spring context.", Collections.emptySet(), moduleTriggersWithNoBeans );
}
// FY makers referenced in module definitions
public void testFiscalYearMakerBeansReferencedInModuleDefinitions() throws Exception {
// get all Job beans
Map<String,FiscalYearMakerImpl> fiscalYearMakers = SpringContext.getBeansOfType(FiscalYearMakerImpl.class);
Map<String,KfsModuleServiceImpl> moduleServices = SpringContext.getBeansOfType(KfsModuleServiceImpl.class);
assertFalse( "FiscalYearMaker list must not be empty", fiscalYearMakers.isEmpty() );
assertFalse( "Module list must not be empty", moduleServices.isEmpty() );
// build a list of all job names
Set<FiscalYearMakerImpl> fiscalYearMakerNamesInBeans = new HashSet<FiscalYearMakerImpl>();
for ( FiscalYearMakerImpl fym : fiscalYearMakers.values() ) {
fiscalYearMakerNamesInBeans.add( (FiscalYearMakerImpl)ProxyUtils.getTargetIfProxied(fym) );
}
Set<FiscalYearMakerImpl> fiscalYearMakerNamesInModules = new HashSet<FiscalYearMakerImpl>();
for ( KfsModuleServiceImpl m : moduleServices.values() ) {
for ( FiscalYearMaker fym : ((FinancialSystemModuleConfiguration)m.getModuleConfiguration()).getFiscalYearMakers() ) {
fiscalYearMakerNamesInModules.add( (FiscalYearMakerImpl)ProxyUtils.getTargetIfProxied(fym) );
}
}
Set<FiscalYearMakerImpl> beansNotReferencedInModules = new HashSet<FiscalYearMakerImpl>( fiscalYearMakerNamesInBeans );
beansNotReferencedInModules.removeAll(fiscalYearMakerNamesInModules);
Set<FiscalYearMakerImpl> moduleFiscalYearMakersWithNoBeans = new HashSet<FiscalYearMakerImpl>( fiscalYearMakerNamesInModules );
moduleFiscalYearMakersWithNoBeans.removeAll(fiscalYearMakerNamesInBeans);
assertEquals( "All of the FiscalYearMaker definitions must be referenced in the module definitions.", Collections.emptySet(), beansNotReferencedInModules );
assertEquals( "All of the FiscalYearMakers in the module definitions must be defined in the Spring context.", Collections.emptySet(), moduleFiscalYearMakersWithNoBeans );
}
public void testParentBeansShouldBeAbstract() {
List<String> failingBeanNames = new ArrayList<String>();
for ( String beanName : SpringContext.applicationContext.getBeanDefinitionNames() ) {
BeanDefinition beanDef = SpringContext.applicationContext.getBeanFactory().getBeanDefinition(beanName);
if ( beanName.endsWith("-parentBean") && !beanDef.isAbstract() ) {
failingBeanNames.add(beanName + " : " + beanDef.getResourceDescription()+"\n");
}
}
assertEquals( "The following parent beans are not defined as abstract:\n" + failingBeanNames, 0, failingBeanNames.size() );
}
public void testServicesShouldHaveParentBeans() {
List<String> failingBeanNames = new ArrayList<String>();
for ( String beanName : SpringContext.applicationContext.getBeanDefinitionNames() ) {
// skip testing mock beans
if ( StringUtils.containsIgnoreCase(beanName, "mock") ) {
continue;
}
BeanDefinition beanDef = SpringContext.applicationContext.getBeanFactory().getBeanDefinition(beanName);
if ( beanName.endsWith("Service") && !beanDef.isAbstract() ) {
String serviceClass = beanDef.getBeanClassName();
// skip Rice classes
if ( serviceClass != null && serviceClass.startsWith("org.kuali.rice") ) {
continue;
}
try {
BeanDefinition parentBean = SpringContext.applicationContext.getBeanFactory().getBeanDefinition(beanName + "-parentBean");
String parentClass = parentBean.getBeanClassName();
// skip Rice classes
if ( parentClass != null && parentClass.startsWith("org.kuali.rice") ) {
continue;
}
} catch ( NoSuchBeanDefinitionException ex ) {
failingBeanNames.add(beanName + " : " + beanDef.getResourceDescription()+"\n");
}
}
}
assertEquals( "The following service beans do not have \"-parentBean\"s:\n" + failingBeanNames, 0, failingBeanNames.size() );
}
// DAOs should extend from the xxxx class
public void testDAOsShouldBeDAOs() throws Exception {
List<String> failingBeanNames = new ArrayList<String>();
for ( String beanName : SpringContext.applicationContext.getBeanDefinitionNames() ) {
BeanDefinition beanDef = SpringContext.applicationContext.getBeanFactory().getBeanDefinition(beanName);
if ( !beanDef.isAbstract() ) {
Object service = TestUtils.getUnproxiedService(beanName);
if ( beanName.endsWith("Dao")
&& !service.getClass().getName().endsWith( "Proxy" )
&& !service.getClass().getName().startsWith( "org.kuali.rice" ) ) {
if ( !(service instanceof PlatformAwareDao) ) {
failingBeanNames.add( " *** FAIL: " + beanName + " does not implement PlatformAwareDao (is " + service.getClass().getName() + ")\n" + " : " + beanDef.getResourceDescription() + "\n" );
}
if ( !(service instanceof PlatformAwareDaoBaseOjb)
&& !(service instanceof PlatformAwareDaoBaseJdbc)) {
failingBeanNames.add( " *** FAIL: " + beanName + " does not extend PlatformAwareDaoBaseOjb/Jdbc (is " + service.getClass().getName() + ")\n" + " : " + beanDef.getResourceDescription() + "\n" );
}
}
}
}
for ( Map.Entry<String,PlatformAwareDao> dao : SpringContext.getBeansOfType(PlatformAwareDao.class).entrySet() ) {
Object service = ProxyUtils.getTargetIfProxied(dao.getValue());
if ( !dao.getKey().endsWith("Dao" )
&& !service.getClass().getName().startsWith( "org.kuali.rice" ) ) {
failingBeanNames.add( " *** FAIL: Bean " + dao.getKey() + " implements PlatformAwareDao (" + service.getClass().getName() + ") but its name does not end in 'Dao'\n");
}
}
assertEquals( "The following problems were detected in the DAO definitions:\n" + failingBeanNames, 0, failingBeanNames.size() );
}
}
|
Updated DAO portion of test to ignore FiscalYearMakerImpl
|
test/unit/src/org/kuali/kfs/sys/context/SpringConfigurationConsistencyCheckTest.java
|
Updated DAO portion of test to ignore FiscalYearMakerImpl
|
|
Java
|
agpl-3.0
|
b5eca452f2fff8aabc8fbb66163f07fb8a0c9d34
| 0
|
DemandCube/NeverwinterDP,DemandCube/NeverwinterDP,DemandCube/NeverwinterDP,DemandCube/NeverwinterDP,DemandCube/NeverwinterDP
|
package com.neverwinterdp.scribengin.dataflow.tracking;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import com.neverwinterdp.kafka.KafkaClient;
import com.neverwinterdp.kafka.consumer.KafkaPartitionReader;
import com.neverwinterdp.message.Message;
import com.neverwinterdp.registry.Registry;
import com.neverwinterdp.util.JSONSerializer;
import com.neverwinterdp.vm.VMApp;
import com.neverwinterdp.vm.VMConfig;
import com.neverwinterdp.vm.VMDescriptor;
import kafka.javaapi.PartitionMetadata;
import kafka.javaapi.TopicMetadata;
public class VMTMValidatorKafkaApp extends VMApp {
private Logger logger;
private KafkaClient kafkaClient;
@Override
public void run() throws Exception {
logger = getVM().getLoggerFactory().getLogger(VMTMValidatorKafkaApp.class) ;
logger.info("Start run()");
VMDescriptor vmDescriptor = getVM().getDescriptor();
VMConfig vmConfig = vmDescriptor.getVmConfig();
TrackingConfig trackingConfig = vmConfig.getVMAppConfigAs(TrackingConfig.class);
Registry registry = getVM().getVMRegistry().getRegistry();
registry.setRetryable(true);
kafkaClient = new KafkaClient("KafkaClient", trackingConfig.getKafkaZKConnects());
TrackingValidatorService validatorService = new TrackingValidatorService(registry, trackingConfig);
validatorService.addReader(new KafkaTrackingMessageReader(trackingConfig));
validatorService.start();
logger.info("reportPath = " + trackingConfig.getReportPath());
logger.info("maxRuntime = " + trackingConfig.getValidatorMaxRuntime());
logger.info("validate topic = " + trackingConfig.getKafkaValidateTopic());
validatorService.awaitForTermination(trackingConfig.getValidatorMaxRuntime(), TimeUnit.MILLISECONDS);
kafkaClient.close();
}
public class KafkaTrackingMessageReader extends TrackingMessageReader {
private BlockingQueue<TrackingMessage> queue = new LinkedBlockingQueue<>(5000);
private String kafkaZkConnects;
private String topic;
private long maxMessageWaitTime;
KafkaTopicConnector connector;
KafkaTrackingMessageReader(TrackingConfig trackingConfig) {
this.kafkaZkConnects = trackingConfig.getKafkaZKConnects();
this.topic = trackingConfig.getKafkaValidateTopic();
this.maxMessageWaitTime = trackingConfig.getKafkaMessageWaitTimeout();
}
public void onInit(TrackingRegistry registry) throws Exception {
connector = new KafkaTopicConnector(kafkaZkConnects, topic) {
@Override
public void onTrackingMessage(TrackingMessage tMesg) throws Exception {
queue.offer(tMesg, maxMessageWaitTime, TimeUnit.MILLISECONDS);
}
};
connector.start();
}
public void onDestroy(TrackingRegistry registry) throws Exception{
connector.shutdown();
}
@Override
public TrackingMessage next() throws Exception {
return queue.poll(maxMessageWaitTime, TimeUnit.MILLISECONDS);
}
}
abstract public class KafkaTopicConnector {
private KafkaPartitionReader[] partitionReader;
private BlockingQueue<KafkaPartitionReader> readerQueue = new LinkedBlockingQueue<>();
private ExecutorService executorService;
public KafkaTopicConnector(String kafkaZkConnects, String topic) throws Exception {
TopicMetadata topicMeta = kafkaClient.findTopicMetadata(topic);
List<PartitionMetadata> partitionMetas = topicMeta.partitionsMetadata();
int numOfPartitions = partitionMetas.size();
partitionReader = new KafkaPartitionReader[numOfPartitions];
for (int i = 0; i < numOfPartitions; i++) {
partitionReader[i] = new KafkaPartitionReader("VMTMValidatorKafkaApp", kafkaClient, topic, partitionMetas.get(i));
readerQueue.offer(partitionReader[i]);
}
}
public void start() {
int NUM_OF_THREAD = 3;
executorService = Executors.newFixedThreadPool(NUM_OF_THREAD);
for(int i = 0; i < NUM_OF_THREAD; i++) {
Runnable runnable = new Runnable() {
public void run() {
try {
while(true) {
KafkaPartitionReader pReader = readerQueue.take();
Message message = null;
int count = 0;
while((message = pReader.nextAs(Message.class, 100)) != null) {
TrackingMessage tMesg = JSONSerializer.INSTANCE.fromBytes(message.getData(), TrackingMessage.class);
onTrackingMessage(tMesg);
count++;
if(count == 5000) break;
}
readerQueue.offer(pReader);
}
} catch (InterruptedException e) {
logger.error("Interrupted", e);
} catch (Throwable e) {
logger.error("Fail to load the data from kafka", e);
} finally {
try {
shutdown();
} catch (Exception e) {
logger.error("Fail to shutdown kafka connector", e);
}
}
}
};
executorService.submit(runnable);
}
executorService.shutdown();
}
public void shutdown() throws Exception {
executorService.shutdownNow();
for(int i = 0; i < partitionReader.length; i++) {
partitionReader[i].close();
}
}
abstract public void onTrackingMessage(TrackingMessage tMesg) throws Exception ;
}
}
|
scribengin/core/src/main/java/com/neverwinterdp/scribengin/dataflow/tracking/VMTMValidatorKafkaApp.java
|
package com.neverwinterdp.scribengin.dataflow.tracking;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import com.neverwinterdp.kafka.KafkaClient;
import com.neverwinterdp.kafka.consumer.KafkaPartitionReader;
import com.neverwinterdp.message.Message;
import com.neverwinterdp.registry.Registry;
import com.neverwinterdp.util.JSONSerializer;
import com.neverwinterdp.vm.VMApp;
import com.neverwinterdp.vm.VMConfig;
import com.neverwinterdp.vm.VMDescriptor;
import kafka.javaapi.PartitionMetadata;
import kafka.javaapi.TopicMetadata;
public class VMTMValidatorKafkaApp extends VMApp {
private Logger logger;
private KafkaClient kafkaClient;
@Override
public void run() throws Exception {
logger = getVM().getLoggerFactory().getLogger(VMTMValidatorKafkaApp.class) ;
logger.info("Start run()");
VMDescriptor vmDescriptor = getVM().getDescriptor();
VMConfig vmConfig = vmDescriptor.getVmConfig();
TrackingConfig trackingConfig = vmConfig.getVMAppConfigAs(TrackingConfig.class);
Registry registry = getVM().getVMRegistry().getRegistry();
registry.setRetryable(true);
kafkaClient = new KafkaClient("KafkaClient", trackingConfig.getKafkaZKConnects());
TrackingValidatorService validatorService = new TrackingValidatorService(registry, trackingConfig);
validatorService.addReader(new KafkaTrackingMessageReader(trackingConfig));
validatorService.start();
validatorService.awaitForTermination(trackingConfig.getValidatorMaxRuntime(), TimeUnit.MILLISECONDS);
kafkaClient.close();
}
public class KafkaTrackingMessageReader extends TrackingMessageReader {
private BlockingQueue<TrackingMessage> queue = new LinkedBlockingQueue<>(5000);
private String kafkaZkConnects;
private String topic;
private long maxMessageWaitTime;
KafkaTopicConnector connector;
KafkaTrackingMessageReader(TrackingConfig trackingConfig) {
this.kafkaZkConnects = trackingConfig.getKafkaZKConnects();
this.topic = trackingConfig.getKafkaValidateTopic();
this.maxMessageWaitTime = trackingConfig.getKafkaMessageWaitTimeout();
}
public void onInit(TrackingRegistry registry) throws Exception {
connector = new KafkaTopicConnector(kafkaZkConnects, topic) {
@Override
public void onTrackingMessage(TrackingMessage tMesg) throws Exception {
queue.offer(tMesg, maxMessageWaitTime, TimeUnit.MILLISECONDS);
}
};
connector.start();
}
public void onDestroy(TrackingRegistry registry) throws Exception{
connector.shutdown();
}
@Override
public TrackingMessage next() throws Exception {
return queue.poll(maxMessageWaitTime, TimeUnit.MILLISECONDS);
}
}
abstract public class KafkaTopicConnector {
private KafkaPartitionReader[] partitionReader;
private BlockingQueue<KafkaPartitionReader> readerQueue = new LinkedBlockingQueue<>();
private ExecutorService executorService;
public KafkaTopicConnector(String kafkaZkConnects, String topic) throws Exception {
TopicMetadata topicMeta = kafkaClient.findTopicMetadata(topic);
List<PartitionMetadata> partitionMetas = topicMeta.partitionsMetadata();
int numOfPartitions = partitionMetas.size();
partitionReader = new KafkaPartitionReader[numOfPartitions];
for (int i = 0; i < numOfPartitions; i++) {
partitionReader[i] = new KafkaPartitionReader("VMTMValidatorKafkaApp", kafkaClient, topic, partitionMetas.get(i));
readerQueue.offer(partitionReader[i]);
}
}
public void start() {
int NUM_OF_THREAD = 3;
executorService = Executors.newFixedThreadPool(NUM_OF_THREAD);
for(int i = 0; i < NUM_OF_THREAD; i++) {
Runnable runnable = new Runnable() {
public void run() {
try {
while(true) {
KafkaPartitionReader pReader = readerQueue.take();
Message rec = null;
int count = 0;
while((rec = pReader.nextAs(Message.class, 100)) != null) {
TrackingMessage tMesg = JSONSerializer.INSTANCE.fromBytes(rec.getData(), TrackingMessage.class);
onTrackingMessage(tMesg);
count++;
if(count == 5000) break;
}
readerQueue.offer(pReader);
}
} catch (InterruptedException e) {
} catch (Exception e) {
logger.error("Fail to load the data from kafka", e);
} finally {
try {
shutdown();
} catch (Exception e) {
logger.error("Fail to shutdown kafka connector", e);
}
}
}
};
executorService.submit(runnable);
}
executorService.shutdown();
}
public void shutdown() throws Exception {
executorService.shutdownNow();
for(int i = 0; i < partitionReader.length; i++) {
partitionReader[i].close();
}
}
abstract public void onTrackingMessage(TrackingMessage tMesg) throws Exception ;
}
abstract public class KafkaTopicReaderThread extends Thread {
}
}
|
enhance log and error catch for the kafka validator
|
scribengin/core/src/main/java/com/neverwinterdp/scribengin/dataflow/tracking/VMTMValidatorKafkaApp.java
|
enhance log and error catch for the kafka validator
|
|
Java
|
lgpl-2.1
|
4c7ff27dafa667f532e470b632155ea2f29a2d25
| 0
|
ShefronYudy/opentsdb,OpenTSDB/opentsdb,OpenTSDB/opentsdb,alienth/opentsdb,kidaa/opentsdb,sidhhu/opentsdb,OpenTSDB/opentsdb,ShefronYudy/opentsdb,andyflury/opentsdb,johann8384/opentsdb,MadDogTechnology/opentsdb,andyflury/opentsdb,MadDogTechnology/opentsdb,eswdd/opentsdb,eswdd/opentsdb,alienth/opentsdb,kidaa/opentsdb,MadDogTechnology/opentsdb,sidhhu/opentsdb,johann8384/opentsdb
|
// This file is part of OpenTSDB.
// Copyright (C) 2011 StumbleUpon, Inc.
//
// This program is free software: you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or (at your
// option) any later version. This program is distributed in the hope that it
// will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser
// General Public License for more details. You should have received a copy
// of the GNU Lesser General Public License along with this program. If not,
// see <http://www.gnu.org/licenses/>.
package net.opentsdb.core;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import com.stumbleupon.async.Callback;
import com.stumbleupon.async.Deferred;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.hbase.async.Bytes;
import org.hbase.async.HBaseRpc;
import org.hbase.async.KeyValue;
import org.hbase.async.PleaseThrottleException;
import net.opentsdb.stats.StatsCollector;
/**
* "Queue" of rows to compact.
* <p>
* Whenever we write a data point to HBase, the row key we write to is added
* to this queue, which is effectively a sorted set. There is a separate
* thread that periodically goes through the queue and look for "old rows" to
* compact. A row is considered "old" if the timestamp in the row key is
* older than a certain threshold.
* <p>
* The compaction process consists in reading all the cells within a given row
* and writing them back out as a single big cell. Once that writes succeeds,
* we delete all the individual little cells.
* <p>
* This process is effective because in HBase the row key is repeated for
* every single cell. And because there is no way to efficiently append bytes
* at the end of a cell, we have to do this instead.
*/
final class CompactionQueue extends ConcurrentSkipListMap<byte[], Boolean> {
private static final Logger LOG = LoggerFactory.getLogger(CompactionQueue.class);
/**
* How many items are currently in the queue.
* Because {@link ConcurrentSkipListMap#size} has O(N) complexity.
*/
private final AtomicInteger size = new AtomicInteger();
private final AtomicLong trivial_compactions = new AtomicLong();
private final AtomicLong complex_compactions = new AtomicLong();
private final AtomicLong written_cells = new AtomicLong();
private final AtomicLong deleted_cells = new AtomicLong();
/** The {@code TSDB} instance we belong to. */
private final TSDB tsdb;
/** On how many bytes do we encode metrics IDs. */
private final short metric_width;
/**
* Constructor.
* @param tsdb The TSDB we belong to.
*/
public CompactionQueue(final TSDB tsdb) {
super(new Cmp(tsdb));
this.tsdb = tsdb;
metric_width = tsdb.metrics.width();
if (TSDB.enable_compactions) {
startCompactionThread();
}
}
@Override
public int size() {
return size.get();
}
public void add(final byte[] row) {
if (super.put(row, Boolean.TRUE) == null) {
size.incrementAndGet(); // We added a new entry, count it.
}
}
/**
* Forces a flush of the entire compaction queue.
* @return A deferred that will be called back once everything has been
* flushed (or something failed, in which case the deferred will carry the
* exception). In case of success, the kind of object returned is
* unspecified.
*/
public Deferred<ArrayList<Object>> flush() {
final int size = size();
if (size > 0) {
LOG.info("Flushing all " + size + " outstanding rows");
}
return flush(Long.MAX_VALUE, Integer.MAX_VALUE);
}
/**
* Collects the stats and metrics tracked by this instance.
* @param collector The collector to use.
*/
void collectStats(final StatsCollector collector) {
collector.record("compaction.count", trivial_compactions, "type=trivial");
collector.record("compaction.count", complex_compactions, "type=complex");
if (!TSDB.enable_compactions) {
return;
}
// The remaining stats only make sense with compactions enabled.
collector.record("compaction.queue.size", size);
collector.record("compaction.errors", handle_read_error.errors, "rpc=read");
collector.record("compaction.errors", handle_write_error.errors, "rpc=put");
collector.record("compaction.errors", handle_delete_error.errors,
"rpc=delete");
collector.record("compaction.writes", written_cells);
collector.record("compaction.deletes", deleted_cells);
}
/**
* Flushes all the rows in the compaction queue older than the cutoff time.
* @param cut_off A UNIX timestamp in seconds (unsigned 32-bit integer).
* @param maxflushes How many rows to flush off the queue at once.
* This integer is expected to be strictly positive.
* @return A deferred that will be called back once everything has been
* flushed.
*/
private Deferred<ArrayList<Object>> flush(final long cut_off, int maxflushes) {
assert maxflushes > 0: "maxflushes must be > 0, but I got " + maxflushes;
// We can't possibly flush more entries than size().
maxflushes = Math.min(maxflushes, size());
if (maxflushes == 0) { // Because size() might be 0.
return Deferred.fromResult(new ArrayList<Object>(0));
}
final ArrayList<Deferred<Object>> ds =
new ArrayList<Deferred<Object>>(Math.min(maxflushes,
MAX_CONCURRENT_FLUSHES));
int nflushes = 0;
for (final byte[] row : this.keySet()) {
if (maxflushes == 0) {
break;
}
final long base_time = Bytes.getUnsignedInt(row, metric_width);
if (base_time > cut_off) {
break;
} else if (nflushes == MAX_CONCURRENT_FLUSHES) {
// We kicked off the compaction of too many rows already, let's wait
// until they're done before kicking off more.
break;
}
// You'd think that it would be faster to grab an iterator on the map
// and then call remove() on the iterator to "unlink" the element
// directly from where the iterator is at, but no, the JDK implements
// it by calling remove(key) so it has to lookup the key again anyway.
if (super.remove(row) == null) { // We didn't remove anything.
continue; // So someone else already took care of this entry.
}
nflushes++;
maxflushes--;
size.decrementAndGet();
ds.add(tsdb.get(row).addCallbacks(compactcb, handle_read_error));
}
final Deferred<ArrayList<Object>> group = Deferred.group(ds);
if (nflushes == MAX_CONCURRENT_FLUSHES && maxflushes > 0) {
// We're not done yet. Once this group of flushes completes, we need
// to kick off more.
tsdb.flush(); // Speed up this batch by telling the client to flush.
final int maxflushez = maxflushes; // Make it final for closure.
final class FlushMoreCB implements Callback<Deferred<ArrayList<Object>>,
ArrayList<Object>> {
public Deferred<ArrayList<Object>> call(final ArrayList<Object> arg) {
return flush(cut_off, maxflushez);
}
public String toString() {
return "Continue flushing with cut_off=" + cut_off
+ ", maxflushes=" + maxflushez;
}
}
group.addCallbackDeferring(new FlushMoreCB());
}
return group;
}
private final CompactCB compactcb = new CompactCB();
/**
* Callback to compact a row once it's been read.
* <p>
* This is used once the "get" completes, to actually compact the row and
* write back the compacted version.
*/
private final class CompactCB implements Callback<Object, ArrayList<KeyValue>> {
public Object call(final ArrayList<KeyValue> row) {
return compact(row, null);
}
public String toString() {
return "compact";
}
}
/**
* Compacts a row into a single {@link KeyValue}.
* @param row The row containing all the KVs to compact.
* Must contain at least one element.
* @return A compacted version of this row.
*/
KeyValue compact(final ArrayList<KeyValue> row) {
final KeyValue[] compacted = { null };
compact(row, compacted);
return compacted[0];
}
/**
* Compacts a row into a single {@link KeyValue}.
* <p>
* If the {@code row} is empty, this function does literally nothing.
* If {@code compacted} is not {@code null}, then the compacted form of this
* {@code row} will be stored in {@code compacted[0]}. Obviously, if the
* {@code row} contains a single cell, then that cell is the compacted form.
* Otherwise the compaction process takes places.
* @param row The row containing all the KVs to compact. Must be non-null.
* @param compacted If non-null, the first item in the array will be set to
* a {@link KeyValue} containing the compacted form of this row.
* If non-null, we will also not write the compacted form back to HBase
* unless the timestamp in the row key is old enough.
* @return A {@link Deferred} if the compaction processed required a write
* to HBase, otherwise {@code null}.
*/
private Deferred<Object> compact(final ArrayList<KeyValue> row,
final KeyValue[] compacted) {
if (row.size() <= 1) {
if (row.isEmpty()) { // Maybe the row got deleted in the mean time?
LOG.debug("Attempted to compact a row that doesn't exist.");
} else if (compacted != null) {
// no need to re-compact rows containing a single value.
compacted[0] = row.get(0);
}
return null;
}
// We know we have at least 2 cells. We need to go through all the cells
// to determine what kind of compaction we're going to do. If each cell
// contains a single individual data point, then we can do a trivial
// compaction. Otherwise, we have a partially compacted row, and the
// logic required to compact it is more complex.
boolean write = true; // Do we need to write a compacted cell?
final KeyValue compact;
{
boolean trivial = true; // Are we doing a trivial compaction?
int qual_len = 0; // Pre-compute the size of the qualifier we'll need.
int val_len = 1; // Reserve an extra byte for meta-data.
short last_delta = -1; // Time delta, extracted from the qualifier.
KeyValue longest = row.get(0); // KV with the longest qualifier.
int longest_idx = 0; // Index of `longest'.
final int nkvs = row.size();
for (int i = 0; i < nkvs; i++) {
final KeyValue kv = row.get(i);
final byte[] qual = kv.qualifier();
// If the qualifier length isn't 2, this row might have already
// been compacted, potentially partially, so we need to merge the
// partially compacted set of cells, with the rest.
final int len = qual.length;
if (len != 2) {
trivial = false;
// We only do this here because no qualifier can be < 2 bytes.
if (len > longest.qualifier().length) {
longest = kv;
longest_idx = i;
}
} else {
// In the trivial case, do some sanity checking here.
// For non-trivial cases, the sanity checking logic is more
// complicated and is thus pushed down to `complexCompact'.
final short delta = (short) ((Bytes.getShort(qual) & 0xFFFF)
>>> Const.FLAG_BITS);
// This data point has a time delta that's less than or equal to
// the previous one. This typically means we have 2 data points
// at the same timestamp but they have different flags. We're
// going to abort here because someone needs to fsck the table.
if (delta <= last_delta) {
throw new IllegalDataException("Found out of order or duplicate"
+ " data: last_delta=" + last_delta + ", delta=" + delta
+ ", offending KV=" + kv + ", row=" + row + " -- run an fsck.");
}
last_delta = delta;
// We don't need it below for complex compactions, so we update it
// only here in the `else' branch.
final byte[] v = kv.value();
val_len += floatingPointValueToFix(qual[1], v) ? 4 : v.length;
}
qual_len += len;
}
if (trivial) {
trivial_compactions.incrementAndGet();
compact = trivialCompact(row, qual_len, val_len);
} else {
complex_compactions.incrementAndGet();
compact = complexCompact(row, qual_len / 2);
// Now it's vital that we check whether the compact KV has the same
// qualifier as one of the qualifiers that were already in the row.
// Otherwise we might do a `put' in this cell, followed by a delete.
// We don't want to delete what we just wrote.
// This can happen if this row was already compacted but someone
// wrote another individual data point at the same timestamp.
// Optimization: since we kept track of which KV had the longest
// qualifier, we can opportunistically check here if it happens to
// have the same qualifier as the one we just created.
final byte[] qual = compact.qualifier();
final byte[] longest_qual = longest.qualifier();
if (qual.length <= longest_qual.length) {
KeyValue dup = null;
int dup_idx = -1;
if (Bytes.equals(longest_qual, qual)) {
dup = longest;
dup_idx = longest_idx;
} else {
// Worst case: to be safe we have to loop again and check all
// the qualifiers and make sure we're not going to overwrite
// anything.
// TODO(tsuna): Try to write a unit test that triggers this code
// path. I'm not even sure it's possible. Should we replace
// this code with an `assert false: "should never be here"'?
for (int i = 0; i < nkvs; i++) {
final KeyValue kv = row.get(i);
if (Bytes.equals(kv.qualifier(), qual)) {
dup = kv;
dup_idx = i;
break;
}
}
}
if (dup != null) {
// So we did find an existing KV with the same qualifier.
// Let's check if, by chance, the value is the same too.
if (Bytes.equals(dup.value(), compact.value())) {
// Since the values are the same, we don't need to write
// anything. There's already a properly compacted version of
// this row in TSDB.
write = false;
}
// Now let's make sure we don't delete this qualifier. This
// re-allocates the entire array, but should be a rare case.
row.remove(dup_idx);
} // else: no dup, we're good.
} // else: most common case: the compact qualifier is longer than
// the previously longest qualifier, so we cannot possibly
// overwrite an existing cell we would then delete.
}
}
if (compacted != null) { // Caller is interested in the compacted form.
compacted[0] = compact;
final long base_time = Bytes.getUnsignedInt(compact.key(), metric_width);
final long cut_off = System.currentTimeMillis() / 1000
- Const.MAX_TIMESPAN - 1;
if (base_time > cut_off) { // If row is too recent...
return null; // ... Don't write back compacted.
}
}
if (!TSDB.enable_compactions) {
return null;
}
final byte[] key = compact.key();
//LOG.debug("Compacting row " + Arrays.toString(key));
deleted_cells.addAndGet(row.size()); // We're going to delete this.
if (write) {
final byte[] qual = compact.qualifier();
final byte[] value = compact.value();
written_cells.incrementAndGet();
return tsdb.put(key, qual, value)
.addCallbacks(new DeleteCompactedCB(row), handle_write_error);
} else {
// We had nothing to write, because one of the cells is already the
// correctly compacted version, so we can go ahead and delete the
// individual cells directly.
new DeleteCompactedCB(row).call(null);
return null;
}
}
/**
* Performs a trivial compaction of a row.
* <p>
* This method is to be used only when all the cells in the given row
* are individual data points (nothing has been compacted yet). If any of
* the cells have already been compacted, the caller is expected to call
* {@link #complexCompact} instead.
* @param row The row to compact. Assumed to have 2 elements or more.
* @param qual_len Exact number of bytes to hold the compacted qualifiers.
* @param val_len Exact number of bytes to hold the compacted values.
* @return a {@link KeyValue} containing the result of the merge of all the
* {@code KeyValue}s given in argument.
*/
private static KeyValue trivialCompact(final ArrayList<KeyValue> row,
final int qual_len,
final int val_len) {
// Now let's simply concatenate all the qualifiers and values together.
final byte[] qualifier = new byte[qual_len];
final byte[] value = new byte[val_len];
// Now populate the arrays by copying qualifiers/values over.
int qual_idx = 0;
int val_idx = 0;
for (final KeyValue kv : row) {
final byte[] q = kv.qualifier();
// We shouldn't get into this function if this isn't true.
assert q.length == 2: "Qualifier length must be 2: " + kv;
final byte[] v = fixFloatingPointValue(q[1], kv.value());
qualifier[qual_idx++] = q[0];
qualifier[qual_idx++] = fixQualifierFlags(q[1], v.length);
System.arraycopy(v, 0, value, val_idx, v.length);
val_idx += v.length;
}
// Right now we leave the last byte all zeros, this last byte will be
// used in the future to introduce more formats/encodings.
final KeyValue first = row.get(0);
return new KeyValue(first.key(), first.family(), qualifier, value);
}
/**
* Fix the flags inside the last byte of a qualifier.
* <p>
* OpenTSDB used to not rely on the size recorded in the flags being
* correct, and so for a long time it was setting the wrong size for
* floating point values (pretending they were encoded on 8 bytes when
* in fact they were on 4). So overwrite these bits here to make sure
* they're correct now, because once they're compacted it's going to
* be quite hard to tell if the flags are right or wrong, and we need
* them to be correct to easily decode the values.
* @param flags The least significant byte of a qualifier.
* @param val_len The number of bytes in the value of this qualifier.
* @return The least significant byte of the qualifier with correct flags.
*/
private static byte fixQualifierFlags(byte flags, final int val_len) {
// Explanation:
// (1) Take the last byte of the qualifier.
// (2) Zero out all the flag bits but one.
// The one we keep is the type (floating point vs integer value).
// (3) Set the length properly based on the value we have.
return (byte) ((flags & ~(Const.FLAGS_MASK >>> 1)) | (val_len - 1));
// ^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^
// (1) (2) (3)
}
/**
* Returns whether or not this is a floating value that needs to be fixed.
* <p>
* OpenTSDB used to encode all floating point values as `float' (4 bytes)
* but actually store them on 8 bytes, with 4 leading 0 bytes, and flags
* correctly stating the value was on 4 bytes.
* @param flags The least significant byte of a qualifier.
* @param value The value that may need to be corrected.
*/
private static boolean floatingPointValueToFix(final byte flags,
final byte[] value) {
return (flags & Const.FLAG_FLOAT) != 0 // We need a floating point value.
&& (flags & Const.LENGTH_MASK) == 0x3 // That pretends to be on 4 bytes.
&& value.length == 8; // But is actually using 8 bytes.
}
/**
* Returns a corrected value if this is a floating point value to fix.
* <p>
* OpenTSDB used to encode all floating point values as `float' (4 bytes)
* but actually store them on 8 bytes, with 4 leading 0 bytes, and flags
* correctly stating the value was on 4 bytes.
* <p>
* This function detects such values and returns a corrected value, without
* the 4 leading zeros. Otherwise it returns the value unchanged.
* @param flags The least significant byte of a qualifier.
* @param value The value that may need to be corrected.
* @throws IllegalDataException if the value is malformed.
*/
private static byte[] fixFloatingPointValue(final byte flags,
final byte[] value) {
if (floatingPointValueToFix(flags, value)) {
// The first 4 bytes should really be zeros.
if (value[0] == 0 && value[1] == 0 && value[2] == 0 && value[3] == 0) {
// Just keep the last 4 bytes.
return new byte[] { value[4], value[5], value[6], value[7] };
} else { // Very unlikely.
throw new IllegalDataException("Corrupted floating point value: "
+ Arrays.toString(value) + " flags=0x" + Integer.toHexString(flags)
+ " -- first 4 bytes are expected to be zeros.");
}
}
return value;
}
/**
* Helper class for complex compaction cases.
* <p>
* This is simply a glorified pair of (qualifier, value) that's comparable.
* Only the qualifier is used to make comparisons.
* @see #complexCompact
*/
private static final class Cell implements Comparable<Cell> {
/** Tombstone used as a helper during the complex compaction. */
static final Cell SKIP = new Cell(null, null);
final byte[] qualifier;
final byte[] value;
Cell(final byte[] qualifier, final byte[] value) {
this.qualifier = qualifier;
this.value = value;
}
public int compareTo(final Cell other) {
return Bytes.memcmp(qualifier, other.qualifier);
}
public boolean equals(final Object o) {
return o != null && o instanceof Cell && compareTo((Cell) o) == 0;
}
public int hashCode() {
return Arrays.hashCode(qualifier);
}
public String toString() {
return "Cell(" + Arrays.toString(qualifier)
+ ", " + Arrays.toString(value) + ')';
}
}
/**
* Compacts a partially compacted row.
* <p>
* This method is called in the non-trivial re-compaction cases, where a row
* already contains one or more partially compacted cells. This can happen
* for various reasons, such as TSDs dying in the middle of a compaction or
* races involved with TSDs trying to compact the same row at the same
* time, or old data being slowly written to a TSD.
* @param row The row to compact. Assumed to have 2 elements or more.
* @param estimated_nvalues Estimate of the number of values to compact.
* Used to pre-allocate a collection of the right size, so it's better to
* overshoot a bit to avoid re-allocations.
* @return a {@link KeyValue} containing the result of the merge of all the
* {@code KeyValue}s given in argument.
* @throws IllegalDataException if one of the cells cannot be read because
* it's corrupted or in a format we don't understand.
*/
private static KeyValue complexCompact(final ArrayList<KeyValue> row,
final int estimated_nvalues) {
// We know at least one of the cells contains multiple values, and we need
// to merge all the cells together in a sorted fashion. We use a simple
// strategy: split all the cells into individual objects, sort them,
// merge the result while ignoring duplicates (same qualifier & value).
final ArrayList<Cell> cells = breakDownValues(row, estimated_nvalues);
Collections.sort(cells);
// Now let's done one pass first to compute the length of the compacted
// value and to find if we have any bad duplicates (same qualifier,
// different value).
int nvalues = 0;
int val_len = 1; // Reserve an extra byte for meta-data.
short last_delta = -1; // Time delta, extracted from the qualifier.
int ncells = cells.size();
for (int i = 0; i < ncells; i++) {
final Cell cell = cells.get(i);
final short delta = (short) ((Bytes.getShort(cell.qualifier) & 0xFFFF)
>>> Const.FLAG_BITS);
// Because we sorted `cells' by qualifier, and because the time delta
// occupies the most significant bits, this should never trigger.
assert delta >= last_delta: ("WTF? It's supposed to be sorted: " + cells
+ " at " + i + " delta=" + delta
+ ", last_delta=" + last_delta);
// The only troublesome case is where we have two (or more) consecutive
// cells with the same time delta, but different flags or values.
if (delta == last_delta) {
// Find the previous cell. Because we potentially replace the one
// right before `i' with a tombstone, we might need to look further
// back a bit more.
Cell prev = Cell.SKIP;
// i > 0 because we can't get here during the first iteration.
// Also the first Cell cannot be Cell.SKIP, so `j' will never
// underflow. And even if it does, we'll get an exception.
for (int j = i - 1; prev == Cell.SKIP; j--) {
prev = cells.get(j);
}
if (cell.qualifier[1] != prev.qualifier[1]
|| !Bytes.equals(cell.value, prev.value)) {
throw new IllegalDataException("Found out of order or duplicate"
+ " data: cell=" + cell + ", delta=" + delta + ", prev cell="
+ prev + ", last_delta=" + last_delta + ", in row=" + row
+ " -- run an fsck.");
}
// else: we're good, this is a true duplicate (same qualifier & value).
// Just replace it with a tombstone so we'll skip it. We don't delete
// it from the array because that would cause a re-allocation.
cells.set(i, Cell.SKIP);
continue;
}
last_delta = delta;
nvalues++;
val_len += cell.value.length;
}
final byte[] qualifier = new byte[nvalues * 2];
final byte[] value = new byte[val_len];
// Now populate the arrays by copying qualifiers/values over.
int qual_idx = 0;
int val_idx = 0;
for (final Cell cell : cells) {
if (cell == Cell.SKIP) {
continue;
}
byte[] b = cell.qualifier;
System.arraycopy(b, 0, qualifier, qual_idx, b.length);
qual_idx += b.length;
b = cell.value;
System.arraycopy(b, 0, value, val_idx, b.length);
val_idx += b.length;
}
// Right now we leave the last byte all zeros, this last byte will be
// used in the future to introduce more formats/encodings.
final KeyValue first = row.get(0);
final KeyValue kv = new KeyValue(first.key(), first.family(),
qualifier, value);
return kv;
}
/**
* Breaks down all the values in a row into individual {@link Cell}s.
* @param row The row to compact. Assumed to have 2 elements or more.
* @param estimated_nvalues Estimate of the number of values to compact.
* Used to pre-allocate a collection of the right size, so it's better to
* overshoot a bit to avoid re-allocations.
* @throws IllegalDataException if one of the cells cannot be read because
* it's corrupted or in a format we don't understand.
*/
private static ArrayList<Cell> breakDownValues(final ArrayList<KeyValue> row,
final int estimated_nvalues) {
final ArrayList<Cell> cells = new ArrayList<Cell>(estimated_nvalues);
for (final KeyValue kv : row) {
final byte[] qual = kv.qualifier();
final int len = qual.length;
final byte[] val = kv.value();
if (len == 2) { // Single-value cell.
// Maybe we need to fix the flags in the qualifier.
final byte[] actual_val = fixFloatingPointValue(qual[1], val);
final byte q = fixQualifierFlags(qual[1], actual_val.length);
final byte[] actual_qual;
if (q != qual[1]) { // We need to fix the qualifier.
actual_qual = new byte[] { qual[0], q }; // So make a copy.
} else {
actual_qual = qual; // Otherwise use the one we already have.
}
final Cell cell = new Cell(actual_qual, actual_val);
cells.add(cell);
continue;
}
// else: we have a multi-value cell. We need to break it down into
// individual Cell objects.
// First check that the last byte is 0, otherwise it might mean that
// this compacted cell has been written by a future version of OpenTSDB
// and we don't know how to decode it, so we shouldn't touch it.
if (val[val.length - 1] != 0) {
throw new IllegalDataException("Don't know how to read this value:"
+ Arrays.toString(val) + " found in " + kv
+ " -- this compacted value might have been written by a future"
+ " version of OpenTSDB, or could be corrupt.");
}
// Now break it down into Cells.
int val_idx = 0;
for (int i = 0; i < len; i += 2) {
final byte[] q = new byte[] { qual[i], qual[i + 1] };
final int vlen = (q[1] & Const.LENGTH_MASK) + 1;
final byte[] v = new byte[vlen];
System.arraycopy(val, val_idx, v, 0, vlen);
val_idx += vlen;
final Cell cell = new Cell(q, v);
cells.add(cell);
}
// Check we consumed all the bytes of the value. Remember the last byte
// is metadata, so it's normal that we didn't consume it.
if (val_idx != val.length - 1) {
throw new IllegalDataException("Corrupted value: couldn't break down"
+ " into individual values (consumed " + val_idx + " bytes, but was"
+ " expecting to consume " + (val.length - 1) + "): " + kv
+ ", cells so far: " + cells);
}
}
return cells;
}
/**
* Callback to delete a row that's been successfully compacted.
*/
private final class DeleteCompactedCB implements Callback<Object, Object> {
/** What we're going to delete. */
private final byte[] key;
private final byte[] family;
private final byte[][] qualifiers;
public DeleteCompactedCB(final ArrayList<KeyValue> cells) {
final KeyValue first = cells.get(0);
key = first.key();
family = first.family();
qualifiers = new byte[cells.size()][];
for (int i = 0; i < qualifiers.length; i++) {
qualifiers[i] = cells.get(i).qualifier();
}
}
public Object call(final Object arg) {
return tsdb.delete(key, qualifiers).addErrback(handle_delete_error);
}
public String toString() {
return "delete compacted cells";
}
}
private final HandleErrorCB handle_read_error = new HandleErrorCB("read");
private final HandleErrorCB handle_write_error = new HandleErrorCB("write");
private final HandleErrorCB handle_delete_error = new HandleErrorCB("delete");
/**
* Callback to handle exceptions during the compaction process.
*/
private final class HandleErrorCB implements Callback<Object, Exception> {
private volatile int errors;
private final String what;
/**
* Constructor.
* @param what String describing what kind of operation (e.g. "read").
*/
public HandleErrorCB(final String what) {
this.what = what;
}
public Object call(final Exception e) {
if (e instanceof PleaseThrottleException) { // HBase isn't keeping up.
final HBaseRpc rpc = ((PleaseThrottleException) e).getFailedRpc();
if (rpc instanceof HBaseRpc.HasKey) {
// We failed to compact this row. Whether it's because of a failed
// get, put or delete, we should re-schedule this row for a future
// compaction.
add(((HBaseRpc.HasKey) rpc).key());
return Boolean.TRUE; // We handled it, so don't return an exception.
} else { // Should never get in this clause.
LOG.error("WTF? Cannot retry this RPC, and this shouldn't happen: "
+ rpc);
}
}
// `++' is not atomic but doesn't matter if we miss some increments.
if (++errors % 100 == 1) { // Basic rate-limiting to not flood logs.
LOG.error("Failed to " + what + " a row to re-compact", e);
}
return e;
}
public String toString() {
return "handle " + what + " error";
}
}
static final long serialVersionUID = 1307386642;
/** Starts a compaction thread. Only one such thread is needed. */
private void startCompactionThread() {
final Thrd thread = new Thrd();
thread.setDaemon(true);
thread.start();
}
/** How frequently the compaction thread wakes up flush stuff. */
// TODO(tsuna): Make configurable?
private static final int FLUSH_INTERVAL = 10; // seconds
/** Minimum number of rows we'll attempt to compact at once. */
// TODO(tsuna): Make configurable?
private static final int MIN_FLUSH_THRESHOLD = 100; // rows
/** Maximum number of rows we'll compact concurrently. */
// TODO(tsuna): Make configurable?
private static final int MAX_CONCURRENT_FLUSHES = 10000; // rows
/** If this is X then we'll flush X times faster than we really need. */
// TODO(tsuna): Make configurable?
private static final int FLUSH_SPEED = 2; // multiplicative factor
/**
* Background thread to trigger periodic compactions.
*/
final class Thrd extends Thread {
public Thrd() {
super("CompactionThread");
}
public void run() {
long last_flush = 0;
while (true) {
try {
final long now = System.currentTimeMillis();
final int size = size();
// Let's suppose MAX_TIMESPAN = 1h. We have `size' rows to compact,
// and we better compact them all before in less than 1h, otherwise
// we're going to "fall behind" when a new hour start (as we'll be
// creating a ton of new rows then). So slice MAX_TIMESPAN using
// FLUSH_INTERVAL to compute what fraction of `size' we need to
// flush at each iteration. Note that `size' will usually account
// for many rows that can't be flushed yet (not old enough) so we're
// overshooting a bit (flushing more aggressively than necessary).
// This isn't a problem at all. The only thing that matters is that
// the rate at which we flush stuff is proportional to how much work
// is sitting in the queue. The multiplicative factor FLUSH_SPEED
// is added to make flush even faster than we need. For example, if
// FLUSH_SPEED is 2, then instead of taking 1h to flush what we have
// for the previous hour, we'll take only 30m. This is desirable so
// that we evict old entries from the queue a bit faster.
final int maxflushes = Math.max(MIN_FLUSH_THRESHOLD,
size * FLUSH_INTERVAL * FLUSH_SPEED / Const.MAX_TIMESPAN);
// Flush if either (1) it's been too long since the last flush
// or (2) we have too many rows to recompact already.
// Note that in the case (2) we might not be able to flush anything
// if the rows aren't old enough.
if (last_flush - now > Const.MAX_TIMESPAN // (1)
|| size > maxflushes) { // (2)
flush(now / 1000 - Const.MAX_TIMESPAN - 1, maxflushes);
if (LOG.isDebugEnabled()) {
final int newsize = size();
LOG.debug("flush() took " + (System.currentTimeMillis() - now)
+ "ms, new queue size=" + newsize
+ " (" + (newsize - size) + ')');
}
}
} catch (Exception e) {
LOG.error("Uncaught exception in compaction thread", e);
} catch (OutOfMemoryError e) {
// Let's free up some memory by throwing away the compaction queue.
final int sz = size.get();
CompactionQueue.super.clear();
size.set(0);
LOG.error("Discarded the compaction queue, size=" + sz, e);
} catch (Throwable e) {
LOG.error("Uncaught *Throwable* in compaction thread", e);
// Catching this kind of error is totally unexpected and is really
// bad. If we do nothing and let this thread die, we'll run out of
// memory as new entries are added to the queue. We could always
// commit suicide, but it's kind of drastic and nothing else in the
// code does this. If `enable_compactions' wasn't final, we could
// always set it to false, but that's not an option. So in order to
// try to get a fresh start, let this compaction thread terminate
// and spin off a new one instead.
try {
Thread.sleep(1000); // Avoid busy looping creating new threads.
} catch (InterruptedException i) {
LOG.error("Compaction thread interrupted in error handling", i);
return; // Don't flush, we're truly hopeless.
}
startCompactionThread();
return;
}
try {
Thread.sleep(FLUSH_INTERVAL * 1000);
} catch (InterruptedException e) {
LOG.error("Compaction thread interrupted, doing one last flush", e);
flush();
return;
}
}
}
}
/**
* Helper to sort the byte arrays in the compaction queue.
* <p>
* This comparator sorts things by timestamp first, this way we can find
* all rows of the same age at once.
*/
private static final class Cmp implements Comparator<byte[]> {
/** On how many bytes do we encode metrics IDs. */
private final short metric_width;
public Cmp(final TSDB tsdb) {
metric_width = tsdb.metrics.width();
}
public int compare(final byte[] a, final byte[] b) {
final int c = Bytes.memcmp(a, b, metric_width, Const.TIMESTAMP_BYTES);
// If the timestamps are equal, sort according to the entire row key.
return c != 0 ? c : Bytes.memcmp(a, b);
}
}
}
|
src/core/CompactionQueue.java
|
// This file is part of OpenTSDB.
// Copyright (C) 2011 StumbleUpon, Inc.
//
// This program is free software: you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or (at your
// option) any later version. This program is distributed in the hope that it
// will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser
// General Public License for more details. You should have received a copy
// of the GNU Lesser General Public License along with this program. If not,
// see <http://www.gnu.org/licenses/>.
package net.opentsdb.core;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import com.stumbleupon.async.Callback;
import com.stumbleupon.async.Deferred;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.hbase.async.Bytes;
import org.hbase.async.HBaseRpc;
import org.hbase.async.KeyValue;
import org.hbase.async.PleaseThrottleException;
import net.opentsdb.stats.StatsCollector;
/**
* "Queue" of rows to compact.
* <p>
* Whenever we write a data point to HBase, the row key we write to is added
* to this queue, which is effectively a sorted set. There is a separate
* thread that periodically goes through the queue and look for "old rows" to
* compact. A row is considered "old" if the timestamp in the row key is
* older than a certain threshold.
* <p>
* The compaction process consists in reading all the cells within a given row
* and writing them back out as a single big cell. Once that writes succeeds,
* we delete all the individual little cells.
* <p>
* This process is effective because in HBase the row key is repeated for
* every single cell. And because there is no way to efficiently append bytes
* at the end of a cell, we have to do this instead.
*/
final class CompactionQueue extends ConcurrentSkipListMap<byte[], Boolean> {
private static final Logger LOG = LoggerFactory.getLogger(CompactionQueue.class);
/**
* How many items are currently in the queue.
* Because {@link ConcurrentSkipListMap#size} has O(N) complexity.
*/
private final AtomicInteger size = new AtomicInteger();
private final AtomicLong trivial_compactions = new AtomicLong();
private final AtomicLong complex_compactions = new AtomicLong();
private final AtomicLong written_cells = new AtomicLong();
private final AtomicLong deleted_cells = new AtomicLong();
/** The {@code TSDB} instance we belong to. */
private final TSDB tsdb;
/** On how many bytes do we encode metrics IDs. */
private final short metric_width;
/**
* Constructor.
* @param tsdb The TSDB we belong to.
*/
public CompactionQueue(final TSDB tsdb) {
super(new Cmp(tsdb));
this.tsdb = tsdb;
metric_width = tsdb.metrics.width();
if (TSDB.enable_compactions) {
startCompactionThread();
}
}
@Override
public int size() {
return size.get();
}
public void add(final byte[] row) {
if (super.put(row, Boolean.TRUE) == null) {
size.incrementAndGet(); // We added a new entry, count it.
}
}
/**
* Forces a flush of the entire compaction queue.
* @return A deferred that will be called back once everything has been
* flushed (or something failed, in which case the deferred will carry the
* exception). In case of success, the kind of object returned is
* unspecified.
*/
public Deferred<ArrayList<Object>> flush() {
LOG.info("Flushing all " + size() + " outstanding rows");
return flush(Long.MAX_VALUE, Integer.MAX_VALUE);
}
/**
* Collects the stats and metrics tracked by this instance.
* @param collector The collector to use.
*/
void collectStats(final StatsCollector collector) {
collector.record("compaction.count", trivial_compactions, "type=trivial");
collector.record("compaction.count", complex_compactions, "type=complex");
if (!TSDB.enable_compactions) {
return;
}
// The remaining stats only make sense with compactions enabled.
collector.record("compaction.queue.size", size);
collector.record("compaction.errors", handle_read_error.errors, "rpc=read");
collector.record("compaction.errors", handle_write_error.errors, "rpc=put");
collector.record("compaction.errors", handle_delete_error.errors,
"rpc=delete");
collector.record("compaction.writes", written_cells);
collector.record("compaction.deletes", deleted_cells);
}
/**
* Flushes all the rows in the compaction queue older than the cutoff time.
* @param cut_off A UNIX timestamp in seconds (unsigned 32-bit integer).
* @param maxflushes How many rows to flush off the queue at once.
* This integer is expected to be strictly positive.
* @return A deferred that will be called back once everything has been
* flushed.
*/
private Deferred<ArrayList<Object>> flush(final long cut_off, int maxflushes) {
assert maxflushes > 0: "maxflushes must be > 0, but I got " + maxflushes;
// We can't possibly flush more entries than size().
maxflushes = Math.min(maxflushes, size());
final ArrayList<Deferred<Object>> ds =
new ArrayList<Deferred<Object>>(maxflushes);
for (final byte[] row : this.keySet()) {
if (maxflushes-- == 0) {
break;
}
final long base_time = Bytes.getUnsignedInt(row, metric_width);
if (base_time > cut_off) {
break;
}
// You'd think that it would be faster to grab an iterator on the map
// and then call remove() on the iterator to "unlink" the element
// directly from where the iterator is at, but no, the JDK implements
// it by calling remove(key) so it has to lookup the key again anyway.
if (super.remove(row) == null) { // We didn't remove anything.
continue; // So someone else already took care of this entry.
}
size.decrementAndGet();
ds.add(tsdb.get(row).addCallbacks(compactcb, handle_read_error));
}
return Deferred.group(ds);
}
private final CompactCB compactcb = new CompactCB();
/**
* Callback to compact a row once it's been read.
* <p>
* This is used once the "get" completes, to actually compact the row and
* write back the compacted version.
*/
private final class CompactCB implements Callback<Object, ArrayList<KeyValue>> {
public Object call(final ArrayList<KeyValue> row) {
return compact(row, null);
}
public String toString() {
return "compact";
}
}
/**
* Compacts a row into a single {@link KeyValue}.
* @param row The row containing all the KVs to compact.
* Must contain at least one element.
* @return A compacted version of this row.
*/
KeyValue compact(final ArrayList<KeyValue> row) {
final KeyValue[] compacted = { null };
compact(row, compacted);
return compacted[0];
}
/**
* Compacts a row into a single {@link KeyValue}.
* <p>
* If the {@code row} is empty, this function does literally nothing.
* If {@code compacted} is not {@code null}, then the compacted form of this
* {@code row} will be stored in {@code compacted[0]}. Obviously, if the
* {@code row} contains a single cell, then that cell is the compacted form.
* Otherwise the compaction process takes places.
* @param row The row containing all the KVs to compact. Must be non-null.
* @param compacted If non-null, the first item in the array will be set to
* a {@link KeyValue} containing the compacted form of this row.
* If non-null, we will also not write the compacted form back to HBase
* unless the timestamp in the row key is old enough.
* @return A {@link Deferred} if the compaction processed required a write
* to HBase, otherwise {@code null}.
*/
private Deferred<Object> compact(final ArrayList<KeyValue> row,
final KeyValue[] compacted) {
if (row.size() <= 1) {
if (row.isEmpty()) { // Maybe the row got deleted in the mean time?
LOG.debug("Attempted to compact a row that doesn't exist.");
} else if (compacted != null) {
// no need to re-compact rows containing a single value.
compacted[0] = row.get(0);
}
return null;
}
// We know we have at least 2 cells. We need to go through all the cells
// to determine what kind of compaction we're going to do. If each cell
// contains a single individual data point, then we can do a trivial
// compaction. Otherwise, we have a partially compacted row, and the
// logic required to compact it is more complex.
boolean write = true; // Do we need to write a compacted cell?
final KeyValue compact;
{
boolean trivial = true; // Are we doing a trivial compaction?
int qual_len = 0; // Pre-compute the size of the qualifier we'll need.
int val_len = 1; // Reserve an extra byte for meta-data.
short last_delta = -1; // Time delta, extracted from the qualifier.
KeyValue longest = row.get(0); // KV with the longest qualifier.
int longest_idx = 0; // Index of `longest'.
final int nkvs = row.size();
for (int i = 0; i < nkvs; i++) {
final KeyValue kv = row.get(i);
final byte[] qual = kv.qualifier();
// If the qualifier length isn't 2, this row might have already
// been compacted, potentially partially, so we need to merge the
// partially compacted set of cells, with the rest.
final int len = qual.length;
if (len != 2) {
trivial = false;
// We only do this here because no qualifier can be < 2 bytes.
if (len > longest.qualifier().length) {
longest = kv;
longest_idx = i;
}
} else {
// In the trivial case, do some sanity checking here.
// For non-trivial cases, the sanity checking logic is more
// complicated and is thus pushed down to `complexCompact'.
final short delta = (short) ((Bytes.getShort(qual) & 0xFFFF)
>>> Const.FLAG_BITS);
// This data point has a time delta that's less than or equal to
// the previous one. This typically means we have 2 data points
// at the same timestamp but they have different flags. We're
// going to abort here because someone needs to fsck the table.
if (delta <= last_delta) {
throw new IllegalDataException("Found out of order or duplicate"
+ " data: last_delta=" + last_delta + ", delta=" + delta
+ ", offending KV=" + kv + ", row=" + row + " -- run an fsck.");
}
last_delta = delta;
// We don't need it below for complex compactions, so we update it
// only here in the `else' branch.
final byte[] v = kv.value();
val_len += floatingPointValueToFix(qual[1], v) ? 4 : v.length;
}
qual_len += len;
}
if (trivial) {
trivial_compactions.incrementAndGet();
compact = trivialCompact(row, qual_len, val_len);
} else {
complex_compactions.incrementAndGet();
compact = complexCompact(row, qual_len / 2);
// Now it's vital that we check whether the compact KV has the same
// qualifier as one of the qualifiers that were already in the row.
// Otherwise we might do a `put' in this cell, followed by a delete.
// We don't want to delete what we just wrote.
// This can happen if this row was already compacted but someone
// wrote another individual data point at the same timestamp.
// Optimization: since we kept track of which KV had the longest
// qualifier, we can opportunistically check here if it happens to
// have the same qualifier as the one we just created.
final byte[] qual = compact.qualifier();
final byte[] longest_qual = longest.qualifier();
if (qual.length <= longest_qual.length) {
KeyValue dup = null;
int dup_idx = -1;
if (Bytes.equals(longest_qual, qual)) {
dup = longest;
dup_idx = longest_idx;
} else {
// Worst case: to be safe we have to loop again and check all
// the qualifiers and make sure we're not going to overwrite
// anything.
// TODO(tsuna): Try to write a unit test that triggers this code
// path. I'm not even sure it's possible. Should we replace
// this code with an `assert false: "should never be here"'?
for (int i = 0; i < nkvs; i++) {
final KeyValue kv = row.get(i);
if (Bytes.equals(kv.qualifier(), qual)) {
dup = kv;
dup_idx = i;
break;
}
}
}
if (dup != null) {
// So we did find an existing KV with the same qualifier.
// Let's check if, by chance, the value is the same too.
if (Bytes.equals(dup.value(), compact.value())) {
// Since the values are the same, we don't need to write
// anything. There's already a properly compacted version of
// this row in TSDB.
write = false;
}
// Now let's make sure we don't delete this qualifier. This
// re-allocates the entire array, but should be a rare case.
row.remove(dup_idx);
} // else: no dup, we're good.
} // else: most common case: the compact qualifier is longer than
// the previously longest qualifier, so we cannot possibly
// overwrite an existing cell we would then delete.
}
}
if (compacted != null) { // Caller is interested in the compacted form.
compacted[0] = compact;
final long base_time = Bytes.getUnsignedInt(compact.key(), metric_width);
final long cut_off = System.currentTimeMillis() / 1000
- Const.MAX_TIMESPAN - 1;
if (base_time > cut_off) { // If row is too recent...
return null; // ... Don't write back compacted.
}
}
if (!TSDB.enable_compactions) {
return null;
}
final byte[] key = compact.key();
//LOG.debug("Compacting row " + Arrays.toString(key));
deleted_cells.addAndGet(row.size()); // We're going to delete this.
if (write) {
final byte[] qual = compact.qualifier();
final byte[] value = compact.value();
written_cells.incrementAndGet();
return tsdb.put(key, qual, value)
.addCallbacks(new DeleteCompactedCB(row), handle_write_error);
} else {
// We had nothing to write, because one of the cells is already the
// correctly compacted version, so we can go ahead and delete the
// individual cells directly.
new DeleteCompactedCB(row).call(null);
return null;
}
}
/**
* Performs a trivial compaction of a row.
* <p>
* This method is to be used only when all the cells in the given row
* are individual data points (nothing has been compacted yet). If any of
* the cells have already been compacted, the caller is expected to call
* {@link #complexCompact} instead.
* @param row The row to compact. Assumed to have 2 elements or more.
* @param qual_len Exact number of bytes to hold the compacted qualifiers.
* @param val_len Exact number of bytes to hold the compacted values.
* @return a {@link KeyValue} containing the result of the merge of all the
* {@code KeyValue}s given in argument.
*/
private static KeyValue trivialCompact(final ArrayList<KeyValue> row,
final int qual_len,
final int val_len) {
// Now let's simply concatenate all the qualifiers and values together.
final byte[] qualifier = new byte[qual_len];
final byte[] value = new byte[val_len];
// Now populate the arrays by copying qualifiers/values over.
int qual_idx = 0;
int val_idx = 0;
for (final KeyValue kv : row) {
final byte[] q = kv.qualifier();
// We shouldn't get into this function if this isn't true.
assert q.length == 2: "Qualifier length must be 2: " + kv;
final byte[] v = fixFloatingPointValue(q[1], kv.value());
qualifier[qual_idx++] = q[0];
qualifier[qual_idx++] = fixQualifierFlags(q[1], v.length);
System.arraycopy(v, 0, value, val_idx, v.length);
val_idx += v.length;
}
// Right now we leave the last byte all zeros, this last byte will be
// used in the future to introduce more formats/encodings.
final KeyValue first = row.get(0);
return new KeyValue(first.key(), first.family(), qualifier, value);
}
/**
* Fix the flags inside the last byte of a qualifier.
* <p>
* OpenTSDB used to not rely on the size recorded in the flags being
* correct, and so for a long time it was setting the wrong size for
* floating point values (pretending they were encoded on 8 bytes when
* in fact they were on 4). So overwrite these bits here to make sure
* they're correct now, because once they're compacted it's going to
* be quite hard to tell if the flags are right or wrong, and we need
* them to be correct to easily decode the values.
* @param flags The least significant byte of a qualifier.
* @param val_len The number of bytes in the value of this qualifier.
* @return The least significant byte of the qualifier with correct flags.
*/
private static byte fixQualifierFlags(byte flags, final int val_len) {
// Explanation:
// (1) Take the last byte of the qualifier.
// (2) Zero out all the flag bits but one.
// The one we keep is the type (floating point vs integer value).
// (3) Set the length properly based on the value we have.
return (byte) ((flags & ~(Const.FLAGS_MASK >>> 1)) | (val_len - 1));
// ^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^
// (1) (2) (3)
}
/**
* Returns whether or not this is a floating value that needs to be fixed.
* <p>
* OpenTSDB used to encode all floating point values as `float' (4 bytes)
* but actually store them on 8 bytes, with 4 leading 0 bytes, and flags
* correctly stating the value was on 4 bytes.
* @param flags The least significant byte of a qualifier.
* @param value The value that may need to be corrected.
*/
private static boolean floatingPointValueToFix(final byte flags,
final byte[] value) {
return (flags & Const.FLAG_FLOAT) != 0 // We need a floating point value.
&& (flags & Const.LENGTH_MASK) == 0x3 // That pretends to be on 4 bytes.
&& value.length == 8; // But is actually using 8 bytes.
}
/**
* Returns a corrected value if this is a floating point value to fix.
* <p>
* OpenTSDB used to encode all floating point values as `float' (4 bytes)
* but actually store them on 8 bytes, with 4 leading 0 bytes, and flags
* correctly stating the value was on 4 bytes.
* <p>
* This function detects such values and returns a corrected value, without
* the 4 leading zeros. Otherwise it returns the value unchanged.
* @param flags The least significant byte of a qualifier.
* @param value The value that may need to be corrected.
* @throws IllegalDataException if the value is malformed.
*/
private static byte[] fixFloatingPointValue(final byte flags,
final byte[] value) {
if (floatingPointValueToFix(flags, value)) {
// The first 4 bytes should really be zeros.
if (value[0] == 0 && value[1] == 0 && value[2] == 0 && value[3] == 0) {
// Just keep the last 4 bytes.
return new byte[] { value[4], value[5], value[6], value[7] };
} else { // Very unlikely.
throw new IllegalDataException("Corrupted floating point value: "
+ Arrays.toString(value) + " flags=0x" + Integer.toHexString(flags)
+ " -- first 4 bytes are expected to be zeros.");
}
}
return value;
}
/**
* Helper class for complex compaction cases.
* <p>
* This is simply a glorified pair of (qualifier, value) that's comparable.
* Only the qualifier is used to make comparisons.
* @see #complexCompact
*/
private static final class Cell implements Comparable<Cell> {
/** Tombstone used as a helper during the complex compaction. */
static final Cell SKIP = new Cell(null, null);
final byte[] qualifier;
final byte[] value;
Cell(final byte[] qualifier, final byte[] value) {
this.qualifier = qualifier;
this.value = value;
}
public int compareTo(final Cell other) {
return Bytes.memcmp(qualifier, other.qualifier);
}
public boolean equals(final Object o) {
return o != null && o instanceof Cell && compareTo((Cell) o) == 0;
}
public int hashCode() {
return Arrays.hashCode(qualifier);
}
public String toString() {
return "Cell(" + Arrays.toString(qualifier)
+ ", " + Arrays.toString(value) + ')';
}
}
/**
* Compacts a partially compacted row.
* <p>
* This method is called in the non-trivial re-compaction cases, where a row
* already contains one or more partially compacted cells. This can happen
* for various reasons, such as TSDs dying in the middle of a compaction or
* races involved with TSDs trying to compact the same row at the same
* time, or old data being slowly written to a TSD.
* @param row The row to compact. Assumed to have 2 elements or more.
* @param estimated_nvalues Estimate of the number of values to compact.
* Used to pre-allocate a collection of the right size, so it's better to
* overshoot a bit to avoid re-allocations.
* @return a {@link KeyValue} containing the result of the merge of all the
* {@code KeyValue}s given in argument.
* @throws IllegalDataException if one of the cells cannot be read because
* it's corrupted or in a format we don't understand.
*/
private static KeyValue complexCompact(final ArrayList<KeyValue> row,
final int estimated_nvalues) {
// We know at least one of the cells contains multiple values, and we need
// to merge all the cells together in a sorted fashion. We use a simple
// strategy: split all the cells into individual objects, sort them,
// merge the result while ignoring duplicates (same qualifier & value).
final ArrayList<Cell> cells = breakDownValues(row, estimated_nvalues);
Collections.sort(cells);
// Now let's done one pass first to compute the length of the compacted
// value and to find if we have any bad duplicates (same qualifier,
// different value).
int nvalues = 0;
int val_len = 1; // Reserve an extra byte for meta-data.
short last_delta = -1; // Time delta, extracted from the qualifier.
int ncells = cells.size();
for (int i = 0; i < ncells; i++) {
final Cell cell = cells.get(i);
final short delta = (short) ((Bytes.getShort(cell.qualifier) & 0xFFFF)
>>> Const.FLAG_BITS);
// Because we sorted `cells' by qualifier, and because the time delta
// occupies the most significant bits, this should never trigger.
assert delta >= last_delta: ("WTF? It's supposed to be sorted: " + cells
+ " at " + i + " delta=" + delta
+ ", last_delta=" + last_delta);
// The only troublesome case is where we have two (or more) consecutive
// cells with the same time delta, but different flags or values.
if (delta == last_delta) {
// Find the previous cell. Because we potentially replace the one
// right before `i' with a tombstone, we might need to look further
// back a bit more.
Cell prev = Cell.SKIP;
// i > 0 because we can't get here during the first iteration.
// Also the first Cell cannot be Cell.SKIP, so `j' will never
// underflow. And even if it does, we'll get an exception.
for (int j = i - 1; prev == Cell.SKIP; j--) {
prev = cells.get(j);
}
if (cell.qualifier[1] != prev.qualifier[1]
|| !Bytes.equals(cell.value, prev.value)) {
throw new IllegalDataException("Found out of order or duplicate"
+ " data: cell=" + cell + ", delta=" + delta + ", prev cell="
+ prev + ", last_delta=" + last_delta + ", in row=" + row
+ " -- run an fsck.");
}
// else: we're good, this is a true duplicate (same qualifier & value).
// Just replace it with a tombstone so we'll skip it. We don't delete
// it from the array because that would cause a re-allocation.
cells.set(i, Cell.SKIP);
continue;
}
last_delta = delta;
nvalues++;
val_len += cell.value.length;
}
final byte[] qualifier = new byte[nvalues * 2];
final byte[] value = new byte[val_len];
// Now populate the arrays by copying qualifiers/values over.
int qual_idx = 0;
int val_idx = 0;
for (final Cell cell : cells) {
if (cell == Cell.SKIP) {
continue;
}
byte[] b = cell.qualifier;
System.arraycopy(b, 0, qualifier, qual_idx, b.length);
qual_idx += b.length;
b = cell.value;
System.arraycopy(b, 0, value, val_idx, b.length);
val_idx += b.length;
}
// Right now we leave the last byte all zeros, this last byte will be
// used in the future to introduce more formats/encodings.
final KeyValue first = row.get(0);
final KeyValue kv = new KeyValue(first.key(), first.family(),
qualifier, value);
return kv;
}
/**
* Breaks down all the values in a row into individual {@link Cell}s.
* @param row The row to compact. Assumed to have 2 elements or more.
* @param estimated_nvalues Estimate of the number of values to compact.
* Used to pre-allocate a collection of the right size, so it's better to
* overshoot a bit to avoid re-allocations.
* @throws IllegalDataException if one of the cells cannot be read because
* it's corrupted or in a format we don't understand.
*/
private static ArrayList<Cell> breakDownValues(final ArrayList<KeyValue> row,
final int estimated_nvalues) {
final ArrayList<Cell> cells = new ArrayList<Cell>(estimated_nvalues);
for (final KeyValue kv : row) {
final byte[] qual = kv.qualifier();
final int len = qual.length;
final byte[] val = kv.value();
if (len == 2) { // Single-value cell.
// Maybe we need to fix the flags in the qualifier.
final byte[] actual_val = fixFloatingPointValue(qual[1], val);
final byte q = fixQualifierFlags(qual[1], actual_val.length);
final byte[] actual_qual;
if (q != qual[1]) { // We need to fix the qualifier.
actual_qual = new byte[] { qual[0], q }; // So make a copy.
} else {
actual_qual = qual; // Otherwise use the one we already have.
}
final Cell cell = new Cell(actual_qual, actual_val);
cells.add(cell);
continue;
}
// else: we have a multi-value cell. We need to break it down into
// individual Cell objects.
// First check that the last byte is 0, otherwise it might mean that
// this compacted cell has been written by a future version of OpenTSDB
// and we don't know how to decode it, so we shouldn't touch it.
if (val[val.length - 1] != 0) {
throw new IllegalDataException("Don't know how to read this value:"
+ Arrays.toString(val) + " found in " + kv
+ " -- this compacted value might have been written by a future"
+ " version of OpenTSDB, or could be corrupt.");
}
// Now break it down into Cells.
int val_idx = 0;
for (int i = 0; i < len; i += 2) {
final byte[] q = new byte[] { qual[i], qual[i + 1] };
final int vlen = (q[1] & Const.LENGTH_MASK) + 1;
final byte[] v = new byte[vlen];
System.arraycopy(val, val_idx, v, 0, vlen);
val_idx += vlen;
final Cell cell = new Cell(q, v);
cells.add(cell);
}
// Check we consumed all the bytes of the value. Remember the last byte
// is metadata, so it's normal that we didn't consume it.
if (val_idx != val.length - 1) {
throw new IllegalDataException("Corrupted value: couldn't break down"
+ " into individual values (consumed " + val_idx + " bytes, but was"
+ " expecting to consume " + (val.length - 1) + "): " + kv
+ ", cells so far: " + cells);
}
}
return cells;
}
/**
* Callback to delete a row that's been successfully compacted.
*/
private final class DeleteCompactedCB implements Callback<Object, Object> {
/** What we're going to delete. */
private final byte[] key;
private final byte[] family;
private final byte[][] qualifiers;
public DeleteCompactedCB(final ArrayList<KeyValue> cells) {
final KeyValue first = cells.get(0);
key = first.key();
family = first.family();
qualifiers = new byte[cells.size()][];
for (int i = 0; i < qualifiers.length; i++) {
qualifiers[i] = cells.get(i).qualifier();
}
}
public Object call(final Object arg) {
return tsdb.delete(key, qualifiers).addErrback(handle_delete_error);
}
public String toString() {
return "delete compacted cells";
}
}
private final HandleErrorCB handle_read_error = new HandleErrorCB("read");
private final HandleErrorCB handle_write_error = new HandleErrorCB("write");
private final HandleErrorCB handle_delete_error = new HandleErrorCB("delete");
/**
* Callback to handle exceptions during the compaction process.
*/
private final class HandleErrorCB implements Callback<Object, Exception> {
private volatile int errors;
private final String what;
/**
* Constructor.
* @param what String describing what kind of operation (e.g. "read").
*/
public HandleErrorCB(final String what) {
this.what = what;
}
public Object call(final Exception e) {
if (e instanceof PleaseThrottleException) { // HBase isn't keeping up.
final HBaseRpc rpc = ((PleaseThrottleException) e).getFailedRpc();
if (rpc instanceof HBaseRpc.HasKey) {
// We failed to compact this row. Whether it's because of a failed
// get, put or delete, we should re-schedule this row for a future
// compaction.
add(((HBaseRpc.HasKey) rpc).key());
return Boolean.TRUE; // We handled it, so don't return an exception.
} else { // Should never get in this clause.
LOG.error("WTF? Cannot retry this RPC, and this shouldn't happen: "
+ rpc);
}
}
// `++' is not atomic but doesn't matter if we miss some increments.
if (++errors % 100 == 1) { // Basic rate-limiting to not flood logs.
LOG.error("Failed to " + what + " a row to re-compact", e);
}
return e;
}
public String toString() {
return "handle " + what + " error";
}
}
static final long serialVersionUID = 1307386642;
/** Starts a compaction thread. Only one such thread is needed. */
private void startCompactionThread() {
final Thrd thread = new Thrd();
thread.setDaemon(true);
thread.start();
}
/** How frequently the compaction thread wakes up flush stuff. */
// TODO(tsuna): Make configurable?
private static final int FLUSH_INTERVAL = 10; // seconds
/** Minimum number of rows we'll attempt to compact at once. */
// TODO(tsuna): Make configurable?
private static final int MIN_FLUSH_THRESHOLD = 100; // rows
/** If this is X then we'll flush X times faster than we really need. */
// TODO(tsuna): Make configurable?
private static final int FLUSH_SPEED = 2; // multiplicative factor
/**
* Background thread to trigger periodic compactions.
*/
final class Thrd extends Thread {
public Thrd() {
super("CompactionThread");
}
public void run() {
long last_flush = 0;
while (true) {
try {
final long now = System.currentTimeMillis();
final int size = size();
// Let's suppose MAX_TIMESPAN = 1h. We have `size' rows to compact,
// and we better compact them all before in less than 1h, otherwise
// we're going to "fall behind" when a new hour start (as we'll be
// creating a ton of new rows then). So slice MAX_TIMESPAN using
// FLUSH_INTERVAL to compute what fraction of `size' we need to
// flush at each iteration. Note that `size' will usually account
// for many rows that can't be flushed yet (not old enough) so we're
// overshooting a bit (flushing more aggressively than necessary).
// This isn't a problem at all. The only thing that matters is that
// the rate at which we flush stuff is proportional to how much work
// is sitting in the queue. The multiplicative factor FLUSH_SPEED
// is added to make flush even faster than we need. For example, if
// FLUSH_SPEED is 2, then instead of taking 1h to flush what we have
// for the previous hour, we'll take only 30m. This is desirable so
// that we evict old entries from the queue a bit faster.
final int maxflushes = Math.max(MIN_FLUSH_THRESHOLD,
size * FLUSH_INTERVAL * FLUSH_SPEED / Const.MAX_TIMESPAN);
// Flush if either (1) it's been too long since the last flush
// or (2) we have too many rows to recompact already.
// Note that in the case (2) we might not be able to flush anything
// if the rows aren't old enough.
if (last_flush - now > Const.MAX_TIMESPAN // (1)
|| size > maxflushes) { // (2)
flush(now / 1000 - Const.MAX_TIMESPAN - 1, maxflushes);
if (LOG.isDebugEnabled()) {
final int newsize = size();
LOG.debug("flush() took " + (System.currentTimeMillis() - now)
+ "ms, new queue size=" + newsize
+ " (" + (newsize - size) + ')');
}
}
} catch (Exception e) {
LOG.error("Uncaught exception in compaction thread", e);
} catch (OutOfMemoryError e) {
// Let's free up some memory by throwing away the compaction queue.
final int sz = size.get();
CompactionQueue.super.clear();
size.set(0);
LOG.error("Discarded the compaction queue, size=" + sz, e);
} catch (Throwable e) {
LOG.error("Uncaught *Throwable* in compaction thread", e);
// Catching this kind of error is totally unexpected and is really
// bad. If we do nothing and let this thread die, we'll run out of
// memory as new entries are added to the queue. We could always
// commit suicide, but it's kind of drastic and nothing else in the
// code does this. If `enable_compactions' wasn't final, we could
// always set it to false, but that's not an option. So in order to
// try to get a fresh start, let this compaction thread terminate
// and spin off a new one instead.
try {
Thread.sleep(1000); // Avoid busy looping creating new threads.
} catch (InterruptedException i) {
LOG.error("Compaction thread interrupted in error handling", i);
return; // Don't flush, we're truly hopeless.
}
startCompactionThread();
return;
}
try {
Thread.sleep(FLUSH_INTERVAL * 1000);
} catch (InterruptedException e) {
LOG.error("Compaction thread interrupted, doing one last flush", e);
flush();
return;
}
}
}
}
/**
* Helper to sort the byte arrays in the compaction queue.
* <p>
* This comparator sorts things by timestamp first, this way we can find
* all rows of the same age at once.
*/
private static final class Cmp implements Comparator<byte[]> {
/** On how many bytes do we encode metrics IDs. */
private final short metric_width;
public Cmp(final TSDB tsdb) {
metric_width = tsdb.metrics.width();
}
public int compare(final byte[] a, final byte[] b) {
final int c = Bytes.memcmp(a, b, metric_width, Const.TIMESTAMP_BYTES);
// If the timestamps are equal, sort according to the entire row key.
return c != 0 ? c : Bytes.memcmp(a, b);
}
}
}
|
Limit the number of concurrent flushes that can happen.
When the CompactionQueue contains, say, 1M rows, and flush() is called,
the code was attempting to compact all these rows concurrently. This
is unrealistic and can either kill HBase and/or run the TSD out of RAM.
With this change, a single call to flush() can only initiate up to 10k
concurrent compactions, after which the code asynchronously waits until
the batch of 10k is done before flushing more.
Change-Id: I05ec3839e08f13455f80b3aba31acf5f42c7ac38
|
src/core/CompactionQueue.java
|
Limit the number of concurrent flushes that can happen.
|
|
Java
|
lgpl-2.1
|
476d9a043288ce7f377e92059024e05607406362
| 0
|
lucee/Lucee,lucee/Lucee,jzuijlek/Lucee,lucee/Lucee,jzuijlek/Lucee,lucee/Lucee,jzuijlek/Lucee
|
/**
*
* Copyright (c) 2014, the Railo Company Ltd. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*
**/
package lucee.runtime.schedule;
import java.util.Calendar;
import java.util.TimeZone;
import lucee.commons.date.DateTimeUtil;
import lucee.commons.date.JREDateTimeUtil;
import lucee.commons.io.log.Log;
import lucee.commons.lang.ExceptionUtil;
import lucee.runtime.config.Config;
import lucee.runtime.config.ConfigImpl;
import lucee.runtime.engine.CFMLEngineImpl;
import lucee.runtime.engine.ThreadLocalPageContext;
import lucee.runtime.type.dt.DateTimeImpl;
import static lucee.commons.date.DateTimeUtil.DATETIME_FORMAT_LOCAL;
public class ScheduledTaskThread extends Thread {
private static final long DAY=24*3600000;
//private Calendar calendar;
private long startDate;
private long startTime;
private long endDate;
private long endTime;
private int intervall;
private int amount;
private DateTimeUtil util;
private int cIntervall;
private Config config;
private ScheduleTask task;
private String charset;
private final CFMLEngineImpl engine;
private TimeZone timeZone;
private SchedulerImpl scheduler;
public ScheduledTaskThread(CFMLEngineImpl engine,SchedulerImpl scheduler, Config config, ScheduleTask task, String charset) {
util = DateTimeUtil.getInstance();
this.engine=engine;
this.scheduler=scheduler;
this.config=config;
this.task=task;
this.charset=charset;
timeZone=ThreadLocalPageContext.getTimeZone(config);
this.startDate=util.getMilliSecondsAdMidnight(timeZone,task.getStartDate().getTime());
this.startTime=util.getMilliSecondsInDay(timeZone, task.getStartTime().getTime());
this.endDate=task.getEndDate()==null?Long.MAX_VALUE:util.getMilliSecondsAdMidnight(timeZone,task.getEndDate().getTime());
this.endTime=task.getEndTime()==null?DAY:util.getMilliSecondsInDay(timeZone, task.getEndTime().getTime());
this.intervall=task.getInterval();
if(intervall>=10){
amount=intervall;
intervall=ScheduleTaskImpl.INTERVAL_EVEREY;
}
else amount=1;
cIntervall = toCalndarIntervall(intervall);
}
@Override
public void run(){
try{
_run();
}
catch(Exception e) {
log(Log.LEVEL_ERROR,e);
if(e instanceof RuntimeException) throw (RuntimeException)e;
throw new RuntimeException(e);
}
finally {
task.setValid(false);
try {
scheduler.removeIfNoLonerValid(task);
} catch(Exception e) {}
}
}
public void _run(){
// check values
if(startDate>endDate) {
log(Log.LEVEL_ERROR,"Invalid task definition: enddate is before startdate");
return;
}
if(intervall==ScheduleTaskImpl.INTERVAL_EVEREY && startTime>endTime) {
log(Log.LEVEL_ERROR,"Invalid task definition: endtime is before starttime");
return;
}
long today = System.currentTimeMillis();
long execution ;
boolean isOnce=intervall==ScheduleTask.INTERVAL_ONCE;
if(isOnce){
if(startDate+startTime<today) return;
execution=startDate+startTime;
}
else execution = calculateNextExecution(today,false);
//long sleep=execution-today;
log(Log.LEVEL_INFO,"First execution runs at " + DATETIME_FORMAT_LOCAL.format(execution));
while(true){
sleepEL(execution,today);
if(!engine.isRunning()){
log(Log.LEVEL_ERROR,"Engine is not running");
break;
}
today=System.currentTimeMillis();
long todayTime=util.getMilliSecondsInDay(null,today);
long todayDate=today-todayTime;
if(!task.isValid()){
log(Log.LEVEL_ERROR,"Task is not valid");
break;
}
if(!task.isPaused()){
if(endDate<todayDate && endTime<todayTime) {
log(Log.LEVEL_ERROR, String.format("End date %s has passed; now: %s"
, DATETIME_FORMAT_LOCAL.format(endDate + endTime)
, DATETIME_FORMAT_LOCAL.format(todayDate + todayTime)));
break;
}
execute();
}
if(isOnce)break;
today=System.currentTimeMillis();
execution=calculateNextExecution(today,true);
if (!task.isPaused())
log(Log.LEVEL_INFO, "next execution runs at " + DATETIME_FORMAT_LOCAL.format(execution));
//sleep=execution-today;
}
}
private void log(int level, String msg) {
String logName="schedule task:"+task.getTask();
((ConfigImpl)config).getLog("scheduler").log(level,logName, msg);
}
private void log(int level, Exception e) {
String logName="schedule task:"+task.getTask();
((ConfigImpl)config).getLog("scheduler").log(level,logName, e);
}
private void sleepEL(long when, long now) {
long millis = when-now;
try {
while(true){
sleep(millis);
millis=when-System.currentTimeMillis();
if(millis<=0)break;
millis=10;
}
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
private void execute() {
if(config!=null)new ExecutionThread(config,task,charset).start();
}
private long calculateNextExecution(long now, boolean notNow) {
long nowTime=util.getMilliSecondsInDay(timeZone,now);
long nowDate=now-nowTime;
// when second or date intervall switch to current date
if(startDate<nowDate && (cIntervall==Calendar.SECOND || cIntervall==Calendar.DATE))
startDate=nowDate;
// init calendar
Calendar calendar = JREDateTimeUtil.getThreadCalendar(timeZone);
calendar.setTimeInMillis(startDate+startTime);
long time;
while(true) {
time=getMilliSecondsInDay(calendar);
if(now<=calendar.getTimeInMillis() && time>=startTime) {
// this is used because when cames back sometme to early
if(notNow && (calendar.getTimeInMillis()-now)<1000);
else if(intervall==ScheduleTaskImpl.INTERVAL_EVEREY && time>endTime)
now=nowDate+DAY;
else
break;
}
calendar.add(cIntervall, amount);
}
return calendar.getTimeInMillis();
}
private static int toCalndarIntervall(int intervall) {
switch(intervall){
case ScheduleTask.INTERVAL_DAY:return Calendar.DATE;
case ScheduleTask.INTERVAL_MONTH:return Calendar.MONTH;
case ScheduleTask.INTERVAL_WEEK:return Calendar.WEEK_OF_YEAR;
case ScheduleTask.INTERVAL_ONCE:return -1;
}
return Calendar.SECOND;
}
public static long getMilliSecondsInDay(Calendar c) {
return (c.get(Calendar.HOUR_OF_DAY)*3600000)+
(c.get(Calendar.MINUTE)*60000)+
(c.get(Calendar.SECOND)*1000)+
(c.get(Calendar.MILLISECOND));
}
public Config getConfig() {
return config;
}
public ScheduleTask getTask() {
return task;
}
}
|
core/src/main/java/lucee/runtime/schedule/ScheduledTaskThread.java
|
/**
*
* Copyright (c) 2014, the Railo Company Ltd. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*
**/
package lucee.runtime.schedule;
import java.util.Calendar;
import java.util.TimeZone;
import lucee.commons.date.DateTimeUtil;
import lucee.commons.date.JREDateTimeUtil;
import lucee.commons.io.log.Log;
import lucee.commons.lang.ExceptionUtil;
import lucee.runtime.config.Config;
import lucee.runtime.config.ConfigImpl;
import lucee.runtime.engine.CFMLEngineImpl;
import lucee.runtime.engine.ThreadLocalPageContext;
import lucee.runtime.type.dt.DateTimeImpl;
import static lucee.commons.date.DateTimeUtil.DATETIME_FORMAT_LOCAL;
public class ScheduledTaskThread extends Thread {
private static final long DAY=24*3600000;
//private Calendar calendar;
private long startDate;
private long startTime;
private long endDate;
private long endTime;
private int intervall;
private int amount;
private DateTimeUtil util;
private int cIntervall;
private Config config;
private ScheduleTask task;
private String charset;
private final CFMLEngineImpl engine;
private TimeZone timeZone;
private SchedulerImpl scheduler;
public ScheduledTaskThread(CFMLEngineImpl engine,SchedulerImpl scheduler, Config config, ScheduleTask task, String charset) {
util = DateTimeUtil.getInstance();
this.engine=engine;
this.scheduler=scheduler;
this.config=config;
this.task=task;
this.charset=charset;
timeZone=ThreadLocalPageContext.getTimeZone(config);
this.startDate=util.getMilliSecondsAdMidnight(timeZone,task.getStartDate().getTime());
this.startTime=util.getMilliSecondsInDay(timeZone, task.getStartTime().getTime());
this.endDate=task.getEndDate()==null?Long.MAX_VALUE:util.getMilliSecondsAdMidnight(timeZone,task.getEndDate().getTime());
this.endTime=task.getEndTime()==null?DAY:util.getMilliSecondsInDay(timeZone, task.getEndTime().getTime());
this.intervall=task.getInterval();
if(intervall>=10){
amount=intervall;
intervall=ScheduleTaskImpl.INTERVAL_EVEREY;
}
else amount=1;
cIntervall = toCalndarIntervall(intervall);
}
@Override
public void run(){
try{
_run();
}
catch (Throwable t) {
log(Log.LEVEL_ERROR,"Error running task - see System.err log for more details " + t.getMessage());
t.printStackTrace();
}
finally{
task.setValid(false);
try {
scheduler.removeIfNoLonerValid(task);
} catch(Throwable t) {ExceptionUtil.rethrowIfNecessary(t);}
}
}
public void _run(){
// check values
if(startDate>endDate) {
log(Log.LEVEL_ERROR,"Invalid task definition: enddate is before startdate");
return;
}
if(intervall==ScheduleTaskImpl.INTERVAL_EVEREY && startTime>endTime) {
log(Log.LEVEL_ERROR,"Invalid task definition: endtime is before starttime");
return;
}
long today = System.currentTimeMillis();
long execution ;
boolean isOnce=intervall==ScheduleTask.INTERVAL_ONCE;
if(isOnce){
if(startDate+startTime<today) return;
execution=startDate+startTime;
}
else execution = calculateNextExecution(today,false);
//long sleep=execution-today;
log(Log.LEVEL_INFO,"First execution runs at " + DATETIME_FORMAT_LOCAL.format(execution));
while(true){
sleepEL(execution,today);
if(!engine.isRunning()){
log(Log.LEVEL_ERROR,"Engine is not running");
break;
}
today=System.currentTimeMillis();
long todayTime=util.getMilliSecondsInDay(null,today);
long todayDate=today-todayTime;
if(!task.isValid()){
log(Log.LEVEL_ERROR,"Task is not valid");
break;
}
if(!task.isPaused()){
if(endDate<todayDate && endTime<todayTime) {
log(Log.LEVEL_ERROR, String.format("End date %s has passed; now: %s"
, DATETIME_FORMAT_LOCAL.format(endDate + endTime)
, DATETIME_FORMAT_LOCAL.format(todayDate + todayTime)));
break;
}
execute();
}
if(isOnce)break;
today=System.currentTimeMillis();
execution=calculateNextExecution(today,true);
if (!task.isPaused())
log(Log.LEVEL_INFO, "next execution runs at " + DATETIME_FORMAT_LOCAL.format(execution));
//sleep=execution-today;
}
}
private void log(int level, String msg) {
String logName="schedule task:"+task.getTask();
((ConfigImpl)config).getLog("scheduler").log(level,logName, msg);
}
private void sleepEL(long when, long now) {
long millis = when-now;
try {
while(true){
sleep(millis);
millis=when-System.currentTimeMillis();
if(millis<=0)break;
millis=10;
}
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
private void execute() {
if(config!=null)new ExecutionThread(config,task,charset).start();
}
private long calculateNextExecution(long now, boolean notNow) {
long nowTime=util.getMilliSecondsInDay(timeZone,now);
long nowDate=now-nowTime;
// when second or date intervall switch to current date
if(startDate<nowDate && (cIntervall==Calendar.SECOND || cIntervall==Calendar.DATE))
startDate=nowDate;
// init calendar
Calendar calendar = JREDateTimeUtil.getThreadCalendar(timeZone);
calendar.setTimeInMillis(startDate+startTime);
long time;
while(true) {
time=getMilliSecondsInDay(calendar);
if(now<=calendar.getTimeInMillis() && time>=startTime) {
// this is used because when cames back sometme to early
if(notNow && (calendar.getTimeInMillis()-now)<1000);
else if(intervall==ScheduleTaskImpl.INTERVAL_EVEREY && time>endTime)
now=nowDate+DAY;
else
break;
}
calendar.add(cIntervall, amount);
}
return calendar.getTimeInMillis();
}
private static int toCalndarIntervall(int intervall) {
switch(intervall){
case ScheduleTask.INTERVAL_DAY:return Calendar.DATE;
case ScheduleTask.INTERVAL_MONTH:return Calendar.MONTH;
case ScheduleTask.INTERVAL_WEEK:return Calendar.WEEK_OF_YEAR;
case ScheduleTask.INTERVAL_ONCE:return -1;
}
return Calendar.SECOND;
}
public static long getMilliSecondsInDay(Calendar c) {
return (c.get(Calendar.HOUR_OF_DAY)*3600000)+
(c.get(Calendar.MINUTE)*60000)+
(c.get(Calendar.SECOND)*1000)+
(c.get(Calendar.MILLISECOND));
}
public Config getConfig() {
return config;
}
public ScheduleTask getTask() {
return task;
}
}
|
improve #120
|
core/src/main/java/lucee/runtime/schedule/ScheduledTaskThread.java
|
improve #120
|
|
Java
|
unlicense
|
5f1274bfced7f49c5972817807b7360e51bbc091
| 0
|
danieljohnson2/SnowballMadness,airwindows/SnowballMadness
|
package snowballmadness;
import java.util.*;
import com.google.common.base.*;
import com.google.common.collect.Lists;
import org.bukkit.*;
import org.bukkit.entity.*;
import org.bukkit.event.entity.*;
import org.bukkit.inventory.*;
import org.bukkit.inventory.meta.SkullMeta;
import org.bukkit.plugin.Plugin;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import org.bukkit.scheduler.BukkitRunnable;
/**
* This class is the base class that hosts the logic that triggers when a snowball hits a target.
*
* We keep these in a weak hash map, so it is important that this object (and all subclasses) not hold onto a reference to a
* Snowball, or that snowball may never be collected.
*
* @author DanJ
*/
public abstract class SnowballLogic {
////////////////////////////////////////////////////////////////
// Logic
//
/**
* This is called when the snowball is launched.
*
* @param snowball The snowball being launched.
* @param info Other information about the snowball.
*/
public void launch(Snowball snowball, SnowballInfo info) {
}
/**
* This method decides whether the snowball should continue to operate; for performance reasons we destroy snowball that have
* gone too high.
*
* This is called before tick() is, but only about 1/16th as often as tick(); snowballs can therefore exist 'outside the
* reservation' for a short time.
*
* @param snowball The snowball that we may destroy.
* @param info The info about he snowball.
* @return True to continue with this snowball; false to silently terminate it.
*/
public boolean shouldContinue(Snowball snowball, SnowballInfo info) {
Location here = snowball.getLocation();
double y = here.getY();
if (y < 0 || y > snowball.getWorld().getMaxHeight()) {
return false;
}
final double maxDistance = 128.0;
final double maxDistanceSq = maxDistance * maxDistance;
double distanceSq = info.launchLocation.distanceSquared(here);
if (distanceSq > maxDistanceSq) {
return false;
}
return true;
}
/**
* this is called every many times every second.
*
* @param snowball A snowball that gets a chance to do something.
* @param info Other information about the snowball.
*/
public void tick(Snowball snowball, SnowballInfo info) {
}
/**
* This is called when the snowball hits something and returns teh damange to be done (which can be 0).
*
* @param snowball The snowball hitting something.
* @param info Other information about the snowball.
* @param target The entity that was hit.
* @param damage The damage the snowball is expected to do..
* @return The damage teh snowball will do.
*/
public double damage(Snowball snowball, SnowballInfo info, Entity target, double proposedDamage) {
return proposedDamage;
}
/**
* This is called when the snowball hits something.
*
* @param snowball The snowball hitting something.
* @param info Other information about the snowball.
*/
public void hit(Snowball snowball, SnowballInfo info) {
}
@Override
public String toString() {
return getClass().getSimpleName();
}
////////////////////////////////////////////////////////////////
// Creation
//
/**
* This method creates a new logic, but does not start it. It chooses the logic based on 'hint', which is the stack
* immediately above the snowball being thrown.
*
* @param slice The inventory slice above the snowball in the inventory.
* @return The new logic, not yet started or attached to a snowball, or null if the snowball will be illogical.
*/
public static SnowballLogic createLogic(InventorySlice slice) {
ItemStack hint = slice.getBottomItem();
if (hint == null) {
return null;
}
switch (hint.getType()) {
case ARROW:
return new ArrowSnowballLogic(hint);
case FIREWORK_CHARGE:
case BLAZE_ROD:
case EGG:
case EXP_BOTTLE:
return new ProjectileSnowballLogic(hint.getType());
case COBBLESTONE:
case BOOKSHELF:
case BRICK:
case SAND:
case GRAVEL:
return new BlockPlacementSnowballLogic(hint.getType());
//considering adding data values to smooth brick so it randomizes
//including mossy, cracked and even silverfish
case EMERALD_BLOCK:
case EMERALD_ORE:
return new FeeshVariationsSnowballLogic(hint);
case EMERALD:
//fires poisoned feesh
return new SpawnSnowballLogic<Silverfish>(Silverfish.class) {
@Override
protected void initializeEntity(Silverfish spawned, SnowballInfo info) {
super.initializeEntity(spawned, info);
spawned.addPotionEffect(new PotionEffect(PotionEffectType.POISON, Integer.MAX_VALUE, 250));
spawned.setTarget(spawned); //seems to trigger only if feesh has a object of its ire.
}
};
case ENDER_PEARL:
return new BlockPlacementSnowballLogic(Material.ENDER_CHEST);
case ANVIL:
return new AnvilSnowballLogic();
case DAYLIGHT_DETECTOR:
return new DaylightFinderSnowballLogic();
case WATCH:
return new WatchSnowballLogic();
case REDSTONE:
return new StartRainLogic();
case CACTUS:
return new StopRainLogic();
case WATER_BUCKET:
return new BlockPlacementSnowballLogic(Material.WATER);
case LAVA_BUCKET:
return new BlockPlacementSnowballLogic(Material.LAVA);
case RED_ROSE:
case YELLOW_FLOWER:
return new FireworkSnowballLogic(hint);
case QUARTZ:
case COAL:
case COAL_BLOCK:
case REDSTONE_BLOCK:
case NETHERRACK:
case LADDER:
case VINE:
case DIAMOND_ORE:
case ENDER_STONE:
return BlockEmbedSnowballLogic.fromMaterial(hint.getType());
case SAPLING:
return new ArboristSnowballLogic(hint);
case WOOD_SWORD:
case STONE_SWORD:
case IRON_SWORD:
case GOLD_SWORD:
case DIAMOND_SWORD:
return new SwordSnowballLogic(slice);
case WOOD_PICKAXE:
case STONE_PICKAXE:
case IRON_PICKAXE:
case GOLD_PICKAXE:
case DIAMOND_PICKAXE:
return new PickaxeSnowballLogic(hint.getType());
case SHEARS:
return new ShearsSnowballLogic();
case STICK:
case BONE:
case FENCE:
case COBBLE_WALL:
case NETHER_FENCE:
return new KnockbackSnowballLogic(hint.getType());
case LEAVES:
case STONE:
case SMOOTH_BRICK:
case IRON_FENCE:
return new BoxSnowballLogic(hint.getType());
//all structures that can be broken with any pick, but can be
//large with use of glowstone. Provides a defensive game
case GLASS:
return new BoxSnowballLogic(Material.GLASS, Material.AIR);
case GLASS_BOTTLE:
return new RingSnowballLogic(Material.GLASS);
case POTION:
return PotionInfo.fromItemStack(hint).createPotionLogic();
case BUCKET:
return new BoxSnowballLogic(Material.AIR);
case WEB:
case WOOD:
case LOG:
case MOSSY_COBBLESTONE:
return new RingSnowballLogic(hint.getType());
case TORCH:
return new BoxSnowballLogic(Material.GLASS, Material.STATIONARY_LAVA); //gives you a tiny lava box.
//Will set delayed fires, glass doesn't replace leaves so they catch.
case FENCE_GATE:
return new LinkedTrailSnowballLogic(Material.FENCE);
case CAULDRON_ITEM:
return new LinkedTrailSnowballLogic(Material.STATIONARY_WATER);
case WATER_LILY:
return new LinkedWaterTrailSnowballLogic(Material.WATER_LILY);
case TNT:
return new TNTSnowballLogic(4.0f);
case SULPHUR:
return new TNTSnowballLogic(1.4f);
case FIREWORK:
return new JetpackSnowballLogic();
case FLINT_AND_STEEL:
return new FlintAndSteelSnowballLogic(Material.FIRE);
case SPIDER_EYE:
return new ReversedSnowballLogic(1);
case FERMENTED_SPIDER_EYE:
return new EchoSnowballLogic(hint.getAmount(), slice.skip(1));
case APPLE:
return new SpeededSnowballLogic(1.3, slice.skip(1));
case MELON:
return new SpeededSnowballLogic(1.4, slice.skip(1));
case SUGAR:
return new SpeededSnowballLogic(1.5, slice.skip(1));
case BOW:
return new SpeededSnowballLogic(1.8, slice.skip(1));
case COOKIE:
return new SpeededSnowballLogic(2, slice.skip(1));
case PUMPKIN_PIE:
return new SpeededSnowballLogic(2.5, slice.skip(1));
case CAKE:
return new SpeededSnowballLogic(3, slice.skip(1));
//the cake is a... lazor!
case BEACON:
return new SpeededSnowballLogic(4, slice.skip(1));
//the beacon is the REAL lazor.
case GLOWSTONE_DUST:
return new PoweredSnowballLogic(1.6, slice.skip(1));
case GLOWSTONE:
return new PoweredSnowballLogic(3, slice.skip(1));
case NETHER_STAR:
return new PoweredSnowballLogic(4, slice.skip(1));
//nuclear option. Beacon/netherstar designed to be insane
//overkill but not that cost-effective, plus more unwieldy.
case SNOW_BALL:
return new MultiplierSnowballLogic(hint.getAmount(), hint.getItemMeta().getDisplayName(), slice.skip(1));
case SLIME_BALL:
return new BouncySnowballLogic(hint.getAmount(), slice.skip(1));
case QUARTZ_BLOCK:
return new KapwingSnowballLogic(hint.getAmount(), slice.skip(1));
case GRASS:
case DIRT:
return new RegenerationSnowballLogic();
case GHAST_TEAR:
return SpawnSnowballLogic.fromEntityClass(Ghast.class);
case ENCHANTMENT_TABLE:
return new EnchantingTableSnowballLogic();
case GOLD_NUGGET:
return new ItemDropSnowballLogic(Material.ROTTEN_FLESH) {
@Override
protected EntityType getEntityToSpawn(Snowball snowball, SnowballInfo info) {
if (info.power > 2) {
return EntityType.PIG_ZOMBIE;
} else {
return null;
}
}
};
case DRAGON_EGG:
return new DeathVortexSnowballLogic();
case IRON_INGOT:
return new MagneticSnowballLogic();
case CARROT_STICK:
case FISHING_ROD:
case STRING:
case OBSIDIAN:
return new ComeAlongSnowballLogic(hint.getType());
case LEATHER:
return new ItemDropSnowballLogic(
Material.BOOK,
Material.LEATHER_HELMET,
Material.LEATHER_CHESTPLATE,
Material.LEATHER_LEGGINGS,
Material.LEATHER_BOOTS,
Material.STICK,
Material.WOOD_SWORD,
Material.WOOD_PICKAXE,
Material.WOOD_AXE,
Material.WOOD_SPADE,
Material.WOOD_HOE,
Material.WORKBENCH,
Material.SADDLE);
case IRON_BLOCK:
return new ItemDropSnowballLogic(
Material.IRON_HELMET,
Material.IRON_CHESTPLATE,
Material.IRON_LEGGINGS,
Material.IRON_BOOTS,
Material.IRON_SWORD,
Material.IRON_PICKAXE,
Material.IRON_AXE,
Material.IRON_SPADE,
Material.IRON_HOE);
case GOLD_BLOCK:
return new ItemDropSnowballLogic(
Material.GOLD_HELMET,
Material.GOLD_CHESTPLATE,
Material.GOLD_LEGGINGS,
Material.GOLD_BOOTS,
Material.GOLD_SWORD,
Material.GOLD_PICKAXE,
Material.GOLD_AXE,
Material.GOLD_SPADE,
Material.GOLD_HOE);
case DIAMOND_BLOCK:
return new ItemDropSnowballLogic(
Material.DIAMOND_HELMET,
Material.DIAMOND_CHESTPLATE,
Material.DIAMOND_LEGGINGS,
Material.DIAMOND_BOOTS,
Material.DIAMOND_SWORD,
Material.DIAMOND_PICKAXE,
Material.DIAMOND_AXE,
Material.DIAMOND_SPADE,
Material.DIAMOND_HOE);
case SADDLE:
return new ItemDropSnowballLogic(Material.LEASH) {
@Override
protected EntityType getEntityToSpawn(Snowball snowball, SnowballInfo info) {
if (info.power > 2) {
return EntityType.HORSE;
} else {
return null;
}
}
};
//developing ItemDropSnowball to be a randomizer, it won't be
//heavily used so it can be full of special cases
case GOLD_INGOT:
return SpawnSnowballLogic.fromEntityClass(PigZombie.class);
case EYE_OF_ENDER:
return SpawnSnowballLogic.fromEntityClass(Enderman.class);
case MILK_BUCKET:
return SpawnSnowballLogic.fromEntityClass(Cow.class);
//get cow if you have ever milked one
//path to leather -> book -> enchanting table
case MUSHROOM_SOUP:
return SpawnSnowballLogic.fromEntityClass(MushroomCow.class);
//get mooshroom if you can get both mushrooms and wood
//alternate path to leather -> book -> enchanting table!
case JACK_O_LANTERN:
return new SpawnSnowballLogic<Skeleton>(Skeleton.class) {
@Override
protected void initializeEntity(Skeleton spawned, final SnowballInfo info) {
super.initializeEntity(spawned, info);
//my skellington army of undead minions!
if (info.power > 1) {
//you have to use at least some glowstone to get the special stuff to work, but then
//the real gains are in speed
spawned.setMaxHealth(spawned.getMaxHealth() * info.power);
spawned.setHealth(spawned.getMaxHealth());
if (info.speed > 1) {
//if you speed the snowballs, you get speedyjumpyskeles
spawned.addPotionEffect(new PotionEffect(PotionEffectType.JUMP, Integer.MAX_VALUE, (int) info.speed));
spawned.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, Integer.MAX_VALUE, (int) Math.pow(info.speed, 2)));
}
}
}
@Override
protected void equipEntity(Skeleton spawned, SnowballInfo info) {
super.equipEntity(spawned, info);
equipSkele(info.plugin, spawned, info);
}
};
case ROTTEN_FLESH:
return new SpawnSnowballLogic<Zombie>(Zombie.class) {
@Override
protected void initializeEntity(Zombie spawned, SnowballInfo info) {
super.initializeEntity(spawned, info);
//my zombie army of yucky minions!
if (info.power > 1) {
//you have to use at least some glowstone to get it to work, but then
//the real gains are in speed
spawned.setMaxHealth(spawned.getMaxHealth() * info.power);
spawned.setHealth(spawned.getMaxHealth());
if (info.speed > 1) {
//if you speed the snowballs, you get speedyjumpyzombies
spawned.addPotionEffect(new PotionEffect(PotionEffectType.JUMP, Integer.MAX_VALUE, (int) info.speed));
spawned.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, Integer.MAX_VALUE, (int) Math.pow(info.speed, 2)));
}
}
}
@Override
protected void equipEntity(Zombie spawned, SnowballInfo info) {
super.equipEntity(spawned, info);
equipZombie(info.plugin, spawned, info);
}
};
case SKULL_ITEM:
SkullType skullType = SkullType.values()[hint.getDurability()];
return SpawnSnowballLogic.fromSkullType(skullType);
case FEATHER:
return new FeatherSnowballLogic();
default:
return null;
}
}
////////////////////////////////////////////////////////////////
// Event Handling
//
/**
* This method processes a new snowball, executing its launch() method and also recording it so the hit() method can be called
* later.
*
* The shooter may be provided as well; this allows us to launch snowballs from places that are not a player, but associated
* it with a player anyway.
*
* @param inventory The inventory slice that determines the logic type.
* @param snowball The snowball to be launched.
* @param info The info record that describes the snowball.
* @return The logic associated with the snowball; may be null.
*/
public static SnowballLogic performLaunch(InventorySlice inventory, Snowball snowball, SnowballInfo info) {
SnowballLogic logic = createLogic(inventory);
if (logic != null) {
performLaunch(logic, snowball, info);
}
return logic;
}
/**
* This overload of performLaunch takes the logic to associate with the snowball instead of an inventory.
*
* @param logic The logic to apply to the snowball; can't be null.
* @param snowball The snowball to be launched.
* @param info The info record that describes the snowball.
*/
public static void performLaunch(SnowballLogic logic, Snowball snowball, SnowballInfo info) {
logic.start(snowball, info);
if (info.shouldLogMessages) {
Bukkit.getLogger().info(String.format("Snowball launched: %s [%d]", logic, inFlight.size()));
}
logic.launch(snowball, info);
}
/**
* This method processes the impact of a snowball, and invokes the hit() method on its logic object, if it has one.
*
* @param snowball The impacting snowball.
*/
public static void performHit(Snowball snowball) {
SnowballLogicData data = getData(Preconditions.checkNotNull(snowball));
if (data != null) {
try {
if (data.info.shouldLogMessages) {
Bukkit.getLogger().info(String.format("Snowball hit: %s [%d]", data.logic, inFlight.size()));
}
data.logic.hit(snowball, data.info);
} finally {
data.logic.end(snowball);
}
}
}
public static double performDamage(Snowball snowball, Entity target, double damage) {
SnowballLogicData data = getData(Preconditions.checkNotNull(snowball));
if (data != null) {
if (data.info.shouldLogMessages) {
Bukkit.getLogger().info(String.format("Snowball damage: %s [%d]", data.logic, inFlight.size()));
}
return data.logic.damage(snowball, data.info, target, damage);
}
return damage;
}
/**
* This method handles a projectile launch; it selects a logic and runs its launch method.
*
* @param e The event data.
*/
public static void onProjectileLaunch(SnowballMadness plugin, ProjectileLaunchEvent e) {
Projectile proj = e.getEntity();
LivingEntity shooter = proj.getShooter();
if (proj instanceof Snowball && shooter instanceof Player) {
Snowball snowball = (Snowball) proj;
Player player = (Player) shooter;
PlayerInventory inv = player.getInventory();
int heldSlot = inv.getHeldItemSlot();
ItemStack sourceStack = inv.getItem(heldSlot);
if (sourceStack == null || sourceStack.getType() == Material.SNOW_BALL) {
InventorySlice slice = InventorySlice.fromSlot(player, heldSlot).skip(1);
SnowballLogic logic = performLaunch(slice, snowball,
new SnowballInfo(plugin, snowball.getLocation(), player));
if (logic != null && player.getGameMode() != GameMode.CREATIVE) {
replenishSnowball(plugin, inv, heldSlot);
}
}
}
}
/**
* This method calls tick() on each snowball that has any logic. This also checks shouldContinue() on each snowball and
* removes snowball that shouldn't continue.
*/
public static void onTick(long tickCount) {
ArrayList<Map.Entry<Snowball, SnowballLogicData>> toRemove = null;
// we use the tick count to decide which snowballs to
// check shouldContinue() on; we increment this so
// on each tick we can check 1/16th of the snowballs.
long continuationThrottle = tickCount;
for (Map.Entry<Snowball, SnowballLogicData> e : inFlight.entrySet()) {
Snowball snowball = e.getKey();
SnowballLogic logic = e.getValue().logic;
SnowballInfo info = e.getValue().info;
boolean shouldContinue = true;
if ((continuationThrottle & 0xF) == 0) {
shouldContinue = logic.shouldContinue(snowball, info);
}
if (shouldContinue) {
logic.tick(snowball, info);
} else {
if (toRemove == null) {
toRemove = Lists.newArrayList();
}
toRemove.add(e);
}
++continuationThrottle;
}
if (toRemove != null) {
for (Map.Entry<Snowball, SnowballLogicData> e : toRemove) {
Snowball snowball = e.getKey();
SnowballLogic logic = e.getValue().logic;
SnowballInfo info = e.getValue().info;
try {
if (info.shouldLogMessages) {
Bukkit.getLogger().info(String.format("Snowball has left the reservation: %s [%d]", logic, inFlight.size()));
}
} finally {
logic.end(snowball);
snowball.remove();
}
}
}
}
/**
* This method handles the damage a snowball does on impact, and can adjust that damage.
*
* @param e The damage event.
*/
public static void onEntityDamageByEntityEvent(EntityDamageByEntityEvent e) {
Entity damagee = e.getEntity();
Entity damager = e.getDamager();
double damage = e.getDamage();
if (damager instanceof Snowball) {
double newDamage = performDamage((Snowball) damager, damagee, damage);
if (newDamage != damage) {
e.setDamage(newDamage);
}
}
}
/**
* This method increments the number of snowballs in the slot indicated; but it does this after a brief delay since changes
* made during the launch are ignored. If the indicated slot contains something that is not a snowball, we don't update it. If
* it is empty, we put one snowball in there.
*
* @param plugin The plugin, used to schedule the update.
* @param inventory The inventory to update.
* @param slotIndex The slot to update.
*/
private static void replenishSnowball(Plugin plugin, final PlayerInventory inventory, final int slotIndex) {
// ugh. We must delay the inventory update or it won't take.
new BukkitRunnable() {
@Override
public void run() {
ItemStack replacing = inventory.getItem(slotIndex);
if (replacing == null) {
inventory.setItem(slotIndex, new ItemStack(Material.SNOW_BALL));
} else if (replacing.getType() == Material.SNOW_BALL) {
int oldCount = replacing.getAmount();
int newCount = Math.min(16, oldCount + 1);
if (oldCount != newCount) {
inventory.setItem(slotIndex, new ItemStack(Material.SNOW_BALL, newCount));
}
}
}
}.runTaskLater(plugin, 1);
}
private static void equipSkele(Plugin plugin, final Skeleton spawned, final SnowballInfo info) {
new BukkitRunnable() {
@Override
public void run() {
if (info.power > 1 && info.shooter != null) {
//you have to use at least some glowstone to get the special stuff to work.
ItemStack gear = info.shooter.getInventory().getHelmet();
if (gear == null) {
gear = info.shooter.getInventory().getItem(27);
}
if (gear != null) {
spawned.getEquipment().setHelmet(gear);
spawned.getEquipment().setHelmetDropChance(1.0f);
} else {
ItemStack skull = new ItemStack(Material.SKULL_ITEM, 1, (byte) 3);
SkullMeta meta = (SkullMeta) skull.getItemMeta();
meta.setOwner(info.shooter.getName());
skull.setItemMeta(meta);
// OH GOD IT HAS MY FAAAAAAACE!
spawned.getEquipment().setHelmet(skull);
spawned.getEquipment().setHelmetDropChance(1.0f);
}
gear = info.shooter.getInventory().getChestplate();
if (gear != null) {
spawned.getEquipment().setChestplate(gear);
spawned.getEquipment().setChestplateDropChance(1.0f);
}
gear = info.shooter.getInventory().getLeggings();
if (gear != null) {
spawned.getEquipment().setLeggings(gear);
spawned.getEquipment().setLeggingsDropChance(1.0f);
}
gear = info.shooter.getInventory().getBoots();
if (gear != null) {
spawned.getEquipment().setBoots(gear);
spawned.getEquipment().setBootsDropChance(1.0f);
}
gear = info.shooter.getInventory().getItem(0);
if (gear != null) {
spawned.getEquipment().setItemInHand(gear);
spawned.getEquipment().setItemInHandDropChance(1.0f);
}
spawned.setCustomName(info.shooter.getInventory().getItem(27).getItemMeta().getDisplayName());
if (spawned.getCustomName() == null) {
spawned.setCustomName(info.shooter.getName() + "'s Minion");
}
spawned.setCustomNameVisible(true);
}
}
}.runTaskLater(plugin, 1L);
}
private static void equipZombie(Plugin plugin, final Zombie spawned, final SnowballInfo info) {
new BukkitRunnable() {
@Override
public void run() {
if (info.power > 1 && info.shooter != null) {
//you have to use at least some glowstone to get the special stuff to work.
ItemStack gear = info.shooter.getInventory().getHelmet();
if (gear == null) {
gear = info.shooter.getInventory().getItem(27);
}
if (gear != null) {
spawned.getEquipment().setHelmet(gear);
spawned.getEquipment().setHelmetDropChance(1.0f);
} else {
ItemStack skull = new ItemStack(Material.SKULL_ITEM, 1, (byte) 3);
SkullMeta meta = (SkullMeta) skull.getItemMeta();
meta.setOwner(info.shooter.getName());
skull.setItemMeta(meta);
// OH GOD IT HAS MY FAAAAAAACE!
spawned.getEquipment().setHelmet(skull);
spawned.getEquipment().setHelmetDropChance(1.0f);
}
gear = info.shooter.getInventory().getChestplate();
if (gear != null) {
spawned.getEquipment().setChestplate(gear);
spawned.getEquipment().setChestplateDropChance(1.0f);
}
gear = info.shooter.getInventory().getLeggings();
if (gear != null) {
spawned.getEquipment().setLeggings(gear);
spawned.getEquipment().setLeggingsDropChance(1.0f);
}
gear = info.shooter.getInventory().getBoots();
if (gear != null) {
spawned.getEquipment().setBoots(gear);
spawned.getEquipment().setBootsDropChance(1.0f);
}
gear = info.shooter.getInventory().getItem(0);
if (gear != null) {
spawned.getEquipment().setItemInHand(gear);
spawned.getEquipment().setItemInHandDropChance(1.0f);
}
spawned.setCustomName(info.shooter.getInventory().getItem(27).getItemMeta().getDisplayName());
if (spawned.getCustomName() == null) {
spawned.setCustomName(info.shooter.getName() + "'s Minion");
}
spawned.setCustomNameVisible(true);
}
}
}.runTaskLater(plugin, 1L);
}
/**
* This method handles a projectile hit event, and runs the hit method.
*
* @param e The event data.
*/
public static void onProjectileHit(ProjectileHitEvent e) {
Projectile proj = e.getEntity();
if (proj instanceof Snowball) {
performHit((Snowball) proj);
}
}
////////////////////////////////////////////////////////////////
// Logic Association
//
private final static WeakHashMap<Snowball, SnowballLogicData> inFlight = new WeakHashMap<Snowball, SnowballLogicData>();
private static int approximateInFlightCount = 0;
private static long inFlightSyncDeadline = 0;
/**
* this class just holds the snowball logic and info for a snowball; the snowball itself must not be kept here, as this is the
* value of a weak-hash-map keyed on the snowballs. We don't want to keep them alive.
*/
private final static class SnowballLogicData {
public final SnowballLogic logic;
public final SnowballInfo info;
public SnowballLogicData(SnowballLogic logic, SnowballInfo info) {
this.logic = logic;
this.info = info;
}
}
/**
* This returns the number of snowballs (that have attached logic) that are currently in flight. This may count snowballs that
* have been unloaded or otherwise destroyed for a time; it is not exact.
*
* @return The number of in-flight snowballs.
*/
public static int getInFlightCount() {
long now = System.currentTimeMillis();
if (inFlightSyncDeadline <= now) {
inFlightSyncDeadline = now + 1000;
approximateInFlightCount = inFlight.size();
}
return approximateInFlightCount;
}
/**
* This returns the logic and shooter for a snowball that has one.
*
* @param snowball The snowball of interest; can be null.
* @return The logic and info of the snowball, or null if it is an illogical snowball or it was null.
*/
private static SnowballLogicData getData(Snowball snowball) {
if (snowball != null) {
return inFlight.get(snowball);
} else {
return null;
}
}
/**
* This method registers the logic so getLogic() can find it. Logics only work once started.
*
* @param snowball The snowball being launched.
* @param info Other information about the snowball.
*/
public void start(Snowball snowball, SnowballInfo info) {
inFlight.put(snowball, new SnowballLogicData(this, info));
approximateInFlightCount++;
}
/**
* This method unregisters this logic so it is no longer invoked; this is done when snowball hits something.
*
* @param snowball The snowball to deregister.
*/
public void end(Snowball snowball) {
approximateInFlightCount--;
inFlight.remove(snowball);
}
////////////////////////////////////////////////////////////////
// Utilitu Methods
//
/**
* This returns the of the nearest non-air block underneath 'location' that is directly over the ground. If 'locaiton' is
* inside the ground, we'll return a new copy of the same location.
*
* @param location The starting location; this is not modified.
* @return A new location describing the place found.
*/
public static Location getGroundUnderneath(Location location) {
Location loc = location.clone();
for (;;) {
// just in case we have a shaft to the void, we need
// to give up before we reach it.
if (loc.getBlockY() <= 0) {
return loc;
}
switch (loc.getBlock().getType()) {
case AIR:
case WATER:
case STATIONARY_WATER:
case LEAVES:
case LONG_GRASS:
case DOUBLE_PLANT:
case LAVA:
case SNOW:
case WATER_LILY:
case RED_ROSE:
case YELLOW_FLOWER:
case DEAD_BUSH:
loc.add(0, -1, 0);
break;
default:
return loc;
}
}
}
}
|
SnowballMadness/src/snowballmadness/SnowballLogic.java
|
package snowballmadness;
import java.util.*;
import com.google.common.base.*;
import com.google.common.collect.Lists;
import org.bukkit.*;
import org.bukkit.entity.*;
import org.bukkit.event.entity.*;
import org.bukkit.inventory.*;
import org.bukkit.inventory.meta.SkullMeta;
import org.bukkit.plugin.Plugin;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import org.bukkit.scheduler.BukkitRunnable;
/**
* This class is the base class that hosts the logic that triggers when a
* snowball hits a target.
*
* We keep these in a weak hash map, so it is important that this object (and
* all subclasses) not hold onto a reference to a Snowball, or that snowball may
* never be collected.
*
* @author DanJ
*/
public abstract class SnowballLogic {
////////////////////////////////////////////////////////////////
// Logic
//
/**
* This is called when the snowball is launched.
*
* @param snowball The snowball being launched.
* @param info Other information about the snowball.
*/
public void launch(Snowball snowball, SnowballInfo info) {
}
/**
* This method decides whether the snowball should continue to operate; for
* performance reasons we destroy snowball that have gone too high.
*
* This is called before tick() is, but only about 1/16th as often as
* tick(); snowballs can therefore exist 'outside the reservation' for a
* short time.
*
* @param snowball The snowball that we may destroy.
* @param info The info about he snowball.
* @return True to continue with this snowball; false to silently terminate
* it.
*/
public boolean shouldContinue(Snowball snowball, SnowballInfo info) {
Location here = snowball.getLocation();
double y = here.getY();
if (y < 0 || y > snowball.getWorld().getMaxHeight()) {
return false;
}
final double maxDistance = 128.0;
final double maxDistanceSq = maxDistance * maxDistance;
double distanceSq = info.launchLocation.distanceSquared(here);
if (distanceSq > maxDistanceSq) {
return false;
}
return true;
}
/**
* this is called every many times every second.
*
* @param snowball A snowball that gets a chance to do something.
* @param info Other information about the snowball.
*/
public void tick(Snowball snowball, SnowballInfo info) {
}
/**
* This is called when the snowball hits something and returns teh damange
* to be done (which can be 0).
*
* @param snowball The snowball hitting something.
* @param info Other information about the snowball.
* @param target The entity that was hit.
* @param damage The damage the snowball is expected to do..
* @return The damage teh snowball will do.
*/
public double damage(Snowball snowball, SnowballInfo info, Entity target, double proposedDamage) {
return proposedDamage;
}
/**
* This is called when the snowball hits something.
*
* @param snowball The snowball hitting something.
* @param info Other information about the snowball.
*/
public void hit(Snowball snowball, SnowballInfo info) {
}
@Override
public String toString() {
return getClass().getSimpleName();
}
////////////////////////////////////////////////////////////////
// Creation
//
/**
* This method creates a new logic, but does not start it. It chooses the
* logic based on 'hint', which is the stack immediately above the snowball
* being thrown.
*
* @param slice The inventory slice above the snowball in the inventory.
* @return The new logic, not yet started or attached to a snowball, or null
* if the snowball will be illogical.
*/
public static SnowballLogic createLogic(InventorySlice slice) {
ItemStack hint = slice.getBottomItem();
if (hint == null) {
return null;
}
switch (hint.getType()) {
case ARROW:
return new ArrowSnowballLogic(hint);
case FIREWORK_CHARGE:
case BLAZE_ROD:
case EGG:
case EXP_BOTTLE:
return new ProjectileSnowballLogic(hint.getType());
case COBBLESTONE:
case BOOKSHELF:
case BRICK:
case SAND:
case GRAVEL:
return new BlockPlacementSnowballLogic(hint.getType());
//considering adding data values to smooth brick so it randomizes
//including mossy, cracked and even silverfish
case EMERALD_BLOCK:
case EMERALD_ORE:
return new FeeshVariationsSnowballLogic(hint);
case EMERALD:
//fires poisoned feesh
return new SpawnSnowballLogic<Silverfish>(Silverfish.class) {
@Override
protected void initializeEntity(Silverfish spawned, SnowballInfo info) {
super.initializeEntity(spawned, info);
spawned.addPotionEffect(new PotionEffect(PotionEffectType.POISON, Integer.MAX_VALUE, 250));
spawned.setTarget(spawned); //seems to trigger only if feesh has a object of its ire.
}
};
case ENDER_PEARL:
return new BlockPlacementSnowballLogic(Material.ENDER_CHEST);
case ANVIL:
return new AnvilSnowballLogic();
case DAYLIGHT_DETECTOR:
return new DaylightFinderSnowballLogic();
case WATCH:
return new WatchSnowballLogic();
case REDSTONE:
return new StartRainLogic();
case CACTUS:
return new StopRainLogic();
case WATER_BUCKET:
return new BlockPlacementSnowballLogic(Material.WATER);
case LAVA_BUCKET:
return new BlockPlacementSnowballLogic(Material.LAVA);
case RED_ROSE:
case YELLOW_FLOWER:
return new FireworkSnowballLogic(hint);
case QUARTZ:
case COAL:
case COAL_BLOCK:
case REDSTONE_BLOCK:
case NETHERRACK:
case LADDER:
case VINE:
case DIAMOND_ORE:
case ENDER_STONE:
return BlockEmbedSnowballLogic.fromMaterial(hint.getType());
case SAPLING:
return new ArboristSnowballLogic(hint);
case WOOD_SWORD:
case STONE_SWORD:
case IRON_SWORD:
case GOLD_SWORD:
case DIAMOND_SWORD:
return new SwordSnowballLogic(slice);
case WOOD_PICKAXE:
case STONE_PICKAXE:
case IRON_PICKAXE:
case GOLD_PICKAXE:
case DIAMOND_PICKAXE:
return new PickaxeSnowballLogic(hint.getType());
case SHEARS:
return new ShearsSnowballLogic();
case STICK:
case BONE:
case FENCE:
case COBBLE_WALL:
case NETHER_FENCE:
return new KnockbackSnowballLogic(hint.getType());
case LEAVES:
case STONE:
case SMOOTH_BRICK:
case IRON_FENCE:
return new BoxSnowballLogic(hint.getType());
//all structures that can be broken with any pick, but can be
//large with use of glowstone. Provides a defensive game
case GLASS:
return new BoxSnowballLogic(Material.GLASS, Material.AIR);
case GLASS_BOTTLE:
return new RingSnowballLogic(Material.GLASS);
case POTION:
return PotionInfo.fromItemStack(hint).createPotionLogic();
case BUCKET:
return new BoxSnowballLogic(Material.AIR);
case WEB:
case WOOD:
case LOG:
case MOSSY_COBBLESTONE:
return new RingSnowballLogic(hint.getType());
case TORCH:
return new BoxSnowballLogic(Material.GLASS, Material.STATIONARY_LAVA); //gives you a tiny lava box.
//Will set delayed fires, glass doesn't replace leaves so they catch.
case FENCE_GATE:
return new LinkedTrailSnowballLogic(Material.FENCE);
case CAULDRON_ITEM:
return new LinkedTrailSnowballLogic(Material.STATIONARY_WATER);
case WATER_LILY:
return new LinkedWaterTrailSnowballLogic(Material.WATER_LILY);
case TNT:
return new TNTSnowballLogic(4.0f);
case SULPHUR:
return new TNTSnowballLogic(1.4f);
case FIREWORK:
return new JetpackSnowballLogic();
case FLINT_AND_STEEL:
return new FlintAndSteelSnowballLogic(Material.FIRE);
case SPIDER_EYE:
return new ReversedSnowballLogic(1);
case FERMENTED_SPIDER_EYE:
return new EchoSnowballLogic(hint.getAmount(), slice.skip(1));
case APPLE:
return new SpeededSnowballLogic(1.3, slice.skip(1));
case MELON:
return new SpeededSnowballLogic(1.4, slice.skip(1));
case SUGAR:
return new SpeededSnowballLogic(1.5, slice.skip(1));
case BOW:
return new SpeededSnowballLogic(1.8, slice.skip(1));
case COOKIE:
return new SpeededSnowballLogic(2, slice.skip(1));
case PUMPKIN_PIE:
return new SpeededSnowballLogic(2.5, slice.skip(1));
case CAKE:
return new SpeededSnowballLogic(3, slice.skip(1));
//the cake is a... lazor!
case BEACON:
return new SpeededSnowballLogic(4, slice.skip(1));
//the beacon is the REAL lazor.
case GLOWSTONE_DUST:
return new PoweredSnowballLogic(1.6, slice.skip(1));
case GLOWSTONE:
return new PoweredSnowballLogic(3, slice.skip(1));
case NETHER_STAR:
return new PoweredSnowballLogic(4, slice.skip(1));
//nuclear option. Beacon/netherstar designed to be insane
//overkill but not that cost-effective, plus more unwieldy.
case SNOW_BALL:
return new MultiplierSnowballLogic(hint.getAmount(), hint.getItemMeta().getDisplayName(), slice.skip(1));
case SLIME_BALL:
return new BouncySnowballLogic(hint.getAmount(), slice.skip(1));
case QUARTZ_BLOCK:
return new KapwingSnowballLogic(hint.getAmount(), slice.skip(1));
case GRASS:
case DIRT:
return new RegenerationSnowballLogic();
case GHAST_TEAR:
return SpawnSnowballLogic.fromEntityClass(Ghast.class);
case ENCHANTMENT_TABLE:
return new EnchantingTableSnowballLogic();
case GOLD_NUGGET:
return new ItemDropSnowballLogic(Material.ROTTEN_FLESH) {
@Override
protected EntityType getEntityToSpawn(Snowball snowball, SnowballInfo info) {
if (info.power > 2) {
return EntityType.PIG_ZOMBIE;
} else {
return null;
}
}
};
case DRAGON_EGG:
return new DeathVortexSnowballLogic();
case IRON_INGOT:
return new MagneticSnowballLogic();
case CARROT_STICK:
case FISHING_ROD:
case STRING:
case OBSIDIAN:
return new ComeAlongSnowballLogic(hint.getType());
case LEATHER:
return new ItemDropSnowballLogic(
Material.BOOK,
Material.LEATHER_HELMET,
Material.LEATHER_CHESTPLATE,
Material.LEATHER_LEGGINGS,
Material.LEATHER_BOOTS,
Material.STICK,
Material.WOOD_SWORD,
Material.WOOD_PICKAXE,
Material.WOOD_AXE,
Material.WOOD_SPADE,
Material.WOOD_HOE,
Material.WORKBENCH,
Material.SADDLE);
case IRON_BLOCK:
return new ItemDropSnowballLogic(
Material.IRON_HELMET,
Material.IRON_CHESTPLATE,
Material.IRON_LEGGINGS,
Material.IRON_BOOTS,
Material.IRON_SWORD,
Material.IRON_PICKAXE,
Material.IRON_AXE,
Material.IRON_SPADE,
Material.IRON_HOE);
case GOLD_BLOCK:
return new ItemDropSnowballLogic(
Material.GOLD_HELMET,
Material.GOLD_CHESTPLATE,
Material.GOLD_LEGGINGS,
Material.GOLD_BOOTS,
Material.GOLD_SWORD,
Material.GOLD_PICKAXE,
Material.GOLD_AXE,
Material.GOLD_SPADE,
Material.GOLD_HOE);
case DIAMOND_BLOCK:
return new ItemDropSnowballLogic(
Material.DIAMOND_HELMET,
Material.DIAMOND_CHESTPLATE,
Material.DIAMOND_LEGGINGS,
Material.DIAMOND_BOOTS,
Material.DIAMOND_SWORD,
Material.DIAMOND_PICKAXE,
Material.DIAMOND_AXE,
Material.DIAMOND_SPADE,
Material.DIAMOND_HOE);
case SADDLE:
return new ItemDropSnowballLogic(Material.LEASH) {
@Override
protected EntityType getEntityToSpawn(Snowball snowball, SnowballInfo info) {
if (info.power > 2) {
return EntityType.HORSE;
} else {
return null;
}
}
};
//developing ItemDropSnowball to be a randomizer, it won't be
//heavily used so it can be full of special cases
case GOLD_INGOT:
return SpawnSnowballLogic.fromEntityClass(PigZombie.class);
case EYE_OF_ENDER:
return SpawnSnowballLogic.fromEntityClass(Enderman.class);
case MILK_BUCKET:
return SpawnSnowballLogic.fromEntityClass(Cow.class);
//get cow if you have ever milked one
//path to leather -> book -> enchanting table
case MUSHROOM_SOUP:
return SpawnSnowballLogic.fromEntityClass(MushroomCow.class);
//get mooshroom if you can get both mushrooms and wood
//alternate path to leather -> book -> enchanting table!
case JACK_O_LANTERN:
return new SpawnSnowballLogic<Skeleton>(Skeleton.class) {
@Override
protected void initializeEntity(Skeleton spawned, final SnowballInfo info) {
super.initializeEntity(spawned, info);
//my skellington army of undead minions!
if (info.power > 1) {
//you have to use at least some glowstone to get the special stuff to work, but then
//the real gains are in speed
spawned.setMaxHealth(spawned.getMaxHealth() * info.power);
spawned.setHealth(spawned.getMaxHealth());
if (info.speed > 1) {
//if you speed the snowballs, you get speedyjumpyskeles
spawned.addPotionEffect(new PotionEffect(PotionEffectType.JUMP, Integer.MAX_VALUE, (int) info.speed));
spawned.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, Integer.MAX_VALUE, (int) Math.pow(info.speed, 2)));
}
}
}
@Override
protected void equipEntity(Skeleton spawned, SnowballInfo info) {
super.equipEntity(spawned, info);
if (info.power > 1 && info.shooter != null) {
//you have to use at least some glowstone to get the special stuff to work.
ItemStack skull = new ItemStack(Material.SKULL_ITEM, 1, (byte) 3);
SkullMeta meta = (SkullMeta) skull.getItemMeta();
meta.setOwner(info.shooter.getName());
skull.setItemMeta(meta);
// OH GOD IT HAS MY FAAAAAAACE!
spawned.getEquipment().setHelmet(skull);
}
}
};
case ROTTEN_FLESH:
return new SpawnSnowballLogic<Zombie>(Zombie.class) {
@Override
protected void initializeEntity(Zombie spawned, SnowballInfo info) {
super.initializeEntity(spawned, info);
//my zombie army of yucky minions!
if (info.power > 1) {
//you have to use at least some glowstone to get it to work, but then
//the real gains are in speed
spawned.setMaxHealth(spawned.getMaxHealth() * info.power);
spawned.setHealth(spawned.getMaxHealth());
if (info.speed > 1) {
//if you speed the snowballs, you get speedyjumpyzombies
spawned.addPotionEffect(new PotionEffect(PotionEffectType.JUMP, Integer.MAX_VALUE, (int) info.speed));
spawned.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, Integer.MAX_VALUE, (int) Math.pow(info.speed, 2)));
}
}
}
@Override
protected void equipEntity(Zombie spawned, SnowballInfo info) {
super.equipEntity(spawned, info);
// No funny faces for villager zombies- it looks dumb.
if (info.power > 1 && info.shooter != null && !spawned.isVillager()) {
ItemStack skull = new ItemStack(Material.SKULL_ITEM, 1, (byte) 3);
SkullMeta meta = (SkullMeta) skull.getItemMeta();
meta.setOwner(info.shooter.getName());
skull.setItemMeta(meta);
// OH GOD IT HAS MY FAAAAAAACE!
spawned.getEquipment().setHelmet(skull);
}
}
};
case SKULL_ITEM:
SkullType skullType = SkullType.values()[hint.getDurability()];
return SpawnSnowballLogic.fromSkullType(skullType);
case FEATHER:
return new FeatherSnowballLogic();
default:
return null;
}
}
////////////////////////////////////////////////////////////////
// Event Handling
//
/**
* This method processes a new snowball, executing its launch() method and
* also recording it so the hit() method can be called later.
*
* The shooter may be provided as well; this allows us to launch snowballs
* from places that are not a player, but associated it with a player
* anyway.
*
* @param inventory The inventory slice that determines the logic type.
* @param snowball The snowball to be launched.
* @param info The info record that describes the snowball.
* @return The logic associated with the snowball; may be null.
*/
public static SnowballLogic performLaunch(InventorySlice inventory, Snowball snowball, SnowballInfo info) {
SnowballLogic logic = createLogic(inventory);
if (logic != null) {
performLaunch(logic, snowball, info);
}
return logic;
}
/**
* This overload of performLaunch takes the logic to associate with the
* snowball instead of an inventory.
*
* @param logic The logic to apply to the snowball; can't be null.
* @param snowball The snowball to be launched.
* @param info The info record that describes the snowball.
*/
public static void performLaunch(SnowballLogic logic, Snowball snowball, SnowballInfo info) {
logic.start(snowball, info);
if (info.shouldLogMessages) {
Bukkit.getLogger().info(String.format("Snowball launched: %s [%d]", logic, inFlight.size()));
}
logic.launch(snowball, info);
}
/**
* This method processes the impact of a snowball, and invokes the hit()
* method on its logic object, if it has one.
*
* @param snowball The impacting snowball.
*/
public static void performHit(Snowball snowball) {
SnowballLogicData data = getData(Preconditions.checkNotNull(snowball));
if (data != null) {
try {
if (data.info.shouldLogMessages) {
Bukkit.getLogger().info(String.format("Snowball hit: %s [%d]", data.logic, inFlight.size()));
}
data.logic.hit(snowball, data.info);
} finally {
data.logic.end(snowball);
}
}
}
public static double performDamage(Snowball snowball, Entity target, double damage) {
SnowballLogicData data = getData(Preconditions.checkNotNull(snowball));
if (data != null) {
if (data.info.shouldLogMessages) {
Bukkit.getLogger().info(String.format("Snowball damage: %s [%d]", data.logic, inFlight.size()));
}
return data.logic.damage(snowball, data.info, target, damage);
}
return damage;
}
/**
* This method handles a projectile launch; it selects a logic and runs its
* launch method.
*
* @param e The event data.
*/
public static void onProjectileLaunch(SnowballMadness plugin, ProjectileLaunchEvent e) {
Projectile proj = e.getEntity();
LivingEntity shooter = proj.getShooter();
if (proj instanceof Snowball && shooter instanceof Player) {
Snowball snowball = (Snowball) proj;
Player player = (Player) shooter;
PlayerInventory inv = player.getInventory();
int heldSlot = inv.getHeldItemSlot();
ItemStack sourceStack = inv.getItem(heldSlot);
if (sourceStack == null || sourceStack.getType() == Material.SNOW_BALL) {
InventorySlice slice = InventorySlice.fromSlot(player, heldSlot).skip(1);
SnowballLogic logic = performLaunch(slice, snowball,
new SnowballInfo(plugin, snowball.getLocation(), player));
if (logic != null && player.getGameMode() != GameMode.CREATIVE) {
replenishSnowball(plugin, inv, heldSlot);
}
}
}
}
/**
* This method calls tick() on each snowball that has any logic. This also
* checks shouldContinue() on each snowball and removes snowball that
* shouldn't continue.
*/
public static void onTick(long tickCount) {
ArrayList<Map.Entry<Snowball, SnowballLogicData>> toRemove = null;
// we use the tick count to decide which snowballs to
// check shouldContinue() on; we increment this so
// on each tick we can check 1/16th of the snowballs.
long continuationThrottle = tickCount;
for (Map.Entry<Snowball, SnowballLogicData> e : inFlight.entrySet()) {
Snowball snowball = e.getKey();
SnowballLogic logic = e.getValue().logic;
SnowballInfo info = e.getValue().info;
boolean shouldContinue = true;
if ((continuationThrottle & 0xF) == 0) {
shouldContinue = logic.shouldContinue(snowball, info);
}
if (shouldContinue) {
logic.tick(snowball, info);
} else {
if (toRemove == null) {
toRemove = Lists.newArrayList();
}
toRemove.add(e);
}
++continuationThrottle;
}
if (toRemove != null) {
for (Map.Entry<Snowball, SnowballLogicData> e : toRemove) {
Snowball snowball = e.getKey();
SnowballLogic logic = e.getValue().logic;
SnowballInfo info = e.getValue().info;
try {
if (info.shouldLogMessages) {
Bukkit.getLogger().info(String.format("Snowball has left the reservation: %s [%d]", logic, inFlight.size()));
}
} finally {
logic.end(snowball);
snowball.remove();
}
}
}
}
/**
* This method handles the damage a snowball does on impact, and can adjust
* that damage.
*
* @param e The damage event.
*/
public static void onEntityDamageByEntityEvent(EntityDamageByEntityEvent e) {
Entity damagee = e.getEntity();
Entity damager = e.getDamager();
double damage = e.getDamage();
if (damager instanceof Snowball) {
double newDamage = performDamage((Snowball) damager, damagee, damage);
if (newDamage != damage) {
e.setDamage(newDamage);
}
}
}
/**
* This method increments the number of snowballs in the slot indicated; but
* it does this after a brief delay since changes made during the launch are
* ignored. If the indicated slot contains something that is not a snowball,
* we don't update it. If it is empty, we put one snowball in there.
*
* @param plugin The plugin, used to schedule the update.
* @param inventory The inventory to update.
* @param slotIndex The slot to update.
*/
private static void replenishSnowball(Plugin plugin, final PlayerInventory inventory, final int slotIndex) {
// ugh. We must delay the inventory update or it won't take.
new BukkitRunnable() {
@Override
public void run() {
ItemStack replacing = inventory.getItem(slotIndex);
if (replacing == null) {
inventory.setItem(slotIndex, new ItemStack(Material.SNOW_BALL));
} else if (replacing.getType() == Material.SNOW_BALL) {
int oldCount = replacing.getAmount();
int newCount = Math.min(16, oldCount + 1);
if (oldCount != newCount) {
inventory.setItem(slotIndex, new ItemStack(Material.SNOW_BALL, newCount));
}
}
}
}.runTaskLater(plugin, 1);
}
/**
* This method handles a projectile hit event, and runs the hit method.
*
* @param e The event data.
*/
public static void onProjectileHit(ProjectileHitEvent e) {
Projectile proj = e.getEntity();
if (proj instanceof Snowball) {
performHit((Snowball) proj);
}
}
////////////////////////////////////////////////////////////////
// Logic Association
//
private final static WeakHashMap<Snowball, SnowballLogicData> inFlight = new WeakHashMap<Snowball, SnowballLogicData>();
private static int approximateInFlightCount = 0;
private static long inFlightSyncDeadline = 0;
/**
* this class just holds the snowball logic and info for a snowball; the
* snowball itself must not be kept here, as this is the value of a
* weak-hash-map keyed on the snowballs. We don't want to keep them alive.
*/
private final static class SnowballLogicData {
public final SnowballLogic logic;
public final SnowballInfo info;
public SnowballLogicData(SnowballLogic logic, SnowballInfo info) {
this.logic = logic;
this.info = info;
}
}
/**
* This returns the number of snowballs (that have attached logic) that are
* currently in flight. This may count snowballs that have been unloaded or
* otherwise destroyed for a time; it is not exact.
*
* @return The number of in-flight snowballs.
*/
public static int getInFlightCount() {
long now = System.currentTimeMillis();
if (inFlightSyncDeadline <= now) {
inFlightSyncDeadline = now + 1000;
approximateInFlightCount = inFlight.size();
}
return approximateInFlightCount;
}
/**
* This returns the logic and shooter for a snowball that has one.
*
* @param snowball The snowball of interest; can be null.
* @return The logic and info of the snowball, or null if it is an illogical
* snowball or it was null.
*/
private static SnowballLogicData getData(Snowball snowball) {
if (snowball != null) {
return inFlight.get(snowball);
} else {
return null;
}
}
/**
* This method registers the logic so getLogic() can find it. Logics only
* work once started.
*
* @param snowball The snowball being launched.
* @param info Other information about the snowball.
*/
public void start(Snowball snowball, SnowballInfo info) {
inFlight.put(snowball, new SnowballLogicData(this, info));
approximateInFlightCount++;
}
/**
* This method unregisters this logic so it is no longer invoked; this is
* done when snowball hits something.
*
* @param snowball The snowball to deregister.
*/
public void end(Snowball snowball) {
approximateInFlightCount--;
inFlight.remove(snowball);
}
////////////////////////////////////////////////////////////////
// Utilitu Methods
//
/**
* This returns the of the nearest non-air block underneath 'location' that
* is directly over the ground. If 'locaiton' is inside the ground, we'll
* return a new copy of the same location.
*
* @param location The starting location; this is not modified.
* @return A new location describing the place found.
*/
public static Location getGroundUnderneath(Location location) {
Location loc = location.clone();
for (;;) {
// just in case we have a shaft to the void, we need
// to give up before we reach it.
if (loc.getBlockY() <= 0) {
return loc;
}
switch (loc.getBlock().getType()) {
case AIR:
case WATER:
case STATIONARY_WATER:
case LEAVES:
case LONG_GRASS:
case DOUBLE_PLANT:
case LAVA:
case SNOW:
case WATER_LILY:
case RED_ROSE:
case YELLOW_FLOWER:
case DEAD_BUSH:
loc.add(0, -1, 0);
break;
default:
return loc;
}
}
}
}
|
Using BukkitRunnable (much like the snowball replenish) I've got armored skeles and zombies. They are wearing the same armor you're wearing, including enchants, and they wield whatever weapon or thing is at the start of your hotbar. They have your helmet, or if there's no helmet and there's a block above the weapon they'll wear that as a head, or they'll try to have your head (and fail, and be Steve-head). If the block above the weapon has a name, they're named that. Otherwise they're named "(shooter)'s Minion". Lastly, named mobs shouldn't (?) despawn. This is pretty much everything terrifying and awesome. Huzzah! New ultimate weapon!
|
SnowballMadness/src/snowballmadness/SnowballLogic.java
|
Using BukkitRunnable (much like the snowball replenish) I've got armored skeles and zombies. They are wearing the same armor you're wearing, including enchants, and they wield whatever weapon or thing is at the start of your hotbar. They have your helmet, or if there's no helmet and there's a block above the weapon they'll wear that as a head, or they'll try to have your head (and fail, and be Steve-head). If the block above the weapon has a name, they're named that. Otherwise they're named "(shooter)'s Minion". Lastly, named mobs shouldn't (?) despawn. This is pretty much everything terrifying and awesome. Huzzah! New ultimate weapon!
|
|
Java
|
apache-2.0
|
a0b4c899507d34dcfaf6f0a959a05b201a80de3b
| 0
|
samaitra/jena,kamir/jena,samaitra/jena,adrapereira/jena,kamir/jena,tr3vr/jena,tr3vr/jena,adrapereira/jena,CesarPantoja/jena,samaitra/jena,apache/jena,apache/jena,kidaa/jena,tr3vr/jena,atsolakid/jena,CesarPantoja/jena,atsolakid/jena,adrapereira/jena,atsolakid/jena,kidaa/jena,atsolakid/jena,jianglili007/jena,samaitra/jena,jianglili007/jena,CesarPantoja/jena,kamir/jena,apache/jena,CesarPantoja/jena,kidaa/jena,apache/jena,jianglili007/jena,kamir/jena,kamir/jena,apache/jena,tr3vr/jena,tr3vr/jena,atsolakid/jena,samaitra/jena,apache/jena,adrapereira/jena,samaitra/jena,atsolakid/jena,tr3vr/jena,kidaa/jena,apache/jena,jianglili007/jena,samaitra/jena,CesarPantoja/jena,kidaa/jena,CesarPantoja/jena,jianglili007/jena,tr3vr/jena,apache/jena,jianglili007/jena,kidaa/jena,adrapereira/jena,adrapereira/jena,jianglili007/jena,atsolakid/jena,kamir/jena,kidaa/jena,CesarPantoja/jena,adrapereira/jena,kamir/jena
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hp.hpl.jena.sparql;
import java.util.ArrayList ;
import java.util.Iterator ;
import java.util.List ;
import org.openjena.atlas.iterator.Iter ;
import org.openjena.atlas.lib.Sync ;
import com.hp.hpl.jena.graph.Graph ;
import com.hp.hpl.jena.graph.Node ;
import com.hp.hpl.jena.graph.compose.Polyadic ;
import com.hp.hpl.jena.query.Dataset ;
import com.hp.hpl.jena.rdf.model.Model ;
import com.hp.hpl.jena.reasoner.InfGraph ;
import com.hp.hpl.jena.sparql.core.DatasetGraph ;
import com.hp.hpl.jena.sparql.core.Transactional ;
import com.hp.hpl.jena.sparql.graph.GraphWrapper ;
import com.hp.hpl.jena.sparql.mgt.SystemInfo ;
public class SystemARQ
{
/** Sync a Model if it provides the underlying graph provides sync . Do nothing otherwise. */
public static void sync(Model model)
{
sync(model.getGraph()) ;
}
/** Sync if provided. Do nothing if not. */
public static void sync(Graph graph)
{
syncGraph(graph) ;
}
private static void syncGraph(Graph graph)
{
// "Temporary" hack. Graph ought to implement sync and casade it down.
if ( graph instanceof InfGraph )
syncGraph(((InfGraph)graph).getRawGraph()) ;
else if ( graph instanceof Polyadic ) // MultiUnion
// Only the base graph is updatable.
syncGraph(((Polyadic)graph).getBaseGraph()) ;
else if ( graph instanceof GraphWrapper )
syncGraph(((GraphWrapper)graph).get()) ;
// else if ( graph instanceof WrappedGraph )
// // Does not expose the WrappedGraph : checking, no subclass needs a sync().
// syncGraph(((WrappedGraph)graph).get()) ;
else
syncObject(graph) ;
}
/** Sync a Dataset, if underlying storage provides sync. */
public static void sync(Dataset dataset)
{
sync(dataset.asDatasetGraph()) ;
}
/** Sync carefully for compound objects*/
public static void sync(DatasetGraph dataset)
{
if ( dataset instanceof Transactional )
return ;
if ( dataset instanceof Sync )
{
((Sync)dataset).sync() ;
return ;
}
else
{
sync(dataset.getDefaultGraph()) ;
// Go through each graph.
Iterator<Node> iter = Iter.iterator(dataset.listGraphNodes()) ;
for ( ; iter.hasNext() ; )
{
Node n = iter.next();
Graph g = dataset.getGraph(n) ;
sync(g) ;
}
}
}
/** Sync an object if synchronizable (model, graph, dataset).
* If force is true, synchronize as much as possible (e.g. file metadata)
* else make a reasonable attenpt at synchronization but does not gauarantee disk state.
* Do nothing otherwise
*/
public static void syncObject(Object object)
{
if ( object instanceof Sync )
((Sync)object).sync() ;
}
private static List<SystemInfo> versions = new ArrayList<SystemInfo>() ;
public static void registerSubSystem(SystemInfo systemInfo)
{
versions.add(systemInfo) ;
}
public static Iterator<SystemInfo> registeredSubsystems()
{
return versions.iterator() ;
}
}
|
jena-arq/src/main/java/com/hp/hpl/jena/sparql/SystemARQ.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hp.hpl.jena.sparql;
import java.util.ArrayList ;
import java.util.Iterator ;
import java.util.List ;
import org.openjena.atlas.iterator.Iter ;
import org.openjena.atlas.lib.Sync ;
import com.hp.hpl.jena.graph.Graph ;
import com.hp.hpl.jena.graph.Node ;
import com.hp.hpl.jena.graph.compose.Polyadic ;
import com.hp.hpl.jena.query.Dataset ;
import com.hp.hpl.jena.rdf.model.Model ;
import com.hp.hpl.jena.reasoner.InfGraph ;
import com.hp.hpl.jena.sparql.core.DatasetGraph ;
import com.hp.hpl.jena.sparql.graph.GraphWrapper ;
import com.hp.hpl.jena.sparql.mgt.SystemInfo ;
public class SystemARQ
{
/** Sync a Model if it provides the underlying graph provides sync . Do nothing otherwise. */
public static void sync(Model model)
{
sync(model.getGraph()) ;
}
/** Sync if provided. Do nothing if not. */
public static void sync(Graph graph)
{
syncGraph(graph) ;
}
private static void syncGraph(Graph graph)
{
// "Temporary" hack. Graph ought to implement sync and casade it down.
if ( graph instanceof InfGraph )
syncGraph(((InfGraph)graph).getRawGraph()) ;
else if ( graph instanceof Polyadic ) // MultiUnion
// Only the base graph is updatable.
syncGraph(((Polyadic)graph).getBaseGraph()) ;
else if ( graph instanceof GraphWrapper )
syncGraph(((GraphWrapper)graph).get()) ;
// else if ( graph instanceof WrappedGraph )
// // Does not expose the WrappedGraph : checking, no subclass needs a sync().
// syncGraph(((WrappedGraph)graph).get()) ;
else
syncObject(graph) ;
}
/** Sync a Dataset, if underlying storage provides sync. */
public static void sync(Dataset dataset)
{
sync(dataset.asDatasetGraph()) ;
}
/** Sync carefully for compound objects*/
public static void sync(DatasetGraph dataset)
{
if ( dataset instanceof Sync )
{
((Sync)dataset).sync() ;
return ;
}
else
{
sync(dataset.getDefaultGraph()) ;
// Go through each graph.
Iterator<Node> iter = Iter.iterator(dataset.listGraphNodes()) ;
for ( ; iter.hasNext() ; )
{
Node n = iter.next();
Graph g = dataset.getGraph(n) ;
sync(g) ;
}
}
}
/** Sync an object if synchronizable (model, graph, dataset).
* If force is true, synchronize as much as possible (e.g. file metadata)
* else make a reasonable attenpt at synchronization but does not gauarantee disk state.
* Do nothing otherwise
*/
public static void syncObject(Object object)
{
if ( object instanceof Sync )
((Sync)object).sync() ;
}
private static List<SystemInfo> versions = new ArrayList<SystemInfo>() ;
public static void registerSubSystem(SystemInfo systemInfo)
{
versions.add(systemInfo) ;
}
public static Iterator<SystemInfo> registeredSubsystems()
{
return versions.iterator() ;
}
}
|
sync on transactional is a no-op
git-svn-id: bc509ec38c1227b3e85ea1246fda136342965d36@1408129 13f79535-47bb-0310-9956-ffa450edef68
|
jena-arq/src/main/java/com/hp/hpl/jena/sparql/SystemARQ.java
|
sync on transactional is a no-op
|
|
Java
|
apache-2.0
|
8b66f35c00ea6347265b054c4a7f35230d60f9f0
| 0
|
iservport/helianto,iservport/helianto
|
package org.helianto.user.repository;
import java.io.Serializable;
import java.util.List;
import org.helianto.core.data.FilterRepository;
import org.helianto.core.domain.Entity;
import org.helianto.user.domain.UserGroup;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Query;
/**
* User group repository.
*
* @author mauriciofernandesdecastro
*/
public interface UserGroupRepository extends FilterRepository<UserGroup, Serializable> {
/**
* Find by natural key.
*
* @param entity
* @param userKey
*/
UserGroup findByEntityAndUserKey(Entity entity, String userKey);
/**
* Find by natural key.
*
* @param entityId
* @param userKey
*/
UserGroup findByEntity_IdAndUserKey(int entityId, String userKey);
/**
* Find by user key.
*
* @param entity
* @param userKey
*/
List<UserGroup> findByUserKey(String userKey);
// select user from User user where user.userKey = ? order by lastEvent DESC
/**
* Find by user key order by lastEvent DESC.
*
* @param userKey
*/
List<UserGroup> findByUserKeyOrderByLastEventDesc(String userKey);
/**
* Find children by parent key.
*
* @param parentKey
*/
@Query(value="select distinct child from User child " +
"join child.parentAssociations parents " +
"where lower(parents.parent.userKey) like ?1 ")
List<UserGroup> findByParent(String parentKey);
/**
* Find parents by child.
*
* @param child
*/
@Query(value="select association.parent from UserAssociation association " +
"where association.child = ?1 ")
List<UserGroup> findParentsByChild(UserGroup child);
/**
* Find parents by child.
*
* @param childId
*/
@Query(value="select association.parent from UserAssociation association " +
"where association.child.id = ?1 ")
List<UserGroup> findParentsByChildId(int childId);
/**
* Find by entity userType.
*
* @param entityId
* @param userType
* @param page
*/
List<UserGroup> findByEntity_IdAndUserType(int entityId, Character userType, Pageable page);
/**
* Find by entity and nature (containing).
*
* @param entityId
* @param userNature
*/
List<UserGroup> findByEntity_IdAndNatureContainingOrderByUserKeyAsc(int entityId, String userNature);
/**
* Find by identity id.
*
* @param identityId
* @return
*/
@Query("select new "
+ "org.helianto.user.repository.UserReadAdapter"
+ "(user.id, user.entity.operator.id, user.entity.id, user.identity.id, "
+ "user.userKey, user.userName, user.userState) "
+ "from User user "
+ "where user.identity.id = ?1 "
+ "and user.class = 'U' "
+ "order by user.lastEvent DESC ")
List<UserReadAdapter> findByIdentityIdOrderByLastEventDesc(int identityId);
}
|
helianto-core/src/main/java/org/helianto/user/repository/UserGroupRepository.java
|
package org.helianto.user.repository;
import java.io.Serializable;
import java.util.List;
import org.helianto.core.data.FilterRepository;
import org.helianto.core.domain.Entity;
import org.helianto.user.domain.UserGroup;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Query;
/**
* User group repository.
*
* @author mauriciofernandesdecastro
*/
public interface UserGroupRepository extends FilterRepository<UserGroup, Serializable> {
/**
* Find by natural key.
*
* @param entity
* @param userKey
*/
UserGroup findByEntityAndUserKey(Entity entity, String userKey);
/**
* Find by user key.
*
* @param entity
* @param userKey
*/
List<UserGroup> findByUserKey(String userKey);
// select user from User user where user.userKey = ? order by lastEvent DESC
/**
* Find by user key order by lastEvent DESC.
*
* @param userKey
*/
List<UserGroup> findByUserKeyOrderByLastEventDesc(String userKey);
/**
* Find children by parent key.
*
* @param parentKey
*/
@Query(value="select distinct child from User child " +
"join child.parentAssociations parents " +
"where lower(parents.parent.userKey) like ?1 ")
List<UserGroup> findByParent(String parentKey);
/**
* Find parents by child.
*
* @param child
*/
@Query(value="select association.parent from UserAssociation association " +
"where association.child = ?1 ")
List<UserGroup> findParentsByChild(UserGroup child);
/**
* Find by entity userType.
*
* @param entityId
* @param userType
* @param page
*/
List<UserGroup> findByEntity_IdAndUserType(int entityId, Character userType, Pageable page);
/**
* Find by entity and nature (containing).
*
* @param entityId
* @param userNature
*/
List<UserGroup> findByEntity_IdAndNatureContainingOrderByUserKeyAsc(int entityId, String userNature);
/**
* Find by identity id.
*
* @param identityId
* @return
*/
@Query("select new "
+ "org.helianto.user.repository.UserReadAdapter"
+ "(user.id, user.entity.operator.id, user.entity.id, user.identity.id, "
+ "user.userKey, user.userName, user.userState) "
+ "from User user "
+ "where user.identity.id = ?1 "
+ "and user.class = 'U' "
+ "order by user.lastEvent DESC ")
List<UserReadAdapter> findByIdentityIdOrderByLastEventDesc(int identityId);
}
|
Improved repository.
|
helianto-core/src/main/java/org/helianto/user/repository/UserGroupRepository.java
|
Improved repository.
|
|
Java
|
apache-2.0
|
7216ef9f7ea9f0c916f25b239935e216e371ca29
| 0
|
ASU-Capstone/uPortal-Forked,joansmith/uPortal,apetro/uPortal,GIP-RECIA/esco-portail,timlevett/uPortal,apetro/uPortal,EdiaEducationTechnology/uPortal,chasegawa/uPortal,chasegawa/uPortal,EsupPortail/esup-uportal,mgillian/uPortal,jl1955/uPortal5,Mines-Albi/esup-uportal,joansmith/uPortal,Jasig/SSP-Platform,ASU-Capstone/uPortal-Forked,phillips1021/uPortal,stalele/uPortal,vertein/uPortal,bjagg/uPortal,jhelmer-unicon/uPortal,stalele/uPortal,jl1955/uPortal5,Jasig/uPortal,doodelicious/uPortal,andrewstuart/uPortal,cousquer/uPortal,jameswennmacher/uPortal,joansmith/uPortal,ChristianMurphy/uPortal,EdiaEducationTechnology/uPortal,Mines-Albi/esup-uportal,EsupPortail/esup-uportal,kole9273/uPortal,ASU-Capstone/uPortal,ASU-Capstone/uPortal,vertein/uPortal,pspaude/uPortal,jonathanmtran/uPortal,ChristianMurphy/uPortal,pspaude/uPortal,andrewstuart/uPortal,kole9273/uPortal,phillips1021/uPortal,Jasig/uPortal-start,vertein/uPortal,stalele/uPortal,Jasig/uPortal,chasegawa/uPortal,vbonamy/esup-uportal,jameswennmacher/uPortal,Mines-Albi/esup-uportal,groybal/uPortal,MichaelVose2/uPortal,chasegawa/uPortal,doodelicious/uPortal,kole9273/uPortal,apetro/uPortal,jhelmer-unicon/uPortal,Jasig/uPortal-start,ASU-Capstone/uPortal,ASU-Capstone/uPortal-Forked,ASU-Capstone/uPortal,MichaelVose2/uPortal,GIP-RECIA/esup-uportal,GIP-RECIA/esco-portail,GIP-RECIA/esco-portail,Mines-Albi/esup-uportal,jl1955/uPortal5,GIP-RECIA/esup-uportal,doodelicious/uPortal,ChristianMurphy/uPortal,phillips1021/uPortal,jameswennmacher/uPortal,ASU-Capstone/uPortal,GIP-RECIA/esup-uportal,mgillian/uPortal,doodelicious/uPortal,drewwills/uPortal,Jasig/SSP-Platform,EdiaEducationTechnology/uPortal,kole9273/uPortal,timlevett/uPortal,Jasig/SSP-Platform,drewwills/uPortal,ASU-Capstone/uPortal-Forked,Jasig/SSP-Platform,timlevett/uPortal,jhelmer-unicon/uPortal,jameswennmacher/uPortal,vbonamy/esup-uportal,vertein/uPortal,EsupPortail/esup-uportal,chasegawa/uPortal,apetro/uPortal,mgillian/uPortal,kole9273/uPortal,phillips1021/uPortal,vbonamy/esup-uportal,bjagg/uPortal,groybal/uPortal,MichaelVose2/uPortal,bjagg/uPortal,groybal/uPortal,andrewstuart/uPortal,pspaude/uPortal,cousquer/uPortal,joansmith/uPortal,timlevett/uPortal,vbonamy/esup-uportal,pspaude/uPortal,joansmith/uPortal,vbonamy/esup-uportal,GIP-RECIA/esup-uportal,EdiaEducationTechnology/uPortal,andrewstuart/uPortal,ASU-Capstone/uPortal-Forked,EsupPortail/esup-uportal,groybal/uPortal,MichaelVose2/uPortal,MichaelVose2/uPortal,stalele/uPortal,EsupPortail/esup-uportal,Mines-Albi/esup-uportal,groybal/uPortal,doodelicious/uPortal,Jasig/SSP-Platform,andrewstuart/uPortal,phillips1021/uPortal,drewwills/uPortal,drewwills/uPortal,jl1955/uPortal5,stalele/uPortal,apetro/uPortal,jhelmer-unicon/uPortal,GIP-RECIA/esup-uportal,jonathanmtran/uPortal,jhelmer-unicon/uPortal,Jasig/uPortal,jl1955/uPortal5,jonathanmtran/uPortal,jameswennmacher/uPortal,cousquer/uPortal
|
/**
* Copyright 2001 The JA-SIG Collaborative. All rights reserved.
*
* Redistribution and use in source and binary forms, with or withoutu
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the JA-SIG Collaborative
* (http://www.jasig.org/)."
*
* THIS SOFTWARE IS PROVIDED BY THE JA-SIG COLLABORATIVE "AS IS" AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE JA-SIG COLLABORATIVE OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*
*
* formatted with JxBeauty (c) johann.langhofer@nextra.at
*/
package org.jasig.portal.utils;
import org.jasig.portal.*;
import org.apache.xalan.xslt.*;
import org.apache.xerces.parsers.SAXParser;
import java.io.File;
import java.io.StringReader;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Hashtable;
import java.util.Enumeration;
import java.net.URL;
import org.xml.sax.DocumentHandler;
import org.xml.sax.SAXException;
import org.w3c.dom.Document;
/**
* <p>This utility provides methods for transforming XML documents
* via XSLT. It takes advantage of Xalan's ability to pre-compile
* stylehseets into StylesheetRoot objects. The first time a transform
* is requested, a stylesheet is compiled and cached.</p>
* <p>None of the method signatures in this class should contain
* classes specific to a particular XSLT engine, e.g. Xalan, or
* XML parser, e.g. Xerces.</p>
* @author Ken Weiner, kweiner@interactivebusiness.com
* @version $Revision$
*/
public class XSLT {
// developmentMode flag should be set to false for production to
// ensure that pre-compiled stylesheets are cached
// I'm hoping that this setting can come from some globally-set
// property. I'll leave this for later.
// Until then, it'll stay checked in set to true so that
// developers can simply reload the page to see the effect of
// a modified XSLT stylesheet
private static boolean developmentMode = true;
private static final String mediaProps = UtilitiesBean.getPortalBaseDir() + "properties" + File.separator + "media.properties";
private static Hashtable stylesheetRootCache = new Hashtable();
/**
* Performs an XSL transformation. Accepts stylesheet parameters
* (key, value pairs) stored in a Hashtable.
* @param xml a string representing the xml document
* @param sslUri the URI of the stylesheet list file (.ssl)
* @param out a document handler
* @param stylesheetParams a Hashtable of key/value pairs or <code>null</code> if no parameters
* @param stylesheetTitle the title that identifies the stylesheet in the stylesheet list file (.ssl), <code>null</code> if no title
* @param media the media type
* @throws org.xml.sax.SAXException
* @throws java.io.IOException
* @throws org.jasig.portal.ResourceMissingException
*/
public static void transform (String xml, URL sslUri, DocumentHandler out, Hashtable stylesheetParams, String stylesheetTitle,
String media) throws SAXException, IOException, ResourceMissingException, GeneralRenderingException {
XSLTInputSource xmlSource = new XSLTInputSource(new StringReader(xml));
XSLTResultTarget xmlResult = new XSLTResultTarget(out);
StylesheetSet set = new StylesheetSet(sslUri.toExternalForm());
set.setMediaProps(mediaProps);
XSLTProcessor processor = XSLTProcessorFactory.getProcessor();
StylesheetRoot stylesheetRoot = getStylesheetRoot(set.getStylesheetURI(stylesheetTitle, media));
processor.reset();
setStylesheetParams(processor, stylesheetParams);
stylesheetRoot.process(processor, xmlSource, xmlResult);
}
/**
* Performs an XSL transformation. Accepts stylesheet parameters
* (key, value pairs) stored in a Hashtable.
* @param xml a string representing the xml document
* @param sslUri the URI of the stylesheet list file (.ssl)
* @param out a StringWriter
* @param stylesheetParams a Hashtable of key/value pairs or <code>null</code> if no parameters
* @param stylesheetTitle the title that identifies the stylesheet in the stylesheet list file (.ssl), <code>null</code> if no title
* @param media the media type
* @throws org.xml.sax.SAXException
* @throws java.io.IOException
* @throws org.jasig.portal.ResourceMissingException
*/
public static void transform (String xml, URL sslUri, StringWriter out, Hashtable stylesheetParams, String stylesheetTitle,
String media) throws SAXException, IOException, ResourceMissingException, GeneralRenderingException {
XSLTInputSource xmlSource = new XSLTInputSource(new StringReader(xml));
XSLTResultTarget xmlResult = new XSLTResultTarget(out);
StylesheetSet set = new StylesheetSet(sslUri.toExternalForm());
set.setMediaProps(mediaProps);
XSLTProcessor processor = XSLTProcessorFactory.getProcessor();
StylesheetRoot stylesheetRoot = getStylesheetRoot(set.getStylesheetURI(stylesheetTitle, media));
processor.reset();
setStylesheetParams(processor, stylesheetParams);
// Make sure to generate XML in order to cache it
stylesheetRoot.setOutputMethod("xml");
// Process the XML/XSLT and store the result in the StringWriter
stylesheetRoot.process(processor, xmlSource, xmlResult);
}
/**
* Performs an XSL transformation.
* @param xml a string representing the xml document
* @param sslUri the URI of the stylesheet list file (.ssl)
* @param out a document handler
* @param stylesheetTitle the title that identifies the stylsheet in the stylesheet list file (.ssl)
* @param media the media type
* @throws org.xml.sax.SAXException
* @throws java.io.IOException
* @throws org.jasig.portal.ResourceMissingException
*/
public static void transform (String xml, URL sslUri, DocumentHandler out, String stylesheetTitle, String media) throws SAXException,
IOException, ResourceMissingException, GeneralRenderingException {
transform(xml, sslUri, out, (Hashtable)null, stylesheetTitle, media);
}
/**
* Performs an XSL transformation. Accepts stylesheet parameters
* (key, value pairs) stored in a Hashtable.
* @param xml a string representing the xml document
* @param sslUri the URI of the stylesheet list file (.ssl)
* @param out a document handler
* @param stylesheetParams a Hashtable of key/value pairs or <code>null</code> if no parameters
* @param media the media type
* @throws org.xml.sax.SAXException
* @throws java.io.IOException
* @throws org.jasig.portal.ResourceMissingException
*/
public static void transform (String xml, URL sslUri, DocumentHandler out, Hashtable stylesheetParams, String media) throws SAXException,
IOException, ResourceMissingException, GeneralRenderingException {
transform(xml, sslUri, out, stylesheetParams, (String)null, media);
}
/**
* Performs an XSL transformation.
* @param xml a string representing the xml document
* @param sslUri the URI of the stylesheet list file (.ssl)
* @param out a document handler
* @param media the media type
* @throws org.xml.sax.SAXException
* @throws java.io.IOException
* @throws org.jasig.portal.ResourceMissingException
*/
public static void transform (String xml, URL sslUri, DocumentHandler out, String media) throws SAXException, IOException,
ResourceMissingException, GeneralRenderingException {
transform(xml, sslUri, out, (Hashtable)null, (String)null, media);
}
/**
* Performs an XSL transformation. Accepts stylesheet parameters
* (key, value pairs) stored in a Hashtable.
* @param xmlDoc a DOM object representing the xml document
* @param sslUri the URI of the stylesheet list file (.ssl)
* @param out a document handler
* @param stylesheetParams a Hashtable of key/value pairs or <code>null</code> if no parameters
* @param stylesheetTitle the title that identifies the stylesheet in the stylesheet list file (.ssl), <code>null</code> if no title
* @param media the media type
* @throws org.xml.sax.SAXException
* @throws java.io.IOException
* @throws org.jasig.portal.ResourceMissingException
*/
public static void transform (Document xmlDoc, URL sslUri, DocumentHandler out, Hashtable stylesheetParams, String stylesheetTitle,
String media) throws SAXException, IOException, ResourceMissingException, GeneralRenderingException {
XSLTInputSource xmlSource = new XSLTInputSource(xmlDoc);
XSLTResultTarget xmlResult = new XSLTResultTarget(out);
StylesheetSet set = new StylesheetSet(sslUri.toExternalForm());
set.setMediaProps(mediaProps);
XSLTProcessor processor = XSLTProcessorFactory.getProcessor(new org.apache.xalan.xpath.xdom.XercesLiaison());
StylesheetRoot stylesheetRoot = getStylesheetRoot(set.getStylesheetURI(stylesheetTitle, media));
processor.reset();
setStylesheetParams(processor, stylesheetParams);
stylesheetRoot.process(processor, xmlSource, xmlResult);
}
/**
* Performs an XSL transformation. Accepts stylesheet parameters
* (key, value pairs) stored in a Hashtable.
* @param xmlDoc a DOM object representing the xml document
* @param sslUri the URI of the stylesheet list file (.ssl)
* @param out a string writer
* @param stylesheetParams a Hashtable of key/value pairs or <code>null</code> if no parameters
* @param stylesheetTitle the title that identifies the stylesheet in the stylesheet list file (.ssl), <code>null</code> if no title
* @param media the media type
* @throws org.xml.sax.SAXException
* @throws java.io.IOException
* @throws org.jasig.portal.ResourceMissingException
*/
public static void transform (Document xmlDoc, URL sslUri, StringWriter out, Hashtable stylesheetParams, String stylesheetTitle,
String media) throws SAXException, IOException, ResourceMissingException, GeneralRenderingException {
XSLTInputSource xmlSource = new XSLTInputSource(xmlDoc);
XSLTResultTarget xmlResult = new XSLTResultTarget(out);
StylesheetSet set = new StylesheetSet(sslUri.toExternalForm());
set.setMediaProps(mediaProps);
XSLTProcessor processor = XSLTProcessorFactory.getProcessor(new org.apache.xalan.xpath.xdom.XercesLiaison());
StylesheetRoot stylesheetRoot = getStylesheetRoot(set.getStylesheetURI(stylesheetTitle, media));
processor.reset();
setStylesheetParams(processor, stylesheetParams);
stylesheetRoot.process(processor, xmlSource, xmlResult);
}
/**
* Performs an XSL transformation.
* @param xmlDoc a DOM object representing the xml document
* @param sslUri the URI of the stylesheet list file (.ssl)
* @param out a document handler
* @param stylesheetTitle the title that identifies the stylsheet in the stylesheet list file (.ssl)
* @param media the media type
* @throws org.xml.sax.SAXException
* @throws java.io.IOException
* @throws org.jasig.portal.ResourceMissingException
*/
public static void transform (Document xmlDoc, URL sslUri, DocumentHandler out, String stylesheetTitle, String media) throws SAXException,
IOException, ResourceMissingException, GeneralRenderingException {
transform(xmlDoc, sslUri, out, (Hashtable)null, stylesheetTitle, media);
}
/**
* Performs an XSL transformation. Accepts stylesheet parameters
* (key, value pairs) stored in a Hashtable.
* @param xmlDoc a DOM object representing the xml document
* @param sslUri the URI of the stylesheet list file (.ssl)
* @param out a document handler
* @param stylesheetParams a Hashtable of key/value pairs or <code>null</code> if no parameters
* @param media the media type
* @throws org.xml.sax.SAXException
* @throws java.io.IOException
* @throws org.jasig.portal.ResourceMissingException
*/
public static void transform (Document xmlDoc, URL sslUri, DocumentHandler out, Hashtable stylesheetParams, String media) throws SAXException,
IOException, ResourceMissingException, GeneralRenderingException {
transform(xmlDoc, sslUri, out, stylesheetParams, (String)null, media);
}
/**
* Performs an XSL transformation. Accepts stylesheet parameters
* (key, value pairs) stored in a Hashtable.
* @param xmlDoc a DOM object representing the xml document
* @param sslUri the URI of the stylesheet list file (.ssl)
* @param out a StringWriter
* @param stylesheetParams a Hashtable of key/value pairs or <code>null</code> if no parameters
* @param media the media type
* @throws org.xml.sax.SAXException
* @throws java.io.IOException
* @throws org.jasig.portal.ResourceMissingException
*/
public static void transform (Document xmlDoc, URL sslUri, StringWriter out, Hashtable stylesheetParams, String media) throws SAXException,
IOException, ResourceMissingException, GeneralRenderingException {
transform(xmlDoc, sslUri, out, stylesheetParams, (String)null, media);
}
/**
* Performs an XSL transformation.
* @param xmlDoc a DOM object representing the xml document
* @param sslUri the URI of the stylesheet list file (.ssl)
* @param out a document handler
* @param media the media type
* @throws org.xml.sax.SAXException
* @throws java.io.IOException
* @throws org.jasig.portal.ResourceMissingException
*/
public static void transform (Document xmlDoc, URL sslUri, DocumentHandler out, String media) throws SAXException, IOException,
ResourceMissingException, GeneralRenderingException {
transform(xmlDoc, sslUri, out, (Hashtable)null, (String)null, media);
}
/**/
/**
* Performs an XSL transformation. Accepts stylesheet parameters
* (key, value pairs) stored in a Hashtable.
* @param xml a string representing the xml document
* @param xslUri the URI of the stylesheet file (.xsl)
* @param out a document handler
* @param stylesheetParams a Hashtable of key/value pairs or <code>null</code> if no parameters
* @throws org.xml.sax.SAXException
* @throws java.io.IOException
* @throws org.jasig.portal.ResourceMissingException
*/
public static void transform (String xml, URL xslUri, DocumentHandler out, Hashtable stylesheetParams) throws SAXException,
IOException, ResourceMissingException {
XSLTInputSource xmlSource = new XSLTInputSource(new StringReader(xml));
XSLTResultTarget xmlResult = new XSLTResultTarget(out);
XSLTProcessor processor = XSLTProcessorFactory.getProcessor();
StylesheetRoot stylesheetRoot = getStylesheetRoot(xslUri.toExternalForm());
processor.reset();
setStylesheetParams(processor, stylesheetParams);
stylesheetRoot.process(processor, xmlSource, xmlResult);
}
/**
* Performs an XSL transformation.
* @param xml a string representing the xml document
* @param xslUri the URI of the stylesheet file
* @param out a document handler
* @throws org.xml.sax.SAXException
* @throws java.io.IOException
* @throws org.jasig.portal.ResourceMissingException
*/
public static void transform (String xml, URL xslUri, DocumentHandler out) throws SAXException, IOException, ResourceMissingException {
transform(xml, xslUri, out, (Hashtable)null);
}
/**
* Performs an XSL transformation. Accepts stylesheet parameters
* (key, value pairs) stored in a Hashtable.
* @param xmlDoc a DOM object representing the xml document
* @param xslUri the URI of the stylesheet file (.xsl)
* @param out a document handler
* @param stylesheetParams a Hashtable of key/value pairs or <code>null</code> if no parameters
* @throws org.xml.sax.SAXException
* @throws java.io.IOException
* @throws org.jasig.portal.ResourceMissingException
*/
public static void transform (Document xmlDoc, URL xslUri, DocumentHandler out, Hashtable stylesheetParams) throws SAXException,
IOException, ResourceMissingException {
XSLTInputSource xmlSource = new XSLTInputSource(xmlDoc);
XSLTResultTarget xmlResult = new XSLTResultTarget(out);
XSLTProcessor processor = XSLTProcessorFactory.getProcessor(new org.apache.xalan.xpath.xdom.XercesLiaison());
StylesheetRoot stylesheetRoot = getStylesheetRoot(xslUri.toExternalForm());
processor.reset();
setStylesheetParams(processor, stylesheetParams);
stylesheetRoot.process(processor, xmlSource, xmlResult);
}
/**
* Performs an XSL transformation. Accepts stylesheet parameters
* (key, value pairs) stored in a Hashtable.
* @param xmlDoc a DOM object representing the xml document
* @param xslUri the URI of the stylesheet file (.xsl)
* @param out a string writer
* @param stylesheetParams a Hashtable of key/value pairs or <code>null</code> if no parameters
* @throws org.xml.sax.SAXException
* @throws java.io.IOException
* @throws org.jasig.portal.ResourceMissingException
*/
public static void transform (Document xmlDoc, URL xslUri, StringWriter out, Hashtable stylesheetParams) throws SAXException,
IOException, ResourceMissingException {
XSLTInputSource xmlSource = new XSLTInputSource(xmlDoc);
XSLTResultTarget xmlResult = new XSLTResultTarget(out);
XSLTProcessor processor = XSLTProcessorFactory.getProcessor(new org.apache.xalan.xpath.xdom.XercesLiaison());
StylesheetRoot stylesheetRoot = getStylesheetRoot(xslUri.toExternalForm());
processor.reset();
setStylesheetParams(processor, stylesheetParams);
stylesheetRoot.process(processor, xmlSource, xmlResult);
}
/**
* Performs an XSL transformation. Accepts stylesheet parameters
* (key, value pairs) stored in a Hashtable.
* @param xmlDoc a DOM object representing the xml document
* @param xslUri the URI of the stylesheet file (.xsl)
* @param out a document handler
* @throws org.xml.sax.SAXException
* @throws java.io.IOException
* @throws org.jasig.portal.ResourceMissingException
*/
public static void transform (Document xmlDoc, URL xslUri, DocumentHandler out) throws SAXException, IOException, ResourceMissingException {
transform(xmlDoc, xslUri, out, (Hashtable)null);
}
/**
* put your documentation comment here
* @param xmlDoc
* @param stylesheetSet
* @param out
* @param stylesheetParams
* @param stylesheetTitle
* @param media
* @exception SAXException, IOException, ResourceMissingException, GeneralRenderingException
*/
public static void transform (Document xmlDoc, StylesheetSet stylesheetSet, DocumentHandler out, Hashtable stylesheetParams,
String stylesheetTitle, String media) throws SAXException, IOException, ResourceMissingException, GeneralRenderingException {
// Create the input source for the input xml
XSLTInputSource xmlSource = new XSLTInputSource(xmlDoc);
// Create the result target for the DocumentHandler
XSLTResultTarget xmlResult = new XSLTResultTarget(out);
// Get an instance of the XSLT processor
XSLTProcessor processor = XSLTProcessorFactory.getProcessor(new org.apache.xalan.xpath.xdom.XercesLiaison());
// Reset the processor
processor.reset();
// Get the XSL stylesheet location
StylesheetRoot stylesheetRoot = getStylesheetRoot(stylesheetSet.getStylesheetURI(stylesheetTitle, media));
// Set the parameters for the transformation
setStylesheetParams(processor, stylesheetParams);
// Perform the transformation
stylesheetRoot.process(processor, xmlSource, xmlResult);
}
/**
* put your documentation comment here
* @param processor
* @param stylesheetParams
*/
private static void setStylesheetParams (XSLTProcessor processor, Hashtable stylesheetParams) {
if (stylesheetParams != null) {
Enumeration e = stylesheetParams.keys();
while (e.hasMoreElements()) {
String key = (String)e.nextElement();
Object o = stylesheetParams.get(key);
if (o instanceof String) {
processor.setStylesheetParam(key, processor.createXString((String)o));
}
else if (o.getClass().getName().equals("[Ljava.lang.String;")) {
// This situation occurs for some requests from cell phones
String[] sa = (String[])o;
processor.setStylesheetParam(key, processor.createXString(sa[0]));
}
else if (o instanceof Boolean) {
processor.setStylesheetParam(key, processor.createXBoolean(((Boolean)o).booleanValue()));
}
else if (o instanceof Double) {
processor.setStylesheetParam(key, processor.createXNumber(((Double)o).doubleValue()));
}
}
}
}
/**
* put your documentation comment here
* @param stylesheetURI
* @return
* @exception SAXException, ResourceMissingException
*/
public static StylesheetRoot getStylesheetRoot (String stylesheetURI) throws SAXException, ResourceMissingException {
// First, check the cache...
StylesheetRoot stylesheetRoot = (StylesheetRoot)stylesheetRootCache.get(stylesheetURI);
if (stylesheetRoot == null) {
// Get the StylesheetRoot and cache it
XSLTProcessor processor = XSLTProcessorFactory.getProcessor();
stylesheetRoot = processor.processStylesheet(stylesheetURI);
if (!developmentMode) {
stylesheetRootCache.put(stylesheetURI, stylesheetRoot);
Logger.log(Logger.INFO, "Caching StylesheetRoot for: " + stylesheetURI);
}
}
return stylesheetRoot;
}
}
|
source/org/jasig/portal/utils/XSLT.java
|
/**
* Copyright 2001 The JA-SIG Collaborative. All rights reserved.
*
* Redistribution and use in source and binary forms, with or withoutu
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the JA-SIG Collaborative
* (http://www.jasig.org/)."
*
* THIS SOFTWARE IS PROVIDED BY THE JA-SIG COLLABORATIVE "AS IS" AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE JA-SIG COLLABORATIVE OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*
*
* formatted with JxBeauty (c) johann.langhofer@nextra.at
*/
package org.jasig.portal.utils;
import org.jasig.portal.*;
import org.apache.xalan.xslt.*;
import org.apache.xerces.parsers.SAXParser;
import java.io.File;
import java.io.StringReader;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Hashtable;
import java.util.Enumeration;
import java.net.URL;
import org.xml.sax.DocumentHandler;
import org.xml.sax.SAXException;
import org.w3c.dom.Document;
/**
* <p>This utility provides methods for transforming XML documents
* via XSLT. It takes advantage of Xalan's ability to pre-compile
* stylehseets into StylesheetRoot objects. The first time a transform
* is requested, a stylesheet is compiled and cached.</p>
* <p>None of the method signatures in this class should contain
* classes specific to a particular XSLT engine, e.g. Xalan, or
* XML parser, e.g. Xerces.</p>
* @author Ken Weiner, kweiner@interactivebusiness.com
* @version $Revision$
*/
public class XSLT {
// developmentMode flag should be set to false for production to
// ensure that pre-compiled stylesheets are cached
// I'm hoping that this setting can come from some globally-set
// property. I'll leave this for later.
// Until then, it'll stay checked in set to true so that
// developers can simply reload the page to see the effect of
// a modified XSLT stylesheet
private static boolean developmentMode = true;
private static final String mediaProps = UtilitiesBean.getPortalBaseDir() + "properties" + File.separator + "media.properties";
private static Hashtable stylesheetRootCache = new Hashtable();
/**
* Performs an XSL transformation. Accepts stylesheet parameters
* (key, value pairs) stored in a Hashtable.
* @param xml a string representing the xml document
* @param sslUri the URI of the stylesheet list file (.ssl)
* @param out a document handler
* @param stylesheetParams a Hashtable of key/value pairs or <code>null</code> if no parameters
* @param stylesheetTitle the title that identifies the stylesheet in the stylesheet list file (.ssl), <code>null</code> if no title
* @param media the media type
* @throws org.xml.sax.SAXException
* @throws java.io.IOException
* @throws org.jasig.portal.ResourceMissingException
*/
public static void transform (String xml, URL sslUri, DocumentHandler out, Hashtable stylesheetParams, String stylesheetTitle,
String media) throws SAXException, IOException, ResourceMissingException, GeneralRenderingException {
XSLTInputSource xmlSource = new XSLTInputSource(new StringReader(xml));
XSLTResultTarget xmlResult = new XSLTResultTarget(out);
StylesheetSet set = new StylesheetSet(sslUri.toExternalForm());
set.setMediaProps(mediaProps);
XSLTProcessor processor = XSLTProcessorFactory.getProcessor();
StylesheetRoot stylesheetRoot = getStylesheetRoot(set.getStylesheetURI(stylesheetTitle, media));
processor.reset();
setStylesheetParams(processor, stylesheetParams);
stylesheetRoot.process(processor, xmlSource, xmlResult);
}
/**
* Performs an XSL transformation. Accepts stylesheet parameters
* (key, value pairs) stored in a Hashtable.
* @param xml a string representing the xml document
* @param sslUri the URI of the stylesheet list file (.ssl)
* @param out a StringWriter
* @param stylesheetParams a Hashtable of key/value pairs or <code>null</code> if no parameters
* @param stylesheetTitle the title that identifies the stylesheet in the stylesheet list file (.ssl), <code>null</code> if no title
* @param media the media type
* @throws org.xml.sax.SAXException
* @throws java.io.IOException
* @throws org.jasig.portal.ResourceMissingException
*/
public static void transform (String xml, URL sslUri, StringWriter out, Hashtable stylesheetParams, String stylesheetTitle,
String media) throws SAXException, IOException, ResourceMissingException, GeneralRenderingException {
XSLTInputSource xmlSource = new XSLTInputSource(new StringReader(xml));
XSLTResultTarget xmlResult = new XSLTResultTarget(out);
StylesheetSet set = new StylesheetSet(sslUri.toExternalForm());
set.setMediaProps(mediaProps);
XSLTProcessor processor = XSLTProcessorFactory.getProcessor();
StylesheetRoot stylesheetRoot = getStylesheetRoot(set.getStylesheetURI(stylesheetTitle, media));
processor.reset();
setStylesheetParams(processor, stylesheetParams);
// Make sure to generate XML in order to cache it
stylesheetRoot.setOutputMethod("xml");
// Process the XML/XSLT and store the result in the StringWriter
stylesheetRoot.process(processor, xmlSource, xmlResult);
}
/**
* Performs an XSL transformation.
* @param xml a string representing the xml document
* @param sslUri the URI of the stylesheet list file (.ssl)
* @param out a document handler
* @param stylesheetTitle the title that identifies the stylsheet in the stylesheet list file (.ssl)
* @param media the media type
* @throws org.xml.sax.SAXException
* @throws java.io.IOException
* @throws org.jasig.portal.ResourceMissingException
*/
public static void transform (String xml, URL sslUri, DocumentHandler out, String stylesheetTitle, String media) throws SAXException,
IOException, ResourceMissingException, GeneralRenderingException {
transform(xml, sslUri, out, (Hashtable)null, stylesheetTitle, media);
}
/**
* Performs an XSL transformation. Accepts stylesheet parameters
* (key, value pairs) stored in a Hashtable.
* @param xml a string representing the xml document
* @param sslUri the URI of the stylesheet list file (.ssl)
* @param out a document handler
* @param stylesheetParams a Hashtable of key/value pairs or <code>null</code> if no parameters
* @param media the media type
* @throws org.xml.sax.SAXException
* @throws java.io.IOException
* @throws org.jasig.portal.ResourceMissingException
*/
public static void transform (String xml, URL sslUri, DocumentHandler out, Hashtable stylesheetParams, String media) throws SAXException,
IOException, ResourceMissingException, GeneralRenderingException {
transform(xml, sslUri, out, stylesheetParams, (String)null, media);
}
/**
* Performs an XSL transformation.
* @param xml a string representing the xml document
* @param sslUri the URI of the stylesheet list file (.ssl)
* @param out a document handler
* @param media the media type
* @throws org.xml.sax.SAXException
* @throws java.io.IOException
* @throws org.jasig.portal.ResourceMissingException
*/
public static void transform (String xml, URL sslUri, DocumentHandler out, String media) throws SAXException, IOException,
ResourceMissingException, GeneralRenderingException {
transform(xml, sslUri, out, (Hashtable)null, (String)null, media);
}
/**
* Performs an XSL transformation. Accepts stylesheet parameters
* (key, value pairs) stored in a Hashtable.
* @param xmlDoc a DOM object representing the xml document
* @param sslUri the URI of the stylesheet list file (.ssl)
* @param out a document handler
* @param stylesheetParams a Hashtable of key/value pairs or <code>null</code> if no parameters
* @param stylesheetTitle the title that identifies the stylesheet in the stylesheet list file (.ssl), <code>null</code> if no title
* @param media the media type
* @throws org.xml.sax.SAXException
* @throws java.io.IOException
* @throws org.jasig.portal.ResourceMissingException
*/
public static void transform (Document xmlDoc, URL sslUri, DocumentHandler out, Hashtable stylesheetParams, String stylesheetTitle,
String media) throws SAXException, IOException, ResourceMissingException, GeneralRenderingException {
XSLTInputSource xmlSource = new XSLTInputSource(xmlDoc);
XSLTResultTarget xmlResult = new XSLTResultTarget(out);
StylesheetSet set = new StylesheetSet(sslUri.toExternalForm());
set.setMediaProps(mediaProps);
XSLTProcessor processor = XSLTProcessorFactory.getProcessor(new org.apache.xalan.xpath.xdom.XercesLiaison());
StylesheetRoot stylesheetRoot = getStylesheetRoot(set.getStylesheetURI(stylesheetTitle, media));
processor.reset();
setStylesheetParams(processor, stylesheetParams);
stylesheetRoot.process(processor, xmlSource, xmlResult);
}
/**
* Performs an XSL transformation. Accepts stylesheet parameters
* (key, value pairs) stored in a Hashtable.
* @param xmlDoc a DOM object representing the xml document
* @param sslUri the URI of the stylesheet list file (.ssl)
* @param out a string writer
* @param stylesheetParams a Hashtable of key/value pairs or <code>null</code> if no parameters
* @param stylesheetTitle the title that identifies the stylesheet in the stylesheet list file (.ssl), <code>null</code> if no title
* @param media the media type
* @throws org.xml.sax.SAXException
* @throws java.io.IOException
* @throws org.jasig.portal.ResourceMissingException
*/
public static void transform (Document xmlDoc, URL sslUri, StringWriter out, Hashtable stylesheetParams, String stylesheetTitle,
String media) throws SAXException, IOException, ResourceMissingException, GeneralRenderingException {
XSLTInputSource xmlSource = new XSLTInputSource(xmlDoc);
XSLTResultTarget xmlResult = new XSLTResultTarget(out);
StylesheetSet set = new StylesheetSet(sslUri.toExternalForm());
set.setMediaProps(mediaProps);
XSLTProcessor processor = XSLTProcessorFactory.getProcessor(new org.apache.xalan.xpath.xdom.XercesLiaison());
StylesheetRoot stylesheetRoot = getStylesheetRoot(set.getStylesheetURI(stylesheetTitle, media));
processor.reset();
setStylesheetParams(processor, stylesheetParams);
stylesheetRoot.process(processor, xmlSource, xmlResult);
}
/**
* Performs an XSL transformation.
* @param xmlDoc a DOM object representing the xml document
* @param sslUri the URI of the stylesheet list file (.ssl)
* @param out a document handler
* @param stylesheetTitle the title that identifies the stylsheet in the stylesheet list file (.ssl)
* @param media the media type
* @throws org.xml.sax.SAXException
* @throws java.io.IOException
* @throws org.jasig.portal.ResourceMissingException
*/
public static void transform (Document xmlDoc, URL sslUri, DocumentHandler out, String stylesheetTitle, String media) throws SAXException,
IOException, ResourceMissingException, GeneralRenderingException {
transform(xmlDoc, sslUri, out, (Hashtable)null, stylesheetTitle, media);
}
/**
* Performs an XSL transformation. Accepts stylesheet parameters
* (key, value pairs) stored in a Hashtable.
* @param xmlDoc a DOM object representing the xml document
* @param sslUri the URI of the stylesheet list file (.ssl)
* @param out a document handler
* @param stylesheetParams a Hashtable of key/value pairs or <code>null</code> if no parameters
* @param media the media type
* @throws org.xml.sax.SAXException
* @throws java.io.IOException
* @throws org.jasig.portal.ResourceMissingException
*/
public static void transform (Document xmlDoc, URL sslUri, DocumentHandler out, Hashtable stylesheetParams, String media) throws SAXException,
IOException, ResourceMissingException, GeneralRenderingException {
transform(xmlDoc, sslUri, out, stylesheetParams, (String)null, media);
}
/**
* Performs an XSL transformation. Accepts stylesheet parameters
* (key, value pairs) stored in a Hashtable.
* @param xmlDoc a DOM object representing the xml document
* @param sslUri the URI of the stylesheet list file (.ssl)
* @param out a StringWriter
* @param stylesheetParams a Hashtable of key/value pairs or <code>null</code> if no parameters
* @param media the media type
* @throws org.xml.sax.SAXException
* @throws java.io.IOException
* @throws org.jasig.portal.ResourceMissingException
*/
public static void transform (Document xmlDoc, URL sslUri, StringWriter out, Hashtable stylesheetParams, String media) throws SAXException,
IOException, ResourceMissingException, GeneralRenderingException {
transform(xmlDoc, sslUri, out, stylesheetParams, (String)null, media);
}
/**
* Performs an XSL transformation.
* @param xmlDoc a DOM object representing the xml document
* @param sslUri the URI of the stylesheet list file (.ssl)
* @param out a document handler
* @param media the media type
* @throws org.xml.sax.SAXException
* @throws java.io.IOException
* @throws org.jasig.portal.ResourceMissingException
*/
public static void transform (Document xmlDoc, URL sslUri, DocumentHandler out, String media) throws SAXException, IOException,
ResourceMissingException, GeneralRenderingException {
transform(xmlDoc, sslUri, out, (Hashtable)null, (String)null, media);
}
/**/
/**
* Performs an XSL transformation. Accepts stylesheet parameters
* (key, value pairs) stored in a Hashtable.
* @param xml a string representing the xml document
* @param xslUri the URI of the stylesheet file (.xsl)
* @param out a document handler
* @param stylesheetParams a Hashtable of key/value pairs or <code>null</code> if no parameters
* @throws org.xml.sax.SAXException
* @throws java.io.IOException
* @throws org.jasig.portal.ResourceMissingException
*/
public static void transform (String xml, URL xslUri, DocumentHandler out, Hashtable stylesheetParams) throws SAXException,
IOException, ResourceMissingException {
XSLTInputSource xmlSource = new XSLTInputSource(new StringReader(xml));
XSLTResultTarget xmlResult = new XSLTResultTarget(out);
XSLTProcessor processor = XSLTProcessorFactory.getProcessor();
StylesheetRoot stylesheetRoot = getStylesheetRoot(xslUri.toExternalForm());
processor.reset();
setStylesheetParams(processor, stylesheetParams);
stylesheetRoot.process(processor, xmlSource, xmlResult);
}
/**
* Performs an XSL transformation.
* @param xml a string representing the xml document
* @param xslUri the URI of the stylesheet file
* @param out a document handler
* @throws org.xml.sax.SAXException
* @throws java.io.IOException
* @throws org.jasig.portal.ResourceMissingException
*/
public static void transform (String xml, URL xslUri, DocumentHandler out) throws SAXException, IOException, ResourceMissingException {
transform(xml, xslUri, out, (Hashtable)null);
}
/**
* Performs an XSL transformation. Accepts stylesheet parameters
* (key, value pairs) stored in a Hashtable.
* @param xmlDoc a DOM object representing the xml document
* @param xslUri the URI of the stylesheet file (.xsl)
* @param out a document handler
* @param stylesheetParams a Hashtable of key/value pairs or <code>null</code> if no parameters
* @throws org.xml.sax.SAXException
* @throws java.io.IOException
* @throws org.jasig.portal.ResourceMissingException
*/
public static void transform (Document xmlDoc, URL xslUri, DocumentHandler out, Hashtable stylesheetParams) throws SAXException,
IOException, ResourceMissingException {
XSLTInputSource xmlSource = new XSLTInputSource(xmlDoc);
XSLTResultTarget xmlResult = new XSLTResultTarget(out);
XSLTProcessor processor = XSLTProcessorFactory.getProcessor(new org.apache.xalan.xpath.xdom.XercesLiaison());
StylesheetRoot stylesheetRoot = getStylesheetRoot(xslUri.toExternalForm());
processor.reset();
setStylesheetParams(processor, stylesheetParams);
stylesheetRoot.process(processor, xmlSource, xmlResult);
}
/**
* Performs an XSL transformation. Accepts stylesheet parameters
* (key, value pairs) stored in a Hashtable.
* @param xmlDoc a DOM object representing the xml document
* @param xslUri the URI of the stylesheet file (.xsl)
* @param out a string writer
* @param stylesheetParams a Hashtable of key/value pairs or <code>null</code> if no parameters
* @throws org.xml.sax.SAXException
* @throws java.io.IOException
* @throws org.jasig.portal.ResourceMissingException
*/
public static void transform (Document xmlDoc, URL xslUri, StringWriter out, Hashtable stylesheetParams) throws SAXException,
IOException, ResourceMissingException {
XSLTInputSource xmlSource = new XSLTInputSource(xmlDoc);
XSLTResultTarget xmlResult = new XSLTResultTarget(out);
XSLTProcessor processor = XSLTProcessorFactory.getProcessor(new org.apache.xalan.xpath.xdom.XercesLiaison());
StylesheetRoot stylesheetRoot = getStylesheetRoot(xslUri.toExternalForm());
processor.reset();
setStylesheetParams(processor, stylesheetParams);
stylesheetRoot.process(processor, xmlSource, xmlResult);
}
/**
* Performs an XSL transformation. Accepts stylesheet parameters
* (key, value pairs) stored in a Hashtable.
* @param xmlDoc a DOM object representing the xml document
* @param xslUri the URI of the stylesheet file (.xsl)
* @param out a document handler
* @throws org.xml.sax.SAXException
* @throws java.io.IOException
* @throws org.jasig.portal.ResourceMissingException
*/
public static void transform (Document xmlDoc, URL xslUri, DocumentHandler out) throws SAXException, IOException, ResourceMissingException {
transform(xmlDoc, xslUri, out, (Hashtable)null);
}
/**
* put your documentation comment here
* @param processor
* @param stylesheetParams
*/
private static void setStylesheetParams (XSLTProcessor processor, Hashtable stylesheetParams) {
if (stylesheetParams != null) {
Enumeration e = stylesheetParams.keys();
while (e.hasMoreElements()) {
String key = (String)e.nextElement();
Object o = stylesheetParams.get(key);
if (o instanceof String) {
processor.setStylesheetParam(key, processor.createXString((String)o));
}
else if (o.getClass().getName().equals("[Ljava.lang.String;")) {
// This situation occurs for some requests from cell phones
String[] sa = (String[])o;
processor.setStylesheetParam(key, processor.createXString(sa[0]));
}
else if (o instanceof Boolean) {
processor.setStylesheetParam(key, processor.createXBoolean(((Boolean)o).booleanValue()));
}
else if (o instanceof Double) {
processor.setStylesheetParam(key, processor.createXNumber(((Double)o).doubleValue()));
}
}
}
}
/**
* put your documentation comment here
* @param stylesheetURI
* @return
* @exception SAXException, ResourceMissingException
*/
public static StylesheetRoot getStylesheetRoot (String stylesheetURI) throws SAXException, ResourceMissingException {
// First, check the cache...
StylesheetRoot stylesheetRoot = (StylesheetRoot)stylesheetRootCache.get(stylesheetURI);
if (stylesheetRoot == null) {
// Get the StylesheetRoot and cache it
XSLTProcessor processor = XSLTProcessorFactory.getProcessor();
stylesheetRoot = processor.processStylesheet(stylesheetURI);
if (!developmentMode) {
stylesheetRootCache.put(stylesheetURI, stylesheetRoot);
Logger.log(Logger.INFO, "Caching StylesheetRoot for: " + stylesheetURI);
}
}
return stylesheetRoot;
}
}
|
Added a transform() method that takes a StylesheetSet as an argument instead of the URI.
git-svn-id: 477788cc2a8229a747c5b8073e47c1d0f6ec0604@4627 f5dbab47-78f9-eb45-b975-e544023573eb
|
source/org/jasig/portal/utils/XSLT.java
|
Added a transform() method that takes a StylesheetSet as an argument instead of the URI.
|
|
Java
|
apache-2.0
|
e69ce7a20d503a8cab45df113bae8069aeeb63c3
| 0
|
BankingBoys/amos-ss17-proj7,BankingBoys/amos-ss17-proj7
|
package de.fau.amos.virtualledger.server.api;
import de.fau.amos.virtualledger.dtos.Contact;
import de.fau.amos.virtualledger.server.auth.KeycloakUtilizer;
import de.fau.amos.virtualledger.server.contacts.ContactsController;
import de.fau.amos.virtualledger.server.contacts.UserNotFoundException;
import de.fau.amos.virtualledger.server.factories.StringApiModelFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.ServletException;
import java.lang.invoke.MethodHandles;
/**
* Endpoints for contacts
*/
@RestController
public class ContactsApiEndpoint {
@SuppressWarnings("unused")
private static final Logger LOGGER = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
private final ContactsController contactsController;
private KeycloakUtilizer keycloakUtilizer;
@Autowired
private StringApiModelFactory stringApiModelFactory;
@Autowired
public ContactsApiEndpoint(KeycloakUtilizer keycloakUtilizer, final ContactsController contactsController) {
this.keycloakUtilizer = keycloakUtilizer;
this.contactsController = contactsController;
}
@RequestMapping(method = RequestMethod.GET, value = "api/contacts", produces = "application/json")
public ResponseEntity<?> getContactsEndpoint() throws ServletException {
final String username = keycloakUtilizer.getEmail();
if (username == null || username.isEmpty()) {
return new ResponseEntity<>("Authentication failed! Your username wasn't found.", HttpStatus.FORBIDDEN);
}
LOGGER.info("getContactsEndpoint of " + username + " was requested");
ResponseEntity<?> entity;
try {
entity = this.getContacts(username);
} catch (UserNotFoundException e) {
return new ResponseEntity<>(e.getMessage(), HttpStatus.FORBIDDEN);
}
return entity;
}
@RequestMapping(method = RequestMethod.POST, value = "api/contacts", produces = "application/json")
public ResponseEntity<?> addContactEndpoint(@RequestBody final Contact contact) throws ServletException {
final String username = keycloakUtilizer.getEmail();
if (username == null || username.isEmpty()) {
return new ResponseEntity<>("Authentication failed! Your username wasn't found.", HttpStatus.FORBIDDEN);
}
LOGGER.info("addContactEndpoint of " + username + " was requested");
return this.addContact(contact, username);
}
@RequestMapping(method = RequestMethod.DELETE, value = "api/contacts/{contactEmail:.+}", produces = "application/json")
public ResponseEntity<?> deleteContactEndpoint(@PathVariable("contactEmail") String contactEmail) throws ServletException {
final String username = keycloakUtilizer.getEmail();
if (username == null || username.isEmpty()) {
return new ResponseEntity<>("Authentication failed! Your username wasn't found.", HttpStatus.FORBIDDEN);
}
LOGGER.info("deleteContactEndpoint of " + username + " was requested");
return this.deleteContact(contactEmail, username);
}
private ResponseEntity<?> getContacts(final String username) throws UserNotFoundException {
return new ResponseEntity<>(contactsController.getContactsByEmail(username), HttpStatus.OK);
}
private ResponseEntity<?> addContact(final Contact contact, final String username) {
try {
contactsController.addContact(contact, username);
} catch (Exception e) {
LOGGER.info("Returning for add:" + e.getMessage() + HttpStatus.FORBIDDEN);
return new ResponseEntity<>(stringApiModelFactory.createStringApiModel(e.getMessage()), HttpStatus.FORBIDDEN);
}
LOGGER.info("Returning for add:" + "Adding of Contacts Successful" + HttpStatus.CREATED);
return new ResponseEntity<>(stringApiModelFactory.createStringApiModel("Adding of Contacts Successful"), HttpStatus.CREATED);
}
private ResponseEntity<?> deleteContact(final String contactEmail, final String username) {
try {
contactsController.deleteContact(contactEmail, username);
} catch (Exception e) {
return new ResponseEntity<>(e.getMessage(), HttpStatus.FORBIDDEN);
}
return new ResponseEntity<>("Deleting of Contact successful", HttpStatus.OK);
}
}
|
server/src/main/java/de/fau/amos/virtualledger/server/api/ContactsApiEndpoint.java
|
package de.fau.amos.virtualledger.server.api;
import de.fau.amos.virtualledger.dtos.Contact;
import de.fau.amos.virtualledger.server.auth.KeycloakUtilizer;
import de.fau.amos.virtualledger.server.contacts.ContactsController;
import de.fau.amos.virtualledger.server.contacts.UserNotFoundException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.ServletException;
import java.lang.invoke.MethodHandles;
/**
* Endpoints for contacts
*/
@RestController
public class ContactsApiEndpoint {
@SuppressWarnings("unused")
private static final Logger LOGGER = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
private final ContactsController contactsController;
private KeycloakUtilizer keycloakUtilizer;
@Autowired
public ContactsApiEndpoint(KeycloakUtilizer keycloakUtilizer, final ContactsController contactsController) {
this.keycloakUtilizer = keycloakUtilizer;
this.contactsController = contactsController;
}
@RequestMapping(method = RequestMethod.GET, value = "api/contacts", produces = "application/json")
public ResponseEntity<?> getContactsEndpoint() throws ServletException {
final String username = keycloakUtilizer.getEmail();
if (username == null || username.isEmpty()) {
return new ResponseEntity<>("Authentication failed! Your username wasn't found.", HttpStatus.FORBIDDEN);
}
LOGGER.info("getContactsEndpoint of " + username + " was requested");
ResponseEntity<?> entity;
try {
entity = this.getContacts(username);
} catch (UserNotFoundException e) {
return new ResponseEntity<>(e.getMessage(), HttpStatus.FORBIDDEN);
}
return entity;
}
@RequestMapping(method = RequestMethod.POST, value = "api/contacts", produces = "application/json")
public ResponseEntity<?> addContactEndpoint(@RequestBody final Contact contact) throws ServletException {
final String username = keycloakUtilizer.getEmail();
if (username == null || username.isEmpty()) {
return new ResponseEntity<>("Authentication failed! Your username wasn't found.", HttpStatus.FORBIDDEN);
}
LOGGER.info("addContactEndpoint of " + username + " was requested");
return this.addContact(contact, username);
}
@RequestMapping(method = RequestMethod.DELETE, value = "api/contacts/{contactEmail:.+}", produces = "application/json")
public ResponseEntity<?> deleteContactEndpoint(@PathVariable("contactEmail") String contactEmail) throws ServletException {
final String username = keycloakUtilizer.getEmail();
if (username == null || username.isEmpty()) {
return new ResponseEntity<>("Authentication failed! Your username wasn't found.", HttpStatus.FORBIDDEN);
}
LOGGER.info("deleteContactEndpoint of " + username + " was requested");
return this.deleteContact(contactEmail, username);
}
private ResponseEntity<?> getContacts(final String username) throws UserNotFoundException {
return new ResponseEntity<>(contactsController.getContactsByEmail(username), HttpStatus.OK);
}
private ResponseEntity<?> addContact(final Contact contact, final String username) {
try {
contactsController.addContact(contact, username);
} catch (Exception e) {
LOGGER.info("Returning for add:" + e.getMessage() + HttpStatus.FORBIDDEN);
return new ResponseEntity<>(e.getMessage(), HttpStatus.FORBIDDEN);
}
LOGGER.info("Returning for add:" + "Adding of Contacts Successful" + HttpStatus.CREATED);
return new ResponseEntity<>("Adding of Contacts Successful", HttpStatus.CREATED);
}
private ResponseEntity<?> deleteContact(final String contactEmail, final String username) {
try {
contactsController.deleteContact(contactEmail, username);
} catch (Exception e) {
return new ResponseEntity<>(e.getMessage(), HttpStatus.FORBIDDEN);
}
return new ResponseEntity<>("Deleting of Contact successful", HttpStatus.OK);
}
}
|
changed Rest Api body of Add to StringApiModel instead of String
|
server/src/main/java/de/fau/amos/virtualledger/server/api/ContactsApiEndpoint.java
|
changed Rest Api body of Add to StringApiModel instead of String
|
|
Java
|
apache-2.0
|
e3f469b5982557a761dd95bc14e6f404557c069b
| 0
|
mdogan/hazelcast,emre-aydin/hazelcast,tufangorel/hazelcast,dbrimley/hazelcast,mdogan/hazelcast,emrahkocaman/hazelcast,tkountis/hazelcast,mesutcelik/hazelcast,emre-aydin/hazelcast,tombujok/hazelcast,lmjacksoniii/hazelcast,mdogan/hazelcast,dbrimley/hazelcast,dbrimley/hazelcast,mesutcelik/hazelcast,Donnerbart/hazelcast,Donnerbart/hazelcast,Donnerbart/hazelcast,emrahkocaman/hazelcast,tufangorel/hazelcast,juanavelez/hazelcast,tufangorel/hazelcast,lmjacksoniii/hazelcast,juanavelez/hazelcast,tkountis/hazelcast,dsukhoroslov/hazelcast,dsukhoroslov/hazelcast,emre-aydin/hazelcast,tkountis/hazelcast,tombujok/hazelcast,mesutcelik/hazelcast
|
/*
* Copyright (c) 2008-2013, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.map.proxy;
import com.hazelcast.core.EntryListener;
import com.hazelcast.core.EntryView;
import com.hazelcast.map.*;
import com.hazelcast.nio.serialization.Data;
import com.hazelcast.query.Predicate;
import com.hazelcast.spi.Invocation;
import com.hazelcast.spi.NodeEngine;
import com.hazelcast.spi.Operation;
import com.hazelcast.util.QueryResultStream;
import com.hazelcast.util.executor.DelegatingFuture;
import java.util.*;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import static com.hazelcast.map.MapService.SERVICE_NAME;
public class ObjectMapProxy<K, V> extends MapProxySupport implements MapProxy<K, V> {
public ObjectMapProxy(final String name, final MapService mapService, final NodeEngine nodeEngine) {
super(name, mapService, nodeEngine);
}
public V get(Object k) {
Data key = getService().toData(k);
return (V) getService().toObject(getInternal(key));
}
public V put(final K k, final V v) {
return put(k, v, -1, null);
}
public V put(final K k, final V v, final long ttl, final TimeUnit timeunit) {
final Data key = getService().toData(k);
final Data value = getService().toData(v);
final Data result = putInternal(key, value, ttl, timeunit);
return (V) getService().toObject(result);
}
public boolean tryPut(final K k, final V v, final long timeout, final TimeUnit timeunit) {
final Data key = getService().toData(k);
final Data value = getService().toData(v);
return tryPutInternal(key, value, timeout, timeunit);
}
public V putIfAbsent(final K k, final V v) {
return putIfAbsent(k, v, -1, null);
}
public V putIfAbsent(final K k, final V v, final long ttl, final TimeUnit timeunit) {
final Data key = getService().toData(k);
final Data value = getService().toData(v);
final Data result = putIfAbsentInternal(key, value, ttl, timeunit);
return (V) getService().toObject(result);
}
public void putTransient(final K k, final V v, final long ttl, final TimeUnit timeunit) {
final Data key = getService().toData(k);
final Data value = getService().toData(v);
putTransientInternal(key, value, ttl, timeunit);
}
public boolean replace(final K k, final V o, final V v) {
final Data key = getService().toData(k);
final Data oldValue = getService().toData(o);
final Data value = getService().toData(v);
return replaceInternal(key, oldValue, value);
}
public V replace(final K k, final V v) {
final Data key = getService().toData(k);
final Data value = getService().toData(v);
return (V) getService().toObject(replaceInternal(key, value));
}
public void set(K key, V value) {
set(key, value, -1, TimeUnit.MILLISECONDS);
}
public void set(final K k, final V v, final long ttl, final TimeUnit timeunit) {
final Data key = getService().toData(k);
final Data value = getService().toData(v);
setInternal(key, value, ttl, timeunit);
}
public V remove(Object k) {
final Data key = getService().toData(k);
final Data result = removeInternal(key);
return (V) getService().toObject(result);
}
public boolean remove(final Object k, final Object v) {
final Data key = getService().toData(k);
final Data value = getService().toData(v);
return removeInternal(key, value);
}
public void delete(Object k) {
final Data key = getService().toData(k);
deleteInternal(key);
}
public boolean containsKey(Object k) {
Data key = getService().toData(k);
return containsKeyInternal(key);
}
public boolean containsValue(final Object v) {
Data value = getService().toData(v);
return containsValueInternal(value);
}
public void lock(final K key) {
NodeEngine nodeEngine = getNodeEngine();
Data k = getService().toData(key);
lockSupport.lock(nodeEngine, k);
}
public void lock(final Object key, final long leaseTime, final TimeUnit timeUnit) {
lockSupport.lock(getNodeEngine(), getService().toData(key), timeUnit.toMillis(leaseTime));
}
public void unlock(final K key) {
NodeEngine nodeEngine = getNodeEngine();
Data k = getService().toData(key);
lockSupport.unlock(nodeEngine, k);
}
public boolean tryRemove(final K key, final long timeout, final TimeUnit timeunit) {
Data k = getService().toData(key);
return tryRemoveInternal(k, timeout, timeunit);
}
public Future<V> getAsync(final K k) {
Data key = getService().toData(k);
NodeEngine nodeEngine = getNodeEngine();
return new DelegatingFuture<V>(getAsyncInternal(key), nodeEngine.getSerializationService());
}
public boolean isLocked(final K k) {
Data key = getService().toData(k);
NodeEngine nodeEngine = getNodeEngine();
return lockSupport.isLocked(nodeEngine, key);
}
public Future putAsync(final K key, final V value) {
Data k = getService().toData(key);
Data v = getService().toData(value);
return new DelegatingFuture<V>(putAsyncInternal(k, v), getNodeEngine().getSerializationService());
}
public Future removeAsync(final K key) {
Data k = getService().toData(key);
return new DelegatingFuture<V>(removeAsyncInternal(k), getNodeEngine().getSerializationService());
}
public Map<K, V> getAll(final Set<K> keys) {
Set<Data> ks = new HashSet(keys.size());
for (K key : keys) {
Data k = getService().toData(key);
ks.add(k);
}
return (Map<K, V>) getAllObjectInternal(ks);
}
public void putAll(final Map<? extends K, ? extends V> m) {
putAllObjectInternal(m);
}
public boolean tryLock(final K key) {
final NodeEngine nodeEngine = getNodeEngine();
return lockSupport.tryLock(nodeEngine, getService().toData(key));
}
public boolean tryLock(final K key, final long time, final TimeUnit timeunit) throws InterruptedException {
final NodeEngine nodeEngine = getNodeEngine();
return lockSupport.tryLock(nodeEngine, getService().toData(key), time, timeunit);
}
public void forceUnlock(final K key) {
final NodeEngine nodeEngine = getNodeEngine();
Data k = getService().toData(key);
lockSupport.forceUnlock(nodeEngine, k);
}
public void addInterceptor(MapInterceptor interceptor) {
addMapInterceptorInternal(interceptor);
}
public void removeInterceptor(MapInterceptor interceptor) {
removeMapInterceptorInternal(interceptor);
}
public void addEntryListener(final EntryListener listener, final boolean includeValue) {
addEntryListenerInternal(listener, null, includeValue);
}
public void addEntryListener(final EntryListener<K, V> listener, final K key, final boolean includeValue) {
addEntryListenerInternal(listener, getService().toData(key), includeValue);
}
public void addEntryListener(EntryListener<K, V> listener, Predicate<K, V> predicate, K key, boolean includeValue) {
addEntryListenerInternal(listener, predicate, getService().toData(key), includeValue);
}
public void removeEntryListener(final EntryListener<K, V> listener) {
removeEntryListenerInternal(listener);
}
public void removeEntryListener(final EntryListener<K, V> listener, final K key) {
removeEntryListenerInternal(listener, getService().toData(key));
}
public EntryView<K, V> getEntryView(K key) {
SimpleEntryView<K, V> entryViewInternal = (SimpleEntryView) getEntryViewInternal(getService().toData(key));
if(entryViewInternal == null) {
return null;
}
Data value = (Data) entryViewInternal.getValue();
entryViewInternal.setKey(key);
entryViewInternal.setValue((V) getService().toObject(value));
return entryViewInternal;
}
public boolean evict(final Object key) {
return evictInternal(getService().toData(key));
}
public void clear() {
clearInternal();
}
public Set<K> keySet() {
final NodeEngine nodeEngine = getNodeEngine();
Set<Data> dataSet = keySetInternal();
HashSet<K> keySet = new HashSet<K>();
for (Data data : dataSet) {
keySet.add((K) getService().toObject(data));
}
return keySet;
}
public Collection<V> values() {
final NodeEngine nodeEngine = getNodeEngine();
Collection<Data> dataSet = valuesInternal();
Collection<V> valueSet = new ArrayList<V>();
for (Data data : dataSet) {
valueSet.add((V) getService().toObject(data));
}
return valueSet;
}
public Set entrySet() {
Set<Entry<Data, Data>> entries = entrySetInternal();
Set<Entry<K, V>> resultSet = new HashSet<Entry<K, V>>();
for (Entry<Data, Data> entry : entries) {
resultSet.add(new AbstractMap.SimpleImmutableEntry((K) getService().toObject(entry.getKey()), (V) getService().toObject(entry.getValue())));
}
return resultSet;
}
public Set<K> keySet(final Predicate predicate) {
return query(predicate, QueryResultStream.IterationType.KEY, false);
}
public Set entrySet(final Predicate predicate) {
return query(predicate, QueryResultStream.IterationType.ENTRY, false);
}
public Collection<V> values(final Predicate predicate) {
return query(predicate, QueryResultStream.IterationType.VALUE, false);
}
public Set<K> localKeySet() {
final Set<Data> dataSet = localKeySetInternal();
final Set<K> keySet = new HashSet<K>(dataSet.size());
for (Data data : dataSet) {
keySet.add((K) getService().toObject(data));
}
return keySet;
}
public Set<K> localKeySet(final Predicate predicate) {
// todo implement
return null;
}
public Object executeOnKey(K key, EntryProcessor entryProcessor) {
return getService().toObject(executeOnKeyInternal(getService().toData(key), entryProcessor));
}
protected Object invoke(Operation operation, int partitionId) throws Throwable {
NodeEngine nodeEngine = getNodeEngine();
Invocation invocation = nodeEngine.getOperationService().createInvocationBuilder(SERVICE_NAME, operation, partitionId).build();
Future f = invocation.invoke();
Object response = f.get();
Object returnObj = getService().toObject(response);
if (returnObj instanceof Throwable) {
throw (Throwable) returnObj;
}
return returnObj;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("IMap");
sb.append("{name='").append(name).append('\'');
sb.append('}');
return sb.toString();
}
}
|
hazelcast/src/main/java/com/hazelcast/map/proxy/ObjectMapProxy.java
|
/*
* Copyright (c) 2008-2013, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.map.proxy;
import com.hazelcast.core.EntryListener;
import com.hazelcast.core.EntryView;
import com.hazelcast.map.*;
import com.hazelcast.nio.serialization.Data;
import com.hazelcast.query.Predicate;
import com.hazelcast.spi.Invocation;
import com.hazelcast.spi.NodeEngine;
import com.hazelcast.spi.Operation;
import com.hazelcast.util.QueryResultStream;
import com.hazelcast.util.executor.DelegatingFuture;
import java.util.*;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import static com.hazelcast.map.MapService.SERVICE_NAME;
public class ObjectMapProxy<K, V> extends MapProxySupport implements MapProxy<K, V> {
public ObjectMapProxy(final String name, final MapService mapService, final NodeEngine nodeEngine) {
super(name, mapService, nodeEngine);
}
public V get(Object k) {
Data key = getService().toData(k);
return (V) getService().toObject(getInternal(key));
}
public V put(final K k, final V v) {
return put(k, v, -1, null);
}
public V put(final K k, final V v, final long ttl, final TimeUnit timeunit) {
final Data key = getService().toData(k);
final Data value = getService().toData(v);
final Data result = putInternal(key, value, ttl, timeunit);
return (V) getService().toObject(result);
}
public boolean tryPut(final K k, final V v, final long timeout, final TimeUnit timeunit) {
final Data key = getService().toData(k);
final Data value = getService().toData(v);
return tryPutInternal(key, value, timeout, timeunit);
}
public V putIfAbsent(final K k, final V v) {
return putIfAbsent(k, v, -1, null);
}
public V putIfAbsent(final K k, final V v, final long ttl, final TimeUnit timeunit) {
final Data key = getService().toData(k);
final Data value = getService().toData(v);
final Data result = putIfAbsentInternal(key, value, ttl, timeunit);
return (V) getService().toObject(result);
}
public void putTransient(final K k, final V v, final long ttl, final TimeUnit timeunit) {
final Data key = getService().toData(k);
final Data value = getService().toData(v);
putTransientInternal(key, value, ttl, timeunit);
}
public boolean replace(final K k, final V o, final V v) {
final Data key = getService().toData(k);
final Data oldValue = getService().toData(o);
final Data value = getService().toData(v);
return replaceInternal(key, oldValue, value);
}
public V replace(final K k, final V v) {
final Data key = getService().toData(k);
final Data value = getService().toData(v);
return (V) getService().toObject(replaceInternal(key, value));
}
public void set(K key, V value) {
set(key, value, -1, TimeUnit.MILLISECONDS);
}
public void set(final K k, final V v, final long ttl, final TimeUnit timeunit) {
final Data key = getService().toData(k);
final Data value = getService().toData(v);
setInternal(key, value, ttl, timeunit);
}
public V remove(Object k) {
final Data key = getService().toData(k);
final Data result = removeInternal(key);
return (V) getService().toObject(result);
}
public boolean remove(final Object k, final Object v) {
final Data key = getService().toData(k);
final Data value = getService().toData(v);
return removeInternal(key, value);
}
public void delete(Object k) {
final Data key = getService().toData(k);
deleteInternal(key);
}
public boolean containsKey(Object k) {
Data key = getService().toData(k);
return containsKeyInternal(key);
}
public boolean containsValue(final Object v) {
Data value = getService().toData(v);
return containsValueInternal(value);
}
public void lock(final K key) {
NodeEngine nodeEngine = getNodeEngine();
Data k = getService().toData(key);
lockSupport.lock(nodeEngine, k);
}
public void lock(final Object key, final long leaseTime, final TimeUnit timeUnit) {
lockSupport.lock(getNodeEngine(), getService().toData(key), timeUnit.toMillis(leaseTime));
}
public void unlock(final K key) {
NodeEngine nodeEngine = getNodeEngine();
Data k = getService().toData(key);
lockSupport.unlock(nodeEngine, k);
}
public boolean tryRemove(final K key, final long timeout, final TimeUnit timeunit) {
Data k = getService().toData(key);
return tryRemoveInternal(k, timeout, timeunit);
}
public Future<V> getAsync(final K k) {
Data key = getService().toData(k);
NodeEngine nodeEngine = getNodeEngine();
return new DelegatingFuture<V>(getAsyncInternal(key), nodeEngine.getSerializationService());
}
public boolean isLocked(final K k) {
Data key = getService().toData(k);
NodeEngine nodeEngine = getNodeEngine();
return lockSupport.isLocked(nodeEngine, key);
}
public Future putAsync(final K key, final V value) {
Data k = getService().toData(key);
Data v = getService().toData(value);
return new DelegatingFuture<V>(putAsyncInternal(k, v), getNodeEngine().getSerializationService());
}
public Future removeAsync(final K key) {
Data k = getService().toData(key);
return new DelegatingFuture<V>(removeAsyncInternal(k), getNodeEngine().getSerializationService());
}
public Map<K, V> getAll(final Set<K> keys) {
Set<Data> ks = new HashSet(keys.size());
for (K key : keys) {
Data k = getService().toData(key);
ks.add(k);
}
return (Map<K, V>) getAllObjectInternal(ks);
}
public void putAll(final Map<? extends K, ? extends V> m) {
putAllObjectInternal(m);
}
public boolean tryLock(final K key) {
final NodeEngine nodeEngine = getNodeEngine();
return lockSupport.tryLock(nodeEngine, getService().toData(key));
}
public boolean tryLock(final K key, final long time, final TimeUnit timeunit) throws InterruptedException {
final NodeEngine nodeEngine = getNodeEngine();
return lockSupport.tryLock(nodeEngine, getService().toData(key), time, timeunit);
}
public void forceUnlock(final K key) {
final NodeEngine nodeEngine = getNodeEngine();
Data k = getService().toData(key);
lockSupport.forceUnlock(nodeEngine, k);
}
public void addInterceptor(MapInterceptor interceptor) {
addMapInterceptorInternal(interceptor);
}
public void removeInterceptor(MapInterceptor interceptor) {
removeMapInterceptorInternal(interceptor);
}
public void addEntryListener(final EntryListener listener, final boolean includeValue) {
addEntryListenerInternal(listener, null, includeValue);
}
public void addEntryListener(final EntryListener<K, V> listener, final K key, final boolean includeValue) {
addEntryListenerInternal(listener, getService().toData(key), includeValue);
}
public void addEntryListener(EntryListener<K, V> listener, Predicate<K, V> predicate, K key, boolean includeValue) {
addEntryListenerInternal(listener, predicate, getService().toData(key), includeValue);
}
public void removeEntryListener(final EntryListener<K, V> listener) {
removeEntryListenerInternal(listener);
}
public void removeEntryListener(final EntryListener<K, V> listener, final K key) {
removeEntryListenerInternal(listener, getService().toData(key));
}
public EntryView<K, V> getEntryView(K key) {
SimpleEntryView<K, V> entryViewInternal = (SimpleEntryView) getEntryViewInternal(getService().toData(key));
Data value = (Data) entryViewInternal.getValue();
entryViewInternal.setKey(key);
entryViewInternal.setValue((V) getService().toObject(value));
return entryViewInternal;
}
public boolean evict(final Object key) {
return evictInternal(getService().toData(key));
}
public void clear() {
clearInternal();
}
public Set<K> keySet() {
final NodeEngine nodeEngine = getNodeEngine();
Set<Data> dataSet = keySetInternal();
HashSet<K> keySet = new HashSet<K>();
for (Data data : dataSet) {
keySet.add((K) getService().toObject(data));
}
return keySet;
}
public Collection<V> values() {
final NodeEngine nodeEngine = getNodeEngine();
Collection<Data> dataSet = valuesInternal();
Collection<V> valueSet = new ArrayList<V>();
for (Data data : dataSet) {
valueSet.add((V) getService().toObject(data));
}
return valueSet;
}
public Set entrySet() {
Set<Entry<Data, Data>> entries = entrySetInternal();
Set<Entry<K, V>> resultSet = new HashSet<Entry<K, V>>();
for (Entry<Data, Data> entry : entries) {
resultSet.add(new AbstractMap.SimpleImmutableEntry((K) getService().toObject(entry.getKey()), (V) getService().toObject(entry.getValue())));
}
return resultSet;
}
public Set<K> keySet(final Predicate predicate) {
return query(predicate, QueryResultStream.IterationType.KEY, false);
}
public Set entrySet(final Predicate predicate) {
return query(predicate, QueryResultStream.IterationType.ENTRY, false);
}
public Collection<V> values(final Predicate predicate) {
return query(predicate, QueryResultStream.IterationType.VALUE, false);
}
public Set<K> localKeySet() {
final Set<Data> dataSet = localKeySetInternal();
final Set<K> keySet = new HashSet<K>(dataSet.size());
for (Data data : dataSet) {
keySet.add((K) getService().toObject(data));
}
return keySet;
}
public Set<K> localKeySet(final Predicate predicate) {
// todo implement
return null;
}
public Object executeOnKey(K key, EntryProcessor entryProcessor) {
return getService().toObject(executeOnKeyInternal(getService().toData(key), entryProcessor));
}
protected Object invoke(Operation operation, int partitionId) throws Throwable {
NodeEngine nodeEngine = getNodeEngine();
Invocation invocation = nodeEngine.getOperationService().createInvocationBuilder(SERVICE_NAME, operation, partitionId).build();
Future f = invocation.invoke();
Object response = f.get();
Object returnObj = getService().toObject(response);
if (returnObj instanceof Throwable) {
throw (Throwable) returnObj;
}
return returnObj;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("IMap");
sb.append("{name='").append(name).append('\'');
sb.append('}');
return sb.toString();
}
}
|
map small fix
|
hazelcast/src/main/java/com/hazelcast/map/proxy/ObjectMapProxy.java
|
map small fix
|
|
Java
|
apache-2.0
|
36b5ea29331c4da722b9b6e5c81624fd8dffdcc5
| 0
|
rswijesena/carbon-apimgt,tharindu1st/carbon-apimgt,praminda/carbon-apimgt,pubudu538/carbon-apimgt,sineth-neranjana/carbon-apimgt,dewmini/carbon-apimgt,harsha89/carbon-apimgt,thusithak/carbon-apimgt,pubudu538/carbon-apimgt,uvindra/carbon-apimgt,sanjeewa-malalgoda/carbon-apimgt,jaadds/carbon-apimgt,ChamNDeSilva/carbon-apimgt,harsha89/carbon-apimgt,nuwand/carbon-apimgt,lakmali/carbon-apimgt,chamilaadhi/carbon-apimgt,isharac/carbon-apimgt,bhathiya/carbon-apimgt,uvindra/carbon-apimgt,isharac/carbon-apimgt,pubudu538/carbon-apimgt,tharikaGitHub/carbon-apimgt,sanjeewa-malalgoda/carbon-apimgt,sanjeewa-malalgoda/carbon-apimgt,ruks/carbon-apimgt,bhathiya/carbon-apimgt,lakmali/carbon-apimgt,pubudu538/carbon-apimgt,bhathiya/carbon-apimgt,sambaheerathan/carbon-apimgt,Rajith90/carbon-apimgt,nuwand/carbon-apimgt,rswijesena/carbon-apimgt,malinthaprasan/carbon-apimgt,jaadds/carbon-apimgt,malinthaprasan/carbon-apimgt,uvindra/carbon-apimgt,Arshardh/carbon-apimgt,Rajith90/carbon-apimgt,fazlan-nazeem/carbon-apimgt,praminda/carbon-apimgt,ChamNDeSilva/carbon-apimgt,Arshardh/carbon-apimgt,ChamNDeSilva/carbon-apimgt,wso2/carbon-apimgt,abimarank/carbon-apimgt,dewmini/carbon-apimgt,thusithak/carbon-apimgt,sambaheerathan/carbon-apimgt,tharindu1st/carbon-apimgt,jaadds/carbon-apimgt,chamindias/carbon-apimgt,tharikaGitHub/carbon-apimgt,chamilaadhi/carbon-apimgt,Rajith90/carbon-apimgt,tharindu1st/carbon-apimgt,hevayo/carbon-apimgt,ruks/carbon-apimgt,prasa7/carbon-apimgt,ruks/carbon-apimgt,tharikaGitHub/carbon-apimgt,tharikaGitHub/carbon-apimgt,fazlan-nazeem/carbon-apimgt,wso2/carbon-apimgt,Arshardh/carbon-apimgt,isharac/carbon-apimgt,dewmini/carbon-apimgt,nuwand/carbon-apimgt,tharindu1st/carbon-apimgt,hevayo/carbon-apimgt,Minoli/carbon-apimgt,chamilaadhi/carbon-apimgt,jaadds/carbon-apimgt,bhathiya/carbon-apimgt,harsha89/carbon-apimgt,sambaheerathan/carbon-apimgt,wso2/carbon-apimgt,abimarank/carbon-apimgt,prasa7/carbon-apimgt,malinthaprasan/carbon-apimgt,malinthaprasan/carbon-apimgt,chamindias/carbon-apimgt,hevayo/carbon-apimgt,prasa7/carbon-apimgt,sineth-neranjana/carbon-apimgt,ruks/carbon-apimgt,chamindias/carbon-apimgt,isharac/carbon-apimgt,Minoli/carbon-apimgt,harsha89/carbon-apimgt,rswijesena/carbon-apimgt,lalaji/carbon-apimgt,lalaji/carbon-apimgt,sanjeewa-malalgoda/carbon-apimgt,uvindra/carbon-apimgt,thusithak/carbon-apimgt,fazlan-nazeem/carbon-apimgt,fazlan-nazeem/carbon-apimgt,praminda/carbon-apimgt,lakmali/carbon-apimgt,abimarank/carbon-apimgt,Minoli/carbon-apimgt,prasa7/carbon-apimgt,Arshardh/carbon-apimgt,sineth-neranjana/carbon-apimgt,sineth-neranjana/carbon-apimgt,wso2/carbon-apimgt,chamindias/carbon-apimgt,hevayo/carbon-apimgt,nuwand/carbon-apimgt,lalaji/carbon-apimgt,Rajith90/carbon-apimgt,chamilaadhi/carbon-apimgt
|
/*
* Copyright (c) 2005-2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.apimgt.api;
import org.wso2.carbon.apimgt.api.model.API;
import org.wso2.carbon.apimgt.api.model.APIIdentifier;
import org.wso2.carbon.apimgt.api.model.Scope;
import org.wso2.carbon.apimgt.api.model.URITemplate;
import org.wso2.carbon.registry.api.Registry;
import java.util.Map;
import java.util.Set;
/**
* APIDefinition is responsible for providing uri templates, scopes and
* save the api definition according to the permission and visibility
*/
@SuppressWarnings("unused")
public abstract class APIDefinition {
/**
* This method extracts the URI templates from the API definition
*
* @return URI templates
*/
public abstract Set<URITemplate> getURITemplates(API api, String resourceConfigsJSON) throws APIManagementException;
/**
* This method extracts the scopes from the API definition
*
* @param resourceConfigsJSON resource json
* @return scopes
*/
public abstract Set<Scope> getScopes(String resourceConfigsJSON) throws APIManagementException;
/**
* This method saves the API definition
*
* @param api API to be saved
* @param apiDefinitionJSON API definition as JSON string
* @param registry user registry
*/
public abstract void saveAPIDefinition(API api, String apiDefinitionJSON, Registry registry) throws APIManagementException;
/**
* This method reads the API definition from registry
*
* @param apiIdentifier api identifier
* @param registry user registry
* @return API definition
*/
public abstract String getAPIDefinition(APIIdentifier apiIdentifier, Registry registry) throws APIManagementException;
/**
* This method generates API definition to the given api
*
* @param api api
* @return API definition in string format
* @throws APIManagementException
*/
public abstract String generateAPIDefinition(API api) throws APIManagementException;
/**
* This method returns the timestamps for a given API
* @param apiIdentifier
* @param registry
* @return
* @throws APIManagementException
*/
public abstract Map<String ,String> getAPISwaggerDefinitionTimeStamps(APIIdentifier apiIdentifier, Registry registry) throws APIManagementException;
}
|
components/apimgt/org.wso2.carbon.apimgt.api/src/main/java/org/wso2/carbon/apimgt/api/APIDefinition.java
|
/*
* Copyright (c) 2005-2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.apimgt.api;
import org.wso2.carbon.apimgt.api.model.API;
import org.wso2.carbon.apimgt.api.model.APIIdentifier;
import org.wso2.carbon.apimgt.api.model.Scope;
import org.wso2.carbon.apimgt.api.model.URITemplate;
import org.wso2.carbon.registry.api.Registry;
import java.util.Set;
/**
* APIDefinition is responsible for providing uri templates, scopes and
* save the api definition according to the permission and visibility
*/
@SuppressWarnings("unused")
public abstract class APIDefinition {
/**
* This method extracts the URI templates from the API definition
*
* @return URI templates
*/
public abstract Set<URITemplate> getURITemplates(API api, String resourceConfigsJSON) throws APIManagementException;
/**
* This method extracts the scopes from the API definition
*
* @param resourceConfigsJSON resource json
* @return scopes
*/
public abstract Set<Scope> getScopes(String resourceConfigsJSON) throws APIManagementException;
/**
* This method saves the API definition
*
* @param api API to be saved
* @param apiDefinitionJSON API definition as JSON string
* @param registry user registry
*/
public abstract void saveAPIDefinition(API api, String apiDefinitionJSON, Registry registry) throws APIManagementException;
/**
* This method reads the API definition from registry
*
* @param apiIdentifier api identifier
* @param registry user registry
* @return API definition
*/
public abstract String getAPIDefinition(APIIdentifier apiIdentifier, Registry registry) throws APIManagementException;
/**
* This method generates API definition to the given api
*
* @param api api
* @return API definition in string format
* @throws APIManagementException
*/
public abstract String generateAPIDefinition(API api) throws APIManagementException;
}
|
added getAPISwaggerDefinitionTimeStamps abstract method
|
components/apimgt/org.wso2.carbon.apimgt.api/src/main/java/org/wso2/carbon/apimgt/api/APIDefinition.java
|
added getAPISwaggerDefinitionTimeStamps abstract method
|
|
Java
|
bsd-2-clause
|
07ebc77202e824c47b692fde34c289708f72a4e1
| 0
|
henryx/yds
|
/*
* Copyright (C) 2010 Enrico Bianchi (enrico.bianchi@ymail.com)
* Project YDS
* Description The Yggdrasill Document Search - A java based file indexer
* License BSD (see LICENSE.BSD for details)
*/
package it.application.yds.fetch.streams;
import it.application.yds.Main;
import java.io.IOException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
/**
*
* @author enrico
*/
public class PdfStream extends Stream {
public PdfStream() {
super();
}
@Override
public String getStream() throws IOException {
PDDocument document;
PDFTextStripper stripper;
String result;
try {
stripper = new PDFTextStripper();
document = PDDocument.load(this.file);
result = stripper.getText(document);
document.close();
} catch (NullPointerException ex) {
Main.logger.error(null, ex);
result = "";
}
return result;
}
}
|
src/main/java/it/application/yds/fetch/streams/PdfStream.java
|
/*
* Copyright (C) 2010 Enrico Bianchi (enrico.bianchi@ymail.com)
* Project YDS
* Description The Yggdrasill Document Search - A java based file indexer
* License BSD (see LICENSE.BSD for details)
*/
package it.application.yds.fetch.streams;
import it.application.yds.Main;
import java.io.IOException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.util.PDFTextStripper;
/**
*
* @author enrico
*/
public class PdfStream extends Stream {
public PdfStream() {
super();
}
@Override
public String getStream() throws IOException {
PDDocument document;
PDFTextStripper stripper;
String result;
try {
stripper = new PDFTextStripper();
document = PDDocument.load(this.file);
result = stripper.getText(document);
document.close();
} catch (NullPointerException ex) {
Main.logger.error(null, ex);
result = "";
}
return result;
}
}
|
Fixed code
|
src/main/java/it/application/yds/fetch/streams/PdfStream.java
|
Fixed code
|
|
Java
|
bsd-3-clause
|
88da4c7055b999bc64e51fe2a8cf79a112d17e4f
| 0
|
ndexbio/ndex-rest,ndexbio/ndex-rest,ndexbio/ndex-rest,ndexbio/ndex-rest
|
/**
* Copyright (c) 2013, 2016, The Regents of the University of California, The Cytoscape Consortium
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
package org.ndexbio.rest.services;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.nio.file.attribute.FileAttribute;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.PosixFilePermissions;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import javax.annotation.security.PermitAll;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
import org.apache.commons.io.FileUtils;
import org.apache.solr.client.solrj.SolrServerException;
import org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataInput;
import org.ndexbio.common.NdexClasses;
import org.ndexbio.common.cx.CX2NetworkFileGenerator;
import org.ndexbio.common.cx.CXNetworkFileGenerator;
import org.ndexbio.common.models.dao.postgresql.NetworkDAO;
import org.ndexbio.common.models.dao.postgresql.UserDAO;
import org.ndexbio.common.persistence.CX2NetworkLoader;
import org.ndexbio.common.persistence.CXNetworkAspectsUpdater;
import org.ndexbio.common.persistence.CXNetworkLoader;
import org.ndexbio.common.util.NdexUUIDFactory;
import org.ndexbio.common.util.Util;
import org.ndexbio.cx2.aspect.element.core.CxAttributeDeclaration;
import org.ndexbio.cx2.aspect.element.core.CxMetadata;
import org.ndexbio.cx2.aspect.element.core.CxNetworkAttribute;
import org.ndexbio.cx2.converter.AspectAttributeStat;
import org.ndexbio.cx2.converter.CXToCX2Converter;
import org.ndexbio.cx2.io.CX2AspectWriter;
import org.ndexbio.cxio.aspects.datamodels.ATTRIBUTE_DATA_TYPE;
import org.ndexbio.cxio.aspects.datamodels.NetworkAttributesElement;
import org.ndexbio.cxio.core.CXAspectWriter;
import org.ndexbio.cxio.core.OpaqueAspectIterator;
import org.ndexbio.cxio.metadata.MetaDataCollection;
import org.ndexbio.cxio.metadata.MetaDataElement;
import org.ndexbio.cxio.util.JsonWriter;
import org.ndexbio.model.exceptions.BadRequestException;
import org.ndexbio.model.exceptions.ForbiddenOperationException;
import org.ndexbio.model.exceptions.InvalidNetworkException;
import org.ndexbio.model.exceptions.NdexException;
import org.ndexbio.model.exceptions.NetworkConcurrentModificationException;
import org.ndexbio.model.exceptions.ObjectNotFoundException;
import org.ndexbio.model.exceptions.UnauthorizedOperationException;
import org.ndexbio.model.object.NdexPropertyValuePair;
import org.ndexbio.model.object.Permissions;
import org.ndexbio.model.object.ProvenanceEntity;
import org.ndexbio.model.object.User;
import org.ndexbio.model.object.network.NetworkIndexLevel;
import org.ndexbio.model.object.network.NetworkSummary;
import org.ndexbio.model.object.network.VisibilityType;
import org.ndexbio.rest.Configuration;
import org.ndexbio.rest.filters.BasicAuthenticationFilter;
import org.ndexbio.task.CXNetworkLoadingTask;
import org.ndexbio.task.NdexServerQueue;
import org.ndexbio.task.SolrIndexScope;
import org.ndexbio.task.SolrTaskDeleteNetwork;
import org.ndexbio.task.SolrTaskRebuildNetworkIdx;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
@Path("/v2/network")
public class NetworkServiceV2 extends NdexService {
// static Logger logger = LoggerFactory.getLogger(NetworkService.class);
static Logger accLogger = LoggerFactory.getLogger(BasicAuthenticationFilter.accessLoggerName);
static private final String readOnlyParameter = "readOnly";
private static final String cx1NetworkFileName = "network.cx";
public NetworkServiceV2(@Context HttpServletRequest httpRequest
// @Context org.jboss.resteasy.spi.HttpResponse response
) {
super(httpRequest);
}
/**************************************************************************
* Returns network provenance.
* @throws IOException
* @throws JsonMappingException
* @throws JsonParseException
* @throws NdexException
* @throws SQLException
*
**************************************************************************/
@PermitAll
@GET
@Path("/{networkid}/provenance")
@Produces("application/json")
public ProvenanceEntity getProvenance(
@PathParam("networkid") final String networkIdStr,
@QueryParam("accesskey") String accessKey)
throws IllegalArgumentException, JsonParseException, JsonMappingException, IOException, NdexException, SQLException {
UUID networkId = UUID.fromString(networkIdStr);
try (NetworkDAO daoNew = new NetworkDAO()) {
if ( !daoNew.isReadable(networkId, getLoggedInUserId()) && (!daoNew.accessKeyIsValid(networkId, accessKey)))
throw new UnauthorizedOperationException("Network " + networkId + " is not readable to this user.");
return daoNew.getProvenance(networkId);
}
}
/**************************************************************************
* Updates network provenance.
* @throws Exception
*
**************************************************************************/
@PUT
@Path("/{networkid}/provenance")
@Produces("application/json")
public void setProvenance(@PathParam("networkid")final String networkIdStr, final ProvenanceEntity provenance)
throws Exception {
User user = getLoggedInUser();
setProvenance_aux(networkIdStr, provenance, user);
}
@Deprecated
protected static void setProvenance_aux(final String networkIdStr, final ProvenanceEntity provenance, User user)
throws Exception {
try (NetworkDAO daoNew = new NetworkDAO()){
UUID networkId = UUID.fromString(networkIdStr);
if ( !daoNew.isWriteable(networkId, user.getExternalId())) {
throw new UnauthorizedOperationException("User doesn't have write permissions for this network.");
}
if(daoNew.isReadOnly(networkId)) {
daoNew.close();
throw new NdexException ("Can't update readonly network.");
}
if (!daoNew.networkIsValid(networkId))
throw new InvalidNetworkException();
/* if ( daoNew.networkIsLocked(networkId,6)) {
daoNew.close();
throw new NetworkConcurrentModificationException ();
}
daoNew.lockNetwork(networkId); */
daoNew.setProvenance(networkId, provenance);
daoNew.commit();
//Recreate the CX file
// NetworkSummary fullSummary = daoNew.getNetworkSummaryById(networkId);
// MetaDataCollection metadata = daoNew.getMetaDataCollection(networkId);
// CXNetworkFileGenerator g = new CXNetworkFileGenerator(networkId, daoNew, new Provenance(provenance));
// g.reCreateCXFile();
// daoNew.unlockNetwork(networkId);
return ; // provenance; // daoNew.getProvenance(networkUUID);
} catch (Exception e) {
//if (null != daoNew) daoNew.rollback();
throw e;
}
}
/**************************************************************************
* Sets network properties.
* @throws Exception
*
**************************************************************************/
@PUT
@Path("/{networkid}/properties")
@Produces("application/json")
public int setNetworkProperties(
@PathParam("networkid")final String networkId,
final List<NdexPropertyValuePair> properties)
throws Exception {
User user = getLoggedInUser();
UUID networkUUID = UUID.fromString(networkId);
try (NetworkDAO daoNew = new NetworkDAO()) {
if(daoNew.isReadOnly(networkUUID)) {
throw new NdexException ("Can't update readonly network.");
}
if ( !daoNew.isWriteable(networkUUID, user.getExternalId())) {
throw new UnauthorizedOperationException("User doesn't have write permissions for this network.");
}
if ( daoNew.networkIsLocked(networkUUID,10)) {
throw new NetworkConcurrentModificationException ();
}
if ( !daoNew.networkIsValid(networkUUID))
throw new InvalidNetworkException();
daoNew.lockNetwork(networkUUID);
int i = 0;
try {
i = daoNew.setNetworkProperties(networkUUID, properties);
// recreate files and update db
updateNetworkAttributesAspect(daoNew, networkUUID);
} finally {
daoNew.unlockNetwork(networkUUID);
}
NetworkIndexLevel idxLvl = daoNew.getIndexLevel(networkUUID);
if ( idxLvl != NetworkIndexLevel.NONE) {
daoNew.setFlag(networkUUID, "iscomplete",false);
daoNew.commit();
NdexServerQueue.INSTANCE.addSystemTask(new SolrTaskRebuildNetworkIdx(networkUUID,SolrIndexScope.global,false,null,idxLvl,false));
} else {
daoNew.setFlag(networkUUID, "iscomplete", true);
daoNew.commit();
}
return i;
} catch (Exception e) {
//logger.severe("Error occurred when update network properties: " + e.getMessage());
//e.printStackTrace();
//if (null != daoNew) daoNew.rollback();
logger.error("Updating properties of network {}. Exception caught:]{}", networkId, e);
throw new NdexException(e.getMessage(), e);
}
}
/*
*
* Operations returning Networks
*
*/
@PermitAll
@GET
@Path("/{networkid}/summary")
@Produces("application/json")
public NetworkSummary getNetworkSummary(
@PathParam("networkid") final String networkIdStr ,
@QueryParam("accesskey") String accessKey /*,
@Context org.jboss.resteasy.spi.HttpResponse response*/)
throws IllegalArgumentException, NdexException, SQLException, JsonParseException, JsonMappingException, IOException {
try (NetworkDAO dao = new NetworkDAO()) {
UUID userId = getLoggedInUserId();
UUID networkId = UUID.fromString(networkIdStr);
if ( dao.isReadable(networkId, userId) || dao.accessKeyIsValid(networkId, accessKey)) {
NetworkSummary summary = dao.getNetworkSummaryById(networkId);
return summary;
}
throw new UnauthorizedOperationException ("Unauthorized access to network " + networkId);
}
}
@PermitAll
@GET
@Path("/{networkid}/aspect")
public Response getNetworkCXMetadataCollection( @PathParam("networkid") final String networkId,
@QueryParam("accesskey") String accessKey)
throws Exception {
logger.info("[start: Getting CX metadata from network {}]", networkId);
UUID networkUUID = UUID.fromString(networkId);
try (NetworkDAO dao = new NetworkDAO() ) {
if ( dao.isReadable(networkUUID, getLoggedInUserId()) || dao.accessKeyIsValid(networkUUID, accessKey)) {
MetaDataCollection mdc = dao.getMetaDataCollection(networkUUID);
logger.info("[end: Return CX metadata from network {}]", networkId);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
JsonWriter wtr = JsonWriter.createInstance(baos,true);
mdc.toJson(wtr);
String s = baos.toString();//"java.nio.charset.StandardCharsets.UTF_8");
return Response.ok().type(MediaType.APPLICATION_JSON_TYPE).entity(s).build();
// return mdc;
}
throw new UnauthorizedOperationException("User doesn't have access to this network.");
}
}
@PermitAll
@GET
@Path("/{networkid}/aspect/{aspectname}/metadata")
@Produces("application/json")
public MetaDataElement getNetworkCXMetadata(
@PathParam("networkid") final String networkId,
@PathParam("aspectname") final String aspectName
)
throws Exception {
logger.info("[start: Getting {} metadata from network {}]", aspectName, networkId);
UUID networkUUID = UUID.fromString(networkId);
try (NetworkDAO dao = new NetworkDAO() ) {
if ( dao.isReadable(networkUUID, getLoggedInUserId())) {
MetaDataCollection mdc = dao.getMetaDataCollection(networkUUID);
logger.info("[end: Return CX metadata from network {}]", networkId);
return mdc.getMetaDataElement(aspectName);
}
throw new UnauthorizedOperationException("User doesn't have access to this network.");
}
}
@PermitAll
@GET
@Path("/{networkid}/aspect/{aspectname}")
public Response getAspectElements( @PathParam("networkid") final String networkId,
@PathParam("aspectname") final String aspectName,
@DefaultValue("-1") @QueryParam("size") int limit) throws SQLException, NdexException
{
logger.info("[start: Getting one aspect in network {}]", networkId);
UUID networkUUID = UUID.fromString(networkId);
try (NetworkDAO dao = new NetworkDAO()) {
if ( !dao.isReadable(networkUUID, getLoggedInUserId())) {
throw new UnauthorizedOperationException("User doesn't have access to this network.");
}
File cx1AspectDir = new File (Configuration.getInstance().getNdexRoot() + "/data/" + networkId
+ "/" + CXNetworkLoader.CX1AspectDir);
boolean hasCX1AspDir = cx1AspectDir.exists();
FileInputStream in = null;
try {
if ( hasCX1AspDir) {
in = new FileInputStream(cx1AspectDir + "/" + aspectName);
if ( limit <= 0) {
return Response.ok().type(MediaType.APPLICATION_JSON_TYPE).entity(in).build();
}
PipedInputStream pin = new PipedInputStream();
PipedOutputStream out;
try {
out = new PipedOutputStream(pin);
} catch (IOException e) {
try {
pin.close();
in.close();
} catch (IOException e1) {
e1.printStackTrace();
}
throw new NdexException("IOExcetion when creating the piped output stream: "+ e.getMessage());
}
new CXAspectElementsWriterThread(out,in, /*aspectName,*/ limit).start();
// logger.info("[end: Return get one aspect in network {}]", networkId);
return Response.ok().type(MediaType.APPLICATION_JSON_TYPE).entity(pin).build();
}
} catch (FileNotFoundException e) {
throw new ObjectNotFoundException("Aspect "+ aspectName + " not found in this network: " + e.getMessage());
}
//get aspect from cx2 aspects
PipedInputStream pin = new PipedInputStream();
PipedOutputStream out;
try {
out = new PipedOutputStream(pin);
} catch (IOException e) {
try {
pin.close();
} catch (IOException e1) {
e1.printStackTrace();
}
throw new NdexException("IOExcetion when creating the piped output stream: "+ e.getMessage());
}
new CXAspectElementWriter2Thread(out,networkId, aspectName, limit, accLogger).start();
// logger.info("[end: Return get one aspect in network {}]", networkId);
return Response.ok().type(MediaType.APPLICATION_JSON_TYPE).entity(pin).build();
}
}
@PermitAll
@GET
@Path("/{networkid}")
public Response getCompleteNetworkAsCX( @PathParam("networkid") final String networkId,
@QueryParam("download") boolean isDownload,
@QueryParam("accesskey") String accessKey,
@QueryParam("id_token") String id_token,
@QueryParam("auth_token") String auth_token)
throws Exception {
String title = null;
try (NetworkDAO dao = new NetworkDAO()) {
UUID networkUUID = UUID.fromString(networkId);
UUID userId = getLoggedInUserId();
if ( userId == null ) {
if ( auth_token != null) {
userId = getUserIdFromBasicAuthString(auth_token);
} else if ( id_token !=null) {
if ( getGoogleAuthenticator() == null)
throw new UnauthorizedOperationException("Google OAuth is not enabled on this server.");
userId = getGoogleAuthenticator().getUserUUIDByIdToken(id_token);
}
}
if ( ! dao.isReadable(networkUUID, userId) && (!dao.accessKeyIsValid(networkUUID, accessKey)))
throw new UnauthorizedOperationException("User doesn't have read access to this network.");
title = dao.getNetworkName(networkUUID);
}
String cxFilePath = Configuration.getInstance().getNdexRoot() + "/data/" + networkId + "/" + cx1NetworkFileName;
try {
FileInputStream in = new FileInputStream(cxFilePath) ;
// setZipFlag();
logger.info("[end: Return network {}]", networkId);
ResponseBuilder r = Response.ok();
if (isDownload) {
if (title == null || title.length() < 1) {
title = networkId;
}
title.replace('"', '_');
r.header("Content-Disposition", "attachment; filename=\"" + title + ".cx\"");
r.header("Access-Control-Expose-Headers", "Content-Disposition");
}
return r.type(isDownload ? MediaType.APPLICATION_OCTET_STREAM_TYPE : MediaType.APPLICATION_JSON_TYPE)
.entity(in).build();
} catch (IOException e) {
logger.error("[end: Ndex server can't find file: {}]", e.getMessage());
throw new NdexException ("Ndex server can't find file: " + e.getMessage());
}
}
@PermitAll
@GET
@Path("/{networkid}/sample")
public Response getSampleNetworkAsCX( @PathParam("networkid") final String networkIdStr ,
@QueryParam("accesskey") String accessKey)
throws IllegalArgumentException, NdexException, SQLException {
UUID networkId = UUID.fromString(networkIdStr);
try (NetworkDAO dao = new NetworkDAO()) {
if ( ! dao.isReadable(networkId, getLoggedInUserId()) && (!dao.accessKeyIsValid(networkId, accessKey)))
throw new UnauthorizedOperationException("User doesn't have read access to this network.");
}
String cxFilePath = Configuration.getInstance().getNdexRoot() + "/data/" + networkId + "/sample.cx";
try {
FileInputStream in = new FileInputStream(cxFilePath) ;
// setZipFlag();
return Response.ok().type(MediaType.APPLICATION_JSON_TYPE).entity(in).build();
} catch ( FileNotFoundException e) {
throw new ObjectNotFoundException("Sample network of " + networkId + " not found. Error: " + e.getMessage());
}
}
@GET
@Path("/{networkid}/accesskey")
@Produces("application/json")
public Map<String,String> getNetworkAccessKey(@PathParam("networkid") final String networkIdStr)
throws IllegalArgumentException, NdexException, SQLException {
UUID networkId = UUID.fromString(networkIdStr);
try (NetworkDAO dao = new NetworkDAO()) {
if ( ! dao.isAdmin(networkId, getLoggedInUserId()))
throw new UnauthorizedOperationException("User is not admin of this network.");
String key = dao.getNetworkAccessKey(networkId);
if (key == null || key.length()==0)
return null;
Map<String,String> result = new HashMap<>(1);
result.put("accessKey", key);
return result;
}
}
@PUT
@Path("/{networkid}/accesskey")
@Produces("application/json")
public Map<String,String> disableEnableNetworkAccessKey(@PathParam("networkid") final String networkIdStr,
@QueryParam("action") String action)
throws IllegalArgumentException, NdexException, SQLException {
UUID networkId = UUID.fromString(networkIdStr);
if ( ! action.equalsIgnoreCase("disable") && ! action.equalsIgnoreCase("enable"))
throw new NdexException("Value of 'action' paramter can only be 'disable' or 'enable'");
try (NetworkDAO dao = new NetworkDAO()) {
if ( ! dao.isAdmin(networkId, getLoggedInUserId()))
throw new UnauthorizedOperationException("User is not admin of this network.");
String key = null;
if ( action.equalsIgnoreCase("disable"))
dao.disableNetworkAccessKey(networkId);
else
key = dao.enableNetworkAccessKey(networkId);
dao.commit();
if (key == null || key.length()==0)
return null;
Map<String,String> result = new HashMap<>(1);
result.put("accessKey", key);
return result;
}
}
@PUT
@Path("/{networkid}/sample")
public void setSampleNetwork( @PathParam("networkid") final String networkId,
String CXString)
throws IllegalArgumentException, NdexException, SQLException, InterruptedException {
UUID networkUUID = UUID.fromString(networkId);
try (NetworkDAO dao = new NetworkDAO()) {
if (!dao.isAdmin(networkUUID, getLoggedInUserId()))
throw new UnauthorizedOperationException("User is not admin of this network.");
if (dao.networkIsLocked(networkUUID, 10))
throw new NetworkConcurrentModificationException();
if (!dao.networkIsValid(networkUUID))
throw new InvalidNetworkException();
String cxFilePath = Configuration.getInstance().getNdexRoot() + "/data/" + networkId + "/sample.cx";
try (FileWriter w = new FileWriter(cxFilePath)) {
w.write(CXString);
dao.setFlag(networkUUID, "has_sample", true);
dao.commit();
} catch (IOException e) {
throw new NdexException("Failed to write sample network of " + networkId + ": " + e.getMessage(), e);
}
}
}
private class CXAspectElementsWriterThread extends Thread {
private OutputStream o;
// private String networkId;
private FileInputStream in;
// private String aspect;
private int limit;
public CXAspectElementsWriterThread (OutputStream out, FileInputStream inputStream, /*String aspectName,*/ int limit) {
o = out;
// this.networkId = networkId;
// aspect = aspectName;
this.limit = limit;
in = inputStream;
}
@Override
public void run() {
try {
OpaqueAspectIterator asi = new OpaqueAspectIterator(in);
try (CXAspectWriter wtr = new CXAspectWriter (o)) {
for ( int i = 0 ; i < limit && asi.hasNext() ; i++) {
wtr.writeCXElement(asi.next());
}
}
} catch (IOException e) {
logger.error("IOException in CXAspectElementWriterThread: " + e.getMessage());
} catch (Exception e1) {
logger.error("Ndex exception: " + e1.getMessage());
} finally {
try {
o.flush();
o.close();
} catch (IOException e) {
logger.error("Failed to close outputstream in CXElementWriterWriterThread");
e.printStackTrace();
}
}
}
}
/**************************************************************************
* Retrieves array of user membership objects
*
* @param networkId
* The network ID.
* @throws IllegalArgumentException
* Bad input.
* @throws ObjectNotFoundException
* The group doesn't exist.
* @throws NdexException
* Failed to query the database.
* @throws SQLException
**************************************************************************/
@GET
@Path("/{networkid}/permission")
@Produces("application/json")
public Map<String, String> getNetworkUserMemberships(
@PathParam("networkid") final String networkId,
@QueryParam("type") String sourceType,
@QueryParam("permission") final String permissions ,
@DefaultValue("0") @QueryParam("start") int skipBlocks,
@DefaultValue("100") @QueryParam("size") int blockSize) throws NdexException, SQLException {
Permissions permission = null;
if ( permissions != null ){
permission = Permissions.valueOf(permissions.toUpperCase());
}
UUID networkUUID = UUID.fromString(networkId);
boolean returnUsers = true;
if ( sourceType != null ) {
if ( sourceType.toLowerCase().equals("group"))
returnUsers = false;
else if ( !sourceType.toLowerCase().equals("user"))
throw new NdexException("Invalid parameter 'type' " + sourceType + " received, it can only be 'user' or 'group'.");
} else
throw new NdexException("Parameter 'type' is required in this function.");
try (NetworkDAO networkDao = new NetworkDAO()) {
if ( !networkDao.isAdmin(networkUUID, getLoggedInUserId()) )
throw new UnauthorizedOperationException("Authenticate user is not the admin of this network.");
Map<String,String> result = returnUsers?
networkDao.getNetworkUserPermissions(networkUUID, permission, skipBlocks, blockSize):
networkDao.getNetworkGroupPermissions(networkUUID,permission,skipBlocks,blockSize);
return result;
}
}
@DELETE
@Path("/{networkid}/permission")
@Produces("application/json")
public int deleteNetworkPermission(
@PathParam("networkid") final String networkIdStr,
@QueryParam("userid") String userIdStr,
@QueryParam("groupid") String groupIdStr
)
throws IllegalArgumentException, NdexException, IOException, SQLException {
UUID networkId = UUID.fromString(networkIdStr);
UUID userId = null;
if ( userIdStr != null)
userId = UUID.fromString(userIdStr);
UUID groupId = null;
if ( groupIdStr != null)
groupId = UUID.fromString(groupIdStr);
if ( userId == null && groupId == null)
throw new NdexException ("Either userid or groupid parameter need to be set for this function.");
if ( userId !=null && groupId != null)
throw new NdexException ("userid and gorupid can't both be set for this function.");
try (NetworkDAO networkDao = new NetworkDAO()){
// User user = getLoggedInUser();
// networkDao.checkPermissionOperationCondition(networkId, user.getExternalId());
if (!networkDao.isAdmin(networkId,getLoggedInUserId())) {
if ( userId != null && !userId.equals(getLoggedInUserId())) {
throw new UnauthorizedOperationException("Unable to delete network permisison: user need to be admin of this network or grantee of this permission.");
}
if ( groupId!=null ) {
throw new UnauthorizedOperationException("Unable to delete network permission: user is not an admin of this network.");
}
}
if( !networkDao.networkIsValid(networkId))
throw new InvalidNetworkException();
int count;
if ( userId !=null)
count = networkDao.revokeUserPrivilege(networkId, userId);
else
count = networkDao.revokeGroupPrivilege(networkId, groupId);
// update the solr Index
NetworkIndexLevel lvl = networkDao.getIndexLevel(networkId);
if ( lvl != NetworkIndexLevel.NONE) {
networkDao.setFlag(networkId, "iscomplete", false);
networkDao.commit();
NdexServerQueue.INSTANCE.addSystemTask(new SolrTaskRebuildNetworkIdx(networkId,SolrIndexScope.global,false,null,lvl, false));
}
return count;
}
}
/*
*
* Operations on Network permissions
*
*/
@PUT
@Path("/{networkid}/permission")
@Produces("application/json")
public int updateNetworkPermission(
@PathParam("networkid") final String networkIdStr,
@QueryParam("userid") String userIdStr,
@QueryParam("groupid") String groupIdStr,
@QueryParam("permission") final String permissions
)
throws IllegalArgumentException, NdexException, IOException, SQLException {
logger.info("[start: Updating membership for network {}]", networkIdStr);
UUID networkId = UUID.fromString(networkIdStr);
UUID userId = null;
if ( userIdStr != null)
userId = UUID.fromString(userIdStr);
UUID groupId = null;
if ( groupIdStr != null)
groupId = UUID.fromString(groupIdStr);
if ( userId == null && groupId == null)
throw new NdexException ("Either userid or groupid parameter need to be set for this function.");
if ( userId !=null && groupId != null)
throw new NdexException ("userid and gorupid can't both be set for this function.");
if ( permissions == null)
throw new NdexException ("permission parameter is required in this function.");
Permissions p = Permissions.valueOf(permissions.toUpperCase());
try (NetworkDAO networkDao = new NetworkDAO()){
User user = getLoggedInUser();
if (!networkDao.isAdmin(networkId,user.getExternalId())) {
throw new UnauthorizedOperationException("Unable to update network permission: user is not an admin of this network.");
}
if ( !networkDao.networkIsValid(networkId))
throw new InvalidNetworkException();
int count;
if ( userId!=null) {
count = networkDao.grantPrivilegeToUser(networkId, userId, p);
} else
count = networkDao.grantPrivilegeToGroup(networkId, groupId, p);
//networkDao.commit();
// update the solr Index
NetworkIndexLevel lvl = networkDao.getIndexLevel(networkId);
if ( lvl != NetworkIndexLevel.NONE) {
networkDao.setFlag(networkId, "iscomplete", false);
networkDao.commit();
NdexServerQueue.INSTANCE.addSystemTask(new SolrTaskRebuildNetworkIdx(networkId,SolrIndexScope.global,false,null,lvl, false));
}
logger.info("[end: Updated permission for network {}]", networkId);
return count;
}
}
@PUT
@Path("/{networkid}/reference")
@Produces("application/json")
public void updateReferenceOnPreCertifiedNetwork(@PathParam("networkid") final String networkId,
Map<String,String> reference) throws SQLException, NdexException, SolrServerException, IOException {
UUID networkUUID = UUID.fromString(networkId);
UUID userId = getLoggedInUser().getExternalId();
if ( reference.get("reference") == null) {
throw new BadRequestException("Field reference is missing in the object.");
}
try (NetworkDAO networkDao = new NetworkDAO()){
if(networkDao.isAdmin(networkUUID, userId) ) {
if ( networkDao.hasDOI(networkUUID) && (!networkDao.isCertified(networkUUID)) ) {
List<NdexPropertyValuePair> props = networkDao.getNetworkSummaryById(networkUUID).getProperties();
boolean updated= false;
for ( NdexPropertyValuePair p : props ) {
if ( p.getPredicateString().equals("reference")) {
p.setValue(reference.get("reference"));
updated=true;
break;
}
}
if ( !updated) {
props.add(new NdexPropertyValuePair("reference", reference.get("reference")));
}
networkDao.lockNetwork(networkUUID);
networkDao.updateNetworkProperties(networkUUID,props);
// recreate files and update db
updateNetworkAttributesAspect(networkDao, networkUUID);
networkDao.unlockNetwork(networkUUID);
networkDao.updateNetworkVisibility(networkUUID, VisibilityType.PUBLIC, true);
//networkDao.setFlag(networkUUID, "solr_indexed", true);
networkDao.setIndexLevel(networkUUID, NetworkIndexLevel.ALL);
networkDao.setFlag(networkUUID, "certified", true);
networkDao.setFlag(networkUUID, "iscomplete", false);
networkDao.commit();
NdexServerQueue.INSTANCE.addSystemTask(new SolrTaskRebuildNetworkIdx(networkUUID,SolrIndexScope.global,false,null,NetworkIndexLevel.ALL, false));
} else {
if ( networkDao.isCertified(networkUUID))
throw new ForbiddenOperationException("This network has already been certified, updating reference is not allowed.");
throw new ForbiddenOperationException("This network doesn't have a DOI or a pending DOI request.");
}
}
}
}
@PUT
@Path("/{networkid}/profile")
@Produces("application/json")
public void updateNetworkProfile(
@PathParam("networkid") final String networkId,
final NetworkSummary partialSummary
)
throws NdexException, SQLException , IOException, IllegalArgumentException
{
try (NetworkDAO networkDao = new NetworkDAO()){
User user = getLoggedInUser();
UUID networkUUID = UUID.fromString(networkId);
if(networkDao.isReadOnly(networkUUID)) {
throw new NdexException ("Can't update readonly network.");
}
if ( !networkDao.isWriteable(networkUUID, user.getExternalId())) {
throw new UnauthorizedOperationException("User doesn't have write permissions for this network.");
}
Map<String,String> newValues = new HashMap<> ();
// List<SimplePropertyValuePair> entityProperties = new ArrayList<>();
if ( partialSummary.getName() != null) {
newValues.put(NdexClasses.Network_P_name, partialSummary.getName());
// entityProperties.add( new SimplePropertyValuePair("dc:title", partialSummary.getName()) );
}
if ( partialSummary.getDescription() != null) {
newValues.put( NdexClasses.Network_P_desc, partialSummary.getDescription());
// entityProperties.add( new SimplePropertyValuePair("description", partialSummary.getDescription()) );
}
if ( partialSummary.getVersion()!=null ) {
newValues.put( NdexClasses.Network_P_version, partialSummary.getVersion());
// entityProperties.add( new SimplePropertyValuePair("version", partialSummary.getVersion()) );
}
if ( newValues.size() > 0 ) {
if (!networkDao.networkIsValid(networkUUID))
throw new InvalidNetworkException();
try {
if ( networkDao.networkIsLocked(networkUUID,10)) {
throw new NetworkConcurrentModificationException ();
}
} catch (InterruptedException e2) {
e2.printStackTrace();
throw new NdexException("Failed to check network lock: " + e2.getMessage());
}
try {
networkDao.lockNetwork(networkUUID);
networkDao.updateNetworkProfile(networkUUID, newValues);
// recreate files and update db
updateNetworkAttributesAspect(networkDao, networkUUID);
networkDao.unlockNetwork(networkUUID);
// update the solr Index
NetworkIndexLevel lvl = networkDao.getIndexLevel(networkUUID);
if ( lvl != NetworkIndexLevel.NONE) {
networkDao.setFlag(networkUUID, "iscomplete", false);
networkDao.commit();
NdexServerQueue.INSTANCE.addSystemTask(new SolrTaskRebuildNetworkIdx(networkUUID,SolrIndexScope.global,false,null,lvl, false));
} else {
networkDao.setFlag(networkUUID, "iscomplete", true);
networkDao.commit();
}
} catch ( SQLException | IOException | IllegalArgumentException |NdexException e ) {
networkDao.rollback();
try {
networkDao.unlockNetwork(networkUUID);
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
throw e;
}
}
}
}
/**
*
* @param pathPrefix path of the directory that has the CxAttributeDeclaration aspect file.
* It should end with "/"
* @return the declaration object. null if network has no attributes declared.
* @throws JsonParseException
* @throws JsonMappingException
* @throws IOException
*/
protected static CxAttributeDeclaration getAttrDeclarations(String pathPrefix) throws JsonParseException, JsonMappingException, IOException {
File attrDeclF = new File ( pathPrefix + CxAttributeDeclaration.ASPECT_NAME);
CxAttributeDeclaration[] declarations = null;
if ( attrDeclF.exists() ) {
ObjectMapper om = new ObjectMapper();
declarations = om.readValue(attrDeclF, CxAttributeDeclaration[].class);
}
if ( declarations != null)
return declarations[0];
return null;
}
// update the networkAttributes aspect file and also update the metadata in the db.
protected static void updateNetworkAttributesAspect(NetworkDAO networkDao, UUID networkUUID) throws JsonParseException, JsonMappingException, SQLException, IOException, NdexException {
NetworkSummary fullSummary = networkDao.getNetworkSummaryById(networkUUID);
String fileStoreDir = Configuration.getInstance().getNdexRoot() + "/data/" + networkUUID.toString() + "/";
String aspectFilePath = fileStoreDir + CXNetworkLoader.CX1AspectDir + "/" + NetworkAttributesElement.ASPECT_NAME;
String cx2AspectDirPath = fileStoreDir + CX2NetworkLoader.cx2AspectDirName + "/";
boolean isSingleNetwork = fullSummary.getSubnetworkIds().isEmpty();
//update the networkAttributes aspect in cx and cx2
List<NetworkAttributesElement> attrs = getNetworkAttributeAspectsFromSummary(fullSummary);
CxAttributeDeclaration networkAttrDecl = null;
if ( attrs.size() > 0 ) {
AspectAttributeStat attributeStats = new AspectAttributeStat();
CxNetworkAttribute cx2NetAttr = new CxNetworkAttribute();
// write cx network attribute aspect file.
try (CXAspectWriter writer = new CXAspectWriter(aspectFilePath) ) {
for ( NetworkAttributesElement e : attrs) {
writer.writeCXElement(e);
writer.flush();
if ( isSingleNetwork) {
attributeStats.addNetworkAttribute(e);
Object attrValue = CXToCX2Converter.convertAttributeValue(e);
Object oldV = cx2NetAttr.getAttributes().put(e.getName(), attrValue);
if ( oldV !=null)
throw new NdexException("Duplicated network attribute name found: " + e.getName());
}
}
}
// write cx2 network attribute aspect file
if ( isSingleNetwork) {
networkAttrDecl = attributeStats.createCxDeclaration();
try (CX2AspectWriter<CxNetworkAttribute> aspWtr = new CX2AspectWriter<>(cx2AspectDirPath + CxNetworkAttribute.ASPECT_NAME)) {
aspWtr.writeCXElement(cx2NetAttr);
}
}
} else { // remove the aspect file if it exists
File f = new File ( aspectFilePath);
if ( f.exists())
f.delete();
if ( isSingleNetwork) {
f = new File(cx2AspectDirPath + CxNetworkAttribute.ASPECT_NAME);
if ( f.exists())
f.delete();
}
}
//update cx and cx2 metadata for networkAttributes
MetaDataCollection metadata = networkDao.getMetaDataCollection(networkUUID);
List<CxMetadata> cx2metadata = networkDao.getCx2MetaDataList(networkUUID);
if ( attrs.size() == 0 ) {
metadata.remove(NetworkAttributesElement.ASPECT_NAME);
if ( isSingleNetwork)
cx2metadata.removeIf( n -> n.getName().equals(CxNetworkAttribute.ASPECT_NAME));
} else {
MetaDataElement elmt = metadata.getMetaDataElement(NetworkAttributesElement.ASPECT_NAME);
if ( elmt == null) {
elmt = new MetaDataElement(NetworkAttributesElement.ASPECT_NAME, "1.0");
}
elmt.setElementCount(Long.valueOf(attrs.size()));
if ( isSingleNetwork && ! cx2metadata.stream().anyMatch(
(CxMetadata n) -> n.getName().equals(CxNetworkAttribute.ASPECT_NAME) )) {
CxMetadata m = new CxMetadata(CxNetworkAttribute.ASPECT_NAME, 1);
cx2metadata.add(m);
}
}
networkDao.updateMetadataColleciton(networkUUID, metadata);
// update attribute declaration aspect and cx2 metadata
if ( isSingleNetwork) {
CxAttributeDeclaration decls = getAttrDeclarations(cx2AspectDirPath);
if (decls == null) {
if (networkAttrDecl != null) { // has new attributes
decls = new CxAttributeDeclaration();
decls.add(CxNetworkAttribute.ASPECT_NAME,
networkAttrDecl.getAttributesInAspect(CxNetworkAttribute.ASPECT_NAME));
cx2metadata.add(new CxMetadata(CxAttributeDeclaration.ASPECT_NAME, 1));
}
} else {
if (networkAttrDecl != null) {
decls.getDeclarations().put(CxNetworkAttribute.ASPECT_NAME,
networkAttrDecl.getAttributesInAspect(CxNetworkAttribute.ASPECT_NAME));
} else {
decls.removeAspectDeclaration(CxNetworkAttribute.ASPECT_NAME);
cx2metadata.removeIf((CxMetadata m) -> m.getName().equals(CxAttributeDeclaration.ASPECT_NAME));
}
}
networkDao.setCxMetadata(networkUUID, cx2metadata);
try (CX2AspectWriter<CxAttributeDeclaration> aspWtr = new CX2AspectWriter<>(
cx2AspectDirPath + CxAttributeDeclaration.ASPECT_NAME)) {
aspWtr.writeCXElement(decls);
}
}
//Recreate the CX file
CXNetworkFileGenerator g = new CXNetworkFileGenerator(networkUUID, metadata);
long cxFileSize = g.reCreateCXFile();
//Recreate cx2 file
if(isSingleNetwork) {
CX2NetworkFileGenerator g2 = new CX2NetworkFileGenerator(networkUUID, cx2metadata);
String tmpFilePath = g2.createCX2File();
java.nio.file.Path cx2Path = Paths.get(fileStoreDir + CX2NetworkLoader.cx2NetworkFileName);
Files.move(Paths.get(tmpFilePath), cx2Path, StandardCopyOption.ATOMIC_MOVE);
long cx2FileSize = Files.size(cx2Path);
networkDao.setNetworkFileSizes(networkUUID, cxFileSize, cx2FileSize);
}
}
@PUT
@Path("/{networkid}/summary")
@Produces("application/json")
public void updateNetworkSummary(
@PathParam("networkid") final String networkId,
final NetworkSummary summary
)
throws NdexException, SQLException , IOException, IllegalArgumentException
{
try (NetworkDAO networkDao = new NetworkDAO()){
User user = getLoggedInUser();
UUID networkUUID = UUID.fromString(networkId);
if(networkDao.isReadOnly(networkUUID)) {
throw new NdexException ("Can't update readonly network.");
}
if ( !networkDao.isWriteable(networkUUID, user.getExternalId())) {
throw new UnauthorizedOperationException("User doesn't have write permissions for this network.");
}
if (!networkDao.networkIsValid(networkUUID))
throw new InvalidNetworkException();
try {
if ( networkDao.networkIsLocked(networkUUID,10)) {
throw new NetworkConcurrentModificationException ();
}
} catch (InterruptedException e2) {
e2.printStackTrace();
throw new NdexException("Failed to check network lock: " + e2.getMessage());
}
try {
networkDao.lockNetwork(networkUUID);
networkDao.updateNetworkSummary(networkUUID, summary);
//recreate files and update db
updateNetworkAttributesAspect(networkDao, networkUUID);
networkDao.unlockNetwork(networkUUID);
// update the solr Index
NetworkIndexLevel lvl = networkDao.getIndexLevel(networkUUID);
if ( lvl != NetworkIndexLevel.NONE) {
networkDao.setFlag(networkUUID, "iscomplete", false);
networkDao.commit();
NdexServerQueue.INSTANCE.addSystemTask(new SolrTaskRebuildNetworkIdx(networkUUID,SolrIndexScope.global,false,null,lvl,false));
} else {
networkDao.setFlag(networkUUID, "iscomplete", true);
networkDao.commit();
}
} catch ( SQLException | IOException | IllegalArgumentException |NdexException e ) {
networkDao.rollback();
try {
networkDao.unlockNetwork(networkUUID);
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
throw e;
}
}
}
@PUT
@Path("/{networkid}")
@Consumes("multipart/form-data")
@Produces("application/json")
public void updateCXNetwork(final @PathParam("networkid") String networkIdStr,
@QueryParam("visibility") String visibilityStr,
@QueryParam("extranodeindex") String fieldListStr, // comma seperated list
MultipartFormDataInput input) throws Exception
{
VisibilityType visibility = null;
if ( visibilityStr !=null) {
visibility = VisibilityType.valueOf(visibilityStr);
}
Set<String> extraIndexOnNodes = null;
if ( fieldListStr != null) {
extraIndexOnNodes = new HashSet<>(10);
for ( String f: fieldListStr.split("\\s*,\\s*") ) {
extraIndexOnNodes.add(f);
}
}
try (UserDAO dao = new UserDAO()) {
dao.checkDiskSpace(getLoggedInUserId());
}
UUID networkId = UUID.fromString(networkIdStr);
// String ownerAccName = null;
try ( NetworkDAO daoNew = new NetworkDAO() ) {
User user = getLoggedInUser();
try {
if( daoNew.isReadOnly(networkId)) {
throw new NdexException ("Can't update readonly network.");
}
if ( !daoNew.isWriteable(networkId, user.getExternalId())) {
throw new UnauthorizedOperationException("User doesn't have write permissions for this network.");
}
if ( daoNew.networkIsLocked(networkId)) {
daoNew.close();
throw new NetworkConcurrentModificationException ();
}
daoNew.lockNetwork(networkId);
UUID tmpNetworkId = storeRawNetworkFromMultipart (input, cx1NetworkFileName);
updateNetworkFromSavedFile( networkId, daoNew, tmpNetworkId);
} catch (SQLException | NdexException | IOException e) {
e.printStackTrace();
daoNew.rollback();
daoNew.unlockNetwork(networkId);
throw e;
}
}
NdexServerQueue.INSTANCE.addSystemTask(new CXNetworkLoadingTask(networkId, /* ownerAccName,*/ true, visibility,extraIndexOnNodes));
}
@PUT
@Path("/{networkid}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces("application/json")
public void updateNetworkJson(final @PathParam("networkid") String networkIdStr,
@QueryParam("visibility") String visibilityStr,
@QueryParam("extranodeindex") String fieldListStr // comma seperated list
) throws Exception
{
VisibilityType visibility = null;
if ( visibilityStr !=null) {
visibility = VisibilityType.valueOf(visibilityStr);
}
Set<String> extraIndexOnNodes = null;
if ( fieldListStr != null) {
extraIndexOnNodes = new HashSet<>(10);
for ( String f: fieldListStr.split("\\s*,\\s*") ) {
extraIndexOnNodes.add(f);
}
}
UUID networkId = UUID.fromString(networkIdStr);
// String ownerAccName = null;
try ( NetworkDAO daoNew = lockNetworkForUpdate(networkId) ) {
try (InputStream in = this.getInputStreamFromRequest()) {
UUID tmpNetworkId = storeRawNetworkFromStream(in, cx1NetworkFileName);
updateNetworkFromSavedFile(networkId, daoNew, tmpNetworkId);
} catch (SQLException | NdexException | IOException e) {
daoNew.rollback();
daoNew.unlockNetwork(networkId);
throw e;
}
}
NdexServerQueue.INSTANCE.addSystemTask(new CXNetworkLoadingTask(networkId, /* ownerAccName,*/ true, visibility,extraIndexOnNodes));
// return networkIdStr;
}
private static void updateNetworkFromSavedFile(UUID networkId, NetworkDAO daoNew,
UUID tmpNetworkId) throws SQLException, NdexException, IOException, JsonParseException,
JsonMappingException, ObjectNotFoundException {
String cxFileName = Configuration.getInstance().getNdexRoot() + "/data/" + tmpNetworkId.toString()
+ "/network.cx";
long fileSize = new File(cxFileName).length();
daoNew.clearNetworkSummary(networkId, fileSize);
java.nio.file.Path src = Paths
.get(Configuration.getInstance().getNdexRoot() + "/data/" + tmpNetworkId);
java.nio.file.Path tgt = Paths
.get(Configuration.getInstance().getNdexRoot() + "/data/" + networkId);
FileUtils.deleteDirectory(
new File(Configuration.getInstance().getNdexRoot() + "/data/" + networkId));
Files.move(src, tgt, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
daoNew.commit();
}
/**
* This function updates aspects of a network. The payload is a CX document which contains the aspects (and their metadata that we will use
* to update the network). If an aspect only has metadata but no actual data, an Exception will be thrown.
* @param networkIdStr
* @param input
* @throws Exception
*/
@PUT
@Path("/{networkid}/aspects")
@Consumes("multipart/form-data")
@Produces("application/json")
public void updateCXNetworkAspects(final @PathParam("networkid") String networkIdStr,
MultipartFormDataInput input) throws Exception
{
try (UserDAO dao = new UserDAO()) {
dao.checkDiskSpace(getLoggedInUserId());
}
UUID networkId = UUID.fromString(networkIdStr);
try ( NetworkDAO daoNew = new NetworkDAO() ) {
User user = getLoggedInUser();
if( daoNew.isReadOnly(networkId)) {
throw new NdexException ("Can't update readonly network.");
}
if ( !daoNew.isWriteable(networkId, user.getExternalId())) {
throw new UnauthorizedOperationException("User doesn't have write permissions for this network.");
}
if ( daoNew.networkIsLocked(networkId)) {
daoNew.close();
throw new NetworkConcurrentModificationException ();
}
daoNew.lockNetwork(networkId);
UUID tmpNetworkId = storeRawNetworkFromMultipart (input, cx1NetworkFileName); //network stored as a temp network
updateNetworkFromSavedAspects(networkId, daoNew, tmpNetworkId);
}
}
@PUT
@Path("/{networkid}/aspects")
@Consumes(MediaType.APPLICATION_JSON)
@Produces("application/json")
public void updateAspectsJson(final @PathParam("networkid") String networkIdStr
) throws Exception
{
try (UserDAO dao = new UserDAO()) {
dao.checkDiskSpace(getLoggedInUserId());
}
UUID networkId = UUID.fromString(networkIdStr);
// String ownerAccName = null;
try ( NetworkDAO daoNew = new NetworkDAO() ) {
User user = getLoggedInUser();
if( daoNew.isReadOnly(networkId)) {
throw new NdexException ("Can't update readonly network.");
}
if ( !daoNew.isWriteable(networkId, user.getExternalId())) {
throw new UnauthorizedOperationException("User doesn't have write permissions for this network.");
}
if ( daoNew.networkIsLocked(networkId)) {
daoNew.close();
throw new NetworkConcurrentModificationException ();
}
daoNew.lockNetwork(networkId);
try (InputStream in = this.getInputStreamFromRequest()) {
UUID tmpNetworkId = storeRawNetworkFromStream(in, cx1NetworkFileName); //network stored as a temp network
updateNetworkFromSavedAspects( networkId, daoNew, tmpNetworkId);
}
}
}
private static void updateNetworkFromSavedAspects( UUID networkId, NetworkDAO daoNew,
UUID tmpNetworkId) throws SQLException, IOException {
try ( CXNetworkAspectsUpdater aspectUpdater = new CXNetworkAspectsUpdater(networkId, /*ownerAccName,*/daoNew, tmpNetworkId) ) {
aspectUpdater.update();
} catch ( IOException | NdexException | SQLException | RuntimeException e1) {
logger.error("Error occurred when updating aspects of network " + networkId + ": " + e1.getMessage());
e1.printStackTrace();
daoNew.setErrorMessage(networkId, e1.getMessage());
daoNew.unlockNetwork(networkId);
}
FileUtils.deleteDirectory(new File(Configuration.getInstance().getNdexRoot() + "/data/" + tmpNetworkId.toString()));
daoNew.unlockNetwork(networkId);
}
@DELETE
@Path("/{networkid}")
@Produces("application/json")
public void deleteNetwork(final @PathParam("networkid") String id) throws NdexException, SQLException {
try (NetworkDAO networkDao = new NetworkDAO()) {
UUID networkId = UUID.fromString(id);
UUID userId = getLoggedInUser().getExternalId();
if(networkDao.isAdmin(networkId, userId) ) {
if (!networkDao.isReadOnly(networkId) ) {
if ( !networkDao.networkIsLocked(networkId)) {
/*
NetworkGlobalIndexManager globalIdx = new NetworkGlobalIndexManager();
globalIdx.deleteNetwork(id);
try (SingleNetworkSolrIdxManager idxManager = new SingleNetworkSolrIdxManager(id)) {
idxManager.dropIndex();
}
*/
networkDao.deleteNetwork(UUID.fromString(id), getLoggedInUser().getExternalId());
networkDao.commit();
// move the row network to archive folder and delete the folder
String pathPrefix = Configuration.getInstance().getNdexRoot() + "/data/" + networkId.toString();
/*String archivePath = Configuration.getInstance().getNdexRoot() + "/data/_archive/";
File archiveDir = new File(archivePath);
if (!archiveDir.exists())
archiveDir.mkdir();
java.nio.file.Path src = Paths.get(pathPrefix+ "/network.cx");
java.nio.file.Path tgt = Paths.get(archivePath + "/" + networkId.toString() + ".cx");
*/
try {
// Files.move(src, tgt, StandardCopyOption.ATOMIC_MOVE);
FileUtils.deleteDirectory(new File(pathPrefix));
} catch (IOException e) {
e.printStackTrace();
throw new NdexException("Failed to delete directory. Error: " + e.getMessage());
}
NdexServerQueue.INSTANCE.addSystemTask(new SolrTaskDeleteNetwork(networkId));
return;
}
throw new NetworkConcurrentModificationException ();
}
throw new NdexException("Can't delete a read-only network.");
}
//TODO: need to check if the network actually exists and give an 404 error for that case.
throw new NdexException("Only network owner can delete a network.");
} catch ( IOException e ) {
throw new NdexException ("Error occurred when deleting network: " + e.getMessage(), e);
}
}
/* *************************************************************************
* Saves an uploaded network file. Determines the type of file uploaded,
* saves the file, and creates a task.
*
* Removing it. No longer relevent in v2.
* @param uploadedNetwork
* The uploaded network file.
* @throws IllegalArgumentException
* Bad input.
* @throws NdexException
* Failed to parse the file, or create the network in the
* database.
* @throws IOException
* @throws SQLException
**************************************************************************/
/*
* refactored to support non-transactional database operations
*/
/* @POST
@Path("/upload")
@Consumes("multipart/form-data")
@Produces("application/json")
public Task uploadNetwork( MultipartFormDataInput input)
//@MultipartForm UploadedFile uploadedNetwork)
throws IllegalArgumentException, SecurityException, NdexException, IOException, SQLException {
try (UserDAO dao = new UserDAO()) {
dao.checkDiskSpace(getLoggedInUserId());
}
Map<String, List<InputPart>> uploadForm = input.getFormDataMap();
List<InputPart> foo = uploadForm.get("filename");
String fname = "";
for (InputPart inputPart : foo)
{
// convert the uploaded file to inputstream and write it to disk
fname += inputPart.getBodyAsString();
}
if (fname.length() <1) {
throw new NdexException ("");
}
String ext = FilenameUtils.getExtension(fname).toLowerCase();
if ( !ext.equals("sif") && !ext.equals("xbel") && !ext.equals("xgmml") && !ext.equals("owl") && !ext.equals("cx")
&& !ext.equals("xls") && ! ext.equals("xlsx")) {
throw new NdexException(
"The uploaded file type is not supported; must be Excel, XGMML, SIF, BioPAX, cx or XBEL.");
}
UUID taskId = NdexUUIDFactory.INSTANCE.createNewNDExUUID();
final File uploadedNetworkPath = new File(Configuration.getInstance().getNdexRoot() +
"/uploaded-networks");
if (!uploadedNetworkPath.exists())
uploadedNetworkPath.mkdir();
String fileFullPath = uploadedNetworkPath.getAbsolutePath() + "/" + taskId + "." + ext;
//Get file data to save
List<InputPart> inputParts = uploadForm.get("fileUpload");
final File uploadedNetworkFile = new File(fileFullPath);
if (!uploadedNetworkFile.exists())
try {
uploadedNetworkFile.createNewFile();
} catch (IOException e1) {
throw new NdexException ("Failed to create file " + fileFullPath + " on server when uploading " +
fname + ": " + e1.getMessage());
}
byte[] bytes = new byte[2048];
for (InputPart inputPart : inputParts)
{
// convert the uploaded file to inputstream and write it to disk
InputStream inputStream = inputPart.getBody(InputStream.class, null);
OutputStream out = new FileOutputStream(new File(fileFullPath));
int read = 0;
while ((read = inputStream.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
inputStream.close();
out.flush();
out.close();
}
Task processNetworkTask = new Task();
processNetworkTask.setExternalId(taskId);
processNetworkTask.setDescription(fname); //uploadedNetwork.getFilename());
processNetworkTask.setTaskType(TaskType.PROCESS_UPLOADED_NETWORK);
processNetworkTask.setPriority(Priority.LOW);
processNetworkTask.setProgress(0);
processNetworkTask.setResource(fileFullPath);
processNetworkTask.setStatus(Status.QUEUED);
processNetworkTask.setTaskOwnerId(this.getLoggedInUser().getExternalId());
try (TaskDAO dao = new TaskDAO()){
dao.createTask(processNetworkTask);
dao.commit();
} catch (IllegalArgumentException iae) {
logger.error("[end: Exception caught:]{}", iae);
throw iae;
} catch (Exception e) {
logger.error("[end: Exception caught:]{}", e);
throw new NdexException(e.getMessage());
}
logger.info("[end: Uploading network file. Task for uploading network is created.]");
return processNetworkTask;
}
*/
@PUT
@Path("/{networkid}/systemproperty")
@Produces("application/json")
public void setNetworkFlag(
@PathParam("networkid") final String networkIdStr,
final Map<String,Object> parameters)
throws IllegalArgumentException, NdexException, SQLException, IOException {
accLogger.info("[data]\t[" + parameters.entrySet()
.stream()
.map(entry -> entry.getKey() + ":" + entry.getValue()).reduce(null, ((r,e) -> {String rr = r==null? e:r+"," +e; return rr;}))
+ "]" );
try (NetworkDAO networkDao = new NetworkDAO()) {
UUID networkId = UUID.fromString(networkIdStr);
if ( networkDao.hasDOI(networkId)) {
if ( parameters.size() >1 || !parameters.containsKey("showcase"))
throw new ForbiddenOperationException("Network with DOI can't be modified.");
}
UUID userId = getLoggedInUser().getExternalId();
if ( !networkDao.networkIsValid(networkId))
throw new InvalidNetworkException();
if ( parameters.containsKey(readOnlyParameter)) {
if (!networkDao.isAdmin(networkId, userId))
throw new UnauthorizedOperationException("Only network owner can set readOnly Parameter.");
boolean bv = ((Boolean)parameters.get(readOnlyParameter)).booleanValue();
networkDao.setFlag(networkId, "readonly",bv);
}
if ( parameters.containsKey("visibility")) {
if (!networkDao.isAdmin(networkId, userId))
throw new UnauthorizedOperationException("Only network owner can set visibility Parameter.");
VisibilityType visType = VisibilityType.valueOf((String)parameters.get("visibility"));
networkDao.updateNetworkVisibility(networkId, visType, false);
if ( !parameters.containsKey("index_level")) {
NetworkIndexLevel lvl = networkDao.getIndexLevel(networkId);
networkDao.commit();
if ( lvl != NetworkIndexLevel.NONE) {
NdexServerQueue.INSTANCE.addSystemTask(new SolrTaskRebuildNetworkIdx(networkId,SolrIndexScope.global,false,null,lvl,false));
}
}
}
/*if ( parameters.containsKey("index")) {
boolean bv = ((Boolean)parameters.get("index")).booleanValue();
networkDao.setFlag(networkId, "solr_indexed",bv);
if (bv) {
networkDao.setFlag(networkId, "iscomplete",false);
networkDao.commit();
NdexServerQueue.INSTANCE.addSystemTask(new SolrTaskRebuildNetworkIdx(networkId,SolrIndexScope.global,false,null));
} else
NdexServerQueue.INSTANCE.addSystemTask(new SolrTaskDeleteNetwork(networkId, true)); //delete the entry from global idx.
}*/
if ( parameters.containsKey("index_level")) {
NetworkIndexLevel lvl = parameters.get("index_level") == null?
NetworkIndexLevel.NONE :
NetworkIndexLevel.valueOf((String)parameters.get("index_level"));
networkDao.setIndexLevel(networkId, lvl);
if (lvl !=NetworkIndexLevel.NONE) {
networkDao.setFlag(networkId, "iscomplete",false);
networkDao.commit();
NdexServerQueue.INSTANCE.addSystemTask(new SolrTaskRebuildNetworkIdx(networkId,SolrIndexScope.global,false,null,lvl,true));
} else
NdexServerQueue.INSTANCE.addSystemTask(new SolrTaskDeleteNetwork(networkId, true)); //delete the entry from global idx.
}
if ( parameters.containsKey("showcase")) {
boolean bv = ((Boolean)parameters.get("showcase")).booleanValue();
networkDao.setShowcaseFlag(networkId, userId, bv);
}
networkDao.commit();
return;
}
}
@POST
// @PermitAll
@Path("")
@Produces("text/plain")
@Consumes("multipart/form-data")
public Response createCXNetwork( MultipartFormDataInput input,
@QueryParam("visibility") String visibilityStr,
@QueryParam("indexedfields") String fieldListStr // comma seperated list
) throws Exception
{
VisibilityType visibility = null;
if ( visibilityStr !=null) {
visibility = VisibilityType.valueOf(visibilityStr);
}
Set<String> extraIndexOnNodes = null;
if ( fieldListStr != null) {
extraIndexOnNodes = new HashSet<>(10);
for ( String f: fieldListStr.split("\\s*,\\s*") ) {
extraIndexOnNodes.add(f);
}
}
try (UserDAO dao = new UserDAO()) {
dao.checkDiskSpace(getLoggedInUserId());
}
UUID uuid = storeRawNetworkFromMultipart ( input, cx1NetworkFileName);
return processRawNetwork(visibility, extraIndexOnNodes, uuid);
}
private Response processRawNetwork(VisibilityType visibility, Set<String> extraIndexOnNodes, UUID uuid)
throws SQLException, NdexException, IOException, ObjectNotFoundException, JsonProcessingException,
URISyntaxException {
String uuidStr = uuid.toString();
accLogger.info("[data]\t[uuid:" +uuidStr + "]" );
String urlStr = Configuration.getInstance().getHostURI() +
Configuration.getInstance().getRestAPIPrefix()+"/network/"+ uuidStr;
String cxFileName = Configuration.getInstance().getNdexRoot() + "/data/" + uuidStr + "/" + cx1NetworkFileName;
long fileSize = new File(cxFileName).length();
// create entry in db.
try (NetworkDAO dao = new NetworkDAO()) {
// NetworkSummary summary =
dao.CreateEmptyNetworkEntry(uuid, getLoggedInUser().getExternalId(), getLoggedInUser().getUserName(), fileSize,null,null);
dao.commit();
}
NdexServerQueue.INSTANCE.addSystemTask(new CXNetworkLoadingTask(uuid, /*getLoggedInUser().getUserName(),*/ false, visibility, extraIndexOnNodes));
URI l = new URI (urlStr);
return Response.created(l).entity(l).build();
}
@POST
@Path("")
@Produces("text/plain")
@Consumes(MediaType.APPLICATION_JSON)
public Response createNetworkJson(
@QueryParam("visibility") String visibilityStr,
@QueryParam("indexedfields") String fieldListStr // comma seperated list
) throws Exception
{
VisibilityType visibility = null;
if ( visibilityStr !=null) {
visibility = VisibilityType.valueOf(visibilityStr);
}
Set<String> extraIndexOnNodes = null;
if ( fieldListStr != null) {
extraIndexOnNodes = new HashSet<>(10);
for ( String f: fieldListStr.split("\\s*,\\s*") ) {
extraIndexOnNodes.add(f);
}
}
try (UserDAO dao = new UserDAO()) {
dao.checkDiskSpace(getLoggedInUserId());
}
try (InputStream in = this.getInputStreamFromRequest()) {
UUID uuid = storeRawNetworkFromStream(in, cx1NetworkFileName);
return processRawNetwork(visibility, extraIndexOnNodes, uuid);
}
}
/* private static UUID storeRawNetworkFromStream(InputStream in) throws IOException {
UUID uuid = NdexUUIDFactory.INSTANCE.createNewNDExUUID();
String pathPrefix = Configuration.getInstance().getNdexRoot() + "/data/" + uuid.toString();
//Create dir
java.nio.file.Path dir = Paths.get(pathPrefix);
Set<PosixFilePermission> perms =
PosixFilePermissions.fromString("rwxrwxr-x");
FileAttribute<Set<PosixFilePermission>> attr =
PosixFilePermissions.asFileAttribute(perms);
Files.createDirectory(dir,attr);
//write content to file
String cxFilePath = pathPrefix + "/network.cx";
try (OutputStream outputStream = new FileOutputStream(cxFilePath)) {
IOUtils.copy(in, outputStream);
outputStream.close();
}
return uuid;
}
*/
/* private static UUID storeRawNetwork (MultipartFormDataInput input) throws IOException, BadRequestException {
Map<String, List<InputPart>> uploadForm = input.getFormDataMap();
//Get file data to save
List<InputPart> inputParts = uploadForm.get("CXNetworkStream");
if (inputParts == null)
throw new BadRequestException("Field CXNetworkStream is not found in the POSTed Data.");
byte[] bytes = new byte[8192];
UUID uuid = NdexUUIDFactory.INSTANCE.createNewNDExUUID();
String pathPrefix = Configuration.getInstance().getNdexRoot() + "/data/" + uuid.toString();
//Create dir
java.nio.file.Path dir = Paths.get(pathPrefix);
Set<PosixFilePermission> perms =
PosixFilePermissions.fromString("rwxrwxr-x");
FileAttribute<Set<PosixFilePermission>> attr =
PosixFilePermissions.asFileAttribute(perms);
Files.createDirectory(dir,attr);
//write content to file
String cxFilePath = pathPrefix + "/network.cx";
try (FileOutputStream out = new FileOutputStream (cxFilePath ) ){
for (InputPart inputPart : inputParts) {
// convert the uploaded file to inputstream and write it to disk
org.jboss.resteasy.plugins.providers.multipart.MultipartInputImpl.PartImpl p =
(org.jboss.resteasy.plugins.providers.multipart.MultipartInputImpl.PartImpl) inputPart;
try (InputStream inputStream = p.getBody()) {
int read = 0;
while ((read = inputStream.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
}
}
}
return uuid;
}
*/
private static List<NetworkAttributesElement> getNetworkAttributeAspectsFromSummary(NetworkSummary summary)
throws JsonParseException, JsonMappingException, IOException {
List<NetworkAttributesElement> result = new ArrayList<>();
if ( summary.getName() !=null)
result.add(new NetworkAttributesElement(null, NdexClasses.Network_P_name, summary.getName()));
if ( summary.getDescription() != null)
result.add(new NetworkAttributesElement(null, NdexClasses.Network_P_desc, summary.getDescription()));
if ( summary.getVersion() !=null)
result.add(new NetworkAttributesElement(null, NdexClasses.Network_P_version, summary.getVersion()));
if ( summary.getProperties() != null) {
for ( NdexPropertyValuePair p : summary.getProperties()) {
result.add(NetworkAttributesElement.createInstanceWithJsonValue(p.getSubNetworkId(), p.getPredicateString(),
p.getValue(), ATTRIBUTE_DATA_TYPE.fromCxLabel(p.getDataType())));
}
}
return result;
}
@POST
@Path("/{networkid}/copy")
@Produces("text/plain")
public Response cloneNetwork( @PathParam("networkid") final String srcNetworkUUIDStr) throws Exception
{
try (UserDAO dao = new UserDAO()) {
dao.checkDiskSpace(getLoggedInUserId());
}
UUID srcNetUUID = UUID.fromString(srcNetworkUUIDStr);
try ( NetworkDAO dao = new NetworkDAO ()) {
if ( ! dao.isReadable(srcNetUUID, getLoggedInUserId()) )
throw new UnauthorizedOperationException("User doesn't have read access to this network.");
if (!dao.networkIsValid(srcNetUUID)) {
throw new NdexException ("Invalid networks can not be copied.");
}
}
UUID uuid = NdexUUIDFactory.INSTANCE.createNewNDExUUID();
String uuidStr = uuid.toString();
// java.nio.file.Path src = Paths.get(Configuration.getInstance().getNdexRoot() + "/data/" + srcNetUUID.toString());
java.nio.file.Path tgt = Paths.get(Configuration.getInstance().getNdexRoot() + "/data/" + uuidStr);
//Create dir
Set<PosixFilePermission> perms =
PosixFilePermissions.fromString("rwxrwxr-x");
FileAttribute<Set<PosixFilePermission>> attr =
PosixFilePermissions.asFileAttribute(perms);
Files.createDirectory(tgt,attr);
String srcPathPrefix = Configuration.getInstance().getNdexRoot() + "/data/" + srcNetUUID.toString() + "/";
String tgtPathPrefix = Configuration.getInstance().getNdexRoot() + "/data/" + uuidStr + "/";
File srcAspectDir = new File ( srcPathPrefix + CXNetworkLoader.CX1AspectDir);
if ( srcAspectDir.exists()) {
File tgtAspectDir = new File ( tgtPathPrefix + CXNetworkLoader.CX1AspectDir);
FileUtils.copyDirectory(srcAspectDir, tgtAspectDir);
}
//copy the cx2 aspect directories
String tgtCX2AspectPathPrefix = tgtPathPrefix + CX2NetworkLoader.cx2AspectDirName;
String srcCX2AspectPathPrefix = srcPathPrefix + CX2NetworkLoader.cx2AspectDirName;
File srcCX2AspectDir = new File (srcCX2AspectPathPrefix );
Files.createDirectories(Paths.get(tgtCX2AspectPathPrefix), attr);
for ( String fname : srcCX2AspectDir.list() ) {
java.nio.file.Path src = Paths.get(srcPathPrefix + CX2NetworkLoader.cx2AspectDirName , fname);
if (Files.isSymbolicLink(src)) {
java.nio.file.Path link = Paths.get(tgtCX2AspectPathPrefix, fname);
java.nio.file.Path target = Paths.get(tgtPathPrefix + CXNetworkLoader.CX1AspectDir, fname);
Files.createSymbolicLink(link, target);
} else {
Files.copy(Paths.get(srcCX2AspectPathPrefix, fname),
Paths.get(tgtCX2AspectPathPrefix, fname));
}
}
String urlStr = Configuration.getInstance().getHostURI() +
Configuration.getInstance().getRestAPIPrefix()+"/network/"+ uuidStr;
// ProvenanceEntity entity = new ProvenanceEntity();
// entity.setUri(urlStr + "/summary");
String cxFileName = Configuration.getInstance().getNdexRoot() + "/data/" + srcNetUUID.toString() + "/" + cx1NetworkFileName;
long fileSize = new File(cxFileName).length();
// copy sample
java.nio.file.Path srcSample = Paths.get(Configuration.getInstance().getNdexRoot() + "/data/" + srcNetUUID.toString() + "/sample.cx");
if ( Files.exists(srcSample, LinkOption.NOFOLLOW_LINKS)) {
java.nio.file.Path tgtSample = Paths.get(Configuration.getInstance().getNdexRoot() + "/data/" + uuidStr + "/sample.cx");
Files.copy(srcSample, tgtSample);
}
//TODO: generate prov:wasDerivedFrom and prov:wasGeneratedby field in both db record and the recreated CX file.
// Need to handle the case when this network was a clone (means it already has prov:wasGeneratedBy and wasDerivedFrom attributes
// create entry in db.
try (NetworkDAO dao = new NetworkDAO()) {
// NetworkSummary summary =
dao.CreateCloneNetworkEntry(uuid, getLoggedInUser().getExternalId(), getLoggedInUser().getUserName(), fileSize, srcNetUUID);
CXNetworkFileGenerator g = new CXNetworkFileGenerator(uuid, dao /*, new Provenance(copyProv)*/);
g.reCreateCXFile();
CX2NetworkFileGenerator g2 = new CX2NetworkFileGenerator(uuid, dao);
String tmpFilePath = g2.createCX2File();
Files.move(Paths.get(tmpFilePath),
Paths.get(tgtPathPrefix + CX2NetworkLoader.cx2NetworkFileName),
StandardCopyOption.ATOMIC_MOVE);
dao.setFlag(uuid, "iscomplete", true);
dao.commit();
}
NdexServerQueue.INSTANCE.addSystemTask(new SolrTaskRebuildNetworkIdx(uuid, SolrIndexScope.individual,true,null, NetworkIndexLevel.NONE,false));
URI l = new URI (urlStr);
return Response.created(l).entity(l).build();
}
@POST
@PermitAll
@Path("/properties/score")
@Produces("application/json")
public static int getScoresFromProperties(
final List<NdexPropertyValuePair> properties)
throws Exception {
return Util.getNetworkScores (properties, true);
}
@POST
@PermitAll
@Path("/summary/score")
@Produces("application/json")
public static int getScoresFromNetworkSummary(
final NetworkSummary summary)
throws Exception {
return Util.getNdexScoreFromSummary(summary);
}
}
|
src/main/java/org/ndexbio/rest/services/NetworkServiceV2.java
|
/**
* Copyright (c) 2013, 2016, The Regents of the University of California, The Cytoscape Consortium
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
package org.ndexbio.rest.services;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.nio.file.attribute.FileAttribute;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.PosixFilePermissions;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import javax.annotation.security.PermitAll;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
import org.apache.commons.io.FileUtils;
import org.apache.solr.client.solrj.SolrServerException;
import org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataInput;
import org.ndexbio.common.NdexClasses;
import org.ndexbio.common.cx.CX2NetworkFileGenerator;
import org.ndexbio.common.cx.CXNetworkFileGenerator;
import org.ndexbio.common.models.dao.postgresql.NetworkDAO;
import org.ndexbio.common.models.dao.postgresql.UserDAO;
import org.ndexbio.common.persistence.CX2NetworkLoader;
import org.ndexbio.common.persistence.CXNetworkAspectsUpdater;
import org.ndexbio.common.persistence.CXNetworkLoader;
import org.ndexbio.common.util.NdexUUIDFactory;
import org.ndexbio.common.util.Util;
import org.ndexbio.cx2.aspect.element.core.CxAttributeDeclaration;
import org.ndexbio.cx2.aspect.element.core.CxMetadata;
import org.ndexbio.cx2.aspect.element.core.CxNetworkAttribute;
import org.ndexbio.cx2.converter.AspectAttributeStat;
import org.ndexbio.cx2.converter.CXToCX2Converter;
import org.ndexbio.cx2.io.CX2AspectWriter;
import org.ndexbio.cxio.aspects.datamodels.ATTRIBUTE_DATA_TYPE;
import org.ndexbio.cxio.aspects.datamodels.NetworkAttributesElement;
import org.ndexbio.cxio.core.CXAspectWriter;
import org.ndexbio.cxio.core.OpaqueAspectIterator;
import org.ndexbio.cxio.metadata.MetaDataCollection;
import org.ndexbio.cxio.metadata.MetaDataElement;
import org.ndexbio.cxio.util.JsonWriter;
import org.ndexbio.model.exceptions.BadRequestException;
import org.ndexbio.model.exceptions.ForbiddenOperationException;
import org.ndexbio.model.exceptions.InvalidNetworkException;
import org.ndexbio.model.exceptions.NdexException;
import org.ndexbio.model.exceptions.NetworkConcurrentModificationException;
import org.ndexbio.model.exceptions.ObjectNotFoundException;
import org.ndexbio.model.exceptions.UnauthorizedOperationException;
import org.ndexbio.model.object.NdexPropertyValuePair;
import org.ndexbio.model.object.Permissions;
import org.ndexbio.model.object.ProvenanceEntity;
import org.ndexbio.model.object.User;
import org.ndexbio.model.object.network.NetworkIndexLevel;
import org.ndexbio.model.object.network.NetworkSummary;
import org.ndexbio.model.object.network.VisibilityType;
import org.ndexbio.rest.Configuration;
import org.ndexbio.rest.filters.BasicAuthenticationFilter;
import org.ndexbio.task.CXNetworkLoadingTask;
import org.ndexbio.task.NdexServerQueue;
import org.ndexbio.task.SolrIndexScope;
import org.ndexbio.task.SolrTaskDeleteNetwork;
import org.ndexbio.task.SolrTaskRebuildNetworkIdx;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
@Path("/v2/network")
public class NetworkServiceV2 extends NdexService {
// static Logger logger = LoggerFactory.getLogger(NetworkService.class);
static Logger accLogger = LoggerFactory.getLogger(BasicAuthenticationFilter.accessLoggerName);
static private final String readOnlyParameter = "readOnly";
private static final String cx1NetworkFileName = "network.cx";
public NetworkServiceV2(@Context HttpServletRequest httpRequest
// @Context org.jboss.resteasy.spi.HttpResponse response
) {
super(httpRequest);
}
/**************************************************************************
* Returns network provenance.
* @throws IOException
* @throws JsonMappingException
* @throws JsonParseException
* @throws NdexException
* @throws SQLException
*
**************************************************************************/
@PermitAll
@GET
@Path("/{networkid}/provenance")
@Produces("application/json")
public ProvenanceEntity getProvenance(
@PathParam("networkid") final String networkIdStr,
@QueryParam("accesskey") String accessKey)
throws IllegalArgumentException, JsonParseException, JsonMappingException, IOException, NdexException, SQLException {
UUID networkId = UUID.fromString(networkIdStr);
try (NetworkDAO daoNew = new NetworkDAO()) {
if ( !daoNew.isReadable(networkId, getLoggedInUserId()) && (!daoNew.accessKeyIsValid(networkId, accessKey)))
throw new UnauthorizedOperationException("Network " + networkId + " is not readable to this user.");
return daoNew.getProvenance(networkId);
}
}
/**************************************************************************
* Updates network provenance.
* @throws Exception
*
**************************************************************************/
@PUT
@Path("/{networkid}/provenance")
@Produces("application/json")
public void setProvenance(@PathParam("networkid")final String networkIdStr, final ProvenanceEntity provenance)
throws Exception {
User user = getLoggedInUser();
setProvenance_aux(networkIdStr, provenance, user);
}
@Deprecated
protected static void setProvenance_aux(final String networkIdStr, final ProvenanceEntity provenance, User user)
throws Exception {
try (NetworkDAO daoNew = new NetworkDAO()){
UUID networkId = UUID.fromString(networkIdStr);
if ( !daoNew.isWriteable(networkId, user.getExternalId())) {
throw new UnauthorizedOperationException("User doesn't have write permissions for this network.");
}
if(daoNew.isReadOnly(networkId)) {
daoNew.close();
throw new NdexException ("Can't update readonly network.");
}
if (!daoNew.networkIsValid(networkId))
throw new InvalidNetworkException();
/* if ( daoNew.networkIsLocked(networkId,6)) {
daoNew.close();
throw new NetworkConcurrentModificationException ();
}
daoNew.lockNetwork(networkId); */
daoNew.setProvenance(networkId, provenance);
daoNew.commit();
//Recreate the CX file
// NetworkSummary fullSummary = daoNew.getNetworkSummaryById(networkId);
// MetaDataCollection metadata = daoNew.getMetaDataCollection(networkId);
// CXNetworkFileGenerator g = new CXNetworkFileGenerator(networkId, daoNew, new Provenance(provenance));
// g.reCreateCXFile();
// daoNew.unlockNetwork(networkId);
return ; // provenance; // daoNew.getProvenance(networkUUID);
} catch (Exception e) {
//if (null != daoNew) daoNew.rollback();
throw e;
}
}
/**************************************************************************
* Sets network properties.
* @throws Exception
*
**************************************************************************/
@PUT
@Path("/{networkid}/properties")
@Produces("application/json")
public int setNetworkProperties(
@PathParam("networkid")final String networkId,
final List<NdexPropertyValuePair> properties)
throws Exception {
User user = getLoggedInUser();
UUID networkUUID = UUID.fromString(networkId);
try (NetworkDAO daoNew = new NetworkDAO()) {
if(daoNew.isReadOnly(networkUUID)) {
throw new NdexException ("Can't update readonly network.");
}
if ( !daoNew.isWriteable(networkUUID, user.getExternalId())) {
throw new UnauthorizedOperationException("User doesn't have write permissions for this network.");
}
if ( daoNew.networkIsLocked(networkUUID,10)) {
throw new NetworkConcurrentModificationException ();
}
if ( !daoNew.networkIsValid(networkUUID))
throw new InvalidNetworkException();
daoNew.lockNetwork(networkUUID);
int i = 0;
try {
i = daoNew.setNetworkProperties(networkUUID, properties);
// recreate files and update db
updateNetworkAttributesAspect(daoNew, networkUUID);
} finally {
daoNew.unlockNetwork(networkUUID);
}
NetworkIndexLevel idxLvl = daoNew.getIndexLevel(networkUUID);
if ( idxLvl != NetworkIndexLevel.NONE) {
daoNew.setFlag(networkUUID, "iscomplete",false);
daoNew.commit();
NdexServerQueue.INSTANCE.addSystemTask(new SolrTaskRebuildNetworkIdx(networkUUID,SolrIndexScope.global,false,null,idxLvl,false));
} else {
daoNew.setFlag(networkUUID, "iscomplete", true);
}
return i;
} catch (Exception e) {
//logger.severe("Error occurred when update network properties: " + e.getMessage());
//e.printStackTrace();
//if (null != daoNew) daoNew.rollback();
logger.error("Updating properties of network {}. Exception caught:]{}", networkId, e);
throw new NdexException(e.getMessage(), e);
}
}
/*
*
* Operations returning Networks
*
*/
@PermitAll
@GET
@Path("/{networkid}/summary")
@Produces("application/json")
public NetworkSummary getNetworkSummary(
@PathParam("networkid") final String networkIdStr ,
@QueryParam("accesskey") String accessKey /*,
@Context org.jboss.resteasy.spi.HttpResponse response*/)
throws IllegalArgumentException, NdexException, SQLException, JsonParseException, JsonMappingException, IOException {
try (NetworkDAO dao = new NetworkDAO()) {
UUID userId = getLoggedInUserId();
UUID networkId = UUID.fromString(networkIdStr);
if ( dao.isReadable(networkId, userId) || dao.accessKeyIsValid(networkId, accessKey)) {
NetworkSummary summary = dao.getNetworkSummaryById(networkId);
return summary;
}
throw new UnauthorizedOperationException ("Unauthorized access to network " + networkId);
}
}
@PermitAll
@GET
@Path("/{networkid}/aspect")
public Response getNetworkCXMetadataCollection( @PathParam("networkid") final String networkId,
@QueryParam("accesskey") String accessKey)
throws Exception {
logger.info("[start: Getting CX metadata from network {}]", networkId);
UUID networkUUID = UUID.fromString(networkId);
try (NetworkDAO dao = new NetworkDAO() ) {
if ( dao.isReadable(networkUUID, getLoggedInUserId()) || dao.accessKeyIsValid(networkUUID, accessKey)) {
MetaDataCollection mdc = dao.getMetaDataCollection(networkUUID);
logger.info("[end: Return CX metadata from network {}]", networkId);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
JsonWriter wtr = JsonWriter.createInstance(baos,true);
mdc.toJson(wtr);
String s = baos.toString();//"java.nio.charset.StandardCharsets.UTF_8");
return Response.ok().type(MediaType.APPLICATION_JSON_TYPE).entity(s).build();
// return mdc;
}
throw new UnauthorizedOperationException("User doesn't have access to this network.");
}
}
@PermitAll
@GET
@Path("/{networkid}/aspect/{aspectname}/metadata")
@Produces("application/json")
public MetaDataElement getNetworkCXMetadata(
@PathParam("networkid") final String networkId,
@PathParam("aspectname") final String aspectName
)
throws Exception {
logger.info("[start: Getting {} metadata from network {}]", aspectName, networkId);
UUID networkUUID = UUID.fromString(networkId);
try (NetworkDAO dao = new NetworkDAO() ) {
if ( dao.isReadable(networkUUID, getLoggedInUserId())) {
MetaDataCollection mdc = dao.getMetaDataCollection(networkUUID);
logger.info("[end: Return CX metadata from network {}]", networkId);
return mdc.getMetaDataElement(aspectName);
}
throw new UnauthorizedOperationException("User doesn't have access to this network.");
}
}
@PermitAll
@GET
@Path("/{networkid}/aspect/{aspectname}")
public Response getAspectElements( @PathParam("networkid") final String networkId,
@PathParam("aspectname") final String aspectName,
@DefaultValue("-1") @QueryParam("size") int limit) throws SQLException, NdexException
{
logger.info("[start: Getting one aspect in network {}]", networkId);
UUID networkUUID = UUID.fromString(networkId);
try (NetworkDAO dao = new NetworkDAO()) {
if ( !dao.isReadable(networkUUID, getLoggedInUserId())) {
throw new UnauthorizedOperationException("User doesn't have access to this network.");
}
File cx1AspectDir = new File (Configuration.getInstance().getNdexRoot() + "/data/" + networkId
+ "/" + CXNetworkLoader.CX1AspectDir);
boolean hasCX1AspDir = cx1AspectDir.exists();
FileInputStream in = null;
try {
if ( hasCX1AspDir) {
in = new FileInputStream(cx1AspectDir + "/" + aspectName);
if ( limit <= 0) {
return Response.ok().type(MediaType.APPLICATION_JSON_TYPE).entity(in).build();
}
PipedInputStream pin = new PipedInputStream();
PipedOutputStream out;
try {
out = new PipedOutputStream(pin);
} catch (IOException e) {
try {
pin.close();
in.close();
} catch (IOException e1) {
e1.printStackTrace();
}
throw new NdexException("IOExcetion when creating the piped output stream: "+ e.getMessage());
}
new CXAspectElementsWriterThread(out,in, /*aspectName,*/ limit).start();
// logger.info("[end: Return get one aspect in network {}]", networkId);
return Response.ok().type(MediaType.APPLICATION_JSON_TYPE).entity(pin).build();
}
} catch (FileNotFoundException e) {
throw new ObjectNotFoundException("Aspect "+ aspectName + " not found in this network: " + e.getMessage());
}
//get aspect from cx2 aspects
PipedInputStream pin = new PipedInputStream();
PipedOutputStream out;
try {
out = new PipedOutputStream(pin);
} catch (IOException e) {
try {
pin.close();
} catch (IOException e1) {
e1.printStackTrace();
}
throw new NdexException("IOExcetion when creating the piped output stream: "+ e.getMessage());
}
new CXAspectElementWriter2Thread(out,networkId, aspectName, limit, accLogger).start();
// logger.info("[end: Return get one aspect in network {}]", networkId);
return Response.ok().type(MediaType.APPLICATION_JSON_TYPE).entity(pin).build();
}
}
@PermitAll
@GET
@Path("/{networkid}")
public Response getCompleteNetworkAsCX( @PathParam("networkid") final String networkId,
@QueryParam("download") boolean isDownload,
@QueryParam("accesskey") String accessKey,
@QueryParam("id_token") String id_token,
@QueryParam("auth_token") String auth_token)
throws Exception {
String title = null;
try (NetworkDAO dao = new NetworkDAO()) {
UUID networkUUID = UUID.fromString(networkId);
UUID userId = getLoggedInUserId();
if ( userId == null ) {
if ( auth_token != null) {
userId = getUserIdFromBasicAuthString(auth_token);
} else if ( id_token !=null) {
if ( getGoogleAuthenticator() == null)
throw new UnauthorizedOperationException("Google OAuth is not enabled on this server.");
userId = getGoogleAuthenticator().getUserUUIDByIdToken(id_token);
}
}
if ( ! dao.isReadable(networkUUID, userId) && (!dao.accessKeyIsValid(networkUUID, accessKey)))
throw new UnauthorizedOperationException("User doesn't have read access to this network.");
title = dao.getNetworkName(networkUUID);
}
String cxFilePath = Configuration.getInstance().getNdexRoot() + "/data/" + networkId + "/" + cx1NetworkFileName;
try {
FileInputStream in = new FileInputStream(cxFilePath) ;
// setZipFlag();
logger.info("[end: Return network {}]", networkId);
ResponseBuilder r = Response.ok();
if (isDownload) {
if (title == null || title.length() < 1) {
title = networkId;
}
title.replace('"', '_');
r.header("Content-Disposition", "attachment; filename=\"" + title + ".cx\"");
r.header("Access-Control-Expose-Headers", "Content-Disposition");
}
return r.type(isDownload ? MediaType.APPLICATION_OCTET_STREAM_TYPE : MediaType.APPLICATION_JSON_TYPE)
.entity(in).build();
} catch (IOException e) {
logger.error("[end: Ndex server can't find file: {}]", e.getMessage());
throw new NdexException ("Ndex server can't find file: " + e.getMessage());
}
}
@PermitAll
@GET
@Path("/{networkid}/sample")
public Response getSampleNetworkAsCX( @PathParam("networkid") final String networkIdStr ,
@QueryParam("accesskey") String accessKey)
throws IllegalArgumentException, NdexException, SQLException {
UUID networkId = UUID.fromString(networkIdStr);
try (NetworkDAO dao = new NetworkDAO()) {
if ( ! dao.isReadable(networkId, getLoggedInUserId()) && (!dao.accessKeyIsValid(networkId, accessKey)))
throw new UnauthorizedOperationException("User doesn't have read access to this network.");
}
String cxFilePath = Configuration.getInstance().getNdexRoot() + "/data/" + networkId + "/sample.cx";
try {
FileInputStream in = new FileInputStream(cxFilePath) ;
// setZipFlag();
return Response.ok().type(MediaType.APPLICATION_JSON_TYPE).entity(in).build();
} catch ( FileNotFoundException e) {
throw new ObjectNotFoundException("Sample network of " + networkId + " not found. Error: " + e.getMessage());
}
}
@GET
@Path("/{networkid}/accesskey")
@Produces("application/json")
public Map<String,String> getNetworkAccessKey(@PathParam("networkid") final String networkIdStr)
throws IllegalArgumentException, NdexException, SQLException {
UUID networkId = UUID.fromString(networkIdStr);
try (NetworkDAO dao = new NetworkDAO()) {
if ( ! dao.isAdmin(networkId, getLoggedInUserId()))
throw new UnauthorizedOperationException("User is not admin of this network.");
String key = dao.getNetworkAccessKey(networkId);
if (key == null || key.length()==0)
return null;
Map<String,String> result = new HashMap<>(1);
result.put("accessKey", key);
return result;
}
}
@PUT
@Path("/{networkid}/accesskey")
@Produces("application/json")
public Map<String,String> disableEnableNetworkAccessKey(@PathParam("networkid") final String networkIdStr,
@QueryParam("action") String action)
throws IllegalArgumentException, NdexException, SQLException {
UUID networkId = UUID.fromString(networkIdStr);
if ( ! action.equalsIgnoreCase("disable") && ! action.equalsIgnoreCase("enable"))
throw new NdexException("Value of 'action' paramter can only be 'disable' or 'enable'");
try (NetworkDAO dao = new NetworkDAO()) {
if ( ! dao.isAdmin(networkId, getLoggedInUserId()))
throw new UnauthorizedOperationException("User is not admin of this network.");
String key = null;
if ( action.equalsIgnoreCase("disable"))
dao.disableNetworkAccessKey(networkId);
else
key = dao.enableNetworkAccessKey(networkId);
dao.commit();
if (key == null || key.length()==0)
return null;
Map<String,String> result = new HashMap<>(1);
result.put("accessKey", key);
return result;
}
}
@PUT
@Path("/{networkid}/sample")
public void setSampleNetwork( @PathParam("networkid") final String networkId,
String CXString)
throws IllegalArgumentException, NdexException, SQLException, InterruptedException {
UUID networkUUID = UUID.fromString(networkId);
try (NetworkDAO dao = new NetworkDAO()) {
if (!dao.isAdmin(networkUUID, getLoggedInUserId()))
throw new UnauthorizedOperationException("User is not admin of this network.");
if (dao.networkIsLocked(networkUUID, 10))
throw new NetworkConcurrentModificationException();
if (!dao.networkIsValid(networkUUID))
throw new InvalidNetworkException();
String cxFilePath = Configuration.getInstance().getNdexRoot() + "/data/" + networkId + "/sample.cx";
try (FileWriter w = new FileWriter(cxFilePath)) {
w.write(CXString);
dao.setFlag(networkUUID, "has_sample", true);
dao.commit();
} catch (IOException e) {
throw new NdexException("Failed to write sample network of " + networkId + ": " + e.getMessage(), e);
}
}
}
private class CXAspectElementsWriterThread extends Thread {
private OutputStream o;
// private String networkId;
private FileInputStream in;
// private String aspect;
private int limit;
public CXAspectElementsWriterThread (OutputStream out, FileInputStream inputStream, /*String aspectName,*/ int limit) {
o = out;
// this.networkId = networkId;
// aspect = aspectName;
this.limit = limit;
in = inputStream;
}
@Override
public void run() {
try {
OpaqueAspectIterator asi = new OpaqueAspectIterator(in);
try (CXAspectWriter wtr = new CXAspectWriter (o)) {
for ( int i = 0 ; i < limit && asi.hasNext() ; i++) {
wtr.writeCXElement(asi.next());
}
}
} catch (IOException e) {
logger.error("IOException in CXAspectElementWriterThread: " + e.getMessage());
} catch (Exception e1) {
logger.error("Ndex exception: " + e1.getMessage());
} finally {
try {
o.flush();
o.close();
} catch (IOException e) {
logger.error("Failed to close outputstream in CXElementWriterWriterThread");
e.printStackTrace();
}
}
}
}
/**************************************************************************
* Retrieves array of user membership objects
*
* @param networkId
* The network ID.
* @throws IllegalArgumentException
* Bad input.
* @throws ObjectNotFoundException
* The group doesn't exist.
* @throws NdexException
* Failed to query the database.
* @throws SQLException
**************************************************************************/
@GET
@Path("/{networkid}/permission")
@Produces("application/json")
public Map<String, String> getNetworkUserMemberships(
@PathParam("networkid") final String networkId,
@QueryParam("type") String sourceType,
@QueryParam("permission") final String permissions ,
@DefaultValue("0") @QueryParam("start") int skipBlocks,
@DefaultValue("100") @QueryParam("size") int blockSize) throws NdexException, SQLException {
Permissions permission = null;
if ( permissions != null ){
permission = Permissions.valueOf(permissions.toUpperCase());
}
UUID networkUUID = UUID.fromString(networkId);
boolean returnUsers = true;
if ( sourceType != null ) {
if ( sourceType.toLowerCase().equals("group"))
returnUsers = false;
else if ( !sourceType.toLowerCase().equals("user"))
throw new NdexException("Invalid parameter 'type' " + sourceType + " received, it can only be 'user' or 'group'.");
} else
throw new NdexException("Parameter 'type' is required in this function.");
try (NetworkDAO networkDao = new NetworkDAO()) {
if ( !networkDao.isAdmin(networkUUID, getLoggedInUserId()) )
throw new UnauthorizedOperationException("Authenticate user is not the admin of this network.");
Map<String,String> result = returnUsers?
networkDao.getNetworkUserPermissions(networkUUID, permission, skipBlocks, blockSize):
networkDao.getNetworkGroupPermissions(networkUUID,permission,skipBlocks,blockSize);
return result;
}
}
@DELETE
@Path("/{networkid}/permission")
@Produces("application/json")
public int deleteNetworkPermission(
@PathParam("networkid") final String networkIdStr,
@QueryParam("userid") String userIdStr,
@QueryParam("groupid") String groupIdStr
)
throws IllegalArgumentException, NdexException, IOException, SQLException {
UUID networkId = UUID.fromString(networkIdStr);
UUID userId = null;
if ( userIdStr != null)
userId = UUID.fromString(userIdStr);
UUID groupId = null;
if ( groupIdStr != null)
groupId = UUID.fromString(groupIdStr);
if ( userId == null && groupId == null)
throw new NdexException ("Either userid or groupid parameter need to be set for this function.");
if ( userId !=null && groupId != null)
throw new NdexException ("userid and gorupid can't both be set for this function.");
try (NetworkDAO networkDao = new NetworkDAO()){
// User user = getLoggedInUser();
// networkDao.checkPermissionOperationCondition(networkId, user.getExternalId());
if (!networkDao.isAdmin(networkId,getLoggedInUserId())) {
if ( userId != null && !userId.equals(getLoggedInUserId())) {
throw new UnauthorizedOperationException("Unable to delete network permisison: user need to be admin of this network or grantee of this permission.");
}
if ( groupId!=null ) {
throw new UnauthorizedOperationException("Unable to delete network permission: user is not an admin of this network.");
}
}
if( !networkDao.networkIsValid(networkId))
throw new InvalidNetworkException();
int count;
if ( userId !=null)
count = networkDao.revokeUserPrivilege(networkId, userId);
else
count = networkDao.revokeGroupPrivilege(networkId, groupId);
// update the solr Index
NetworkIndexLevel lvl = networkDao.getIndexLevel(networkId);
if ( lvl != NetworkIndexLevel.NONE) {
networkDao.setFlag(networkId, "iscomplete", false);
networkDao.commit();
NdexServerQueue.INSTANCE.addSystemTask(new SolrTaskRebuildNetworkIdx(networkId,SolrIndexScope.global,false,null,lvl, false));
}
return count;
}
}
/*
*
* Operations on Network permissions
*
*/
@PUT
@Path("/{networkid}/permission")
@Produces("application/json")
public int updateNetworkPermission(
@PathParam("networkid") final String networkIdStr,
@QueryParam("userid") String userIdStr,
@QueryParam("groupid") String groupIdStr,
@QueryParam("permission") final String permissions
)
throws IllegalArgumentException, NdexException, IOException, SQLException {
logger.info("[start: Updating membership for network {}]", networkIdStr);
UUID networkId = UUID.fromString(networkIdStr);
UUID userId = null;
if ( userIdStr != null)
userId = UUID.fromString(userIdStr);
UUID groupId = null;
if ( groupIdStr != null)
groupId = UUID.fromString(groupIdStr);
if ( userId == null && groupId == null)
throw new NdexException ("Either userid or groupid parameter need to be set for this function.");
if ( userId !=null && groupId != null)
throw new NdexException ("userid and gorupid can't both be set for this function.");
if ( permissions == null)
throw new NdexException ("permission parameter is required in this function.");
Permissions p = Permissions.valueOf(permissions.toUpperCase());
try (NetworkDAO networkDao = new NetworkDAO()){
User user = getLoggedInUser();
if (!networkDao.isAdmin(networkId,user.getExternalId())) {
throw new UnauthorizedOperationException("Unable to update network permission: user is not an admin of this network.");
}
if ( !networkDao.networkIsValid(networkId))
throw new InvalidNetworkException();
int count;
if ( userId!=null) {
count = networkDao.grantPrivilegeToUser(networkId, userId, p);
} else
count = networkDao.grantPrivilegeToGroup(networkId, groupId, p);
//networkDao.commit();
// update the solr Index
NetworkIndexLevel lvl = networkDao.getIndexLevel(networkId);
if ( lvl != NetworkIndexLevel.NONE) {
networkDao.setFlag(networkId, "iscomplete", false);
networkDao.commit();
NdexServerQueue.INSTANCE.addSystemTask(new SolrTaskRebuildNetworkIdx(networkId,SolrIndexScope.global,false,null,lvl, false));
}
logger.info("[end: Updated permission for network {}]", networkId);
return count;
}
}
@PUT
@Path("/{networkid}/reference")
@Produces("application/json")
public void updateReferenceOnPreCertifiedNetwork(@PathParam("networkid") final String networkId,
Map<String,String> reference) throws SQLException, NdexException, SolrServerException, IOException {
UUID networkUUID = UUID.fromString(networkId);
UUID userId = getLoggedInUser().getExternalId();
if ( reference.get("reference") == null) {
throw new BadRequestException("Field reference is missing in the object.");
}
try (NetworkDAO networkDao = new NetworkDAO()){
if(networkDao.isAdmin(networkUUID, userId) ) {
if ( networkDao.hasDOI(networkUUID) && (!networkDao.isCertified(networkUUID)) ) {
List<NdexPropertyValuePair> props = networkDao.getNetworkSummaryById(networkUUID).getProperties();
boolean updated= false;
for ( NdexPropertyValuePair p : props ) {
if ( p.getPredicateString().equals("reference")) {
p.setValue(reference.get("reference"));
updated=true;
break;
}
}
if ( !updated) {
props.add(new NdexPropertyValuePair("reference", reference.get("reference")));
}
networkDao.lockNetwork(networkUUID);
networkDao.updateNetworkProperties(networkUUID,props);
// recreate files and update db
updateNetworkAttributesAspect(networkDao, networkUUID);
networkDao.unlockNetwork(networkUUID);
networkDao.updateNetworkVisibility(networkUUID, VisibilityType.PUBLIC, true);
//networkDao.setFlag(networkUUID, "solr_indexed", true);
networkDao.setIndexLevel(networkUUID, NetworkIndexLevel.ALL);
networkDao.setFlag(networkUUID, "certified", true);
networkDao.setFlag(networkUUID, "iscomplete", false);
networkDao.commit();
NdexServerQueue.INSTANCE.addSystemTask(new SolrTaskRebuildNetworkIdx(networkUUID,SolrIndexScope.global,false,null,NetworkIndexLevel.ALL, false));
} else {
if ( networkDao.isCertified(networkUUID))
throw new ForbiddenOperationException("This network has already been certified, updating reference is not allowed.");
throw new ForbiddenOperationException("This network doesn't have a DOI or a pending DOI request.");
}
}
}
}
@PUT
@Path("/{networkid}/profile")
@Produces("application/json")
public void updateNetworkProfile(
@PathParam("networkid") final String networkId,
final NetworkSummary partialSummary
)
throws NdexException, SQLException , IOException, IllegalArgumentException
{
try (NetworkDAO networkDao = new NetworkDAO()){
User user = getLoggedInUser();
UUID networkUUID = UUID.fromString(networkId);
if(networkDao.isReadOnly(networkUUID)) {
throw new NdexException ("Can't update readonly network.");
}
if ( !networkDao.isWriteable(networkUUID, user.getExternalId())) {
throw new UnauthorizedOperationException("User doesn't have write permissions for this network.");
}
Map<String,String> newValues = new HashMap<> ();
// List<SimplePropertyValuePair> entityProperties = new ArrayList<>();
if ( partialSummary.getName() != null) {
newValues.put(NdexClasses.Network_P_name, partialSummary.getName());
// entityProperties.add( new SimplePropertyValuePair("dc:title", partialSummary.getName()) );
}
if ( partialSummary.getDescription() != null) {
newValues.put( NdexClasses.Network_P_desc, partialSummary.getDescription());
// entityProperties.add( new SimplePropertyValuePair("description", partialSummary.getDescription()) );
}
if ( partialSummary.getVersion()!=null ) {
newValues.put( NdexClasses.Network_P_version, partialSummary.getVersion());
// entityProperties.add( new SimplePropertyValuePair("version", partialSummary.getVersion()) );
}
if ( newValues.size() > 0 ) {
if (!networkDao.networkIsValid(networkUUID))
throw new InvalidNetworkException();
try {
if ( networkDao.networkIsLocked(networkUUID,10)) {
throw new NetworkConcurrentModificationException ();
}
} catch (InterruptedException e2) {
e2.printStackTrace();
throw new NdexException("Failed to check network lock: " + e2.getMessage());
}
try {
networkDao.lockNetwork(networkUUID);
networkDao.updateNetworkProfile(networkUUID, newValues);
// recreate files and update db
updateNetworkAttributesAspect(networkDao, networkUUID);
networkDao.unlockNetwork(networkUUID);
// update the solr Index
NetworkIndexLevel lvl = networkDao.getIndexLevel(networkUUID);
if ( lvl != NetworkIndexLevel.NONE) {
networkDao.setFlag(networkUUID, "iscomplete", false);
networkDao.commit();
NdexServerQueue.INSTANCE.addSystemTask(new SolrTaskRebuildNetworkIdx(networkUUID,SolrIndexScope.global,false,null,lvl, false));
} else {
networkDao.setFlag(networkUUID, "iscomplete", true);
networkDao.commit();
}
} catch ( SQLException | IOException | IllegalArgumentException |NdexException e ) {
networkDao.rollback();
try {
networkDao.unlockNetwork(networkUUID);
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
throw e;
}
}
}
}
/**
*
* @param pathPrefix path of the directory that has the CxAttributeDeclaration aspect file.
* It should end with "/"
* @return the declaration object. null if network has no attributes declared.
* @throws JsonParseException
* @throws JsonMappingException
* @throws IOException
*/
protected static CxAttributeDeclaration getAttrDeclarations(String pathPrefix) throws JsonParseException, JsonMappingException, IOException {
File attrDeclF = new File ( pathPrefix + CxAttributeDeclaration.ASPECT_NAME);
CxAttributeDeclaration[] declarations = null;
if ( attrDeclF.exists() ) {
ObjectMapper om = new ObjectMapper();
declarations = om.readValue(attrDeclF, CxAttributeDeclaration[].class);
}
if ( declarations != null)
return declarations[0];
return null;
}
// update the networkAttributes aspect file and also update the metadata in the db.
protected static void updateNetworkAttributesAspect(NetworkDAO networkDao, UUID networkUUID) throws JsonParseException, JsonMappingException, SQLException, IOException, NdexException {
NetworkSummary fullSummary = networkDao.getNetworkSummaryById(networkUUID);
String fileStoreDir = Configuration.getInstance().getNdexRoot() + "/data/" + networkUUID.toString() + "/";
String aspectFilePath = fileStoreDir + CXNetworkLoader.CX1AspectDir + "/" + NetworkAttributesElement.ASPECT_NAME;
String cx2AspectDirPath = fileStoreDir + CX2NetworkLoader.cx2AspectDirName + "/";
boolean isSingleNetwork = fullSummary.getSubnetworkIds().isEmpty();
//update the networkAttributes aspect in cx and cx2
List<NetworkAttributesElement> attrs = getNetworkAttributeAspectsFromSummary(fullSummary);
CxAttributeDeclaration networkAttrDecl = null;
if ( attrs.size() > 0 ) {
AspectAttributeStat attributeStats = new AspectAttributeStat();
CxNetworkAttribute cx2NetAttr = new CxNetworkAttribute();
// write cx network attribute aspect file.
try (CXAspectWriter writer = new CXAspectWriter(aspectFilePath) ) {
for ( NetworkAttributesElement e : attrs) {
writer.writeCXElement(e);
writer.flush();
if ( isSingleNetwork) {
attributeStats.addNetworkAttribute(e);
Object attrValue = CXToCX2Converter.convertAttributeValue(e);
Object oldV = cx2NetAttr.getAttributes().put(e.getName(), attrValue);
if ( oldV !=null)
throw new NdexException("Duplicated network attribute name found: " + e.getName());
}
}
}
// write cx2 network attribute aspect file
if ( isSingleNetwork) {
networkAttrDecl = attributeStats.createCxDeclaration();
try (CX2AspectWriter<CxNetworkAttribute> aspWtr = new CX2AspectWriter<>(cx2AspectDirPath + CxNetworkAttribute.ASPECT_NAME)) {
aspWtr.writeCXElement(cx2NetAttr);
}
}
} else { // remove the aspect file if it exists
File f = new File ( aspectFilePath);
if ( f.exists())
f.delete();
if ( isSingleNetwork) {
f = new File(cx2AspectDirPath + CxNetworkAttribute.ASPECT_NAME);
if ( f.exists())
f.delete();
}
}
//update cx and cx2 metadata for networkAttributes
MetaDataCollection metadata = networkDao.getMetaDataCollection(networkUUID);
List<CxMetadata> cx2metadata = networkDao.getCx2MetaDataList(networkUUID);
if ( attrs.size() == 0 ) {
metadata.remove(NetworkAttributesElement.ASPECT_NAME);
if ( isSingleNetwork)
cx2metadata.removeIf( n -> n.getName().equals(CxNetworkAttribute.ASPECT_NAME));
} else {
MetaDataElement elmt = metadata.getMetaDataElement(NetworkAttributesElement.ASPECT_NAME);
if ( elmt == null) {
elmt = new MetaDataElement(NetworkAttributesElement.ASPECT_NAME, "1.0");
}
elmt.setElementCount(Long.valueOf(attrs.size()));
if ( isSingleNetwork && ! cx2metadata.stream().anyMatch(
(CxMetadata n) -> n.getName().equals(CxNetworkAttribute.ASPECT_NAME) )) {
CxMetadata m = new CxMetadata(CxNetworkAttribute.ASPECT_NAME, 1);
cx2metadata.add(m);
}
}
networkDao.updateMetadataColleciton(networkUUID, metadata);
// update attribute declaration aspect and cx2 metadata
if ( isSingleNetwork) {
CxAttributeDeclaration decls = getAttrDeclarations(cx2AspectDirPath);
if (decls == null) {
if (networkAttrDecl != null) { // has new attributes
decls = new CxAttributeDeclaration();
decls.add(CxNetworkAttribute.ASPECT_NAME,
networkAttrDecl.getAttributesInAspect(CxNetworkAttribute.ASPECT_NAME));
cx2metadata.add(new CxMetadata(CxAttributeDeclaration.ASPECT_NAME, 1));
}
} else {
if (networkAttrDecl != null) {
decls.getDeclarations().put(CxNetworkAttribute.ASPECT_NAME,
networkAttrDecl.getAttributesInAspect(CxNetworkAttribute.ASPECT_NAME));
} else {
decls.removeAspectDeclaration(CxNetworkAttribute.ASPECT_NAME);
cx2metadata.removeIf((CxMetadata m) -> m.getName().equals(CxAttributeDeclaration.ASPECT_NAME));
}
}
networkDao.setCxMetadata(networkUUID, cx2metadata);
try (CX2AspectWriter<CxAttributeDeclaration> aspWtr = new CX2AspectWriter<>(
cx2AspectDirPath + CxAttributeDeclaration.ASPECT_NAME)) {
aspWtr.writeCXElement(decls);
}
}
//Recreate the CX file
CXNetworkFileGenerator g = new CXNetworkFileGenerator(networkUUID, metadata);
long cxFileSize = g.reCreateCXFile();
//Recreate cx2 file
if(isSingleNetwork) {
CX2NetworkFileGenerator g2 = new CX2NetworkFileGenerator(networkUUID, cx2metadata);
String tmpFilePath = g2.createCX2File();
java.nio.file.Path cx2Path = Paths.get(fileStoreDir + CX2NetworkLoader.cx2NetworkFileName);
Files.move(Paths.get(tmpFilePath), cx2Path, StandardCopyOption.ATOMIC_MOVE);
long cx2FileSize = Files.size(cx2Path);
networkDao.setNetworkFileSizes(networkUUID, cxFileSize, cx2FileSize);
}
}
@PUT
@Path("/{networkid}/summary")
@Produces("application/json")
public void updateNetworkSummary(
@PathParam("networkid") final String networkId,
final NetworkSummary summary
)
throws NdexException, SQLException , IOException, IllegalArgumentException
{
try (NetworkDAO networkDao = new NetworkDAO()){
User user = getLoggedInUser();
UUID networkUUID = UUID.fromString(networkId);
if(networkDao.isReadOnly(networkUUID)) {
throw new NdexException ("Can't update readonly network.");
}
if ( !networkDao.isWriteable(networkUUID, user.getExternalId())) {
throw new UnauthorizedOperationException("User doesn't have write permissions for this network.");
}
if (!networkDao.networkIsValid(networkUUID))
throw new InvalidNetworkException();
try {
if ( networkDao.networkIsLocked(networkUUID,10)) {
throw new NetworkConcurrentModificationException ();
}
} catch (InterruptedException e2) {
e2.printStackTrace();
throw new NdexException("Failed to check network lock: " + e2.getMessage());
}
try {
networkDao.lockNetwork(networkUUID);
networkDao.updateNetworkSummary(networkUUID, summary);
//recreate files and update db
updateNetworkAttributesAspect(networkDao, networkUUID);
networkDao.unlockNetwork(networkUUID);
// update the solr Index
NetworkIndexLevel lvl = networkDao.getIndexLevel(networkUUID);
if ( lvl != NetworkIndexLevel.NONE) {
networkDao.setFlag(networkUUID, "iscomplete", false);
networkDao.commit();
NdexServerQueue.INSTANCE.addSystemTask(new SolrTaskRebuildNetworkIdx(networkUUID,SolrIndexScope.global,false,null,lvl,false));
} else {
networkDao.setFlag(networkUUID, "iscomplete", true);
networkDao.commit();
}
} catch ( SQLException | IOException | IllegalArgumentException |NdexException e ) {
networkDao.rollback();
try {
networkDao.unlockNetwork(networkUUID);
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
throw e;
}
}
}
@PUT
@Path("/{networkid}")
@Consumes("multipart/form-data")
@Produces("application/json")
public void updateCXNetwork(final @PathParam("networkid") String networkIdStr,
@QueryParam("visibility") String visibilityStr,
@QueryParam("extranodeindex") String fieldListStr, // comma seperated list
MultipartFormDataInput input) throws Exception
{
VisibilityType visibility = null;
if ( visibilityStr !=null) {
visibility = VisibilityType.valueOf(visibilityStr);
}
Set<String> extraIndexOnNodes = null;
if ( fieldListStr != null) {
extraIndexOnNodes = new HashSet<>(10);
for ( String f: fieldListStr.split("\\s*,\\s*") ) {
extraIndexOnNodes.add(f);
}
}
try (UserDAO dao = new UserDAO()) {
dao.checkDiskSpace(getLoggedInUserId());
}
UUID networkId = UUID.fromString(networkIdStr);
// String ownerAccName = null;
try ( NetworkDAO daoNew = new NetworkDAO() ) {
User user = getLoggedInUser();
try {
if( daoNew.isReadOnly(networkId)) {
throw new NdexException ("Can't update readonly network.");
}
if ( !daoNew.isWriteable(networkId, user.getExternalId())) {
throw new UnauthorizedOperationException("User doesn't have write permissions for this network.");
}
if ( daoNew.networkIsLocked(networkId)) {
daoNew.close();
throw new NetworkConcurrentModificationException ();
}
daoNew.lockNetwork(networkId);
UUID tmpNetworkId = storeRawNetworkFromMultipart (input, cx1NetworkFileName);
updateNetworkFromSavedFile( networkId, daoNew, tmpNetworkId);
} catch (SQLException | NdexException | IOException e) {
e.printStackTrace();
daoNew.rollback();
daoNew.unlockNetwork(networkId);
throw e;
}
}
NdexServerQueue.INSTANCE.addSystemTask(new CXNetworkLoadingTask(networkId, /* ownerAccName,*/ true, visibility,extraIndexOnNodes));
}
@PUT
@Path("/{networkid}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces("application/json")
public void updateNetworkJson(final @PathParam("networkid") String networkIdStr,
@QueryParam("visibility") String visibilityStr,
@QueryParam("extranodeindex") String fieldListStr // comma seperated list
) throws Exception
{
VisibilityType visibility = null;
if ( visibilityStr !=null) {
visibility = VisibilityType.valueOf(visibilityStr);
}
Set<String> extraIndexOnNodes = null;
if ( fieldListStr != null) {
extraIndexOnNodes = new HashSet<>(10);
for ( String f: fieldListStr.split("\\s*,\\s*") ) {
extraIndexOnNodes.add(f);
}
}
UUID networkId = UUID.fromString(networkIdStr);
// String ownerAccName = null;
try ( NetworkDAO daoNew = lockNetworkForUpdate(networkId) ) {
try (InputStream in = this.getInputStreamFromRequest()) {
UUID tmpNetworkId = storeRawNetworkFromStream(in, cx1NetworkFileName);
updateNetworkFromSavedFile(networkId, daoNew, tmpNetworkId);
} catch (SQLException | NdexException | IOException e) {
daoNew.rollback();
daoNew.unlockNetwork(networkId);
throw e;
}
}
NdexServerQueue.INSTANCE.addSystemTask(new CXNetworkLoadingTask(networkId, /* ownerAccName,*/ true, visibility,extraIndexOnNodes));
// return networkIdStr;
}
private static void updateNetworkFromSavedFile(UUID networkId, NetworkDAO daoNew,
UUID tmpNetworkId) throws SQLException, NdexException, IOException, JsonParseException,
JsonMappingException, ObjectNotFoundException {
String cxFileName = Configuration.getInstance().getNdexRoot() + "/data/" + tmpNetworkId.toString()
+ "/network.cx";
long fileSize = new File(cxFileName).length();
daoNew.clearNetworkSummary(networkId, fileSize);
java.nio.file.Path src = Paths
.get(Configuration.getInstance().getNdexRoot() + "/data/" + tmpNetworkId);
java.nio.file.Path tgt = Paths
.get(Configuration.getInstance().getNdexRoot() + "/data/" + networkId);
FileUtils.deleteDirectory(
new File(Configuration.getInstance().getNdexRoot() + "/data/" + networkId));
Files.move(src, tgt, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
daoNew.commit();
}
/**
* This function updates aspects of a network. The payload is a CX document which contains the aspects (and their metadata that we will use
* to update the network). If an aspect only has metadata but no actual data, an Exception will be thrown.
* @param networkIdStr
* @param input
* @throws Exception
*/
@PUT
@Path("/{networkid}/aspects")
@Consumes("multipart/form-data")
@Produces("application/json")
public void updateCXNetworkAspects(final @PathParam("networkid") String networkIdStr,
MultipartFormDataInput input) throws Exception
{
try (UserDAO dao = new UserDAO()) {
dao.checkDiskSpace(getLoggedInUserId());
}
UUID networkId = UUID.fromString(networkIdStr);
try ( NetworkDAO daoNew = new NetworkDAO() ) {
User user = getLoggedInUser();
if( daoNew.isReadOnly(networkId)) {
throw new NdexException ("Can't update readonly network.");
}
if ( !daoNew.isWriteable(networkId, user.getExternalId())) {
throw new UnauthorizedOperationException("User doesn't have write permissions for this network.");
}
if ( daoNew.networkIsLocked(networkId)) {
daoNew.close();
throw new NetworkConcurrentModificationException ();
}
daoNew.lockNetwork(networkId);
UUID tmpNetworkId = storeRawNetworkFromMultipart (input, cx1NetworkFileName); //network stored as a temp network
updateNetworkFromSavedAspects(networkId, daoNew, tmpNetworkId);
}
}
@PUT
@Path("/{networkid}/aspects")
@Consumes(MediaType.APPLICATION_JSON)
@Produces("application/json")
public void updateAspectsJson(final @PathParam("networkid") String networkIdStr
) throws Exception
{
try (UserDAO dao = new UserDAO()) {
dao.checkDiskSpace(getLoggedInUserId());
}
UUID networkId = UUID.fromString(networkIdStr);
// String ownerAccName = null;
try ( NetworkDAO daoNew = new NetworkDAO() ) {
User user = getLoggedInUser();
if( daoNew.isReadOnly(networkId)) {
throw new NdexException ("Can't update readonly network.");
}
if ( !daoNew.isWriteable(networkId, user.getExternalId())) {
throw new UnauthorizedOperationException("User doesn't have write permissions for this network.");
}
if ( daoNew.networkIsLocked(networkId)) {
daoNew.close();
throw new NetworkConcurrentModificationException ();
}
daoNew.lockNetwork(networkId);
try (InputStream in = this.getInputStreamFromRequest()) {
UUID tmpNetworkId = storeRawNetworkFromStream(in, cx1NetworkFileName); //network stored as a temp network
updateNetworkFromSavedAspects( networkId, daoNew, tmpNetworkId);
}
}
}
private static void updateNetworkFromSavedAspects( UUID networkId, NetworkDAO daoNew,
UUID tmpNetworkId) throws SQLException, IOException {
try ( CXNetworkAspectsUpdater aspectUpdater = new CXNetworkAspectsUpdater(networkId, /*ownerAccName,*/daoNew, tmpNetworkId) ) {
aspectUpdater.update();
} catch ( IOException | NdexException | SQLException | RuntimeException e1) {
logger.error("Error occurred when updating aspects of network " + networkId + ": " + e1.getMessage());
e1.printStackTrace();
daoNew.setErrorMessage(networkId, e1.getMessage());
daoNew.unlockNetwork(networkId);
}
FileUtils.deleteDirectory(new File(Configuration.getInstance().getNdexRoot() + "/data/" + tmpNetworkId.toString()));
daoNew.unlockNetwork(networkId);
}
@DELETE
@Path("/{networkid}")
@Produces("application/json")
public void deleteNetwork(final @PathParam("networkid") String id) throws NdexException, SQLException {
try (NetworkDAO networkDao = new NetworkDAO()) {
UUID networkId = UUID.fromString(id);
UUID userId = getLoggedInUser().getExternalId();
if(networkDao.isAdmin(networkId, userId) ) {
if (!networkDao.isReadOnly(networkId) ) {
if ( !networkDao.networkIsLocked(networkId)) {
/*
NetworkGlobalIndexManager globalIdx = new NetworkGlobalIndexManager();
globalIdx.deleteNetwork(id);
try (SingleNetworkSolrIdxManager idxManager = new SingleNetworkSolrIdxManager(id)) {
idxManager.dropIndex();
}
*/
networkDao.deleteNetwork(UUID.fromString(id), getLoggedInUser().getExternalId());
networkDao.commit();
// move the row network to archive folder and delete the folder
String pathPrefix = Configuration.getInstance().getNdexRoot() + "/data/" + networkId.toString();
/*String archivePath = Configuration.getInstance().getNdexRoot() + "/data/_archive/";
File archiveDir = new File(archivePath);
if (!archiveDir.exists())
archiveDir.mkdir();
java.nio.file.Path src = Paths.get(pathPrefix+ "/network.cx");
java.nio.file.Path tgt = Paths.get(archivePath + "/" + networkId.toString() + ".cx");
*/
try {
// Files.move(src, tgt, StandardCopyOption.ATOMIC_MOVE);
FileUtils.deleteDirectory(new File(pathPrefix));
} catch (IOException e) {
e.printStackTrace();
throw new NdexException("Failed to delete directory. Error: " + e.getMessage());
}
NdexServerQueue.INSTANCE.addSystemTask(new SolrTaskDeleteNetwork(networkId));
return;
}
throw new NetworkConcurrentModificationException ();
}
throw new NdexException("Can't delete a read-only network.");
}
//TODO: need to check if the network actually exists and give an 404 error for that case.
throw new NdexException("Only network owner can delete a network.");
} catch ( IOException e ) {
throw new NdexException ("Error occurred when deleting network: " + e.getMessage(), e);
}
}
/* *************************************************************************
* Saves an uploaded network file. Determines the type of file uploaded,
* saves the file, and creates a task.
*
* Removing it. No longer relevent in v2.
* @param uploadedNetwork
* The uploaded network file.
* @throws IllegalArgumentException
* Bad input.
* @throws NdexException
* Failed to parse the file, or create the network in the
* database.
* @throws IOException
* @throws SQLException
**************************************************************************/
/*
* refactored to support non-transactional database operations
*/
/* @POST
@Path("/upload")
@Consumes("multipart/form-data")
@Produces("application/json")
public Task uploadNetwork( MultipartFormDataInput input)
//@MultipartForm UploadedFile uploadedNetwork)
throws IllegalArgumentException, SecurityException, NdexException, IOException, SQLException {
try (UserDAO dao = new UserDAO()) {
dao.checkDiskSpace(getLoggedInUserId());
}
Map<String, List<InputPart>> uploadForm = input.getFormDataMap();
List<InputPart> foo = uploadForm.get("filename");
String fname = "";
for (InputPart inputPart : foo)
{
// convert the uploaded file to inputstream and write it to disk
fname += inputPart.getBodyAsString();
}
if (fname.length() <1) {
throw new NdexException ("");
}
String ext = FilenameUtils.getExtension(fname).toLowerCase();
if ( !ext.equals("sif") && !ext.equals("xbel") && !ext.equals("xgmml") && !ext.equals("owl") && !ext.equals("cx")
&& !ext.equals("xls") && ! ext.equals("xlsx")) {
throw new NdexException(
"The uploaded file type is not supported; must be Excel, XGMML, SIF, BioPAX, cx or XBEL.");
}
UUID taskId = NdexUUIDFactory.INSTANCE.createNewNDExUUID();
final File uploadedNetworkPath = new File(Configuration.getInstance().getNdexRoot() +
"/uploaded-networks");
if (!uploadedNetworkPath.exists())
uploadedNetworkPath.mkdir();
String fileFullPath = uploadedNetworkPath.getAbsolutePath() + "/" + taskId + "." + ext;
//Get file data to save
List<InputPart> inputParts = uploadForm.get("fileUpload");
final File uploadedNetworkFile = new File(fileFullPath);
if (!uploadedNetworkFile.exists())
try {
uploadedNetworkFile.createNewFile();
} catch (IOException e1) {
throw new NdexException ("Failed to create file " + fileFullPath + " on server when uploading " +
fname + ": " + e1.getMessage());
}
byte[] bytes = new byte[2048];
for (InputPart inputPart : inputParts)
{
// convert the uploaded file to inputstream and write it to disk
InputStream inputStream = inputPart.getBody(InputStream.class, null);
OutputStream out = new FileOutputStream(new File(fileFullPath));
int read = 0;
while ((read = inputStream.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
inputStream.close();
out.flush();
out.close();
}
Task processNetworkTask = new Task();
processNetworkTask.setExternalId(taskId);
processNetworkTask.setDescription(fname); //uploadedNetwork.getFilename());
processNetworkTask.setTaskType(TaskType.PROCESS_UPLOADED_NETWORK);
processNetworkTask.setPriority(Priority.LOW);
processNetworkTask.setProgress(0);
processNetworkTask.setResource(fileFullPath);
processNetworkTask.setStatus(Status.QUEUED);
processNetworkTask.setTaskOwnerId(this.getLoggedInUser().getExternalId());
try (TaskDAO dao = new TaskDAO()){
dao.createTask(processNetworkTask);
dao.commit();
} catch (IllegalArgumentException iae) {
logger.error("[end: Exception caught:]{}", iae);
throw iae;
} catch (Exception e) {
logger.error("[end: Exception caught:]{}", e);
throw new NdexException(e.getMessage());
}
logger.info("[end: Uploading network file. Task for uploading network is created.]");
return processNetworkTask;
}
*/
@PUT
@Path("/{networkid}/systemproperty")
@Produces("application/json")
public void setNetworkFlag(
@PathParam("networkid") final String networkIdStr,
final Map<String,Object> parameters)
throws IllegalArgumentException, NdexException, SQLException, IOException {
accLogger.info("[data]\t[" + parameters.entrySet()
.stream()
.map(entry -> entry.getKey() + ":" + entry.getValue()).reduce(null, ((r,e) -> {String rr = r==null? e:r+"," +e; return rr;}))
+ "]" );
try (NetworkDAO networkDao = new NetworkDAO()) {
UUID networkId = UUID.fromString(networkIdStr);
if ( networkDao.hasDOI(networkId)) {
if ( parameters.size() >1 || !parameters.containsKey("showcase"))
throw new ForbiddenOperationException("Network with DOI can't be modified.");
}
UUID userId = getLoggedInUser().getExternalId();
if ( !networkDao.networkIsValid(networkId))
throw new InvalidNetworkException();
if ( parameters.containsKey(readOnlyParameter)) {
if (!networkDao.isAdmin(networkId, userId))
throw new UnauthorizedOperationException("Only network owner can set readOnly Parameter.");
boolean bv = ((Boolean)parameters.get(readOnlyParameter)).booleanValue();
networkDao.setFlag(networkId, "readonly",bv);
}
if ( parameters.containsKey("visibility")) {
if (!networkDao.isAdmin(networkId, userId))
throw new UnauthorizedOperationException("Only network owner can set visibility Parameter.");
VisibilityType visType = VisibilityType.valueOf((String)parameters.get("visibility"));
networkDao.updateNetworkVisibility(networkId, visType, false);
if ( !parameters.containsKey("index_level")) {
NetworkIndexLevel lvl = networkDao.getIndexLevel(networkId);
networkDao.commit();
if ( lvl != NetworkIndexLevel.NONE) {
NdexServerQueue.INSTANCE.addSystemTask(new SolrTaskRebuildNetworkIdx(networkId,SolrIndexScope.global,false,null,lvl,false));
}
}
}
/*if ( parameters.containsKey("index")) {
boolean bv = ((Boolean)parameters.get("index")).booleanValue();
networkDao.setFlag(networkId, "solr_indexed",bv);
if (bv) {
networkDao.setFlag(networkId, "iscomplete",false);
networkDao.commit();
NdexServerQueue.INSTANCE.addSystemTask(new SolrTaskRebuildNetworkIdx(networkId,SolrIndexScope.global,false,null));
} else
NdexServerQueue.INSTANCE.addSystemTask(new SolrTaskDeleteNetwork(networkId, true)); //delete the entry from global idx.
}*/
if ( parameters.containsKey("index_level")) {
NetworkIndexLevel lvl = parameters.get("index_level") == null?
NetworkIndexLevel.NONE :
NetworkIndexLevel.valueOf((String)parameters.get("index_level"));
networkDao.setIndexLevel(networkId, lvl);
if (lvl !=NetworkIndexLevel.NONE) {
networkDao.setFlag(networkId, "iscomplete",false);
networkDao.commit();
NdexServerQueue.INSTANCE.addSystemTask(new SolrTaskRebuildNetworkIdx(networkId,SolrIndexScope.global,false,null,lvl,true));
} else
NdexServerQueue.INSTANCE.addSystemTask(new SolrTaskDeleteNetwork(networkId, true)); //delete the entry from global idx.
}
if ( parameters.containsKey("showcase")) {
boolean bv = ((Boolean)parameters.get("showcase")).booleanValue();
networkDao.setShowcaseFlag(networkId, userId, bv);
}
networkDao.commit();
return;
}
}
@POST
// @PermitAll
@Path("")
@Produces("text/plain")
@Consumes("multipart/form-data")
public Response createCXNetwork( MultipartFormDataInput input,
@QueryParam("visibility") String visibilityStr,
@QueryParam("indexedfields") String fieldListStr // comma seperated list
) throws Exception
{
VisibilityType visibility = null;
if ( visibilityStr !=null) {
visibility = VisibilityType.valueOf(visibilityStr);
}
Set<String> extraIndexOnNodes = null;
if ( fieldListStr != null) {
extraIndexOnNodes = new HashSet<>(10);
for ( String f: fieldListStr.split("\\s*,\\s*") ) {
extraIndexOnNodes.add(f);
}
}
try (UserDAO dao = new UserDAO()) {
dao.checkDiskSpace(getLoggedInUserId());
}
UUID uuid = storeRawNetworkFromMultipart ( input, cx1NetworkFileName);
return processRawNetwork(visibility, extraIndexOnNodes, uuid);
}
private Response processRawNetwork(VisibilityType visibility, Set<String> extraIndexOnNodes, UUID uuid)
throws SQLException, NdexException, IOException, ObjectNotFoundException, JsonProcessingException,
URISyntaxException {
String uuidStr = uuid.toString();
accLogger.info("[data]\t[uuid:" +uuidStr + "]" );
String urlStr = Configuration.getInstance().getHostURI() +
Configuration.getInstance().getRestAPIPrefix()+"/network/"+ uuidStr;
String cxFileName = Configuration.getInstance().getNdexRoot() + "/data/" + uuidStr + "/" + cx1NetworkFileName;
long fileSize = new File(cxFileName).length();
// create entry in db.
try (NetworkDAO dao = new NetworkDAO()) {
// NetworkSummary summary =
dao.CreateEmptyNetworkEntry(uuid, getLoggedInUser().getExternalId(), getLoggedInUser().getUserName(), fileSize,null,null);
dao.commit();
}
NdexServerQueue.INSTANCE.addSystemTask(new CXNetworkLoadingTask(uuid, /*getLoggedInUser().getUserName(),*/ false, visibility, extraIndexOnNodes));
URI l = new URI (urlStr);
return Response.created(l).entity(l).build();
}
@POST
@Path("")
@Produces("text/plain")
@Consumes(MediaType.APPLICATION_JSON)
public Response createNetworkJson(
@QueryParam("visibility") String visibilityStr,
@QueryParam("indexedfields") String fieldListStr // comma seperated list
) throws Exception
{
VisibilityType visibility = null;
if ( visibilityStr !=null) {
visibility = VisibilityType.valueOf(visibilityStr);
}
Set<String> extraIndexOnNodes = null;
if ( fieldListStr != null) {
extraIndexOnNodes = new HashSet<>(10);
for ( String f: fieldListStr.split("\\s*,\\s*") ) {
extraIndexOnNodes.add(f);
}
}
try (UserDAO dao = new UserDAO()) {
dao.checkDiskSpace(getLoggedInUserId());
}
try (InputStream in = this.getInputStreamFromRequest()) {
UUID uuid = storeRawNetworkFromStream(in, cx1NetworkFileName);
return processRawNetwork(visibility, extraIndexOnNodes, uuid);
}
}
/* private static UUID storeRawNetworkFromStream(InputStream in) throws IOException {
UUID uuid = NdexUUIDFactory.INSTANCE.createNewNDExUUID();
String pathPrefix = Configuration.getInstance().getNdexRoot() + "/data/" + uuid.toString();
//Create dir
java.nio.file.Path dir = Paths.get(pathPrefix);
Set<PosixFilePermission> perms =
PosixFilePermissions.fromString("rwxrwxr-x");
FileAttribute<Set<PosixFilePermission>> attr =
PosixFilePermissions.asFileAttribute(perms);
Files.createDirectory(dir,attr);
//write content to file
String cxFilePath = pathPrefix + "/network.cx";
try (OutputStream outputStream = new FileOutputStream(cxFilePath)) {
IOUtils.copy(in, outputStream);
outputStream.close();
}
return uuid;
}
*/
/* private static UUID storeRawNetwork (MultipartFormDataInput input) throws IOException, BadRequestException {
Map<String, List<InputPart>> uploadForm = input.getFormDataMap();
//Get file data to save
List<InputPart> inputParts = uploadForm.get("CXNetworkStream");
if (inputParts == null)
throw new BadRequestException("Field CXNetworkStream is not found in the POSTed Data.");
byte[] bytes = new byte[8192];
UUID uuid = NdexUUIDFactory.INSTANCE.createNewNDExUUID();
String pathPrefix = Configuration.getInstance().getNdexRoot() + "/data/" + uuid.toString();
//Create dir
java.nio.file.Path dir = Paths.get(pathPrefix);
Set<PosixFilePermission> perms =
PosixFilePermissions.fromString("rwxrwxr-x");
FileAttribute<Set<PosixFilePermission>> attr =
PosixFilePermissions.asFileAttribute(perms);
Files.createDirectory(dir,attr);
//write content to file
String cxFilePath = pathPrefix + "/network.cx";
try (FileOutputStream out = new FileOutputStream (cxFilePath ) ){
for (InputPart inputPart : inputParts) {
// convert the uploaded file to inputstream and write it to disk
org.jboss.resteasy.plugins.providers.multipart.MultipartInputImpl.PartImpl p =
(org.jboss.resteasy.plugins.providers.multipart.MultipartInputImpl.PartImpl) inputPart;
try (InputStream inputStream = p.getBody()) {
int read = 0;
while ((read = inputStream.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
}
}
}
return uuid;
}
*/
private static List<NetworkAttributesElement> getNetworkAttributeAspectsFromSummary(NetworkSummary summary)
throws JsonParseException, JsonMappingException, IOException {
List<NetworkAttributesElement> result = new ArrayList<>();
if ( summary.getName() !=null)
result.add(new NetworkAttributesElement(null, NdexClasses.Network_P_name, summary.getName()));
if ( summary.getDescription() != null)
result.add(new NetworkAttributesElement(null, NdexClasses.Network_P_desc, summary.getDescription()));
if ( summary.getVersion() !=null)
result.add(new NetworkAttributesElement(null, NdexClasses.Network_P_version, summary.getVersion()));
if ( summary.getProperties() != null) {
for ( NdexPropertyValuePair p : summary.getProperties()) {
result.add(NetworkAttributesElement.createInstanceWithJsonValue(p.getSubNetworkId(), p.getPredicateString(),
p.getValue(), ATTRIBUTE_DATA_TYPE.fromCxLabel(p.getDataType())));
}
}
return result;
}
@POST
@Path("/{networkid}/copy")
@Produces("text/plain")
public Response cloneNetwork( @PathParam("networkid") final String srcNetworkUUIDStr) throws Exception
{
try (UserDAO dao = new UserDAO()) {
dao.checkDiskSpace(getLoggedInUserId());
}
UUID srcNetUUID = UUID.fromString(srcNetworkUUIDStr);
try ( NetworkDAO dao = new NetworkDAO ()) {
if ( ! dao.isReadable(srcNetUUID, getLoggedInUserId()) )
throw new UnauthorizedOperationException("User doesn't have read access to this network.");
if (!dao.networkIsValid(srcNetUUID)) {
throw new NdexException ("Invalid networks can not be copied.");
}
}
UUID uuid = NdexUUIDFactory.INSTANCE.createNewNDExUUID();
String uuidStr = uuid.toString();
// java.nio.file.Path src = Paths.get(Configuration.getInstance().getNdexRoot() + "/data/" + srcNetUUID.toString());
java.nio.file.Path tgt = Paths.get(Configuration.getInstance().getNdexRoot() + "/data/" + uuidStr);
//Create dir
Set<PosixFilePermission> perms =
PosixFilePermissions.fromString("rwxrwxr-x");
FileAttribute<Set<PosixFilePermission>> attr =
PosixFilePermissions.asFileAttribute(perms);
Files.createDirectory(tgt,attr);
String srcPathPrefix = Configuration.getInstance().getNdexRoot() + "/data/" + srcNetUUID.toString() + "/";
String tgtPathPrefix = Configuration.getInstance().getNdexRoot() + "/data/" + uuidStr + "/";
File srcAspectDir = new File ( srcPathPrefix + CXNetworkLoader.CX1AspectDir);
if ( srcAspectDir.exists()) {
File tgtAspectDir = new File ( tgtPathPrefix + CXNetworkLoader.CX1AspectDir);
FileUtils.copyDirectory(srcAspectDir, tgtAspectDir);
}
//copy the cx2 aspect directories
String tgtCX2AspectPathPrefix = tgtPathPrefix + CX2NetworkLoader.cx2AspectDirName;
String srcCX2AspectPathPrefix = srcPathPrefix + CX2NetworkLoader.cx2AspectDirName;
File srcCX2AspectDir = new File (srcCX2AspectPathPrefix );
Files.createDirectories(Paths.get(tgtCX2AspectPathPrefix), attr);
for ( String fname : srcCX2AspectDir.list() ) {
java.nio.file.Path src = Paths.get(srcPathPrefix + CX2NetworkLoader.cx2AspectDirName , fname);
if (Files.isSymbolicLink(src)) {
java.nio.file.Path link = Paths.get(tgtCX2AspectPathPrefix, fname);
java.nio.file.Path target = Paths.get(tgtPathPrefix + CXNetworkLoader.CX1AspectDir, fname);
Files.createSymbolicLink(link, target);
} else {
Files.copy(Paths.get(srcCX2AspectPathPrefix, fname),
Paths.get(tgtCX2AspectPathPrefix, fname));
}
}
String urlStr = Configuration.getInstance().getHostURI() +
Configuration.getInstance().getRestAPIPrefix()+"/network/"+ uuidStr;
// ProvenanceEntity entity = new ProvenanceEntity();
// entity.setUri(urlStr + "/summary");
String cxFileName = Configuration.getInstance().getNdexRoot() + "/data/" + srcNetUUID.toString() + "/" + cx1NetworkFileName;
long fileSize = new File(cxFileName).length();
// copy sample
java.nio.file.Path srcSample = Paths.get(Configuration.getInstance().getNdexRoot() + "/data/" + srcNetUUID.toString() + "/sample.cx");
if ( Files.exists(srcSample, LinkOption.NOFOLLOW_LINKS)) {
java.nio.file.Path tgtSample = Paths.get(Configuration.getInstance().getNdexRoot() + "/data/" + uuidStr + "/sample.cx");
Files.copy(srcSample, tgtSample);
}
//TODO: generate prov:wasDerivedFrom and prov:wasGeneratedby field in both db record and the recreated CX file.
// Need to handle the case when this network was a clone (means it already has prov:wasGeneratedBy and wasDerivedFrom attributes
// create entry in db.
try (NetworkDAO dao = new NetworkDAO()) {
// NetworkSummary summary =
dao.CreateCloneNetworkEntry(uuid, getLoggedInUser().getExternalId(), getLoggedInUser().getUserName(), fileSize, srcNetUUID);
CXNetworkFileGenerator g = new CXNetworkFileGenerator(uuid, dao /*, new Provenance(copyProv)*/);
g.reCreateCXFile();
CX2NetworkFileGenerator g2 = new CX2NetworkFileGenerator(uuid, dao);
String tmpFilePath = g2.createCX2File();
Files.move(Paths.get(tmpFilePath),
Paths.get(tgtPathPrefix + CX2NetworkLoader.cx2NetworkFileName),
StandardCopyOption.ATOMIC_MOVE);
dao.setFlag(uuid, "iscomplete", true);
dao.commit();
}
NdexServerQueue.INSTANCE.addSystemTask(new SolrTaskRebuildNetworkIdx(uuid, SolrIndexScope.individual,true,null, NetworkIndexLevel.NONE,false));
URI l = new URI (urlStr);
return Response.created(l).entity(l).build();
}
@POST
@PermitAll
@Path("/properties/score")
@Produces("application/json")
public static int getScoresFromProperties(
final List<NdexPropertyValuePair> properties)
throws Exception {
return Util.getNetworkScores (properties, true);
}
@POST
@PermitAll
@Path("/summary/score")
@Produces("application/json")
public static int getScoresFromNetworkSummary(
final NetworkSummary summary)
throws Exception {
return Util.getNdexScoreFromSummary(summary);
}
}
|
Resolves bug SRV2-193. statement was not committed in the
setNetworkProperties funtion.
|
src/main/java/org/ndexbio/rest/services/NetworkServiceV2.java
|
Resolves bug SRV2-193. statement was not committed in the setNetworkProperties funtion.
|
|
Java
|
mit
|
2be33bb0a1cfcd905965e3b37c7a31f7bbd5ccf0
| 0
|
fieldenms/tg,fieldenms/tg,fieldenms/tg,fieldenms/tg,fieldenms/tg
|
package ua.com.fielden.platform.entity.functional.master;
import java.util.Set;
import java.util.TreeSet;
import java.util.stream.Collectors;
import com.google.inject.Inject;
import ua.com.fielden.platform.criteria.generator.impl.CriteriaReflector;
import ua.com.fielden.platform.dao.DefaultEntityProducerWithContext;
import ua.com.fielden.platform.entity.factory.EntityFactory;
import ua.com.fielden.platform.entity.factory.ICompanionObjectFinder;
/**
* A producer for new instances of entity {@link AcknowledgeWarnings} to fill its respective property with the actual warnings.
*
* @author TG Team
*
*/
public class AcknowledgeWarningsProducer extends DefaultEntityProducerWithContext<AcknowledgeWarnings> {
@Inject
public AcknowledgeWarningsProducer(final EntityFactory factory, final ICompanionObjectFinder companionFinder) {
super(factory, AcknowledgeWarnings.class, companionFinder);
}
@Override
public AcknowledgeWarnings provideDefaultValues(final AcknowledgeWarnings entity) {
if (getMasterEntity() != null) {
final Set<PropertyWarning> propertyWarnings = getMasterEntity()
.nonProxiedProperties()
.filter(mp -> mp.hasWarnings())
.map(mp -> {
return factory().newEntity(PropertyWarning.class, CriteriaReflector.getCriteriaTitleAndDesc(getMasterEntity().getType(), mp.getName()).getKey(), mp.getFirstWarning().getMessage());
})
.collect(Collectors.toCollection(() -> new TreeSet<PropertyWarning>()));
entity.setWarnings(propertyWarnings);
entity.getProperty("warnings").resetState();
}
return entity;
}
}
|
platform-pojo-bl/src/main/java/ua/com/fielden/platform/entity/functional/master/AcknowledgeWarningsProducer.java
|
package ua.com.fielden.platform.entity.functional.master;
import java.util.Set;
import java.util.stream.Collectors;
import com.google.inject.Inject;
import ua.com.fielden.platform.criteria.generator.impl.CriteriaReflector;
import ua.com.fielden.platform.dao.DefaultEntityProducerWithContext;
import ua.com.fielden.platform.entity.factory.EntityFactory;
import ua.com.fielden.platform.entity.factory.ICompanionObjectFinder;
/**
* A producer for new instances of entity {@link AcknowledgeWarnings} to fill its respective property with the actual warnings.
*
* @author TG Team
*
*/
public class AcknowledgeWarningsProducer extends DefaultEntityProducerWithContext<AcknowledgeWarnings> {
@Inject
public AcknowledgeWarningsProducer(final EntityFactory factory, final ICompanionObjectFinder companionFinder) {
super(factory, AcknowledgeWarnings.class, companionFinder);
}
@Override
public AcknowledgeWarnings provideDefaultValues(final AcknowledgeWarnings entity) {
if (getMasterEntity() != null) {
final Set<PropertyWarning> propertyWarnings = getMasterEntity()
.nonProxiedProperties()
.filter(mp -> mp.hasWarnings())
.map(mp -> {
return factory().newEntity(PropertyWarning.class, CriteriaReflector.getCriteriaTitleAndDesc(getMasterEntity().getType(), mp.getName()).getKey(), mp.getFirstWarning().getMessage());
})
.collect(Collectors.toSet());
entity.setWarnings(propertyWarnings);
entity.getProperty("warnings").resetState();
}
return entity;
}
}
|
#599 Ensured representation of warnings in an alphabetic order by property title.
|
platform-pojo-bl/src/main/java/ua/com/fielden/platform/entity/functional/master/AcknowledgeWarningsProducer.java
|
#599 Ensured representation of warnings in an alphabetic order by property title.
|
|
Java
|
mit
|
bad4a44c95b202bd73caafe3909aa5dd18d64ef9
| 0
|
ParaPenguin/morphix,agilemobiledev/morphix
|
package me.hfox.morphix.mapping.field;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.DBRef;
import me.hfox.morphix.Morphix;
import me.hfox.morphix.MorphixDefaults;
import me.hfox.morphix.annotation.NotSaved;
import me.hfox.morphix.annotation.Reference;
import me.hfox.morphix.annotation.entity.Entity;
import me.hfox.morphix.annotation.entity.StoreEmpty;
import me.hfox.morphix.annotation.entity.StoreNull;
import me.hfox.morphix.annotation.entity.Polymorph;
import me.hfox.morphix.annotation.lifecycle.PostLoad;
import me.hfox.morphix.annotation.lifecycle.PreLoad;
import me.hfox.morphix.exception.MorphixException;
import me.hfox.morphix.util.AnnotationUtils;
import org.bson.types.ObjectId;
import sun.reflect.ReflectionFactory;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
public class EntityMapper<T> extends FieldMapper<T> {
private Class<T> cls;
private Entity entity;
private StoreEmpty storeEmpty;
private StoreNull storeNull;
private Polymorph polymorph;
private boolean polymorphEnabled;
private Reference reference;
private NotSaved notSaved;
private Map<Field, FieldMapper> fields;
public EntityMapper(Class<T> type, Class<?> parent, Field field, Morphix morphix) {
super(type, parent, field, morphix);
this.cls = type;
}
public Entity getEntity() {
return entity;
}
public StoreEmpty getStoreEmpty() {
return storeEmpty;
}
public StoreNull getStoreNull() {
return storeNull;
}
public Polymorph getPolymorph() {
return polymorph;
}
public boolean isPolymorphEnabled() {
return polymorphEnabled;
}
public Reference getReference() {
return reference;
}
public NotSaved getNotSaved() {
return notSaved;
}
@Override
protected void discover() {
super.discover();
entity = AnnotationUtils.getHierarchicalAnnotation(type, Entity.class);
storeEmpty = AnnotationUtils.getHierarchicalAnnotation(type, StoreEmpty.class);
storeNull = AnnotationUtils.getHierarchicalAnnotation(type, StoreNull.class);
polymorph = AnnotationUtils.getHierarchicalAnnotation(type, Polymorph.class);
polymorphEnabled = polymorph != null && polymorph.value();
if (field != null) {
reference = field.getAnnotation(Reference.class);
notSaved = field.getAnnotation(NotSaved.class);
}
fields = getFields(type);
}
@Override
public T unmarshal(Object obj) {
return unmarshal(obj, MorphixDefaults.DEFAULT_LIFECYCLE);
}
@Override
@SuppressWarnings("unchecked")
public T unmarshal(Object obj, boolean lifecycle) {
if (obj == null) {
return null;
}
if (reference != null) {
if (obj instanceof DBRef) {
DBRef ref = (DBRef) obj;
return morphix.createQuery(cls, ref.getRef()).field("_id").equal(ref.getId()).get();
} else if (obj instanceof ObjectId) {
ObjectId id = (ObjectId) obj;
return morphix.createQuery(cls).field("_id").equal(id).get();
}
return null;
}
if (!(obj instanceof DBObject)) {
return null;
}
DBObject object = (DBObject) obj;
Class<?> cls = polymorphEnabled ? morphix.getPolymorhpismHelper().generate(object) : type;
if (cls == null) {
cls = type;
}
Object result = null;
try {
result = cls.newInstance();
} catch (Exception ex) {}
if (result == null) {
final ReflectionFactory reflection = ReflectionFactory.getReflectionFactory();
final Constructor constructor;
try {
// System.out.println("Class: " + cls);
constructor = reflection.newConstructorForSerialization(cls, Object.class.getDeclaredConstructor());
// System.out.println("Constructor: " + constructor);
result = constructor.newInstance();
// System.out.println("Result: " + result);
} catch (Exception ex) {
throw new MorphixException(ex);
}
}
if (lifecycle) {
morphix.getLifecycleHelper().call(PreLoad.class, result);
}
Map<Field, FieldMapper> fields = getFields(cls);
for (Entry<Field, FieldMapper> entry : fields.entrySet()) {
Field field = entry.getKey();
// System.out.println("Attempting to pull " + field);
field.setAccessible(true);
FieldMapper mapper = entry.getValue();
Object dbResult = object.get(mapper.fieldName);
// System.out.println("Result: " + dbResult);
// if (dbResult == null && (storeNull == null || !storeNull.value())) {
// continue;
// }
Object value = mapper.unmarshal(dbResult);
// System.out.println("Mapped: " + value);
if (storeEmpty == null || !storeEmpty.value()) {
if (value instanceof Collection) {
Collection collection = (Collection) value;
if (collection.isEmpty()) {
value = null;
}
} else if (value instanceof Map) {
Map map = (Map) value;
if (map.isEmpty()) {
value = null;
}
}
}
try {
field.set(result, value);
} catch (IllegalAccessException ex) {
throw new MorphixException(ex);
}
}
if (lifecycle) {
morphix.getLifecycleHelper().call(PostLoad.class, result);
}
return (T) result;
}
@Override
public Object marshal(Object obj, boolean lifecycle) {
if (obj == null) {
return null;
}
Class<?> cls = obj.getClass();
if (reference != null) {
ObjectId id = morphix.getEntityHelper().getObjectId(obj, true);
// if (id == null) {
// throw new MorphixException("Can't reference an Entity with no id");
// }
if (reference.dbRef()) {
return new DBRef(null, morphix.getEntityHelper().getCollectionName(obj.getClass()), id);
}
return id;
}
BasicDBObject document = new BasicDBObject();
if (polymorphEnabled) {
morphix.getPolymorhpismHelper().store(document, obj.getClass());
}
Map<Field, FieldMapper> fields = getFields(cls);
for (Entry<Field, FieldMapper> entry : fields.entrySet()) {
Field field = entry.getKey();
field.setAccessible(true);
FieldMapper mapper = entry.getValue();
Object value;
try {
value = field.get(obj);
} catch (IllegalAccessException ex) {
throw new MorphixException(ex);
}
if (value == null && (storeNull == null || !storeNull.value())) {
continue;
}
if ((storeEmpty == null || !storeEmpty.value())) {
if (value instanceof Collection) {
Collection collection = (Collection) value;
if (collection.isEmpty()) {
continue;
}
} else if (value instanceof Map) {
Map map = (Map) value;
if (map.isEmpty()) {
continue;
}
}
}
Object store = mapper.marshal(value);
document.put(mapper.fieldName, store);
}
return document;
}
private Map<Field, FieldMapper> getFields(Class<?> cls) {
if (cls.equals(type) && fields != null) {
return fields;
}
Map<Field, FieldMapper> fields = new HashMap<>();
for (Field field : morphix.getEntityHelper().getFields(cls)) {
FieldMapper mapper = createFromField(cls, field, morphix);
if (mapper != null) {
fields.put(field, mapper);
}
}
return fields;
}
}
|
src/main/java/me/hfox/morphix/mapping/field/EntityMapper.java
|
package me.hfox.morphix.mapping.field;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.DBRef;
import me.hfox.morphix.Morphix;
import me.hfox.morphix.MorphixDefaults;
import me.hfox.morphix.annotation.NotSaved;
import me.hfox.morphix.annotation.Reference;
import me.hfox.morphix.annotation.entity.Entity;
import me.hfox.morphix.annotation.entity.StoreEmpty;
import me.hfox.morphix.annotation.entity.StoreNull;
import me.hfox.morphix.annotation.entity.Polymorph;
import me.hfox.morphix.annotation.lifecycle.PostLoad;
import me.hfox.morphix.annotation.lifecycle.PreLoad;
import me.hfox.morphix.exception.MorphixException;
import me.hfox.morphix.util.AnnotationUtils;
import org.bson.types.ObjectId;
import sun.reflect.ReflectionFactory;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
public class EntityMapper<T> extends FieldMapper<T> {
private Class<T> cls;
private Entity entity;
private StoreEmpty storeEmpty;
private StoreNull storeNull;
private Polymorph polymorph;
private boolean polymorphEnabled;
private Reference reference;
private NotSaved notSaved;
private Map<Field, FieldMapper> fields;
public EntityMapper(Class<T> type, Class<?> parent, Field field, Morphix morphix) {
super(type, parent, field, morphix);
this.cls = type;
}
public Entity getEntity() {
return entity;
}
public StoreEmpty getStoreEmpty() {
return storeEmpty;
}
public StoreNull getStoreNull() {
return storeNull;
}
public Polymorph getPolymorph() {
return polymorph;
}
public boolean isPolymorphEnabled() {
return polymorphEnabled;
}
public Reference getReference() {
return reference;
}
public NotSaved getNotSaved() {
return notSaved;
}
@Override
protected void discover() {
super.discover();
entity = AnnotationUtils.getHierarchicalAnnotation(type, Entity.class);
storeEmpty = AnnotationUtils.getHierarchicalAnnotation(type, StoreEmpty.class);
storeNull = AnnotationUtils.getHierarchicalAnnotation(type, StoreNull.class);
polymorph = AnnotationUtils.getHierarchicalAnnotation(type, Polymorph.class);
polymorphEnabled = polymorph == null || polymorph.value();
if (field != null) {
reference = field.getAnnotation(Reference.class);
notSaved = field.getAnnotation(NotSaved.class);
}
fields = getFields(type);
}
@Override
public T unmarshal(Object obj) {
return unmarshal(obj, MorphixDefaults.DEFAULT_LIFECYCLE);
}
@Override
@SuppressWarnings("unchecked")
public T unmarshal(Object obj, boolean lifecycle) {
if (obj == null) {
return null;
}
if (reference != null) {
if (obj instanceof DBRef) {
DBRef ref = (DBRef) obj;
return morphix.createQuery(cls, ref.getRef()).field("_id").equal(ref.getId()).get();
} else if (obj instanceof ObjectId) {
ObjectId id = (ObjectId) obj;
return morphix.createQuery(cls).field("_id").equal(id).get();
}
return null;
}
if (!(obj instanceof DBObject)) {
return null;
}
DBObject object = (DBObject) obj;
Class<?> cls = polymorphEnabled ? morphix.getPolymorhpismHelper().generate(object) : type;
if (cls == null) {
cls = type;
}
Object result = null;
try {
result = cls.newInstance();
} catch (Exception ex) {}
if (result == null) {
final ReflectionFactory reflection = ReflectionFactory.getReflectionFactory();
final Constructor constructor;
try {
// System.out.println("Class: " + cls);
constructor = reflection.newConstructorForSerialization(cls, Object.class.getDeclaredConstructor());
// System.out.println("Constructor: " + constructor);
result = constructor.newInstance();
// System.out.println("Result: " + result);
} catch (Exception ex) {
throw new MorphixException(ex);
}
}
if (lifecycle) {
morphix.getLifecycleHelper().call(PreLoad.class, result);
}
Map<Field, FieldMapper> fields = getFields(cls);
for (Entry<Field, FieldMapper> entry : fields.entrySet()) {
Field field = entry.getKey();
// System.out.println("Attempting to pull " + field);
field.setAccessible(true);
FieldMapper mapper = entry.getValue();
Object dbResult = object.get(mapper.fieldName);
// System.out.println("Result: " + dbResult);
// if (dbResult == null && (storeNull == null || !storeNull.value())) {
// continue;
// }
Object value = mapper.unmarshal(dbResult);
// System.out.println("Mapped: " + value);
if (storeEmpty == null || !storeEmpty.value()) {
if (value instanceof Collection) {
Collection collection = (Collection) value;
if (collection.isEmpty()) {
value = null;
}
} else if (value instanceof Map) {
Map map = (Map) value;
if (map.isEmpty()) {
value = null;
}
}
}
try {
field.set(result, value);
} catch (IllegalAccessException ex) {
throw new MorphixException(ex);
}
}
if (lifecycle) {
morphix.getLifecycleHelper().call(PostLoad.class, result);
}
return (T) result;
}
@Override
public Object marshal(Object obj, boolean lifecycle) {
if (obj == null) {
return null;
}
Class<?> cls = obj.getClass();
if (reference != null) {
ObjectId id = morphix.getEntityHelper().getObjectId(obj, true);
// if (id == null) {
// throw new MorphixException("Can't reference an Entity with no id");
// }
if (reference.dbRef()) {
return new DBRef(null, morphix.getEntityHelper().getCollectionName(obj.getClass()), id);
}
return id;
}
BasicDBObject document = new BasicDBObject();
if (polymorphEnabled) {
morphix.getPolymorhpismHelper().store(document, obj.getClass());
}
Map<Field, FieldMapper> fields = getFields(cls);
for (Entry<Field, FieldMapper> entry : fields.entrySet()) {
Field field = entry.getKey();
field.setAccessible(true);
FieldMapper mapper = entry.getValue();
Object value;
try {
value = field.get(obj);
} catch (IllegalAccessException ex) {
throw new MorphixException(ex);
}
if (value == null && (storeNull == null || !storeNull.value())) {
continue;
}
if ((storeEmpty == null || !storeEmpty.value())) {
if (value instanceof Collection) {
Collection collection = (Collection) value;
if (collection.isEmpty()) {
continue;
}
} else if (value instanceof Map) {
Map map = (Map) value;
if (map.isEmpty()) {
continue;
}
}
}
Object store = mapper.marshal(value);
document.put(mapper.fieldName, store);
}
return document;
}
private Map<Field, FieldMapper> getFields(Class<?> cls) {
if (cls.equals(type) && fields != null) {
return fields;
}
Map<Field, FieldMapper> fields = new HashMap<>();
for (Field field : morphix.getEntityHelper().getFields(cls)) {
FieldMapper mapper = createFromField(cls, field, morphix);
if (mapper != null) {
fields.put(field, mapper);
}
}
return fields;
}
}
|
Polymorphism should be disabled by default
|
src/main/java/me/hfox/morphix/mapping/field/EntityMapper.java
|
Polymorphism should be disabled by default
|
|
Java
|
mit
|
ffb0d6fa6a564c476d3d600ac51fad6ad6e52a48
| 0
|
cristid9/FunWeb,cristid9/FunWeb,cristid9/FunWeb
|
package serviceResources;
import db.DBConnector;
import serviceRepresentations.GameCharacter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class CharacterDAO {
private DBConnector dbConnector;
public CharacterDAO(DBConnector dbConnector) {
this.dbConnector = dbConnector;
}
/**
* Inserts a new entry in characters table.
* @param character The new character that will be inserted.
* @return TRUE if action succeeded, FALSE otherwise.
*/
public Boolean createCharacter(GameCharacter character) {
// TODO: Needs testing.
try {
Connection connection = dbConnector.getDBConnection();
PreparedStatement statement =
connection.prepareStatement("INSERT INTO CHARACTERS VALUES (?, ?, ?)");
statement.setString(1, character.getName());
statement.setString( 2, character.getPicturePath());
statement.setLong(3, character.getQuestionsNumber());
int affectedRowss = statement.executeUpdate();
if (affectedRowss == 0) {
return Boolean.FALSE; // not sure about this
}
return Boolean.TRUE;
} catch (SQLException e) {
e.printStackTrace();
}
return Boolean.TRUE;
}
/**
* Returns a new `GameCharacter` object representing the NPC at that row.
* @param id The `id` of the NPC.
* @return A `GameCharacter`.
*/
public GameCharacter getCharacter(Long id) {
GameCharacter gameCharacter = null;
try {
Connection connection = dbConnector.getDBConnection();
PreparedStatement statement =
connection.prepareStatement("SELECT " +
"NAME, " +
"PICTURE_PATH, " +
"QUESTION_NUMBER FROM CHARACTERS WHERE ID = ?");
statement.setLong(1, id);
ResultSet rs = statement.executeQuery();
gameCharacter = new GameCharacter();
gameCharacter.setId(id);
gameCharacter.setName(rs.getString("NAME"));
gameCharacter.setPicturePath(rs.getString("PICTURE_PATH"));
gameCharacter.setQuestionsNumber(rs.getLong("QUESTION_NUMBER"));
return gameCharacter;
} catch (SQLException e) {
e.printStackTrace();
}
return gameCharacter;
}
/**
* Removes the NPC with the id `id` from the database.
* @param id The `id` of the targeted NPC.
* @return TRUE if success, FALSE otherwise.
*/
public Boolean removeCharacter(Long id) {
try {
Connection connection = dbConnector.getDBConnection();
PreparedStatement statement =
connection.prepareStatement("DELETE FROM CHARACTERS WHERE ID = ?");
statement.setLong(1, id);
int affectedRows = statement.executeUpdate();
if (affectedRows == 0) {
return Boolean.FALSE;
}
return Boolean.TRUE;
} catch (SQLException e) {
e.printStackTrace();
}
return Boolean.FALSE;
}
}
|
FWDBApi/src/main/java/serviceResources/CharacterDAO.java
|
package serviceResources;
import db.DBConnector;
import serviceRepresentations.GameCharacter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class CharacterDAO {
private DBConnector dbConnector;
public CharacterDAO(DBConnector dbConnector) {
this.dbConnector = dbConnector;
}
/**
* Inserts a new entry in characters table.
* @param character The new character that will be inserted.
* @return TRUE if action succeeded, FALSE otherwise.
*/
public Boolean createCharacter(GameCharacter character) {
// TODO: Needs testing.
try {
Connection connection = dbConnector.getDBConnection();
PreparedStatement statement =
connection.prepareStatement("INSERT INTO CHARACTERS VALUES (?, ?, ?)");
statement.setString(1, character.getName());
statement.setString( 2, character.getPicturePath());
statement.setLong(3, character.getQuestionsNumber());
int affectedRowss = statement.executeUpdate();
if (affectedRowss == 0) {
return Boolean.FALSE; // not sure about this
}
return Boolean.TRUE;
} catch (SQLException e) {
e.printStackTrace();
}
return Boolean.TRUE;
}
/**
* Returns a new `GameCharacter` object representing the NPC at that row.
* @param id The `id` of the NPC.
* @return A `GameCharacter`.
*/
public GameCharacter getCharacter(Long id) {
GameCharacter gameCharacter = null;
try {
Connection connection = dbConnector.getDBConnection();
PreparedStatement statement =
connection.prepareStatement("SELECT " +
"NAME, " +
"PICTURE_PATH, " +
"QUESTION_NUMBER FROM CHARACTERS WHERE ID = ?");
statement.setLong(1, id);
ResultSet rs = statement.executeQuery();
gameCharacter = new GameCharacter();
gameCharacter.setId(id);
gameCharacter.setName(rs.getString("NAME"));
gameCharacter.setPicturePath(rs.getString("PICTURE_PATH"));
gameCharacter.setQuestionsNumber(rs.getLong("QUESTION_NUMBER"));
return gameCharacter;
} catch (SQLException e) {
e.printStackTrace();
}
return gameCharacter;
}
}
|
Added remove method for CharacterDAO
|
FWDBApi/src/main/java/serviceResources/CharacterDAO.java
|
Added remove method for CharacterDAO
|
|
Java
|
mit
|
af54cb2db0b49a2251273160fd8ef79fc4dcf30b
| 0
|
EDACC/edacc_api
|
package edacc.api;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import edacc.model.*;
import edacc.parameterspace.domain.*;
import edacc.parameterspace.graph.ParameterGraph;
import edacc.parameterspace.ParameterConfiguration;
import edacc.properties.PropertyTypeNotExistException;
public class API {
private static DatabaseConnector db = DatabaseConnector.getInstance();
public boolean connect(String hostname, int port, String database, String username, String password) {
try {
db.connect(hostname, port, username, database, password, false, false, 8);
return true;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
public void disconnect() {
db.disconnect();
}
public int createSolverConfig(int experiment_id, ParameterConfiguration config) {
try {
ConfigurationScenario cs = ConfigurationScenarioDAO.getConfigurationScenarioByExperimentId(experiment_id);
SolverBinaries solver_binary = SolverBinariesDAO.getById(cs.getIdSolverBinary());
SolverConfiguration solver_config = SolverConfigurationDAO.createSolverConfiguration(solver_binary, experiment_id, 0, solver_binary.getBinaryName());
for (ConfigurationScenarioParameter param: cs.getParameters()) {
if ("instance".equals(param.getParameter().getName()) || "seed".equals(param.getParameter().getName())) {
ParameterInstance pi = ParameterInstanceDAO.createParameterInstance(param.getParameter().getId(), solver_config, "");
ParameterInstanceDAO.save(pi);
}
else if (!param.isConfigurable()) {
if (param.getParameter().getHasValue()) {
ParameterInstance pi = ParameterInstanceDAO.createParameterInstance(param.getParameter().getId(), solver_config, param.getFixedValue());
ParameterInstanceDAO.save(pi);
}
else { // flag
ParameterInstance pi = ParameterInstanceDAO.createParameterInstance(param.getParameter().getId(), solver_config, "");
ParameterInstanceDAO.save(pi);
}
}
else {
edacc.parameterspace.Parameter config_param = null;
for (edacc.parameterspace.Parameter p: config.getParameter_instances().keySet()) {
if (p.getName().equals(param.getParameter().getName())) {
config_param = p;
break;
}
}
if (OptionalDomain.OPTIONS.NOT_SPECIFIED.equals(config.getParameterValue(config_param))) continue;
else if (FlagDomain.FLAGS.OFF.equals(config.getParameterValue(config_param))) continue;
else {
ParameterInstance pi = ParameterInstanceDAO.createParameterInstance(param.getParameter().getId(), solver_config, config.getParameterValue(config_param).toString());
ParameterInstanceDAO.save(pi);
}
}
}
return solver_config.getId();
}
catch (Exception e) {
e.printStackTrace();
}
return 0;
}
public int launchJob(int experiment_id, int solver_config_id, int instance_id, BigInteger seed, int cpu_time_limit) {
try {
ExperimentResult job = ExperimentResultDAO.createExperimentResult(getCurrentMaxRun(solver_config_id, instance_id) + 1, 0, 0, StatusCode.NOT_STARTED, seed.intValue(), ResultCode.UNKNOWN, 0, solver_config_id, experiment_id, instance_id, null, cpu_time_limit, -1, -1, -1, -1, -1);
ArrayList<ExperimentResult> l = new ArrayList<ExperimentResult>();
l.add(job);
ExperimentResultDAO.batchSave(l);
return job.getId();
}
catch (Exception e) {
e.printStackTrace();
}
return 0;
}
public ExperimentResult getJob(int job_id) {
try {
return ExperimentResultDAO.getById(job_id);
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
public ExperimentResult killJob(int job_id) {
try {
ExperimentResult er = ExperimentResultDAO.getById(job_id);
if (!(er.getStatus().equals(StatusCode.NOT_STARTED) || er.getStatus().equals(StatusCode.RUNNING))) return er;
if (er.getIdClient() != null) {
ClientDAO.sendMessage(er.getIdClient(), "kill " + er.getId());
}
return null;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public boolean deleteResult(int job_id) {
try {
ExperimentResult er = ExperimentResultDAO.getById(job_id);
if (er == null) return false;
ArrayList<ExperimentResult> l = new ArrayList<ExperimentResult>();
l.add(er);
ExperimentResultDAO.deleteExperimentResults(l);
return true;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
public ArrayList<ExperimentResult> getRuns(int solver_config_id) {
try {
return ExperimentResultDAO.getAllBySolverConfiguration(SolverConfigurationDAO.getSolverConfigurationById(solver_config_id));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public ParameterGraph loadParameterGraphFromDB(int experiment_id) {
try {
Statement st = db.getConn().createStatement();
ResultSet rs = st.executeQuery("SELECT serializedGraph FROM ConfigurationScenario JOIN SolverBinaries ON SolverBinaries_idSolverBinary=idSolverBinary JOIN ParameterGraph ON SolverBinaries.idSolver=ParameterGraph.Solver_idSolver WHERE Experiment_idExperiment = " + experiment_id);
try {
if (rs.next()) {
return unmarshal(ParameterGraph.class, rs.getBlob("serializedGraph").getBinaryStream());
}
} catch (JAXBException e) {
e.printStackTrace();
return null;
} finally {
rs.close();
st.close();
}
} catch (SQLException e) {
e.printStackTrace();
return null;
}
return null;
}
public ParameterGraph loadParameterGraphFromFile(String xmlFileName) throws FileNotFoundException {
FileInputStream fis = new FileInputStream(xmlFileName);
ParameterGraph unm;
try {
unm = unmarshal(ParameterGraph.class, fis);
} catch (JAXBException e) {
e.printStackTrace();
return null;
}
unm.buildAdjacencyList();
return unm;
}
@SuppressWarnings("unchecked")
private <T> T unmarshal( Class<T> docClass, InputStream inputStream )
throws JAXBException {
JAXBContext jc = JAXBContext.newInstance( docClass);
Unmarshaller u = jc.createUnmarshaller();
return (T)u.unmarshal(inputStream);
}
private int getCurrentMaxRun(int solver_config_id, int instance_id) {
try {
PreparedStatement ps = db.getConn().prepareStatement("SELECT MAX(run) FROM ExperimentResults WHERE SolverConfig_idSolverConfig=? AND Instances_idInstance=?");
ps.setInt(1, solver_config_id);
ps.setInt(2, instance_id);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
return rs.getInt(1);
}
} catch (SQLException e) {
e.printStackTrace();
return -1;
}
return -1;
}
}
|
src/edacc/api/API.java
|
package edacc.api;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import edacc.model.*;
import edacc.parameterspace.domain.*;
import edacc.parameterspace.graph.ParameterGraph;
import edacc.parameterspace.ParameterConfiguration;
import edacc.properties.PropertyTypeNotExistException;
public class API {
private static DatabaseConnector db = DatabaseConnector.getInstance();
public boolean connect(String hostname, int port, String database, String username, String password) {
try {
db.connect(hostname, port, username, database, password, false, false, 8);
return true;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
public void disconnect() {
db.disconnect();
}
public int createSolverConfig(int experiment_id, ParameterConfiguration config) {
try {
ConfigurationScenario cs = ConfigurationScenarioDAO.getConfigurationScenarioByExperimentId(experiment_id);
SolverBinaries solver_binary = SolverBinariesDAO.getById(cs.getIdSolverBinary());
SolverConfiguration solver_config = SolverConfigurationDAO.createSolverConfiguration(solver_binary, experiment_id, 0, solver_binary.getBinaryName());
for (ConfigurationScenarioParameter param: cs.getParameters()) {
if ("instance".equals(param.getParameter().getName()) || "seed".equals(param.getParameter().getName())) {
ParameterInstance pi = ParameterInstanceDAO.createParameterInstance(param.getParameter().getId(), solver_config, "");
ParameterInstanceDAO.save(pi);
}
else if (!param.isConfigurable()) {
ParameterInstance pi = ParameterInstanceDAO.createParameterInstance(param.getParameter().getId(), solver_config, param.getFixedValue());
ParameterInstanceDAO.save(pi);
}
else {
edacc.parameterspace.Parameter config_param = null;
for (edacc.parameterspace.Parameter p: config.getParameter_instances().keySet()) {
if (p.getName().equals(param.getParameter().getName())) {
config_param = p;
break;
}
}
if (OptionalDomain.OPTIONS.NOT_SPECIFIED.equals(config.getParameterValue(config_param))) continue;
else if (FlagDomain.FLAGS.OFF.equals(config.getParameterValue(config_param))) continue;
else {
ParameterInstance pi = ParameterInstanceDAO.createParameterInstance(param.getParameter().getId(), solver_config, config.getParameterValue(config_param).toString());
ParameterInstanceDAO.save(pi);
}
}
}
return solver_config.getId();
}
catch (Exception e) {
e.printStackTrace();
}
return 0;
}
public int launchJob(int experiment_id, int solver_config_id, int instance_id, BigInteger seed, int cpu_time_limit) {
try {
ExperimentResult job = ExperimentResultDAO.createExperimentResult(getCurrentMaxRun(solver_config_id, instance_id) + 1, 0, 0, StatusCode.NOT_STARTED, seed.intValue(), ResultCode.UNKNOWN, 0, solver_config_id, experiment_id, instance_id, null, cpu_time_limit, -1, -1, -1, -1, -1);
ArrayList<ExperimentResult> l = new ArrayList<ExperimentResult>();
l.add(job);
ExperimentResultDAO.batchSave(l);
return job.getId();
}
catch (Exception e) {
e.printStackTrace();
}
return 0;
}
public ExperimentResult getJob(int job_id) {
try {
return ExperimentResultDAO.getById(job_id);
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
public ExperimentResult killJob(int job_id) {
try {
ExperimentResult er = ExperimentResultDAO.getById(job_id);
if (!(er.getStatus().equals(StatusCode.NOT_STARTED) || er.getStatus().equals(StatusCode.RUNNING))) return er;
if (er.getIdClient() != null) {
ClientDAO.sendMessage(er.getIdClient(), "kill " + er.getId());
}
return null;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public boolean deleteResult(int job_id) {
try {
ExperimentResult er = ExperimentResultDAO.getById(job_id);
if (er == null) return false;
ArrayList<ExperimentResult> l = new ArrayList<ExperimentResult>();
l.add(er);
ExperimentResultDAO.deleteExperimentResults(l);
return true;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
public ArrayList<ExperimentResult> getRuns(int solver_config_id) {
try {
return ExperimentResultDAO.getAllBySolverConfiguration(SolverConfigurationDAO.getSolverConfigurationById(solver_config_id));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public ParameterGraph loadParameterGraphFromDB(int experiment_id) {
try {
Statement st = db.getConn().createStatement();
ResultSet rs = st.executeQuery("SELECT serializedGraph FROM ConfigurationScenario JOIN SolverBinaries ON SolverBinaries_idSolverBinary=idSolverBinary JOIN ParameterGraph ON SolverBinaries.idSolver=ParameterGraph.Solver_idSolver WHERE Experiment_idExperiment = " + experiment_id);
try {
if (rs.next()) {
return unmarshal(ParameterGraph.class, rs.getBlob("serializedGraph").getBinaryStream());
}
} catch (JAXBException e) {
e.printStackTrace();
return null;
} finally {
rs.close();
st.close();
}
} catch (SQLException e) {
e.printStackTrace();
return null;
}
return null;
}
public ParameterGraph loadParameterGraphFromFile(String xmlFileName) throws FileNotFoundException {
FileInputStream fis = new FileInputStream(xmlFileName);
ParameterGraph unm;
try {
unm = unmarshal(ParameterGraph.class, fis);
} catch (JAXBException e) {
e.printStackTrace();
return null;
}
unm.buildAdjacencyList();
return unm;
}
@SuppressWarnings("unchecked")
private <T> T unmarshal( Class<T> docClass, InputStream inputStream )
throws JAXBException {
JAXBContext jc = JAXBContext.newInstance( docClass);
Unmarshaller u = jc.createUnmarshaller();
return (T)u.unmarshal(inputStream);
}
private int getCurrentMaxRun(int solver_config_id, int instance_id) {
try {
PreparedStatement ps = db.getConn().prepareStatement("SELECT MAX(run) FROM ExperimentResults WHERE SolverConfig_idSolverConfig=? AND Instances_idInstance=?");
ps.setInt(1, solver_config_id);
ps.setInt(2, instance_id);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
return rs.getInt(1);
}
} catch (SQLException e) {
e.printStackTrace();
return -1;
}
return -1;
}
}
|
update
|
src/edacc/api/API.java
|
update
|
|
Java
|
mit
|
fc8dbee4c3ecb7ccf5ad4d66f55af60f36824b4d
| 0
|
ebirn/bitcoin-exchange
|
import at.outdated.bitcoin.exchange.api.currency.Currency;
import at.outdated.bitcoin.exchange.api.market.TickerValue;
import at.outdated.bitcoin.exchange.btce.BtcEApiClient;
import org.junit.Assert;
import org.junit.Test;
/**
* Created with IntelliJ IDEA.
* User: ebirn
* Date: 27.05.13
* Time: 00:00
* To change this template use File | Settings | File Templates.
*/
public class ClientTest {
BtcEApiClient client = new BtcEApiClient();
@Test
public void testTicker() {
TickerValue ticker = client.getTicker(Currency.EUR);
Assert.assertNotNull(ticker);
Assert.assertNotNull(ticker.getTimestamp());
System.out.println("ticker: "+ ticker.getTimestamp() +" " + ticker);
ticker = client.getTicker(Currency.USD);
Assert.assertNotNull(ticker);
Assert.assertNotNull(ticker.getTimestamp());
System.out.println("ticker: "+ ticker.getTimestamp() +" " + ticker);
}
}
|
btc-e/src/test/java/ClientTest.java
|
import at.outdated.bitcoin.exchange.api.currency.Currency;
import at.outdated.bitcoin.exchange.api.market.TickerValue;
import at.outdated.bitcoin.exchange.bitkonan.BtcEApiClient;
import org.junit.Assert;
import org.junit.Test;
/**
* Created with IntelliJ IDEA.
* User: ebirn
* Date: 27.05.13
* Time: 00:00
* To change this template use File | Settings | File Templates.
*/
public class ClientTest {
BtcEApiClient client = new BtcEApiClient();
@Test
public void testTicker() {
TickerValue ticker = client.getTicker(Currency.EUR);
Assert.assertNotNull(ticker);
Assert.assertNotNull(ticker.getTimestamp());
System.out.println("ticker: "+ ticker.getTimestamp() +" " + ticker);
ticker = client.getTicker(Currency.USD);
Assert.assertNotNull(ticker);
Assert.assertNotNull(ticker.getTimestamp());
System.out.println("ticker: "+ ticker.getTimestamp() +" " + ticker);
}
}
|
fix test
|
btc-e/src/test/java/ClientTest.java
|
fix test
|
|
Java
|
mit
|
f3a6921bc7600f3beed5c414c5b3505683ffd34e
| 0
|
nullbox/Data-and-Information-Visualization-Project
|
package big.marketing.data;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
/**
* Class stores the information from a single network health message from a node
*
* @author jaakkju
*/
public class HealthMessage implements DBWritable {
public static final int STATUS_GOOD = 1;
public static final int STATUS_WARNING = 2;
public static final int STATUS_PROBLEM = 3;
public static final int CONN_OK = 1;
public static final int CONN_NOK = 0;
// private final int id;
private final String hostname;
private final String serviceName;
private final int time;
private final int statusVal;
private final String receivedFrom;
private final int diskUsage;
private final int pageFileUsage;
private final int numProcs;
private final int loadAverage;
private final int physicalMemoryUsage;
private final int connMade;
@Override
public String toString() {
return "HealthMessage [hostname=" + hostname + ", statusVal=" + statusVal + ", time=" + time + ", diskUsage=" + diskUsage
+ ", pageFileUsage=" + pageFileUsage + ", numProcs=" + numProcs + ", loadAverage=" + loadAverage + ", physicalMemoryUsage="
+ physicalMemoryUsage + "]";
}
public HealthMessage(DBObject dbo) {
this.hostname = (String) dbo.get("hostname");
this.serviceName = (String) dbo.get("serviceName");
this.statusVal = (Integer) dbo.get("statusVal");
this.receivedFrom = (String) dbo.get("receivedFrom");
this.time = (Integer) dbo.get("time");
this.diskUsage = (Integer) dbo.get("diskUsage");
this.pageFileUsage = (Integer) dbo.get("pageFileUsage");
this.numProcs = (Integer) dbo.get("numProcs");
this.loadAverage = (Integer) dbo.get("loadAverage");
this.physicalMemoryUsage = (Integer) dbo.get("physicalMemoryUsage");
this.connMade = (Integer) dbo.get("connMade");
}
/**
* @param args [id, hostname, serviceName, currentTime, statusVal,
* receivedFrom, diskUsage, pageFileusage, numProcs, loadAverage,
* physicalMemoryUsage, connMade]
*/
public HealthMessage(String[] args) {
// this.id = argsToInt(args, 0);
this.hostname = argsToString(args, 1);
this.serviceName = argsToString(args, 2);
int timeSeconds = (int) Double.parseDouble(args[3]);
this.time = (timeSeconds / 60) * 60;
this.statusVal = argsToInt(args, 4);
// args[5] is the unparsed message content
this.receivedFrom = argsToString(args, 6);
this.diskUsage = argsToInt(args, 7);
this.pageFileUsage = argsToInt(args, 8);
this.numProcs = argsToInt(args, 9);
this.loadAverage = argsToInt(args, 10);
this.physicalMemoryUsage = argsToInt(args, 11);
this.connMade = argsToInt(args, 12);
// args[13] is parsedDate from message content
}
private int argsToInt(String args[], int index) {
if (args.length - 1 >= index && !args[index].isEmpty()) {
return Integer.valueOf(args[index]);
}
return 0;
}
private String argsToString(String args[], int index) {
if (args.length - 1 >= index && !args[index].isEmpty()) {
return args[index];
}
return "";
}
public String getHostname() {
return hostname;
}
public String getServiceName() {
return serviceName;
}
public int getStatusVal() {
return statusVal;
}
public String getReceivedFrom() {
return receivedFrom;
}
public int getTime() {
return time;
}
public int getDiskUsage() {
return diskUsage;
}
public int getPageFileUsage() {
return pageFileUsage;
}
public int getNumProcs() {
return numProcs;
}
public int getLoadAverage() {
return loadAverage;
}
public int getPhysicalMemoryUsage() {
return physicalMemoryUsage;
}
public int getConnMade() {
return connMade;
}
public DBObject asDBObject() {
BasicDBObject bdbo = new BasicDBObject();
bdbo.append("hostname", hostname);
bdbo.append("serviceName", serviceName);
bdbo.append("statusVal", statusVal);
bdbo.append("receivedFrom", receivedFrom);
bdbo.append("time", time);
bdbo.append("diskUsage", diskUsage);
bdbo.append("pageFileUsage", pageFileUsage);
bdbo.append("numProcs", numProcs);
bdbo.append("loadAverage", loadAverage);
bdbo.append("physicalMemoryUsage", physicalMemoryUsage);
bdbo.append("connMade", connMade);
return bdbo;
}
}
|
src/big/marketing/data/HealthMessage.java
|
package big.marketing.data;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
/**
* Class stores the information from a single network health message from a node
*
* @author jaakkju
*/
public class HealthMessage implements DBWritable {
public static final int STATUS_GOOD = 1;
public static final int STATUS_WARNING = 2;
public static final int STATUS_PROBLEM = 3;
public static final int CONN_OK = 1;
public static final int CONN_NOK = 0;
private final String hostname;
private final int statusVal;
private final int time;
private final int diskUsage;
private final int pageFileUsage;
private final int numProcs;
private final int loadAverage;
private final int physicalMemoryUsage;
@Override
public String toString() {
return "HealthMessage [hostname=" + hostname + ", statusVal=" + statusVal + ", time=" + time + ", diskUsage=" + diskUsage
+ ", pageFileUsage=" + pageFileUsage + ", numProcs=" + numProcs + ", loadAverage=" + loadAverage + ", physicalMemoryUsage="
+ physicalMemoryUsage + "]";
}
public HealthMessage(DBObject dbo) {
this.hostname = (String) dbo.get("hostname");
this.statusVal = (Integer) dbo.get("statusVal");
this.time = (Integer) dbo.get("time");
this.diskUsage = (Integer) dbo.get("diskUsage");
this.pageFileUsage = (Integer) dbo.get("pageFileUsage");
this.numProcs = (Integer) dbo.get("numProcs");
this.loadAverage = (Integer) dbo.get("loadAverage");
this.physicalMemoryUsage = (Integer) dbo.get("physicalMemoryUsage");
}
/**
* @param args [id, hostname, serviceName, currentTime, statusVal,
* receivedFrom, diskUsage, pageFileusage, numProcs, loadAverage,
* physicalMemoryUsage, connMade]
*/
public HealthMessage(String[] args) {
// this.id = argsToInt(args, 0);
this.hostname = argsToString(args, 1);
// this.serviceName = argsToString(args, 2);
int timeSeconds = (int) Double.parseDouble(args[3]);
this.time = (timeSeconds / 60) * 60;
this.statusVal = argsToInt(args, 4);
// args[5] is the unparsed message content
// this.receivedFrom = argsToString(args, 6);
this.diskUsage = argsToInt(args, 7);
this.pageFileUsage = argsToInt(args, 8);
this.numProcs = argsToInt(args, 9);
this.loadAverage = argsToInt(args, 10);
this.physicalMemoryUsage = argsToInt(args, 11);
// this.connMade = argsToInt(args, 12);
// args[13] is parsedDate from message content
}
private int argsToInt(String args[], int index) {
if (args.length - 1 >= index && !args[index].isEmpty()) {
return Integer.valueOf(args[index]);
}
return 0;
}
private String argsToString(String args[], int index) {
if (args.length - 1 >= index && !args[index].isEmpty()) {
return args[index];
}
return "";
}
public String getHostname() {
return hostname;
}
public int getStatusVal() {
return statusVal;
}
public int getTime() {
return time;
}
public int getDiskUsage() {
return diskUsage;
}
public int getPageFileUsage() {
return pageFileUsage;
}
public int getNumProcs() {
return numProcs;
}
public int getLoadAverage() {
return loadAverage;
}
public int getPhysicalMemoryUsage() {
return physicalMemoryUsage;
}
public DBObject asDBObject() {
BasicDBObject bdbo = new BasicDBObject();
bdbo.append("hostname", hostname);
bdbo.append("statusVal", statusVal);
bdbo.append("time", time);
bdbo.append("diskUsage", diskUsage);
bdbo.append("pageFileUsage", pageFileUsage);
bdbo.append("numProcs", numProcs);
bdbo.append("loadAverage", loadAverage);
bdbo.append("physicalMemoryUsage", physicalMemoryUsage);
return bdbo;
}
}
|
added some more fields to health message
|
src/big/marketing/data/HealthMessage.java
|
added some more fields to health message
|
|
Java
|
mit
|
aeef68eb325e8c043b9cc898d2fe4fb698a3f3e0
| 0
|
andreasdr/tdme,andreasdr/tdme,andreasdr/tdme
|
package net.drewke.tdme.gui;
/**
* GUI Panel
* @author Andreas Drewke
* @version $Id$
*/
public final class GUIPanelNode extends GUILayoutNode {
private String backgroundImage;
private GUIColor backgroundColor;
/**
* Constructor
* @param parent node
* @param id
* @param alignments
* @param requested constraints
* @param alignment
* @param background color
* @param background image
*/
protected GUIPanelNode(
GUINode parentNode,
String id,
Alignments alignments,
RequestedConstraints requestedConstraints,
String alignment,
String backgroundColor,
String backgroundImage)
throws GUIParserException {
//
super(parentNode, id, alignments, requestedConstraints, alignment);
this.backgroundColor = backgroundColor == null || backgroundColor.length() == 0?new GUIColor():new GUIColor(backgroundColor);
this.backgroundImage = backgroundImage;
}
/*
* (non-Javadoc)
* @see net.drewke.tdme.gui.GUINode#getNodeType()
*/
protected String getNodeType() {
return "panel";
}
/*
* (non-Javadoc)
* @see net.drewke.tdme.gui.GUINode#render(net.drewke.tdme.gui.GUIRenderer)
*/
protected void render(GUIRenderer guiRenderer) {
// screen dimension
float screenWidth = guiRenderer.gui.width;
float screenHeight = guiRenderer.gui.height;
// System.out.println(this);
// element location and dimensions
float left = computedConstraints.left + computedConstraints.alignmentLeft;
float top = computedConstraints.top + computedConstraints.alignmentTop;
float width = computedConstraints.width;
float height = computedConstraints.height;
// background color
float[] bgColorData = backgroundColor.getData();
// render panel background
guiRenderer.clear();
guiRenderer.bindTexture(0);
guiRenderer.addQuad(
((left) / (screenWidth / 2f)) - 1f,
((screenHeight - top) / (screenHeight / 2f)) - 1f,
0f,
bgColorData[0], bgColorData[1], bgColorData[2], bgColorData[3],
0f, 1f,
((left + width) / (screenWidth / 2f)) - 1f,
((screenHeight - top) / (screenHeight / 2f)) - 1f,
0f,
bgColorData[0], bgColorData[1], bgColorData[2], bgColorData[3],
1f, 1f,
((left + width) / (screenWidth / 2f)) - 1f,
((screenHeight - top - height) / (screenHeight / 2f)) - 1f,
0f,
bgColorData[0], bgColorData[1], bgColorData[2], bgColorData[3],
1f, 0f,
((left) / (screenWidth / 2f)) - 1f,
((screenHeight - top - height) / (screenHeight / 2f)) - 1f,
0f,
bgColorData[0], bgColorData[1], bgColorData[2], bgColorData[3],
0f, 0f
);
guiRenderer.render();
// render children
super.render(guiRenderer);
}
}
|
src/net/drewke/tdme/gui/GUIPanelNode.java
|
package net.drewke.tdme.gui;
/**
* GUI Panel
* @author Andreas Drewke
* @version $Id$
*/
public final class GUIPanelNode extends GUILayoutNode {
private String backgroundImage;
private GUIColor backgroundColor;
/**
* Constructor
* @param parent node
* @param id
* @param alignments
* @param requested constraints
* @param alignment
* @param background color
* @param background image
*/
protected GUIPanelNode(
GUINode parentNode,
String id,
Alignments alignments,
RequestedConstraints requestedConstraints,
String alignment,
String backgroundColor,
String backgroundImage)
throws GUIParserException {
//
super(parentNode, id, alignments, requestedConstraints, alignment);
this.backgroundColor = backgroundColor == null || backgroundColor.length() == 0?new GUIColor():new GUIColor(backgroundColor);
this.backgroundImage = backgroundImage;
}
/*
* (non-Javadoc)
* @see net.drewke.tdme.gui.GUINode#getNodeType()
*/
protected String getNodeType() {
return "panel";
}
/*
* (non-Javadoc)
* @see net.drewke.tdme.gui.GUINode#render(net.drewke.tdme.gui.GUIRenderer)
*/
protected void render(GUIRenderer guiRenderer) {
// screen dimension
float screenWidth = guiRenderer.gui.width;
float screenHeight = guiRenderer.gui.height;
// System.out.println(this);
// element location and dimensions
float left = computedConstraints.left + computedConstraints.alignmentLeft;
float top = computedConstraints.top + computedConstraints.alignmentTop;
float width = computedConstraints.width;
float height = computedConstraints.height;
// background color
float[] bgColorData = backgroundColor.getData();
// render panel background
guiRenderer.clear();
guiRenderer.bindTexture(0);
guiRenderer.addQuad(
((left) / (screenWidth / 2f)) - 1f,
((screenHeight - top) / (screenHeight / 2f)) - 1f,
0f,
bgColorData[0], bgColorData[1], bgColorData[2], bgColorData[3],
0f, 0f,
((left + width) / (screenWidth / 2f)) - 1f,
((screenHeight - top) / (screenHeight / 2f)) - 1f,
0f,
bgColorData[0], bgColorData[1], bgColorData[2], bgColorData[3],
1f, 0f,
((left + width) / (screenWidth / 2f)) - 1f,
((screenHeight - top - height) / (screenHeight / 2f)) - 1f,
0f,
bgColorData[0], bgColorData[1], bgColorData[2], bgColorData[3],
1f, 1f,
((left) / (screenWidth / 2f)) - 1f,
((screenHeight - top - height) / (screenHeight / 2f)) - 1f,
0f,
bgColorData[0], bgColorData[1], bgColorData[2], bgColorData[3],
0f, 1f
);
guiRenderer.render();
// render children
super.render(guiRenderer);
}
}
|
GUI::PanelNode::have texture coordinates in correct order beginning from top, left clock wise
|
src/net/drewke/tdme/gui/GUIPanelNode.java
|
GUI::PanelNode::have texture coordinates in correct order beginning from top, left clock wise
|
|
Java
|
mit
|
db2c4986dcc7069918f8f289a49b351586a74634
| 0
|
luigi1015/Interest-Calculator
|
package net.codehobby;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.SpinnerNumberModel;
import javax.swing.SwingUtilities;
public class InterestCalculatorGUI extends JFrame
{
private static final long serialVersionUID = 2352202239702195655L;//Automatically generated ID for the class.
public InterestCalculatorGUI()
{
initUI();
}
private void initUI()
{
//Set up the main panel.
JPanel panel = new JPanel();
getContentPane().add( panel );
panel.setLayout(null);
//Set up the Interest rate label and spinner.
//Interest rate label
JLabel interestRateLabel = new JLabel( "Interest Rate (%)" );
interestRateLabel.setBounds( 50, 50, 120, 30 );
panel.add( interestRateLabel );
//Interest rate spinner
SpinnerNumberModel interestRateModel = new SpinnerNumberModel( 7, 1, 100, 1 );
JSpinner interestRateSpinner = new JSpinner( interestRateModel );
interestRateSpinner.setBounds( 170, 50, 120, 30 );
panel.add( interestRateSpinner );
//Set up the Time label and spinner.
//Time label
JLabel timeLabel = new JLabel( "Time (years)" );
timeLabel.setBounds( 50, 100, 120, 30 );
panel.add( timeLabel );
//Time spinner
SpinnerNumberModel timeModel = new SpinnerNumberModel( 30, 1, 100, 1 );
JSpinner timeSpinner = new JSpinner( timeModel );
timeSpinner.setBounds( 170, 100, 120, 30 );
panel.add( timeSpinner );
//Set up the calculate button.
JButton calcButton = new JButton("Calculate");
calcButton.setBounds(50, 150, 120, 30);//Set the x,y coordinates and the width and height.
calcButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{//Just a placeholder function for now.
System.out.println( "You clicked the calculate button! This is just a placeholder." );
}
});
panel.add( calcButton );
//Set up the results label. This will hold the results of the interest calculations.
JLabel resultsLabel = new JLabel( "Results" );
resultsLabel.setBounds( 50, 180, 400, 200 );
panel.add( resultsLabel );
//Set the main window parameters.
setTitle( "Interest Calculator" );
setSize( 600, 600 );
setLocationRelativeTo( null );
setDefaultCloseOperation( EXIT_ON_CLOSE );//Set it to shut down once the close button is pressed.
}
public static void main(String[] args)
{
//The invokeLater puts the application on the Swing Event Queue to make sure all UI updates are concurrency safe.
SwingUtilities.invokeLater( new Runnable() {
public void run() {
InterestCalculatorGUI ic = new InterestCalculatorGUI();
ic.setVisible( true );
}
});
}
}
|
src/net/codehobby/InterestCalculatorGUI.java
|
package net.codehobby;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.SpinnerNumberModel;
import javax.swing.SwingUtilities;
public class InterestCalculatorGUI extends JFrame
{
private static final long serialVersionUID = 2352202239702195655L;//Automatically generated ID for the class.
public InterestCalculatorGUI()
{
initUI();
}
private void initUI()
{
//Set up the main panel.
JPanel panel = new JPanel();
getContentPane().add( panel );
panel.setLayout(null);
//Set up the Interest rate label and spinner.
//Interest rate label
JLabel interestRateLabel = new JLabel( "Interest Rate (%)" );
interestRateLabel.setBounds( 50, 50, 120, 30 );
panel.add( interestRateLabel );
//Interest rate spinner
SpinnerNumberModel interestRateModel = new SpinnerNumberModel( 7, 1, 100, 1 );
JSpinner interestRateSpinner = new JSpinner( interestRateModel );
interestRateSpinner.setBounds( 170, 50, 120, 30 );
panel.add( interestRateSpinner );
//Set up the Time label and spinner.
//Time label
JLabel timeLabel = new JLabel( "Time (years)" );
timeLabel.setBounds( 50, 100, 120, 30 );
panel.add( timeLabel );
//Time spinner
SpinnerNumberModel timeModel = new SpinnerNumberModel( 30, 1, 100, 1 );
JSpinner timeSpinner = new JSpinner( timeModel );
timeSpinner.setBounds( 170, 100, 120, 30 );
panel.add( timeSpinner );
//Set up the calculate button.
JButton calcButton = new JButton("Calculate");
calcButton.setBounds(50, 150, 120, 30);//Set the x,y coordinates and the width and height.
calcButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{//Just a placeholder function for now.
System.out.println( "You clicked the calculate button! This is just a placeholder." );
}
});
panel.add( calcButton );
//Set the main window parameters.
setTitle( "Interest Calculator" );
setSize( 600, 600 );
setLocationRelativeTo( null );
setDefaultCloseOperation( EXIT_ON_CLOSE );//Set it to shut down once the close button is pressed.
}
public static void main(String[] args)
{
//The invokeLater puts the application on the Swing Event Queue to make sure all UI updates are concurrency safe.
SwingUtilities.invokeLater( new Runnable() {
public void run() {
InterestCalculatorGUI ic = new InterestCalculatorGUI();
ic.setVisible( true );
}
});
}
}
|
Created a label for the results.
|
src/net/codehobby/InterestCalculatorGUI.java
|
Created a label for the results.
|
|
Java
|
agpl-3.0
|
2b8805e1594ba9a50f8c903516ff12cfdaaa509b
| 0
|
yichaoS/cbioportal,bihealth/cbioportal,yichaoS/cbioportal,kalletlak/cbioportal,sheridancbio/cbioportal,d3b-center/pedcbioportal,angelicaochoa/cbioportal,yichaoS/cbioportal,bihealth/cbioportal,n1zea144/cbioportal,angelicaochoa/cbioportal,onursumer/cbioportal,cBioPortal/cbioportal,angelicaochoa/cbioportal,d3b-center/pedcbioportal,pughlab/cbioportal,d3b-center/pedcbioportal,jjgao/cbioportal,IntersectAustralia/cbioportal,zhx828/cbioportal,gsun83/cbioportal,adamabeshouse/cbioportal,jjgao/cbioportal,gsun83/cbioportal,jjgao/cbioportal,pughlab/cbioportal,cBioPortal/cbioportal,cBioPortal/cbioportal,inodb/cbioportal,n1zea144/cbioportal,inodb/cbioportal,onursumer/cbioportal,pughlab/cbioportal,onursumer/cbioportal,cBioPortal/cbioportal,bihealth/cbioportal,IntersectAustralia/cbioportal,sheridancbio/cbioportal,IntersectAustralia/cbioportal,kalletlak/cbioportal,cBioPortal/cbioportal,adamabeshouse/cbioportal,bihealth/cbioportal,pughlab/cbioportal,kalletlak/cbioportal,n1zea144/cbioportal,inodb/cbioportal,adamabeshouse/cbioportal,gsun83/cbioportal,mandawilson/cbioportal,zhx828/cbioportal,adamabeshouse/cbioportal,bihealth/cbioportal,n1zea144/cbioportal,n1zea144/cbioportal,gsun83/cbioportal,kalletlak/cbioportal,shrumit/cbioportal-gsoc-final,inodb/cbioportal,cBioPortal/cbioportal,jjgao/cbioportal,shrumit/cbioportal-gsoc-final,yichaoS/cbioportal,zhx828/cbioportal,shrumit/cbioportal-gsoc-final,inodb/cbioportal,kalletlak/cbioportal,IntersectAustralia/cbioportal,IntersectAustralia/cbioportal,shrumit/cbioportal-gsoc-final,kalletlak/cbioportal,adamabeshouse/cbioportal,sheridancbio/cbioportal,d3b-center/pedcbioportal,gsun83/cbioportal,kalletlak/cbioportal,inodb/cbioportal,d3b-center/pedcbioportal,gsun83/cbioportal,sheridancbio/cbioportal,shrumit/cbioportal-gsoc-final,adamabeshouse/cbioportal,zhx828/cbioportal,mandawilson/cbioportal,angelicaochoa/cbioportal,angelicaochoa/cbioportal,n1zea144/cbioportal,bihealth/cbioportal,zhx828/cbioportal,onursumer/cbioportal,angelicaochoa/cbioportal,jjgao/cbioportal,jjgao/cbioportal,adamabeshouse/cbioportal,d3b-center/pedcbioportal,jjgao/cbioportal,bihealth/cbioportal,mandawilson/cbioportal,onursumer/cbioportal,inodb/cbioportal,shrumit/cbioportal-gsoc-final,IntersectAustralia/cbioportal,angelicaochoa/cbioportal,mandawilson/cbioportal,pughlab/cbioportal,pughlab/cbioportal,zhx828/cbioportal,sheridancbio/cbioportal,zhx828/cbioportal,mandawilson/cbioportal,mandawilson/cbioportal,mandawilson/cbioportal,yichaoS/cbioportal,gsun83/cbioportal,n1zea144/cbioportal,d3b-center/pedcbioportal,IntersectAustralia/cbioportal,onursumer/cbioportal,sheridancbio/cbioportal,yichaoS/cbioportal,yichaoS/cbioportal,pughlab/cbioportal,shrumit/cbioportal-gsoc-final
|
/*
* Copyright (c) 2015 Memorial Sloan-Kettering Cancer Center.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY, WITHOUT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS
* FOR A PARTICULAR PURPOSE. The software and documentation provided hereunder
* is on an "as is" basis, and Memorial Sloan-Kettering Cancer Center has no
* obligations to provide maintenance, support, updates, enhancements or
* modifications. In no event shall Memorial Sloan-Kettering Cancer Center be
* liable to any party for direct, indirect, special, incidental or
* consequential damages, including lost profits, arising out of the use of this
* software and its documentation, even if Memorial Sloan-Kettering Cancer
* Center has been advised of the possibility of such damage.
*/
/*
* This file is part of cBioPortal.
*
* cBioPortal is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mskcc.cbio.portal.scripts;
import org.mskcc.cbio.portal.dao.*;
import org.mskcc.cbio.portal.model.CanonicalGene;
import org.mskcc.cbio.portal.util.*;
import java.io.*;
import java.util.*;
/**
* Command Line Tool to Import Background Gene Data.
*/
public class ImportGeneData {
public static void importData(ProgressMonitor pMonitor, File geneFile) throws IOException, DaoException {
Map<String, Set<CanonicalGene>> genesWithSymbolFromNomenClatureAuthority = new LinkedHashMap<>();
Map<String, Set<CanonicalGene>> genesWithoutSymbolFromNomenClatureAuthority = new LinkedHashMap<>();
try (FileReader reader = new FileReader(geneFile)) {
BufferedReader buf = new BufferedReader(reader);
String line;
while ((line = buf.readLine()) != null) {
if (pMonitor != null) {
pMonitor.incrementCurValue();
ConsoleUtil.showProgress(pMonitor);
}
if (line.startsWith("#")) {
continue;
}
String parts[] = line.split("\t");
int taxonimy = Integer.parseInt(parts[0]);
if (taxonimy!=9606) {
// only import human genes
continue;
}
int entrezGeneId = Integer.parseInt(parts[1]);
String geneSymbol = parts[2];
String locusTag = parts[3];
String strAliases = parts[4];
String strXrefs = parts[5];
String cytoband = parts[7];
String desc = parts[8];
String type = parts[9];
String mainSymbol = parts[10]; // use 10 instead of 2 since column 2 may have duplication
Set<String> aliases = new HashSet<String>();
if (!locusTag.equals("-")) {
aliases.add(locusTag);
}
if (!strAliases.equals("-")) {
aliases.addAll(Arrays.asList(strAliases.split("\\|")));
}
if (geneSymbol.startsWith("MIR") && type.equalsIgnoreCase("miscRNA")) {
line = buf.readLine();
continue; // ignore miRNA; process seperately
}
CanonicalGene gene = null;
if (!mainSymbol.equals("-")) {
gene = new CanonicalGene(entrezGeneId, mainSymbol, aliases);
Set<CanonicalGene> genes = genesWithSymbolFromNomenClatureAuthority.get(mainSymbol);
if (genes==null) {
genes = new HashSet<CanonicalGene>();
genesWithSymbolFromNomenClatureAuthority.put(mainSymbol, genes);
}
genes.add(gene);
} else if (!geneSymbol.equals("-")) {
gene = new CanonicalGene(entrezGeneId, geneSymbol, aliases);
Set<CanonicalGene> genes = genesWithoutSymbolFromNomenClatureAuthority.get(geneSymbol);
if (genes==null) {
genes = new HashSet<CanonicalGene>();
genesWithoutSymbolFromNomenClatureAuthority.put(geneSymbol, genes);
}
}
if (gene!=null) {
if (!cytoband.equals("-")) {
gene.setCytoband(cytoband);
}
gene.setType(type);
}
}
}
MySQLbulkLoader.bulkLoadOn();
DaoGeneOptimized daoGene = DaoGeneOptimized.getInstance();
// Add genes with symbol from nomenclature authority
for (Map.Entry<String, Set<CanonicalGene>> entry : genesWithSymbolFromNomenClatureAuthority.entrySet()) {
Set<CanonicalGene> genes = entry.getValue();
if (genes.size()==1) {
daoGene.addGene(genes.iterator().next());
} else {
logDuplicateGeneSymbolWarning(pMonitor, entry.getKey(), genes);
}
}
// Add genes with symbol from nomenclature authority
for (Map.Entry<String, Set<CanonicalGene>> entry : genesWithoutSymbolFromNomenClatureAuthority.entrySet()) {
Set<CanonicalGene> genes = entry.getValue();
String symbol = entry.getKey();
if (genes.size()==1) {
CanonicalGene gene = genes.iterator().next();
if (!genesWithSymbolFromNomenClatureAuthority.containsKey(symbol)) {
daoGene.addGene(gene);
} else {
// ignore entries with a symbol that have the same value as stardard one
pMonitor.logWarning("Ignored line with entrez gene id "+gene.getEntrezGeneId()
+ ". "+symbol+" is already imported.");
}
} else {
logDuplicateGeneSymbolWarning(pMonitor, symbol, genes);
}
}
if (MySQLbulkLoader.isBulkLoad()) {
MySQLbulkLoader.flushAll();
}
}
private static void logDuplicateGeneSymbolWarning(ProgressMonitor pMonitor, String symbol, Set<CanonicalGene> genes) {
StringBuilder sb = new StringBuilder();
sb.append("More than 1 gene has the same standard symbol ")
.append(symbol)
.append(":");
for (CanonicalGene gene : genes) {
sb.append(" ")
.append(gene.getEntrezGeneId())
.append(". Ignore...");
}
pMonitor.logWarning(sb.toString());
}
private static void importGeneLength(ProgressMonitor pMonitor, File geneFile) throws IOException, DaoException {
DaoGeneOptimized daoGeneOptimized = DaoGeneOptimized.getInstance();
FileReader reader = new FileReader(geneFile);
BufferedReader buf = new BufferedReader(reader);
String line;
CanonicalGene currentGene = null;
List<long[]> loci = new ArrayList<long[]>();
while ((line=buf.readLine()) != null) {
if (pMonitor != null) {
pMonitor.incrementCurValue();
ConsoleUtil.showProgress(pMonitor);
}
if (!line.startsWith("#")) {
String parts[] = line.split("\t");
CanonicalGene gene = daoGeneOptimized.getNonAmbiguousGene(parts[3], parts[0]);
if (gene==null) {
System.err.println("Could not find non ambiguous gene: "+parts[3]);
continue;
}
if (currentGene != gene) {
if (currentGene!=null) {
int length = calculateGeneLength(loci);
if (currentGene.getLength()!=0) {
System.err.println(currentGene.getHugoGeneSymbolAllCaps()+" has multiple length.");
} else {
currentGene.setLength(length);
}
}
loci.clear();
currentGene = gene;
}
loci.add(new long[]{Long.parseLong(parts[1]), Long.parseLong(parts[2])});
}
}
daoGeneOptimized.flushUpdateToDatabase();
}
private static int calculateGeneLength(List<long[]> loci) {
long min = Long.MAX_VALUE, max=-1;
for (long[] l : loci) {
if (l[0]<min) {
min = l[0];
}
if (l[1]>max) {
max = l[1];
}
}
BitSet bitSet = new BitSet((int)(max-min));
for (long[] l : loci) {
bitSet.set((int)(l[0]-min), ((int)(l[1]-min)));
}
return bitSet.cardinality();
}
static void importSuppGeneData(ProgressMonitor pMonitor, File suppGeneFile) throws IOException, DaoException {
MySQLbulkLoader.bulkLoadOff();
FileReader reader = new FileReader(suppGeneFile);
BufferedReader buf = new BufferedReader(reader);
String line;
DaoGeneOptimized daoGene = DaoGeneOptimized.getInstance();
while ((line = buf.readLine()) != null) {
if (pMonitor != null) {
pMonitor.incrementCurValue();
ConsoleUtil.showProgress(pMonitor);
}
if (!line.startsWith("#")) {
String parts[] = line.split("\t");
CanonicalGene gene = new CanonicalGene(parts[0]);
if (!parts[1].isEmpty()) {
gene.setType(parts[1]);
}
if (!parts[2].isEmpty()) {
gene.setCytoband(parts[2]);
}
if (!parts[3].isEmpty()) {
gene.setLength(Integer.parseInt(parts[3]));
}
daoGene.addGene(gene);
}
}
reader.close();
}
public static void main(String[] args) throws Exception {
SpringUtil.initDataSource();
DaoGeneOptimized daoGene = DaoGeneOptimized.getInstance();
daoGene.deleteAllRecords();
if (args.length == 0) {
System.out.println("command line usage: importGenes.pl <ncbi_genes.txt> <supp-genes.txt> <microrna.txt> <all_exon_loci.bed>");
return;
}
ProgressMonitor pMonitor = new ProgressMonitor();
pMonitor.setConsoleMode(true);
File geneFile = new File(args[0]);
System.out.println("Reading gene data from: " + geneFile.getAbsolutePath());
int numLines = FileUtil.getNumLines(geneFile);
System.out.println(" --> total number of lines: " + numLines);
pMonitor.setMaxValue(numLines);
ImportGeneData.importData(pMonitor, geneFile);
ConsoleUtil.showWarnings(pMonitor);
System.err.println("Done.");
if (args.length>=2) {
File suppGeneFile = new File(args[1]);
System.out.println("Reading supp. gene data from: " + suppGeneFile.getAbsolutePath());
numLines = FileUtil.getNumLines(suppGeneFile);
System.out.println(" --> total number of lines: " + numLines);
pMonitor.setMaxValue(numLines);
ImportGeneData.importSuppGeneData(pMonitor, suppGeneFile);
}
if (args.length>=3) {
File miRNAFile = new File(args[2]);
System.out.println("Reading miRNA data from: " + miRNAFile.getAbsolutePath());
numLines = FileUtil.getNumLines(miRNAFile);
System.out.println(" --> total number of lines: " + numLines);
pMonitor.setMaxValue(numLines);
ImportMicroRNAIDs.importData(pMonitor, miRNAFile);
}
if (args.length>=4) {
File lociFile = new File(args[3]);
System.out.println("Reading loci data from: " + lociFile.getAbsolutePath());
numLines = FileUtil.getNumLines(lociFile);
System.out.println(" --> total number of lines: " + numLines);
pMonitor.setMaxValue(numLines);
ImportGeneData.importGeneLength(pMonitor, lociFile);
}
}
}
|
core/src/main/java/org/mskcc/cbio/portal/scripts/ImportGeneData.java
|
/*
* Copyright (c) 2015 Memorial Sloan-Kettering Cancer Center.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY, WITHOUT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS
* FOR A PARTICULAR PURPOSE. The software and documentation provided hereunder
* is on an "as is" basis, and Memorial Sloan-Kettering Cancer Center has no
* obligations to provide maintenance, support, updates, enhancements or
* modifications. In no event shall Memorial Sloan-Kettering Cancer Center be
* liable to any party for direct, indirect, special, incidental or
* consequential damages, including lost profits, arising out of the use of this
* software and its documentation, even if Memorial Sloan-Kettering Cancer
* Center has been advised of the possibility of such damage.
*/
/*
* This file is part of cBioPortal.
*
* cBioPortal is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mskcc.cbio.portal.scripts;
import org.mskcc.cbio.portal.dao.*;
import org.mskcc.cbio.portal.model.CanonicalGene;
import org.mskcc.cbio.portal.util.*;
import java.io.*;
import java.util.*;
/**
* Command Line Tool to Import Background Gene Data.
*/
public class ImportGeneData {
public static void importData(ProgressMonitor pMonitor, File geneFile) throws IOException, DaoException {
Map<String, Set<CanonicalGene>> genesWithSymbolFromNomenClatureAuthority = new LinkedHashMap<>();
Map<String, Set<CanonicalGene>> genesWithoutSymbolFromNomenClatureAuthority = new LinkedHashMap<>();
try (FileReader reader = new FileReader(geneFile)) {
BufferedReader buf = new BufferedReader(reader);
String line = buf.readLine();
while (line != null) {
if (pMonitor != null) {
pMonitor.incrementCurValue();
ConsoleUtil.showProgress(pMonitor);
}
if (!line.startsWith("#")) {
String parts[] = line.split("\t");
int entrezGeneId = Integer.parseInt(parts[1]);
String geneSymbol = parts[2];
String locusTag = parts[3];
String strAliases = parts[4];
String strXrefs = parts[5];
String cytoband = parts[7];
String desc = parts[8];
String type = parts[9];
String mainSymbol = parts[10]; // use 10 instead of 2 since column 2 may have duplication
Set<String> aliases = new HashSet<String>();
if (!locusTag.equals("-")) {
aliases.add(locusTag);
}
if (!strAliases.equals("-")) {
aliases.addAll(Arrays.asList(strAliases.split("\\|")));
}
if (geneSymbol.startsWith("MIR") && type.equalsIgnoreCase("miscRNA")) {
line = buf.readLine();
continue; // ignore miRNA; process seperately
}
CanonicalGene gene = null;
if (!mainSymbol.equals("-")) {
gene = new CanonicalGene(entrezGeneId, mainSymbol, aliases);
Set<CanonicalGene> genes = genesWithSymbolFromNomenClatureAuthority.get(mainSymbol);
if (genes==null) {
genes = new HashSet<CanonicalGene>();
genesWithSymbolFromNomenClatureAuthority.put(mainSymbol, genes);
}
genes.add(gene);
} else if (!geneSymbol.equals("-")) {
gene = new CanonicalGene(entrezGeneId, geneSymbol, aliases);
Set<CanonicalGene> genes = genesWithoutSymbolFromNomenClatureAuthority.get(geneSymbol);
if (genes==null) {
genes = new HashSet<CanonicalGene>();
genesWithoutSymbolFromNomenClatureAuthority.put(geneSymbol, genes);
}
}
if (gene!=null) {
if (!cytoband.equals("-")) {
gene.setCytoband(cytoband);
}
gene.setType(type);
}
}
line = buf.readLine();
}
}
MySQLbulkLoader.bulkLoadOn();
DaoGeneOptimized daoGene = DaoGeneOptimized.getInstance();
// Add genes with symbol from nomenclature authority
for (Map.Entry<String, Set<CanonicalGene>> entry : genesWithSymbolFromNomenClatureAuthority.entrySet()) {
Set<CanonicalGene> genes = entry.getValue();
if (genes.size()==1) {
daoGene.addGene(genes.iterator().next());
} else {
logDuplicateGeneSymbolWarning(pMonitor, entry.getKey(), genes);
}
}
// Add genes with symbol from nomenclature authority
for (Map.Entry<String, Set<CanonicalGene>> entry : genesWithoutSymbolFromNomenClatureAuthority.entrySet()) {
Set<CanonicalGene> genes = entry.getValue();
String symbol = entry.getKey();
if (genes.size()==1) {
CanonicalGene gene = genes.iterator().next();
if (!genesWithSymbolFromNomenClatureAuthority.containsKey(symbol)) {
daoGene.addGene(gene);
} else {
// ignore entries with a symbol that have the same value as stardard one
pMonitor.logWarning("Ignored line with entrez gene id "+gene.getEntrezGeneId()
+ ". "+symbol+" is already imported.");
}
} else {
logDuplicateGeneSymbolWarning(pMonitor, symbol, genes);
}
}
if (MySQLbulkLoader.isBulkLoad()) {
MySQLbulkLoader.flushAll();
}
}
private static void logDuplicateGeneSymbolWarning(ProgressMonitor pMonitor, String symbol, Set<CanonicalGene> genes) {
StringBuilder sb = new StringBuilder();
sb.append("More than 1 gene has the same standard symbol ")
.append(symbol)
.append(":");
for (CanonicalGene gene : genes) {
sb.append(" ")
.append(gene.getEntrezGeneId())
.append(". Ignore...");
}
pMonitor.logWarning(sb.toString());
}
private static void importGeneLength(ProgressMonitor pMonitor, File geneFile) throws IOException, DaoException {
DaoGeneOptimized daoGeneOptimized = DaoGeneOptimized.getInstance();
FileReader reader = new FileReader(geneFile);
BufferedReader buf = new BufferedReader(reader);
String line;
CanonicalGene currentGene = null;
List<long[]> loci = new ArrayList<long[]>();
while ((line=buf.readLine()) != null) {
if (pMonitor != null) {
pMonitor.incrementCurValue();
ConsoleUtil.showProgress(pMonitor);
}
if (!line.startsWith("#")) {
String parts[] = line.split("\t");
CanonicalGene gene = daoGeneOptimized.getNonAmbiguousGene(parts[3], parts[0]);
if (gene==null) {
System.err.println("Could not find non ambiguous gene: "+parts[3]);
continue;
}
if (currentGene != gene) {
if (currentGene!=null) {
int length = calculateGeneLength(loci);
if (currentGene.getLength()!=0) {
System.err.println(currentGene.getHugoGeneSymbolAllCaps()+" has multiple length.");
} else {
currentGene.setLength(length);
}
}
loci.clear();
currentGene = gene;
}
loci.add(new long[]{Long.parseLong(parts[1]), Long.parseLong(parts[2])});
}
}
daoGeneOptimized.flushUpdateToDatabase();
}
private static int calculateGeneLength(List<long[]> loci) {
long min = Long.MAX_VALUE, max=-1;
for (long[] l : loci) {
if (l[0]<min) {
min = l[0];
}
if (l[1]>max) {
max = l[1];
}
}
BitSet bitSet = new BitSet((int)(max-min));
for (long[] l : loci) {
bitSet.set((int)(l[0]-min), ((int)(l[1]-min)));
}
return bitSet.cardinality();
}
static void importSuppGeneData(ProgressMonitor pMonitor, File suppGeneFile) throws IOException, DaoException {
MySQLbulkLoader.bulkLoadOff();
FileReader reader = new FileReader(suppGeneFile);
BufferedReader buf = new BufferedReader(reader);
String line;
DaoGeneOptimized daoGene = DaoGeneOptimized.getInstance();
while ((line = buf.readLine()) != null) {
if (pMonitor != null) {
pMonitor.incrementCurValue();
ConsoleUtil.showProgress(pMonitor);
}
if (!line.startsWith("#")) {
String parts[] = line.split("\t");
CanonicalGene gene = new CanonicalGene(parts[0]);
if (!parts[1].isEmpty()) {
gene.setType(parts[1]);
}
if (!parts[2].isEmpty()) {
gene.setCytoband(parts[2]);
}
if (!parts[3].isEmpty()) {
gene.setLength(Integer.parseInt(parts[3]));
}
daoGene.addGene(gene);
}
}
reader.close();
}
public static void main(String[] args) throws Exception {
SpringUtil.initDataSource();
DaoGeneOptimized daoGene = DaoGeneOptimized.getInstance();
daoGene.deleteAllRecords();
if (args.length == 0) {
System.out.println("command line usage: importGenes.pl <ncbi_genes.txt> <supp-genes.txt> <microrna.txt> <all_exon_loci.bed>");
return;
}
ProgressMonitor pMonitor = new ProgressMonitor();
pMonitor.setConsoleMode(true);
File geneFile = new File(args[0]);
System.out.println("Reading gene data from: " + geneFile.getAbsolutePath());
int numLines = FileUtil.getNumLines(geneFile);
System.out.println(" --> total number of lines: " + numLines);
pMonitor.setMaxValue(numLines);
ImportGeneData.importData(pMonitor, geneFile);
ConsoleUtil.showWarnings(pMonitor);
System.err.println("Done.");
if (args.length>=2) {
File suppGeneFile = new File(args[1]);
System.out.println("Reading supp. gene data from: " + suppGeneFile.getAbsolutePath());
numLines = FileUtil.getNumLines(suppGeneFile);
System.out.println(" --> total number of lines: " + numLines);
pMonitor.setMaxValue(numLines);
ImportGeneData.importSuppGeneData(pMonitor, suppGeneFile);
}
if (args.length>=3) {
File miRNAFile = new File(args[2]);
System.out.println("Reading miRNA data from: " + miRNAFile.getAbsolutePath());
numLines = FileUtil.getNumLines(miRNAFile);
System.out.println(" --> total number of lines: " + numLines);
pMonitor.setMaxValue(numLines);
ImportMicroRNAIDs.importData(pMonitor, miRNAFile);
}
if (args.length>=4) {
File lociFile = new File(args[3]);
System.out.println("Reading loci data from: " + lociFile.getAbsolutePath());
numLines = FileUtil.getNumLines(lociFile);
System.out.println(" --> total number of lines: " + numLines);
pMonitor.setMaxValue(numLines);
ImportGeneData.importGeneLength(pMonitor, lociFile);
}
}
}
|
only import human genes
|
core/src/main/java/org/mskcc/cbio/portal/scripts/ImportGeneData.java
|
only import human genes
|
|
Java
|
agpl-3.0
|
e7fd82c9060c7e0772a53938b9d47db3db6a7c06
| 0
|
spyrosg/VISION-Cloud-Monitoring,spyrosg/VISION-Cloud-Monitoring,spyrosg/VISION-Cloud-Monitoring,spyrosg/VISION-Cloud-Monitoring
|
package integration.tests;
import static org.junit.Assert.assertEquals;
import gr.ntua.vision.monitoring.VismoConfiguration;
import gr.ntua.vision.monitoring.VismoVMInfo;
import gr.ntua.vision.monitoring.dispatch.VismoEventDispatcher;
import gr.ntua.vision.monitoring.events.MonitoringEvent;
import gr.ntua.vision.monitoring.notify.EventHandler;
import gr.ntua.vision.monitoring.notify.VismoEventRegistry;
import gr.ntua.vision.monitoring.rules.Rule;
import gr.ntua.vision.monitoring.rules.VismoRulesEngine;
import gr.ntua.vision.monitoring.service.ClusterHeadNodeFactory;
import gr.ntua.vision.monitoring.service.Service;
import gr.ntua.vision.monitoring.zmq.ZMQFactory;
import java.io.IOException;
import java.util.Properties;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.zeromq.ZContext;
/**
*
*/
public class VismoServiceTest {
/**
*
*/
private static class EventCountHandler implements EventHandler {
/***/
private int counter = 0;
/**
* Constructor.
*/
public EventCountHandler() {
}
/**
* @see gr.ntua.vision.monitoring.notify.EventHandler#handle(gr.ntua.vision.monitoring.events.MonitoringEvent)
*/
@Override
public void handle(final MonitoringEvent e) {
if (e != null)
++counter;
}
/**
* @param noExpectedEvents
*/
public void hasSeenExpectedNoEvents(final int noExpectedEvents) {
assertEquals(noExpectedEvents, counter);
}
}
/**
* This is used to count the number of events received.
*/
private final class EventCountRule extends Rule {
/***/
private int counter = 0;
/**
* Constructor.
*
* @param engine
*/
public EventCountRule(final VismoRulesEngine engine) {
super(engine);
}
/**
* @param expectedNoEvents
*/
public void hasSeenExpectedNoEvents(final int expectedNoEvents) {
assertEquals(expectedNoEvents, counter);
}
/**
* @see gr.ntua.vision.monitoring.rules.RuleProc#performWith(java.lang.Object)
*/
@Override
public void performWith(final MonitoringEvent e) {
if (e != null)
++counter;
}
}
/***/
private static final int NO_GET_OPS = 10;
/***/
private static final int NO_PUT_OPS = 10;
/***/
@SuppressWarnings("serial")
private static final Properties p = new Properties() {
{
setProperty("cloud.name", "visioncloud.eu");
setProperty("cloud.heads", "10.0.2.211, 10.0.2.212");
setProperty("cluster.name", "vision-1");
setProperty("cluster.head", "10.0.2.211");
setProperty("producers.point", "tcp://127.0.0.1:56429");
setProperty("consumers.port", "56430");
setProperty("udp.port", "56431");
setProperty("cluster.head.port", "56432");
setProperty("cloud.head.port", "56433");
setProperty("mon.group.addr", "228.5.6.7");
setProperty("mon.group.port", "12345");
}
};
/***/
EventCountRule countRule;
/***/
private final VismoConfiguration conf = new VismoConfiguration(p);
/***/
private final EventCountHandler countHandler = new EventCountHandler();
/***/
private FakeObjectService obs;
/***/
private Service service;
/** the socket factory. */
private final ZMQFactory socketFactory = new ZMQFactory(new ZContext());
/**
* @param noOps
*/
public void doGETs(final int noOps) {
for (int i = 0; i < noOps; ++i)
obs.getEvent("ntua", "bill", "foo-container", "bar-object").send();
}
/**
* @param noOps
*/
public void doPUTs(final int noOps) {
for (int i = 0; i < noOps; ++i)
obs.putEvent("ntua", "bill", "foo-container", "bar-object").send();
}
/**
* @throws IOException
*/
@Before
public void setUp() throws IOException {
obs = new FakeObjectService(new VismoEventDispatcher("fake-obs", conf, socketFactory));
final ClusterHeadNodeFactory serviceFactory = new ClusterHeadNodeFactory(conf, socketFactory) {
@Override
protected void boostrap(final VismoRulesEngine engine) {
super.boostrap(engine);
countRule = new EventCountRule(engine);
countRule.submit();
}
};
service = serviceFactory.build(new VismoVMInfo());
}
/***/
@After
public void tearDown() {
if (service != null)
service.halt();
try {
Thread.sleep(1000);
} catch (final InterruptedException e) {
e.printStackTrace();
}
socketFactory.destroy();
}
/**
* @throws InterruptedException
*/
@Test
public void vismoDeliversEventsToClient() throws InterruptedException {
final VismoEventRegistry reg = new VismoEventRegistry(socketFactory, "tcp://127.0.0.1:" + conf.getConsumersPort());
service.start();
reg.registerToAll(countHandler);
doGETs(NO_GET_OPS);
doPUTs(NO_PUT_OPS);
waitForEventsDelivery(1000);
assertThatClientReceivedEvents();
}
/**
* @throws InterruptedException
*/
@Test
public void vismoReceivesEventsFromProducers() throws InterruptedException {
service.start();
doGETs(NO_GET_OPS);
doPUTs(NO_PUT_OPS);
waitForEventsDelivery(1000);
assertThatVismoReceivedEvents();
}
/**
*
*/
private void assertThatClientReceivedEvents() {
countHandler.hasSeenExpectedNoEvents(NO_GET_OPS + NO_PUT_OPS);
}
/***/
private void assertThatVismoReceivedEvents() {
countRule.hasSeenExpectedNoEvents(NO_GET_OPS + NO_PUT_OPS);
}
/**
* @param n
* @throws InterruptedException
*/
private static void waitForEventsDelivery(final int n) throws InterruptedException {
Thread.sleep(n);
}
}
|
vismo-core/src/test/java/integration/tests/VismoServiceTest.java
|
package integration.tests;
import static org.junit.Assert.assertEquals;
import gr.ntua.vision.monitoring.VismoConfiguration;
import gr.ntua.vision.monitoring.VismoVMInfo;
import gr.ntua.vision.monitoring.dispatch.VismoEventDispatcher;
import gr.ntua.vision.monitoring.events.MonitoringEvent;
import gr.ntua.vision.monitoring.notify.EventHandler;
import gr.ntua.vision.monitoring.notify.VismoEventRegistry;
import gr.ntua.vision.monitoring.rules.Rule;
import gr.ntua.vision.monitoring.rules.VismoRulesEngine;
import gr.ntua.vision.monitoring.service.ClusterHeadNodeFactory;
import gr.ntua.vision.monitoring.service.Service;
import gr.ntua.vision.monitoring.zmq.ZMQFactory;
import java.io.IOException;
import java.util.Properties;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.zeromq.ZContext;
/**
*
*/
public class VismoServiceTest {
/**
*
*/
private static class EventCountHandler implements EventHandler {
/***/
private int counter = 0;
/**
* Constructor.
*/
public EventCountHandler() {
}
/**
* @see gr.ntua.vision.monitoring.notify.EventHandler#handle(gr.ntua.vision.monitoring.events.MonitoringEvent)
*/
@Override
public void handle(final MonitoringEvent e) {
if (e != null)
++counter;
}
/**
* @param noExpectedEvents
*/
public void hasSeenExpectedNoEvents(final int noExpectedEvents) {
assertEquals(noExpectedEvents, counter);
}
}
/**
* This is used to count the number of events received.
*/
private final class EventCountRule extends Rule {
/***/
private int counter = 0;
/**
* Constructor.
*
* @param engine
*/
public EventCountRule(final VismoRulesEngine engine) {
super(engine);
}
/**
* @param expectedNoEvents
*/
public void hasSeenExpectedNoEvents(final int expectedNoEvents) {
assertEquals(expectedNoEvents, counter);
}
/**
* @see gr.ntua.vision.monitoring.rules.RuleProc#performWith(java.lang.Object)
*/
@Override
public void performWith(final MonitoringEvent e) {
if (e != null)
++counter;
}
}
/***/
private static final int NO_GET_OPS = 10;
/***/
private static final int NO_PUT_OPS = 10;
/***/
@SuppressWarnings("serial")
private static final Properties p = new Properties() {
{
setProperty("cloud.name", "visioncloud.eu");
setProperty("cloud.heads", "10.0.2.211, 10.0.2.212");
setProperty("cluster.name", "vision-1");
setProperty("cluster.head", "10.0.2.211");
setProperty("producers.point", "tcp://127.0.0.1:56429");
setProperty("consumers.port", "56430");
setProperty("udp.port", "56431");
setProperty("cluster.head.port", "56432");
setProperty("cloud.head.port", "56433");
}
};
/***/
EventCountRule countRule;
/***/
private final VismoConfiguration conf = new VismoConfiguration(p);
/***/
private final EventCountHandler countHandler = new EventCountHandler();
/***/
private FakeObjectService obs;
/***/
private Service service;
/** the socket factory. */
private final ZMQFactory socketFactory = new ZMQFactory(new ZContext());
/**
* @param noOps
*/
public void doGETs(final int noOps) {
for (int i = 0; i < noOps; ++i)
obs.getEvent("ntua", "bill", "foo-container", "bar-object").send();
}
/**
* @param noOps
*/
public void doPUTs(final int noOps) {
for (int i = 0; i < noOps; ++i)
obs.putEvent("ntua", "bill", "foo-container", "bar-object").send();
}
/**
* @throws IOException
*/
@Before
public void setUp() throws IOException {
obs = new FakeObjectService(new VismoEventDispatcher("fake-obs", conf, socketFactory));
final ClusterHeadNodeFactory serviceFactory = new ClusterHeadNodeFactory(conf, socketFactory) {
@Override
protected void boostrap(final VismoRulesEngine engine) {
super.boostrap(engine);
countRule = new EventCountRule(engine);
countRule.submit();
}
};
service = serviceFactory.build(new VismoVMInfo());
}
/***/
@After
public void tearDown() {
if (service != null)
service.halt();
try {
Thread.sleep(1000);
} catch (final InterruptedException e) {
e.printStackTrace();
}
socketFactory.destroy();
}
/**
* @throws InterruptedException
*/
@Test
public void vismoDeliversEventsToClient() throws InterruptedException {
final VismoEventRegistry reg = new VismoEventRegistry(socketFactory, "tcp://127.0.0.1:" + conf.getConsumersPort());
service.start();
reg.registerToAll(countHandler);
doGETs(NO_GET_OPS);
doPUTs(NO_PUT_OPS);
waitForEventsDelivery(1000);
assertThatClientReceivedEvents();
}
/**
* @throws InterruptedException
*/
@Test
public void vismoReceivesEventsFromProducers() throws InterruptedException {
service.start();
doGETs(NO_GET_OPS);
doPUTs(NO_PUT_OPS);
waitForEventsDelivery(1000);
assertThatVismoReceivedEvents();
}
/**
*
*/
private void assertThatClientReceivedEvents() {
countHandler.hasSeenExpectedNoEvents(NO_GET_OPS + NO_PUT_OPS);
}
/***/
private void assertThatVismoReceivedEvents() {
countRule.hasSeenExpectedNoEvents(NO_GET_OPS + NO_PUT_OPS);
}
/**
* @param n
* @throws InterruptedException
*/
private static void waitForEventsDelivery(final int n) throws InterruptedException {
Thread.sleep(n);
}
}
|
FIX: test was missing vismo group properties
|
vismo-core/src/test/java/integration/tests/VismoServiceTest.java
|
FIX: test was missing vismo group properties
|
|
Java
|
agpl-3.0
|
c7c7ea7b0b2f95973f1e109ab4ca42d92dd414d5
| 0
|
duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test
|
6e3209f4-2e60-11e5-9284-b827eb9e62be
|
hello.java
|
6e2a7aae-2e60-11e5-9284-b827eb9e62be
|
6e3209f4-2e60-11e5-9284-b827eb9e62be
|
hello.java
|
6e3209f4-2e60-11e5-9284-b827eb9e62be
|
|
Java
|
agpl-3.0
|
bc5ab16201ec3a10716d62e8c0150d203f6417c9
| 0
|
servernge/holocore,servernge/holocore,servernge/holocore
|
/***********************************************************************************
* Copyright (c) 2015 /// Project SWG /// www.projectswg.com *
* *
* ProjectSWG is the first NGE emulator for Star Wars Galaxies founded on *
* July 7th, 2011 after SOE announced the official shutdown of Star Wars Galaxies. *
* Our goal is to create an emulator which will provide a server for players to *
* continue playing a game similar to the one they used to play. We are basing *
* it on the final publish of the game prior to end-game events. *
* *
* This file is part of Holocore. *
* *
* -------------------------------------------------------------------------------- *
* *
* Holocore is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Affero General Public License as *
* published by the Free Software Foundation, either version 3 of the *
* License, or (at your option) any later version. *
* *
* Holocore is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Affero General Public License for more details. *
* *
* You should have received a copy of the GNU Affero General Public License *
* along with Holocore. If not, see <http://www.gnu.org/licenses/>. *
* *
***********************************************************************************/
package resources.objects.sound;
import resources.objects.staticobject.StaticObject;
public class SoundObject extends StaticObject {
private static final long serialVersionUID = 1L;
public SoundObject(long objectId) {
super(objectId);
}
}
|
src/resources/objects/sound/SoundObject.java
|
/***********************************************************************************
* Copyright (c) 2015 /// Project SWG /// www.projectswg.com *
* *
* ProjectSWG is the first NGE emulator for Star Wars Galaxies founded on *
* July 7th, 2011 after SOE announced the official shutdown of Star Wars Galaxies. *
* Our goal is to create an emulator which will provide a server for players to *
* continue playing a game similar to the one they used to play. We are basing *
* it on the final publish of the game prior to end-game events. *
* *
* This file is part of Holocore. *
* *
* -------------------------------------------------------------------------------- *
* *
* Holocore is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Affero General Public License as *
* published by the Free Software Foundation, either version 3 of the *
* License, or (at your option) any later version. *
* *
* Holocore is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Affero General Public License for more details. *
* *
* You should have received a copy of the GNU Affero General Public License *
* along with Holocore. If not, see <http://www.gnu.org/licenses/>. *
* *
***********************************************************************************/
package resources.objects.sound;
import resources.objects.SWGObject;
public class SoundObject extends SWGObject {
private static final long serialVersionUID = 1L;
public SoundObject(long objectId) {
super(objectId, null);
}
}
|
Made SoundObject extend StaticObject
|
src/resources/objects/sound/SoundObject.java
|
Made SoundObject extend StaticObject
|
|
Java
|
apache-2.0
|
c7446cfbec0837bd9af88b3122e19a2aac8cdf59
| 0
|
dbrant/apps-android-wikipedia,wikimedia/apps-android-wikipedia,dbrant/apps-android-wikipedia,dbrant/apps-android-wikipedia,dbrant/apps-android-wikipedia,wikimedia/apps-android-wikipedia,wikimedia/apps-android-wikipedia,dbrant/apps-android-wikipedia,wikimedia/apps-android-wikipedia
|
package org.wikipedia.savedpages;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.JobIntentService;
import android.text.TextUtils;
import org.wikipedia.WikipediaApp;
import org.wikipedia.database.contract.PageImageHistoryContract;
import org.wikipedia.dataclient.WikiSite;
import org.wikipedia.dataclient.okhttp.OkHttpConnectionFactory;
import org.wikipedia.dataclient.okhttp.cache.DiskLruCacheUtil;
import org.wikipedia.dataclient.okhttp.cache.SaveHeader;
import org.wikipedia.dataclient.page.PageClient;
import org.wikipedia.dataclient.page.PageClientFactory;
import org.wikipedia.dataclient.page.PageLead;
import org.wikipedia.dataclient.page.PageRemaining;
import org.wikipedia.html.ImageTagParser;
import org.wikipedia.html.PixelDensityDescriptorParser;
import org.wikipedia.page.PageTitle;
import org.wikipedia.pageimages.PageImage;
import org.wikipedia.readinglist.ReadingListData;
import org.wikipedia.readinglist.page.ReadingListPage;
import org.wikipedia.readinglist.page.ReadingListPageRow;
import org.wikipedia.readinglist.page.database.ReadingListDaoProxy;
import org.wikipedia.readinglist.page.database.ReadingListPageDao;
import org.wikipedia.readinglist.page.database.disk.ReadingListPageDiskRow;
import org.wikipedia.readinglist.sync.ReadingListSyncEvent;
import org.wikipedia.settings.Prefs;
import org.wikipedia.util.DimenUtil;
import org.wikipedia.util.FileUtil;
import org.wikipedia.util.ThrowableUtil;
import org.wikipedia.util.UriUtil;
import org.wikipedia.util.log.L;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import okhttp3.CacheControl;
import okhttp3.CacheDelegate;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.internal.cache.DiskLruCache;
import retrofit2.Call;
import static org.wikipedia.dataclient.okhttp.OkHttpConnectionFactory.SAVE_CACHE;
public class SavedPageSyncService extends JobIntentService {
// Unique job ID for this service (do not duplicate).
private static final int JOB_ID = 1000;
@NonNull private ReadingListPageDao dao;
@NonNull private final CacheDelegate cacheDelegate = new CacheDelegate(SAVE_CACHE);
@NonNull private final PageImageUrlParser pageImageUrlParser
= new PageImageUrlParser(new ImageTagParser(), new PixelDensityDescriptorParser());
private long blockSize;
private SavedPageSyncNotification savedPageSyncNotification;
public SavedPageSyncService() {
dao = ReadingListPageDao.instance();
blockSize = FileUtil.blockSize(cacheDelegate.diskLruCache().getDirectory());
savedPageSyncNotification = SavedPageSyncNotification.getInstance();
}
public static void enqueueService(@NonNull Context context) {
enqueueWork(context, SavedPageSyncService.class, JOB_ID,
new Intent(context, SavedPageSyncService.class));
}
@Override protected void onHandleWork(@NonNull Intent intent) {
List<ReadingListPageDiskRow> queue = new ArrayList<>();
Collection<ReadingListPageDiskRow> rows = dao.startDiskTransaction();
for (ReadingListPageDiskRow row : rows) {
switch (row.status()) {
case UNSAVED:
case DELETED:
deleteRow(row);
break;
case OUTDATED:
queue.add(row);
break;
case ONLINE:
case SAVED:
// SavedPageSyncService observes all list changes. No transaction is pending
// when the row is online or saved.
break;
default:
throw new UnsupportedOperationException("Invalid disk row status: "
+ row.status().name());
}
}
int itemsTotal = queue.size();
int itemsSaved = 0;
try {
itemsSaved = saveNewEntries(queue);
} finally {
if (savedPageSyncNotification.isSyncPaused()) {
savedPageSyncNotification.setNotificationPaused(getApplicationContext(), itemsTotal, itemsSaved);
} else {
savedPageSyncNotification.cancelNotification(getApplicationContext());
savedPageSyncNotification.setSyncCanceled(false);
}
}
}
private void sendSyncEvent() {
// Note: this method posts from a background thread but subscribers expect events to be
// received on the main thread.
WikipediaApp.getInstance().getBus().post(new ReadingListSyncEvent());
}
private void deleteRow(@NonNull ReadingListPageDiskRow row) {
ReadingListPageRow dat = row.dat();
PageTitle pageTitle = makeTitleFrom(row);
if (dat != null && pageTitle != null) {
PageLead lead = null;
Call<PageLead> leadCall = reqPageLead(CacheControl.FORCE_CACHE, pageTitle);
try {
lead = leadCall.execute().body();
} catch (IOException ignore) { }
if (lead != null) {
for (String url : pageImageUrlParser.parse(lead)) {
cacheDelegate.remove(saveImageReq(pageTitle.getWikiSite(), url));
}
cacheDelegate.remove(leadCall.request());
}
Call<PageRemaining> sectionsCall = reqPageSections(CacheControl.FORCE_CACHE, pageTitle);
PageRemaining sections = null;
try {
sections = sectionsCall.execute().body();
} catch (IOException ignore) { }
if (sections != null) {
for (String url : pageImageUrlParser.parse(sections)) {
cacheDelegate.remove(saveImageReq(pageTitle.getWikiSite(), url));
}
cacheDelegate.remove(sectionsCall.request());
}
ReadingListPageDao.instance().deleteIfOrphaned(dat);
}
dao.completeDiskTransaction(row);
}
private int saveNewEntries(List<ReadingListPageDiskRow> queue) {
sendSyncEvent();
int itemsTotal = queue.size();
int itemsSaved = 0;
while (!queue.isEmpty()) {
// Pick off the DB row that we'll be working on...
ReadingListPageDiskRow tempRow = queue.remove(0);
if (savedPageSyncNotification.isSyncPaused()) {
// fail all remaining transactions. They'll be picked up again when
// the service is resumed.
dao.failDiskTransaction(tempRow);
continue;
} else if (savedPageSyncNotification.isSyncCanceled()) {
ReadingListPage tempPage = ReadingListPage.fromDiskRow(tempRow);
ReadingListData.instance().setPageOffline(tempPage, false);
continue;
}
savedPageSyncNotification.setNotificationProgress(getApplicationContext(), itemsTotal, itemsSaved);
@Nullable PageTitle pageTitle = makeTitleFrom(tempRow);
if (pageTitle == null) {
// TODO: delete this orphaned row from Disk table, since Page item no longer exists.
dao.failDiskTransaction(tempRow);
continue;
}
boolean success = false;
@Nullable AggregatedResponseSize size = null;
try {
// Lengthy operation during which the db state may change...
size = savePageFor(tempRow, pageTitle);
success = true;
} catch (InterruptedException e) {
// fall through
} catch (Exception e) {
// This can be an IOException from the storage media, or several types
// of network exceptions from malformed URLs, timeouts, etc.
e.printStackTrace();
if (!ThrowableUtil.isOffline(e) && !ThrowableUtil.is404(e)) {
// If it's anything but a transient network error, let's log it aggressively,
// to make sure we've fixed any other errors with saving pages.
L.logRemoteError(e);
}
}
// Query the database again, and see if this page title is still actually there,
// or if the page has been added to more lists.
@Nullable ReadingListPage page = ReadingListData.instance()
.findPageInAnyList(ReadingListDaoProxy.key(pageTitle));
if (page == null) {
// The page has been deleted while we were busy!
continue;
}
// Make an updated DiskRow based on the refreshed page.
ReadingListPageDiskRow updatedRow = new ReadingListPageDiskRow(tempRow,
ReadingListPageRow.builder()
.copy(page)
.logicalSize(size != null ? size.logicalSize() : 0)
.physicalSize(size != null ? size.physicalSize() : 0)
.build());
if (success) {
dao.completeDiskTransaction(updatedRow);
itemsSaved++;
sendSyncEvent();
} else {
dao.failDiskTransaction(updatedRow);
}
}
return itemsSaved;
}
@NonNull private AggregatedResponseSize savePageFor(@NonNull ReadingListPageDiskRow row,
@NonNull PageTitle pageTitle) throws IOException, InterruptedException {
AggregatedResponseSize size = new AggregatedResponseSize(0, 0, 0);
Call<PageLead> leadCall = reqPageLead(null, pageTitle);
Call<PageRemaining> sectionsCall = reqPageSections(null, pageTitle);
retrofit2.Response<PageLead> leadRsp = leadCall.execute();
size = size.add(responseSize(leadRsp));
retrofit2.Response<PageRemaining> sectionsRsp = sectionsCall.execute();
size = size.add(responseSize(sectionsRsp));
if (!TextUtils.isEmpty(leadRsp.body().getThumbUrl())) {
persistPageThumbnail(pageTitle, leadRsp.body().getThumbUrl());
row.dat().setThumbnailUrl(UriUtil.resolveProtocolRelativeUrl(pageTitle.getWikiSite(),
leadRsp.body().getThumbUrl()));
}
row.dat().setDescription(leadRsp.body().getDescription());
Set<String> imageUrls = new HashSet<>(pageImageUrlParser.parse(leadRsp.body()));
imageUrls.addAll(pageImageUrlParser.parse(sectionsRsp.body()));
if (Prefs.isImageDownloadEnabled()) {
size = size.add(reqSaveImage(pageTitle.getWikiSite(), imageUrls));
}
String title = pageTitle.getPrefixedText();
L.i("Saved page " + title + " (" + size + ")");
return size;
}
@NonNull private Call<PageLead> reqPageLead(@Nullable CacheControl cacheControl,
@NonNull PageTitle pageTitle) {
PageClient client = newPageClient(pageTitle);
String title = pageTitle.getPrefixedText();
int thumbnailWidth = DimenUtil.calculateLeadImageWidth();
PageClient.CacheOption cacheOption = PageClient.CacheOption.SAVE;
return client.lead(cacheControl, cacheOption, title, thumbnailWidth);
}
@NonNull private Call<PageRemaining> reqPageSections(@Nullable CacheControl cacheControl,
@NonNull PageTitle pageTitle) {
PageClient client = newPageClient(pageTitle);
String title = pageTitle.getPrefixedText();
PageClient.CacheOption cacheOption = PageClient.CacheOption.SAVE;
return client.sections(cacheControl, cacheOption, title);
}
private AggregatedResponseSize reqSaveImage(@NonNull WikiSite wiki, @NonNull Iterable<String> urls) throws IOException, InterruptedException {
AggregatedResponseSize size = new AggregatedResponseSize(0, 0, 0);
for (String url : urls) {
if (savedPageSyncNotification.isSyncPaused() || savedPageSyncNotification.isSyncCanceled()) {
throw new InterruptedException("Sync paused or cancelled.");
}
try {
size = size.add(reqSaveImage(wiki, url));
} catch (Exception e) {
if (isRetryable(e)) {
throw e;
}
}
}
return size;
}
@NonNull private ResponseSize reqSaveImage(@NonNull WikiSite wiki, @NonNull String url) throws IOException {
Request request = saveImageReq(wiki, url);
Response rsp = OkHttpConnectionFactory.getClient().newCall(request).execute();
// Note: raw non-Retrofit usage of OkHttp Requests requires that the Response body is read
// for the cache to be written.
rsp.body().close();
// Size must be checked after the body has been written.
return responseSize(rsp);
}
@NonNull private Request saveImageReq(@NonNull WikiSite wiki, @NonNull String url) {
return new Request
.Builder()
.addHeader(SaveHeader.FIELD, SaveHeader.VAL_ENABLED)
.url(UriUtil.resolveProtocolRelativeUrl(wiki, url))
.build();
}
private void persistPageThumbnail(@NonNull PageTitle title, @NonNull String url) {
WikipediaApp.getInstance().getDatabaseClient(PageImage.class).upsert(
new PageImage(title, UriUtil.resolveProtocolRelativeUrl(title.getWikiSite(), url)),
PageImageHistoryContract.Image.SELECTION);
}
private boolean isRetryable(@NonNull Throwable t) {
/*
"Retryable" in this case refers to exceptions that will be rethrown up to the
outer exception handler, so that the entire page can be retried on the next pass
of the sync service.
Errors that do *not* qualify for retrying include:
- IllegalArgumentException (thrown for any kind of malformed URL)
- HTTP 404 status (for nonexistent media)
*/
return !(t instanceof IllegalArgumentException
|| ThrowableUtil.is404(t));
}
@NonNull private ResponseSize responseSize(@NonNull Response rsp) {
return responseSize(rsp.request());
}
@NonNull private ResponseSize responseSize(@NonNull retrofit2.Response rsp) {
return responseSize(rsp.raw().request());
}
@NonNull private ResponseSize responseSize(@NonNull Request req) {
return responseSize(cacheDelegate.entry(req));
}
@NonNull private ResponseSize responseSize(@Nullable DiskLruCache.Snapshot snapshot) {
long metadataSize = DiskLruCacheUtil.okHttpResponseMetadataSize(snapshot);
long bodySize = DiskLruCacheUtil.okHttpResponseBodySize(snapshot);
return new ResponseSize(metadataSize, bodySize);
}
@Nullable private PageTitle makeTitleFrom(@NonNull ReadingListPageDiskRow row) {
ReadingListPageRow pageRow = row.dat();
if (pageRow == null) {
return null;
}
String namespace = pageRow.namespace().toLegacyString();
return new PageTitle(namespace, pageRow.title(), pageRow.wikiSite());
}
@NonNull private PageClient newPageClient(@NonNull PageTitle title) {
return PageClientFactory.create(title.getWikiSite(), title.namespace());
}
private static class AggregatedResponseSize {
private final long physicalSize;
private final long logicalSize;
private final int responsesAggregated;
AggregatedResponseSize(long physicalSize, long logicalSize, int responsesAggregated) {
this.physicalSize = physicalSize;
this.logicalSize = logicalSize;
this.responsesAggregated = responsesAggregated;
}
@Override public String toString() {
return "responses=" + responsesAggregated() + " physical=" + physicalSize() + "B logical=" + logicalSize() + "B";
}
long physicalSize() {
return physicalSize;
}
// The size on disk.
long logicalSize() {
return logicalSize;
}
int responsesAggregated() {
return responsesAggregated;
}
@NonNull AggregatedResponseSize add(@NonNull ResponseSize size) {
return new AggregatedResponseSize(physicalSize + size.physicalSize(),
logicalSize + size.logicalSize(), responsesAggregated() + 1);
}
@NonNull AggregatedResponseSize add(@NonNull AggregatedResponseSize size) {
return new AggregatedResponseSize(physicalSize + size.physicalSize(),
logicalSize + size.logicalSize(), responsesAggregated() + size.responsesAggregated());
}
}
private class ResponseSize {
private final long metadataSize;
private final long bodySize;
ResponseSize(long metadataSize, long bodySize) {
this.metadataSize = metadataSize;
this.bodySize = bodySize;
}
@Override public String toString() {
return "physical metadata=" + metadataSize + "B physical body=" + bodySize
+ "B physical=" + physicalSize() + "B logical=" + logicalSize() + "B";
}
long physicalSize() {
return metadataSize + bodySize;
}
long logicalSize() {
return FileUtil.physicalToLogicalSize(metadataSize, blockSize)
+ FileUtil.physicalToLogicalSize(bodySize, blockSize);
}
}
}
|
app/src/main/java/org/wikipedia/savedpages/SavedPageSyncService.java
|
package org.wikipedia.savedpages;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.JobIntentService;
import android.text.TextUtils;
import org.wikipedia.WikipediaApp;
import org.wikipedia.database.contract.PageImageHistoryContract;
import org.wikipedia.dataclient.WikiSite;
import org.wikipedia.dataclient.okhttp.OkHttpConnectionFactory;
import org.wikipedia.dataclient.okhttp.cache.DiskLruCacheUtil;
import org.wikipedia.dataclient.okhttp.cache.SaveHeader;
import org.wikipedia.dataclient.page.PageClient;
import org.wikipedia.dataclient.page.PageClientFactory;
import org.wikipedia.dataclient.page.PageLead;
import org.wikipedia.dataclient.page.PageRemaining;
import org.wikipedia.html.ImageTagParser;
import org.wikipedia.html.PixelDensityDescriptorParser;
import org.wikipedia.page.PageTitle;
import org.wikipedia.pageimages.PageImage;
import org.wikipedia.readinglist.ReadingListData;
import org.wikipedia.readinglist.page.ReadingListPage;
import org.wikipedia.readinglist.page.ReadingListPageRow;
import org.wikipedia.readinglist.page.database.ReadingListDaoProxy;
import org.wikipedia.readinglist.page.database.ReadingListPageDao;
import org.wikipedia.readinglist.page.database.disk.ReadingListPageDiskRow;
import org.wikipedia.readinglist.sync.ReadingListSyncEvent;
import org.wikipedia.settings.Prefs;
import org.wikipedia.util.DimenUtil;
import org.wikipedia.util.FileUtil;
import org.wikipedia.util.ThrowableUtil;
import org.wikipedia.util.UriUtil;
import org.wikipedia.util.log.L;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import okhttp3.CacheControl;
import okhttp3.CacheDelegate;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.internal.cache.DiskLruCache;
import retrofit2.Call;
import static org.wikipedia.dataclient.okhttp.OkHttpConnectionFactory.SAVE_CACHE;
public class SavedPageSyncService extends JobIntentService {
// Unique job ID for this service (do not duplicate).
private static final int JOB_ID = 1000;
@NonNull private ReadingListPageDao dao;
@NonNull private final CacheDelegate cacheDelegate = new CacheDelegate(SAVE_CACHE);
@NonNull private final PageImageUrlParser pageImageUrlParser
= new PageImageUrlParser(new ImageTagParser(), new PixelDensityDescriptorParser());
private long blockSize;
private SavedPageSyncNotification savedPageSyncNotification;
public SavedPageSyncService() {
dao = ReadingListPageDao.instance();
blockSize = FileUtil.blockSize(cacheDelegate.diskLruCache().getDirectory());
savedPageSyncNotification = SavedPageSyncNotification.getInstance();
}
public static void enqueueService(@NonNull Context context) {
enqueueWork(context, SavedPageSyncService.class, JOB_ID,
new Intent(context, SavedPageSyncService.class));
}
@Override protected void onHandleWork(@NonNull Intent intent) {
List<ReadingListPageDiskRow> queue = new ArrayList<>();
Collection<ReadingListPageDiskRow> rows = dao.startDiskTransaction();
for (ReadingListPageDiskRow row : rows) {
switch (row.status()) {
case UNSAVED:
case DELETED:
deleteRow(row);
break;
case OUTDATED:
queue.add(row);
break;
case ONLINE:
case SAVED:
// SavedPageSyncService observes all list changes. No transaction is pending
// when the row is online or saved.
break;
default:
throw new UnsupportedOperationException("Invalid disk row status: "
+ row.status().name());
}
}
int itemsTotal = queue.size();
int itemsSaved = 0;
try {
itemsSaved = saveNewEntries(queue);
} finally {
if (savedPageSyncNotification.isSyncPaused()) {
savedPageSyncNotification.setNotificationPaused(getApplicationContext(), itemsTotal, itemsSaved);
} else {
savedPageSyncNotification.cancelNotification(getApplicationContext());
savedPageSyncNotification.setSyncCanceled(false);
}
}
}
private void sendSyncEvent() {
// Note: this method posts from a background thread but subscribers expect events to be
// received on the main thread.
WikipediaApp.getInstance().getBus().post(new ReadingListSyncEvent());
}
private void deleteRow(@NonNull ReadingListPageDiskRow row) {
ReadingListPageRow dat = row.dat();
PageTitle pageTitle = makeTitleFrom(row);
if (dat != null && pageTitle != null) {
PageLead lead = null;
Call<PageLead> leadCall = reqPageLead(CacheControl.FORCE_CACHE, pageTitle);
try {
lead = leadCall.execute().body();
} catch (IOException ignore) { }
if (lead != null) {
for (String url : pageImageUrlParser.parse(lead)) {
cacheDelegate.remove(saveImageReq(pageTitle.getWikiSite(), url));
}
cacheDelegate.remove(leadCall.request());
}
Call<PageRemaining> sectionsCall = reqPageSections(CacheControl.FORCE_CACHE, pageTitle);
PageRemaining sections = null;
try {
sections = sectionsCall.execute().body();
} catch (IOException ignore) { }
if (sections != null) {
for (String url : pageImageUrlParser.parse(sections)) {
cacheDelegate.remove(saveImageReq(pageTitle.getWikiSite(), url));
}
cacheDelegate.remove(sectionsCall.request());
}
ReadingListPageDao.instance().deleteIfOrphaned(dat);
}
dao.completeDiskTransaction(row);
}
private int saveNewEntries(List<ReadingListPageDiskRow> queue) {
sendSyncEvent();
int itemsTotal = queue.size();
int itemsSaved = 0;
while (!queue.isEmpty()) {
// Pick off the DB row that we'll be working on...
ReadingListPageDiskRow tempRow = queue.remove(0);
if (savedPageSyncNotification.isSyncPaused()) {
// fail all remaining transactions. They'll be picked up again when
// the service is resumed.
dao.failDiskTransaction(tempRow);
continue;
} else if (savedPageSyncNotification.isSyncCanceled()) {
ReadingListPage tempPage = ReadingListPage.fromDiskRow(tempRow);
ReadingListData.instance().setPageOffline(tempPage, false);
continue;
}
savedPageSyncNotification.setNotificationProgress(getApplicationContext(), itemsTotal, itemsSaved);
@Nullable PageTitle pageTitle = makeTitleFrom(tempRow);
if (pageTitle == null) {
// TODO: delete this orphaned row from Disk table, since Page item no longer exists.
dao.failDiskTransaction(tempRow);
continue;
}
boolean success = false;
@Nullable AggregatedResponseSize size = null;
try {
// Lengthy operation during which the db state may change...
size = savePageFor(tempRow, pageTitle);
success = true;
} catch (InterruptedException e) {
// fall through
} catch (Exception e) {
// This can be an IOException from the storage media, or several types
// of network exceptions from malformed URLs, timeouts, etc.
e.printStackTrace();
if (!ThrowableUtil.isOffline(e)) {
// If it's anything but a transient network error, let's log it aggressively,
// to make sure we've fixed any other errors with saving pages.
L.logRemoteError(e);
}
}
// Query the database again, and see if this page title is still actually there,
// or if the page has been added to more lists.
@Nullable ReadingListPage page = ReadingListData.instance()
.findPageInAnyList(ReadingListDaoProxy.key(pageTitle));
if (page == null) {
// The page has been deleted while we were busy!
continue;
}
// Make an updated DiskRow based on the refreshed page.
ReadingListPageDiskRow updatedRow = new ReadingListPageDiskRow(tempRow,
ReadingListPageRow.builder()
.copy(page)
.logicalSize(size != null ? size.logicalSize() : 0)
.physicalSize(size != null ? size.physicalSize() : 0)
.build());
if (success) {
dao.completeDiskTransaction(updatedRow);
itemsSaved++;
sendSyncEvent();
} else {
dao.failDiskTransaction(updatedRow);
}
}
return itemsSaved;
}
@NonNull private AggregatedResponseSize savePageFor(@NonNull ReadingListPageDiskRow row,
@NonNull PageTitle pageTitle) throws IOException, InterruptedException {
AggregatedResponseSize size = new AggregatedResponseSize(0, 0, 0);
Call<PageLead> leadCall = reqPageLead(null, pageTitle);
Call<PageRemaining> sectionsCall = reqPageSections(null, pageTitle);
retrofit2.Response<PageLead> leadRsp = leadCall.execute();
size = size.add(responseSize(leadRsp));
retrofit2.Response<PageRemaining> sectionsRsp = sectionsCall.execute();
size = size.add(responseSize(sectionsRsp));
if (!TextUtils.isEmpty(leadRsp.body().getThumbUrl())) {
persistPageThumbnail(pageTitle, leadRsp.body().getThumbUrl());
row.dat().setThumbnailUrl(UriUtil.resolveProtocolRelativeUrl(pageTitle.getWikiSite(),
leadRsp.body().getThumbUrl()));
}
row.dat().setDescription(leadRsp.body().getDescription());
Set<String> imageUrls = new HashSet<>(pageImageUrlParser.parse(leadRsp.body()));
imageUrls.addAll(pageImageUrlParser.parse(sectionsRsp.body()));
if (Prefs.isImageDownloadEnabled()) {
size = size.add(reqSaveImage(pageTitle.getWikiSite(), imageUrls));
}
String title = pageTitle.getPrefixedText();
L.i("Saved page " + title + " (" + size + ")");
return size;
}
@NonNull private Call<PageLead> reqPageLead(@Nullable CacheControl cacheControl,
@NonNull PageTitle pageTitle) {
PageClient client = newPageClient(pageTitle);
String title = pageTitle.getPrefixedText();
int thumbnailWidth = DimenUtil.calculateLeadImageWidth();
PageClient.CacheOption cacheOption = PageClient.CacheOption.SAVE;
return client.lead(cacheControl, cacheOption, title, thumbnailWidth);
}
@NonNull private Call<PageRemaining> reqPageSections(@Nullable CacheControl cacheControl,
@NonNull PageTitle pageTitle) {
PageClient client = newPageClient(pageTitle);
String title = pageTitle.getPrefixedText();
PageClient.CacheOption cacheOption = PageClient.CacheOption.SAVE;
return client.sections(cacheControl, cacheOption, title);
}
private AggregatedResponseSize reqSaveImage(@NonNull WikiSite wiki, @NonNull Iterable<String> urls) throws IOException, InterruptedException {
AggregatedResponseSize size = new AggregatedResponseSize(0, 0, 0);
for (String url : urls) {
if (savedPageSyncNotification.isSyncPaused() || savedPageSyncNotification.isSyncCanceled()) {
throw new InterruptedException("Sync paused or cancelled.");
}
try {
size = size.add(reqSaveImage(wiki, url));
} catch (Exception e) {
if (isRetryable(e)) {
throw e;
}
}
}
return size;
}
@NonNull private ResponseSize reqSaveImage(@NonNull WikiSite wiki, @NonNull String url) throws IOException {
Request request = saveImageReq(wiki, url);
Response rsp = OkHttpConnectionFactory.getClient().newCall(request).execute();
// Note: raw non-Retrofit usage of OkHttp Requests requires that the Response body is read
// for the cache to be written.
rsp.body().close();
// Size must be checked after the body has been written.
return responseSize(rsp);
}
@NonNull private Request saveImageReq(@NonNull WikiSite wiki, @NonNull String url) {
return new Request
.Builder()
.addHeader(SaveHeader.FIELD, SaveHeader.VAL_ENABLED)
.url(UriUtil.resolveProtocolRelativeUrl(wiki, url))
.build();
}
private void persistPageThumbnail(@NonNull PageTitle title, @NonNull String url) {
WikipediaApp.getInstance().getDatabaseClient(PageImage.class).upsert(
new PageImage(title, UriUtil.resolveProtocolRelativeUrl(title.getWikiSite(), url)),
PageImageHistoryContract.Image.SELECTION);
}
private boolean isRetryable(@NonNull Throwable t) {
/*
"Retryable" in this case refers to exceptions that will be rethrown up to the
outer exception handler, so that the entire page can be retried on the next pass
of the sync service.
Errors that do *not* qualify for retrying include:
- IllegalArgumentException (thrown for any kind of malformed URL)
- HTTP 404 status (for nonexistent media)
*/
return !(t instanceof IllegalArgumentException
|| ThrowableUtil.is404(t));
}
@NonNull private ResponseSize responseSize(@NonNull Response rsp) {
return responseSize(rsp.request());
}
@NonNull private ResponseSize responseSize(@NonNull retrofit2.Response rsp) {
return responseSize(rsp.raw().request());
}
@NonNull private ResponseSize responseSize(@NonNull Request req) {
return responseSize(cacheDelegate.entry(req));
}
@NonNull private ResponseSize responseSize(@Nullable DiskLruCache.Snapshot snapshot) {
long metadataSize = DiskLruCacheUtil.okHttpResponseMetadataSize(snapshot);
long bodySize = DiskLruCacheUtil.okHttpResponseBodySize(snapshot);
return new ResponseSize(metadataSize, bodySize);
}
@Nullable private PageTitle makeTitleFrom(@NonNull ReadingListPageDiskRow row) {
ReadingListPageRow pageRow = row.dat();
if (pageRow == null) {
return null;
}
String namespace = pageRow.namespace().toLegacyString();
return new PageTitle(namespace, pageRow.title(), pageRow.wikiSite());
}
@NonNull private PageClient newPageClient(@NonNull PageTitle title) {
return PageClientFactory.create(title.getWikiSite(), title.namespace());
}
private static class AggregatedResponseSize {
private final long physicalSize;
private final long logicalSize;
private final int responsesAggregated;
AggregatedResponseSize(long physicalSize, long logicalSize, int responsesAggregated) {
this.physicalSize = physicalSize;
this.logicalSize = logicalSize;
this.responsesAggregated = responsesAggregated;
}
@Override public String toString() {
return "responses=" + responsesAggregated() + " physical=" + physicalSize() + "B logical=" + logicalSize() + "B";
}
long physicalSize() {
return physicalSize;
}
// The size on disk.
long logicalSize() {
return logicalSize;
}
int responsesAggregated() {
return responsesAggregated;
}
@NonNull AggregatedResponseSize add(@NonNull ResponseSize size) {
return new AggregatedResponseSize(physicalSize + size.physicalSize(),
logicalSize + size.logicalSize(), responsesAggregated() + 1);
}
@NonNull AggregatedResponseSize add(@NonNull AggregatedResponseSize size) {
return new AggregatedResponseSize(physicalSize + size.physicalSize(),
logicalSize + size.logicalSize(), responsesAggregated() + size.responsesAggregated());
}
}
private class ResponseSize {
private final long metadataSize;
private final long bodySize;
ResponseSize(long metadataSize, long bodySize) {
this.metadataSize = metadataSize;
this.bodySize = bodySize;
}
@Override public String toString() {
return "physical metadata=" + metadataSize + "B physical body=" + bodySize
+ "B physical=" + physicalSize() + "B logical=" + logicalSize() + "B";
}
long physicalSize() {
return metadataSize + bodySize;
}
long logicalSize() {
return FileUtil.physicalToLogicalSize(metadataSize, blockSize)
+ FileUtil.physicalToLogicalSize(bodySize, blockSize);
}
}
}
|
Don't log 404 errors when saving pages.
This has been causing an unnecessary influx of crash logs, and can be
safely ignored.
Change-Id: Ic68b26e908f60063166ea4867b21ff554c8128ad
|
app/src/main/java/org/wikipedia/savedpages/SavedPageSyncService.java
|
Don't log 404 errors when saving pages.
|
|
Java
|
apache-2.0
|
cfab2af77d0c5256ae861327ce8eecb1639d5d34
| 0
|
gchq/Gaffer,GovernmentCommunicationsHeadquarters/Gaffer,gchq/Gaffer,GovernmentCommunicationsHeadquarters/Gaffer,gchq/Gaffer,GovernmentCommunicationsHeadquarters/Gaffer,gchq/Gaffer,GovernmentCommunicationsHeadquarters/Gaffer
|
/*
* Copyright 2016-2018 Crown Copyright
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.gov.gchq.gaffer.types;
import jdk.nashorn.internal.runtime.regexp.joni.Regex;
import uk.gov.gchq.koryphe.serialisation.json.JsonSimpleClassName;
import java.util.HashMap;
import java.util.Map;
import java.util.function.BiPredicate;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
/**
* {@code FreqMap} extends {@link HashMap} with String keys and Long values, adding an upsert operation.
*/
@JsonSimpleClassName
public class FreqMap extends HashMap<String, Long> {
private static final long serialVersionUID = -851105369975081220L;
public FreqMap(final Map<? extends String, ? extends Long> m) {
super(m);
}
public FreqMap() {
}
public FreqMap(final int initialCapacity) {
super(initialCapacity);
}
public FreqMap(final int initialCapacity, final float loadFactor) {
super(initialCapacity, loadFactor);
}
/**
* Adds a new key and value to the map if the key is not already there.
* If the key is already there, the value supplied is added to the existing value for the key and the result is inserted into the map.
*
* @param key The key in the map to increment or insert.
* @param value The value to increment by or initialise to.
*/
public void upsert(final String key, final Long value) {
final Long currentValue = get(key);
if (null == currentValue) {
put(key, value);
} else {
put(key, currentValue + value);
}
}
/**
* Increments the value of an existing key by 1.
* If the key doesn't exist, initialises the value to 1.
*
* @param key The key to increment or insert.
*/
public void upsert(final String key) {
upsert(key, 1L);
}
/**
* Creates a filtered copy of the map using a supplied regex pattern.
*
* @param regexPattern A valid regex pattern as a string.
* @return A new frequency map with only the filtered entries present.
*/
public FreqMap filterRegex(final String regexPattern) {
return filterPredicate((s, l) -> s.matches(regexPattern));
}
/**
* Creates a filtered copy of the map using a supplied predicate.
*
* @param predicate A valid predicate that can use one or both of the key-value pairings.
* @return A new frequency map with only the filtered entries present.
*/
public FreqMap filterPredicate(BiPredicate<String, Long> predicate) {
FreqMap f = new FreqMap();
this.entrySet().stream().filter(e -> predicate.test(e.getKey(), e.getValue()))
.forEach(e -> f.upsert(e.getKey(), e.getValue()));
return f;
}
}
|
core/type/src/main/java/uk/gov/gchq/gaffer/types/FreqMap.java
|
/*
* Copyright 2016-2018 Crown Copyright
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.gov.gchq.gaffer.types;
import uk.gov.gchq.koryphe.serialisation.json.JsonSimpleClassName;
import java.util.HashMap;
import java.util.Map;
/**
* {@code FreqMap} extends {@link HashMap} with String keys and Long values, adding an upsert operation.
*/
@JsonSimpleClassName
public class FreqMap extends HashMap<String, Long> {
private static final long serialVersionUID = -851105369975081220L;
public FreqMap(final Map<? extends String, ? extends Long> m) {
super(m);
}
public FreqMap() {
}
public FreqMap(final int initialCapacity) {
super(initialCapacity);
}
public FreqMap(final int initialCapacity, final float loadFactor) {
super(initialCapacity, loadFactor);
}
/**
* Adds a new key and value to the map if the key is not already there.
* If the key is already there, the value supplied is added to the existing value for the key and the result is inserted into the map.
*
* @param key The key in the map to increment or insert.
* @param value The value to increment by or initialise to.
*/
public void upsert(final String key, final Long value) {
final Long currentValue = get(key);
if (null == currentValue) {
put(key, value);
} else {
put(key, currentValue + value);
}
}
/**
* Increments the value of an existing key by 1.
* If the key doesn't exist, initialises the value to 1.
*
* @param key The key to increment or insert.
*/
public void upsert(final String key) {
upsert(key, 1L);
}
}
|
add filtering methods
|
core/type/src/main/java/uk/gov/gchq/gaffer/types/FreqMap.java
|
add filtering methods
|
|
Java
|
apache-2.0
|
0d4192f356a773ebea4bfaaed381abe962fe532a
| 0
|
MyersResearchGroup/iBioSim,MyersResearchGroup/iBioSim,MyersResearchGroup/iBioSim
|
package graph;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.Paint;
import java.awt.Shape;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.Properties;
import java.util.Scanner;
import java.util.concurrent.locks.ReentrantLock;
import java.util.prefs.Preferences;
import javax.swing.BorderFactory;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JColorChooser;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JTree;
import javax.swing.SwingConstants;
import javax.swing.event.TreeExpansionEvent;
import javax.swing.event.TreeExpansionListener;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.plaf.metal.MetalButtonUI;
import javax.swing.plaf.metal.MetalIconFactory;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.TreePath;
import lpn.parser.LhpnFile;
import main.Gui;
import main.Log;
import main.util.Utility;
import main.util.dataparser.DTSDParser;
import main.util.dataparser.DataParser;
import main.util.dataparser.TSDParser;
import org.apache.batik.dom.GenericDOMImplementation;
import org.apache.batik.svggen.SVGGraphics2D;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.axis.LogarithmicAxis;
import org.jfree.chart.axis.NumberTickUnit;
import org.jfree.chart.axis.StandardTickUnitSource;
import org.jfree.chart.event.ChartProgressEvent;
import org.jfree.chart.event.ChartProgressListener;
import org.jfree.chart.plot.DefaultDrawingSupplier;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.category.BarRenderer;
import org.jfree.chart.renderer.category.GradientBarPainter;
import org.jfree.chart.renderer.category.StandardBarPainter;
import org.jfree.chart.renderer.xy.XYItemRenderer;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.chart.title.LegendTitle;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.xy.XYDataItem;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
import org.jibble.epsgraphics.EpsGraphics2D;
import org.sbml.libsbml.ListOf;
import org.sbml.libsbml.Model;
import org.sbml.libsbml.SBMLDocument;
import org.sbml.libsbml.Species;
import org.w3c.dom.DOMImplementation;
import analysis.AnalysisView;
import biomodel.parser.BioModel;
import com.lowagie.text.Document;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.DefaultFontMapper;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfTemplate;
import com.lowagie.text.pdf.PdfWriter;
/**
* This is the Graph class. It takes in data and draws a graph of that data. The
* Graph class implements the ActionListener class, the ChartProgressListener
* class, and the MouseListener class. This allows the Graph class to perform
* actions when buttons are pressed, when the chart is drawn, or when the chart
* is clicked.
*
* @author Curtis Madsen
*/
public class Graph extends JPanel implements ActionListener, MouseListener, ChartProgressListener {
private static final long serialVersionUID = 4350596002373546900L;
private JFreeChart chart; // Graph of the output data
private XYSeriesCollection curData; // Data in the current graph
private String outDir; // output directory
private String printer_id; // printer id
/*
* Text fields used to change the graph window
*/
private JTextField XMin, XMax, XScale, YMin, YMax, YScale;
private ArrayList<String> graphSpecies; // names of species in the graph
private Gui biomodelsim; // tstubd gui
private JButton save, run, saveAs;
private JButton export, refresh; // buttons
// private JButton exportJPeg, exportPng, exportPdf, exportEps, exportSvg,
// exportCsv; // buttons
private HashMap<String, Paint> colors;
private HashMap<String, Shape> shapes;
private String selected, lastSelected;
private LinkedList<GraphSpecies> graphed;
private LinkedList<GraphProbs> probGraphed;
private JCheckBox resize;
private JComboBox XVariable;
private JCheckBox LogX, LogY;
private JCheckBox visibleLegend;
private LegendTitle legend;
private Log log;
private ArrayList<JCheckBox> boxes;
private ArrayList<JTextField> series;
private ArrayList<JComboBox> colorsCombo;
private ArrayList<JButton> colorsButtons;
private ArrayList<JComboBox> shapesCombo;
private ArrayList<JCheckBox> connected;
private ArrayList<JCheckBox> visible;
private ArrayList<JCheckBox> filled;
private JCheckBox use;
private JCheckBox connectedLabel;
private JCheckBox visibleLabel;
private JCheckBox filledLabel;
private String graphName;
private String separator;
private boolean change;
private boolean timeSeries;
private boolean topLevel;
private ArrayList<String> graphProbs;
private JTree tree;
private IconNode node, simDir;
private AnalysisView reb2sac; // reb2sac options
private ArrayList<String> learnSpecs;
private boolean warn;
private ArrayList<String> averageOrder;
private JPopupMenu popup; // popup menu
private ArrayList<String> directories;
private JPanel specPanel;
private JScrollPane scrollpane;
private JPanel all;
private JPanel titlePanel;
private JScrollPane scroll;
private boolean updateXNumber;
private final ReentrantLock lock, lock2;
/**
* Creates a Graph Object from the data given and calls the private graph
* helper method.
*/
public Graph(AnalysisView reb2sac, String printer_track_quantity, String label, String printer_id, String outDir, String time, Gui biomodelsim,
String open, Log log, String graphName, boolean timeSeries, boolean learnGraph) {
lock = new ReentrantLock(true);
lock2 = new ReentrantLock(true);
this.reb2sac = reb2sac;
averageOrder = null;
popup = new JPopupMenu();
warn = false;
if (File.separator.equals("\\")) {
separator = "\\\\";
}
else {
separator = File.separator;
}
// initializes member variables
this.log = log;
this.timeSeries = timeSeries;
if (graphName != null) {
this.graphName = graphName;
topLevel = true;
}
else {
if (timeSeries) {
this.graphName = outDir.split(separator)[outDir.split(separator).length - 1] + ".grf";
}
else {
this.graphName = outDir.split(separator)[outDir.split(separator).length - 1] + ".prb";
}
topLevel = false;
}
this.outDir = outDir;
this.printer_id = printer_id;
this.biomodelsim = biomodelsim;
XYSeriesCollection data = new XYSeriesCollection();
if (learnGraph) {
updateSpecies();
}
else {
learnSpecs = null;
}
// graph the output data
if (timeSeries) {
setUpShapesAndColors();
graphed = new LinkedList<GraphSpecies>();
selected = "";
lastSelected = "";
graph(printer_track_quantity, label, data, time);
if (open != null) {
open(open);
}
}
else {
setUpShapesAndColors();
probGraphed = new LinkedList<GraphProbs>();
selected = "";
lastSelected = "";
probGraph(label);
if (open != null) {
open(open);
}
}
}
/**
* This private helper method calls the private readData method, sets up a
* graph frame, and graphs the data.
*
* @param dataset
* @param time
*/
private void graph(String printer_track_quantity, String label, XYSeriesCollection dataset, String time) {
chart = ChartFactory.createXYLineChart(label, time, printer_track_quantity, dataset, PlotOrientation.VERTICAL, true, true, false);
chart.setBackgroundPaint(new java.awt.Color(238, 238, 238));
chart.getPlot().setBackgroundPaint(java.awt.Color.WHITE);
chart.getXYPlot().setDomainGridlinePaint(java.awt.Color.LIGHT_GRAY);
chart.getXYPlot().setRangeGridlinePaint(java.awt.Color.LIGHT_GRAY);
chart.addProgressListener(this);
legend = chart.getLegend();
ChartPanel graph = new ChartPanel(chart);
graph.setLayout(new GridLayout(1, 1));
JLabel edit = new JLabel("Double click here to create graph");
edit.addMouseListener(this);
Font font = edit.getFont();
font = font.deriveFont(Font.BOLD, 42.0f);
edit.setFont(font);
edit.setHorizontalAlignment(SwingConstants.CENTER);
graph.add(edit);
graph.addMouseListener(this);
change = false;
// creates text fields for changing the graph's dimensions
resize = new JCheckBox("Auto Resize");
resize.setSelected(true);
XVariable = new JComboBox();
Dimension dim = new Dimension(1,1);
XVariable.setPreferredSize(dim);
updateXNumber = false;
XVariable.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (updateXNumber && node != null) {
String curDir = "";
if (node.getParent().getParent() != null
&& directories.contains(((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName())) {
curDir = ((IconNode) node.getParent().getParent()).getName() + separator + ((IconNode) node.getParent()).getName();
}
else if (directories.contains(((IconNode) node.getParent()).getName())) {
curDir = ((IconNode) node.getParent()).getName();
}
else {
curDir = "";
}
for (int i = 0; i < graphed.size(); i++) {
if (graphed.get(i).getDirectory().equals(curDir)) {
graphed.get(i).setXNumber(XVariable.getSelectedIndex());
}
}
}
}
});
LogX = new JCheckBox("LogX");
LogX.setSelected(false);
LogY = new JCheckBox("LogY");
LogY.setSelected(false);
visibleLegend = new JCheckBox("Visible Legend");
visibleLegend.setSelected(true);
XMin = new JTextField();
XMax = new JTextField();
XScale = new JTextField();
YMin = new JTextField();
YMax = new JTextField();
YScale = new JTextField();
// creates the buttons for the graph frame
JPanel ButtonHolder = new JPanel();
run = new JButton("Save and Run");
save = new JButton("Save Graph");
saveAs = new JButton("Save As");
saveAs.addActionListener(this);
export = new JButton("Export");
refresh = new JButton("Refresh");
// exportJPeg = new JButton("Export As JPEG");
// exportPng = new JButton("Export As PNG");
// exportPdf = new JButton("Export As PDF");
// exportEps = new JButton("Export As EPS");
// exportSvg = new JButton("Export As SVG");
// exportCsv = new JButton("Export As CSV");
run.addActionListener(this);
save.addActionListener(this);
export.addActionListener(this);
refresh.addActionListener(this);
// exportJPeg.addActionListener(this);
// exportPng.addActionListener(this);
// exportPdf.addActionListener(this);
// exportEps.addActionListener(this);
// exportSvg.addActionListener(this);
// exportCsv.addActionListener(this);
if (reb2sac != null) {
ButtonHolder.add(run);
}
ButtonHolder.add(save);
ButtonHolder.add(saveAs);
ButtonHolder.add(export);
ButtonHolder.add(refresh);
// ButtonHolder.add(exportJPeg);
// ButtonHolder.add(exportPng);
// ButtonHolder.add(exportPdf);
// ButtonHolder.add(exportEps);
// ButtonHolder.add(exportSvg);
// ButtonHolder.add(exportCsv);
// puts all the components of the graph gui into a display panel
// JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
// ButtonHolder, null);
// splitPane.setDividerSize(0);
this.removeAll();
this.setLayout(new BorderLayout());
this.add(graph, "Center");
// this.add(splitPane, "South");
// determines maximum and minimum values and resizes
resize(dataset);
this.revalidate();
}
private void readGraphSpecies(String file) {
Gui.frame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
if (file.contains(".dtsd"))
graphSpecies = (new DTSDParser(file)).getSpecies();
else
graphSpecies = new TSDParser(file, true).getSpecies();
Gui.frame.setCursor(null);
if (learnSpecs != null) {
for (String spec : learnSpecs) {
if (!graphSpecies.contains(spec)) {
graphSpecies.add(spec);
}
}
for (int i = 1; i < graphSpecies.size(); i++) {
if (!learnSpecs.contains(graphSpecies.get(i))) {
graphSpecies.remove(i);
i--;
}
}
}
}
/**
* This public helper method parses the output file of ODE, monte carlo, and
* markov abstractions.
*/
public ArrayList<ArrayList<Double>> readData(String file, String label, String directory, boolean warning) {
warn = warning;
String[] s = file.split(separator);
String getLast = s[s.length - 1];
String stem = "";
int t = 0;
try {
while (!Character.isDigit(getLast.charAt(t))) {
stem += getLast.charAt(t);
t++;
}
}
catch (Exception e) {
}
if ((label.contains("average") && file.contains("mean")) || (label.contains("variance") && file.contains("variance"))
|| (label.contains("deviation") && file.contains("standard_deviation"))) {
Gui.frame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
TSDParser p = new TSDParser(file, warn);
Gui.frame.setCursor(null);
warn = p.getWarning();
graphSpecies = p.getSpecies();
ArrayList<ArrayList<Double>> data = p.getData();
if (learnSpecs != null) {
for (String spec : learnSpecs) {
if (!graphSpecies.contains(spec)) {
graphSpecies.add(spec);
ArrayList<Double> d = new ArrayList<Double>();
for (int i = 0; i < data.get(0).size(); i++) {
d.add(0.0);
}
data.add(d);
}
}
for (int i = 1; i < graphSpecies.size(); i++) {
if (!learnSpecs.contains(graphSpecies.get(i))) {
graphSpecies.remove(i);
data.remove(i);
i--;
}
}
}
else if (averageOrder != null) {
for (String spec : averageOrder) {
if (!graphSpecies.contains(spec)) {
graphSpecies.add(spec);
ArrayList<Double> d = new ArrayList<Double>();
for (int i = 0; i < data.get(0).size(); i++) {
d.add(0.0);
}
data.add(d);
}
}
for (int i = 1; i < graphSpecies.size(); i++) {
if (!averageOrder.contains(graphSpecies.get(i))) {
graphSpecies.remove(i);
data.remove(i);
i--;
}
}
}
return data;
}
if (label.contains("average") || label.contains("variance") || label.contains("deviation")) {
ArrayList<String> runs = new ArrayList<String>();
if (directory == null) {
String[] files = new File(outDir).list();
for (String f : files) {
if (f.contains(stem) && f.endsWith("." + printer_id.substring(0, printer_id.length() - 8))) {
runs.add(f);
}
}
}
else {
String[] files = new File(outDir + separator + directory).list();
for (String f : files) {
if (f.contains(stem) && f.endsWith("." + printer_id.substring(0, printer_id.length() - 8))) {
runs.add(f);
}
}
}
if (label.contains("average")) {
return calculateAverageVarianceDeviation(runs, 0, directory, warn, false);
}
else if (label.contains("variance")) {
return calculateAverageVarianceDeviation(runs, 1, directory, warn, false);
}
else {
return calculateAverageVarianceDeviation(runs, 2, directory, warn, false);
}
}
//if it's not a stats file
else {
Gui.frame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
DTSDParser dtsdParser;
TSDParser p;
ArrayList<ArrayList<Double>> data;
if (file.contains(".dtsd")) {
dtsdParser = new DTSDParser(file);
Gui.frame.setCursor(null);
warn = false;
graphSpecies = dtsdParser.getSpecies();
data = dtsdParser.getData();
}
else {
p = new TSDParser(file, warn);
Gui.frame.setCursor(null);
warn = p.getWarning();
graphSpecies = p.getSpecies();
data = p.getData();
}
if (learnSpecs != null) {
for (String spec : learnSpecs) {
if (!graphSpecies.contains(spec)) {
graphSpecies.add(spec);
ArrayList<Double> d = new ArrayList<Double>();
for (int i = 0; i < data.get(0).size(); i++) {
d.add(0.0);
}
data.add(d);
}
}
for (int i = 1; i < graphSpecies.size(); i++) {
if (!learnSpecs.contains(graphSpecies.get(i))) {
graphSpecies.remove(i);
data.remove(i);
i--;
}
}
}
else if (averageOrder != null) {
for (String spec : averageOrder) {
if (!graphSpecies.contains(spec)) {
graphSpecies.add(spec);
ArrayList<Double> d = new ArrayList<Double>();
for (int i = 0; i < data.get(0).size(); i++) {
d.add(0.0);
}
data.add(d);
}
}
for (int i = 1; i < graphSpecies.size(); i++) {
if (!averageOrder.contains(graphSpecies.get(i))) {
graphSpecies.remove(i);
data.remove(i);
i--;
}
}
}
return data;
}
}
/**
* This method adds and removes plots from the graph depending on what check
* boxes are selected.
*/
public void actionPerformed(ActionEvent e) {
// if the save button is clicked
if (e.getSource() == run) {
reb2sac.getRunButton().doClick();
}
if (e.getSource() == save) {
save();
}
// if the save as button is clicked
if (e.getSource() == saveAs) {
saveAs();
}
// if the export button is clicked
else if (e.getSource() == export) {
export();
}
else if (e.getSource() == refresh) {
refresh();
}
else if (e.getActionCommand().equals("rename")) {
String rename = JOptionPane.showInputDialog(Gui.frame, "Enter A New Filename:", "Rename", JOptionPane.PLAIN_MESSAGE);
if (rename != null) {
rename = rename.trim();
}
else {
return;
}
if (!rename.equals("")) {
boolean write = true;
if (rename.equals(node.getName())) {
write = false;
}
else if (new File(outDir + separator + rename).exists()) {
Object[] options = { "Overwrite", "Cancel" };
int value = JOptionPane.showOptionDialog(Gui.frame, "File already exists." + "\nDo you want to overwrite?", "Overwrite",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
if (value == JOptionPane.YES_OPTION) {
File dir = new File(outDir + separator + rename);
if (dir.isDirectory()) {
biomodelsim.deleteDir(dir);
}
else {
dir.delete();
}
for (int i = 0; i < simDir.getChildCount(); i++) {
if (((IconNode) simDir.getChildAt(i)).getChildCount() > 0 && ((IconNode) simDir.getChildAt(i)).getName().equals(rename)) {
simDir.remove(i);
}
}
boolean checked = false;
for (int i = 0; i < simDir.getChildCount(); i++) {
if (((IconNode) simDir.getChildAt(i)).getIconName().equals("" + (char) 10003)) {
checked = true;
}
}
if (!checked) {
simDir.setIcon(MetalIconFactory.getTreeFolderIcon());
simDir.setIconName("");
}
for (int i = 0; i < graphed.size(); i++) {
if (graphed.get(i).getDirectory().equals(rename)) {
graphed.remove(i);
i--;
}
}
}
else {
write = false;
}
}
if (write) {
String getFile = node.getName();
IconNode s = node;
while (s.getParent().getParent() != null) {
getFile = s.getName() + separator + getFile;
s = (IconNode) s.getParent();
}
getFile = outDir + separator + getFile;
new File(getFile).renameTo(new File(outDir + separator + rename));
for (GraphSpecies spec : graphed) {
if (spec.getDirectory().equals(node.getName())) {
spec.setDirectory(rename);
}
}
directories.remove(node.getName());
directories.add(rename);
node.setUserObject(rename);
node.setName(rename);
simDir.remove(node);
int i;
for (i = 0; i < simDir.getChildCount(); i++) {
if (((IconNode) simDir.getChildAt(i)).getChildCount() != 0) {
if (((IconNode) simDir.getChildAt(i)).getName().compareToIgnoreCase(rename) > 0) {
simDir.insert(node, i);
break;
}
}
else {
break;
}
}
simDir.insert(node, i);
ArrayList<String> rows = new ArrayList<String>();
for (i = 0; i < tree.getRowCount(); i++) {
if (tree.isExpanded(i)) {
tree.setSelectionRow(i);
rows.add(node.getName());
}
}
scrollpane = new JScrollPane();
refreshTree();
scrollpane.getViewport().add(tree);
scrollpane.setPreferredSize(new Dimension(175, 100));
all.removeAll();
all.add(titlePanel, "North");
all.add(scroll, "Center");
all.add(scrollpane, "West");
all.revalidate();
all.repaint();
TreeSelectionListener t = new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
node = (IconNode) e.getPath().getLastPathComponent();
}
};
tree.addTreeSelectionListener(t);
int select = 0;
for (i = 0; i < tree.getRowCount(); i++) {
tree.setSelectionRow(i);
if (rows.contains(node.getName())) {
tree.expandRow(i);
}
if (rename.equals(node.getName())) {
select = i;
}
}
tree.removeTreeSelectionListener(t);
addTreeListener();
tree.setSelectionRow(select);
}
}
}
else if (e.getActionCommand().equals("recalculate")) {
TreePath select = tree.getSelectionPath();
String[] files;
if (((IconNode) select.getLastPathComponent()).getParent() != null) {
files = new File(outDir + separator + ((IconNode) select.getLastPathComponent()).getName()).list();
}
else {
files = new File(outDir).list();
}
ArrayList<String> runs = new ArrayList<String>();
for (String file : files) {
if (file.contains("run-") && file.endsWith("." + printer_id.substring(0, printer_id.length() - 8))) {
runs.add(file);
}
}
if (((IconNode) select.getLastPathComponent()).getParent() != null) {
calculateAverageVarianceDeviation(runs, 0, ((IconNode) select.getLastPathComponent()).getName(), warn, true);
}
else {
calculateAverageVarianceDeviation(runs, 0, null, warn, true);
}
}
else if (e.getActionCommand().equals("delete")) {
TreePath[] selected = tree.getSelectionPaths();
TreeSelectionListener t = new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
node = (IconNode) e.getPath().getLastPathComponent();
}
};
for (TreeSelectionListener listen : tree.getTreeSelectionListeners()) {
tree.removeTreeSelectionListener(listen);
}
tree.addTreeSelectionListener(t);
for (TreePath select : selected) {
tree.setSelectionPath(select);
if (((IconNode) select.getLastPathComponent()).getParent() != null) {
for (int i = 0; i < simDir.getChildCount(); i++) {
if (((IconNode) simDir.getChildAt(i)) == ((IconNode) select.getLastPathComponent())) {
if (((IconNode) simDir.getChildAt(i)).getChildCount() != 0) {
simDir.remove(i);
File dir = new File(outDir + separator + ((IconNode) select.getLastPathComponent()).getName());
if (dir.isDirectory()) {
biomodelsim.deleteDir(dir);
}
else {
dir.delete();
}
directories.remove(((IconNode) select.getLastPathComponent()).getName());
for (int j = 0; j < graphed.size(); j++) {
if (graphed.get(j).getDirectory().equals(((IconNode) select.getLastPathComponent()).getName())) {
graphed.remove(j);
j--;
}
}
}
else {
String name = ((IconNode) select.getLastPathComponent()).getName();
if (name.equals("Average")) {
name = "mean";
}
else if (name.equals("Variance")) {
name = "variance";
}
else if (name.equals("Standard Deviation")) {
name = "standard_deviation";
}
else if (name.equals("Percent Termination")) {
name = "percent-term-time";
simDir.remove(i);
}
else if (name.equals("Termination Time")) {
name = "term-time";
simDir.remove(i);
}
else if (name.equals("Constraint Termination")) {
name = "sim-rep";
simDir.remove(i);
}
else if (name.equals("Bifurcation Statistics")) {
name = "bifurcation";
simDir.remove(i);
}
else {
simDir.remove(i);
}
name += "." + printer_id.substring(0, printer_id.length() - 8);
File dir = new File(outDir + separator + name);
if (dir.isDirectory()) {
biomodelsim.deleteDir(dir);
}
else {
dir.delete();
}
int count = 0;
boolean m = false;
if (new File(outDir + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
m = true;
}
boolean v = false;
if (new File(outDir + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
v = true;
}
boolean d = false;
if (new File(outDir + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
d = true;
}
for (int j = 0; j < simDir.getChildCount(); j++) {
if (((IconNode) simDir.getChildAt(j)).getChildCount() == 0) {
if (((IconNode) simDir.getChildAt(j)).getName().contains("run-")) {
count++;
}
}
}
if (count == 0) {
for (int j = 0; j < simDir.getChildCount(); j++) {
if (((IconNode) simDir.getChildAt(j)).getChildCount() == 0) {
if (((IconNode) simDir.getChildAt(j)).getName().contains("Average") && !m) {
simDir.remove(j);
j--;
}
else if (((IconNode) simDir.getChildAt(j)).getName().contains("Variance") && !v) {
simDir.remove(j);
j--;
}
else if (((IconNode) simDir.getChildAt(j)).getName().contains("Deviation") && !d) {
simDir.remove(j);
j--;
}
}
}
}
}
}
else if (((IconNode) simDir.getChildAt(i)).getChildCount() != 0) {
for (int j = 0; j < simDir.getChildAt(i).getChildCount(); j++) {
if (((IconNode) ((IconNode) simDir.getChildAt(i)).getChildAt(j)) == ((IconNode) select.getLastPathComponent())) {
String name = ((IconNode) select.getLastPathComponent()).getName();
if (name.equals("Average")) {
name = "mean";
}
else if (name.equals("Variance")) {
name = "variance";
}
else if (name.equals("Standard Deviation")) {
name = "standard_deviation";
}
else if (name.equals("Percent Termination")) {
name = "percent-term-time";
((IconNode) simDir.getChildAt(i)).remove(j);
}
else if (name.equals("Termination Time")) {
name = "term-time";
((IconNode) simDir.getChildAt(i)).remove(j);
}
else if (name.equals("Constraint Termination")) {
name = "sim-rep";
((IconNode) simDir.getChildAt(i)).remove(j);
}
else if (name.equals("Bifurcation Statistics")) {
name = "bifurcation";
((IconNode) simDir.getChildAt(i)).remove(j);
}
else {
((IconNode) simDir.getChildAt(i)).remove(j);
}
name += "." + printer_id.substring(0, printer_id.length() - 8);
File dir = new File(outDir + separator + ((IconNode) simDir.getChildAt(i)).getName() + separator + name);
if (dir.isDirectory()) {
biomodelsim.deleteDir(dir);
}
else {
dir.delete();
}
boolean checked = false;
for (int k = 0; k < simDir.getChildAt(i).getChildCount(); k++) {
if (((IconNode) simDir.getChildAt(i).getChildAt(k)).getIconName().equals("" + (char) 10003)) {
checked = true;
}
}
if (!checked) {
((IconNode) simDir.getChildAt(i)).setIcon(MetalIconFactory.getTreeFolderIcon());
((IconNode) simDir.getChildAt(i)).setIconName("");
}
int count = 0;
boolean m = false;
if (new File(outDir + separator + ((IconNode) simDir.getChildAt(i)).getName() + separator + "mean" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
m = true;
}
boolean v = false;
if (new File(outDir + separator + ((IconNode) simDir.getChildAt(i)).getName() + separator + "variance" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
v = true;
}
boolean d = false;
if (new File(outDir + separator + ((IconNode) simDir.getChildAt(i)).getName() + separator + "standard_deviation"
+ "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
d = true;
}
for (int k = 0; k < simDir.getChildAt(i).getChildCount(); k++) {
if (((IconNode) simDir.getChildAt(i).getChildAt(k)).getChildCount() == 0) {
if (((IconNode) simDir.getChildAt(i).getChildAt(k)).getName().contains("run-")) {
count++;
}
}
}
if (count == 0) {
for (int k = 0; k < simDir.getChildAt(i).getChildCount(); k++) {
if (((IconNode) simDir.getChildAt(i).getChildAt(k)).getChildCount() == 0) {
if (((IconNode) simDir.getChildAt(i).getChildAt(k)).getName().contains("Average") && !m) {
((IconNode) simDir.getChildAt(i)).remove(k);
k--;
}
else if (((IconNode) simDir.getChildAt(i).getChildAt(k)).getName().contains("Variance") && !v) {
((IconNode) simDir.getChildAt(i)).remove(k);
k--;
}
else if (((IconNode) simDir.getChildAt(i).getChildAt(k)).getName().contains("Deviation") && !d) {
((IconNode) simDir.getChildAt(i)).remove(k);
k--;
}
}
}
}
}
}
}
}
}
}
boolean checked = false;
for (int i = 0; i < simDir.getChildCount(); i++) {
if (((IconNode) simDir.getChildAt(i)).getIconName().equals("" + (char) 10003)) {
checked = true;
}
}
if (!checked) {
simDir.setIcon(MetalIconFactory.getTreeFolderIcon());
simDir.setIconName("");
}
ArrayList<String> rows = new ArrayList<String>();
for (int i = 0; i < tree.getRowCount(); i++) {
if (tree.isExpanded(i)) {
tree.setSelectionRow(i);
rows.add(node.getName());
}
}
scrollpane = new JScrollPane();
refreshTree();
scrollpane.getViewport().add(tree);
scrollpane.setPreferredSize(new Dimension(175, 100));
all.removeAll();
all.add(titlePanel, "North");
all.add(scroll, "Center");
all.add(scrollpane, "West");
all.revalidate();
all.repaint();
t = new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
node = (IconNode) e.getPath().getLastPathComponent();
}
};
tree.addTreeSelectionListener(t);
for (int i = 0; i < tree.getRowCount(); i++) {
tree.setSelectionRow(i);
if (rows.contains(node.getName())) {
tree.expandRow(i);
}
}
tree.removeTreeSelectionListener(t);
addTreeListener();
}
else if (e.getActionCommand().equals("delete runs")) {
for (int i = simDir.getChildCount() - 1; i >= 0; i--) {
if (((IconNode) simDir.getChildAt(i)).getChildCount() == 0) {
String name = ((IconNode) simDir.getChildAt(i)).getName();
if (name.equals("Average")) {
name = "mean";
}
else if (name.equals("Variance")) {
name = "variance";
}
else if (name.equals("Standard Deviation")) {
name = "standard_deviation";
}
else if (name.equals("Percent Termination")) {
name = "percent-term-time";
}
else if (name.equals("Termination Time")) {
name = "term-time";
}
else if (name.equals("Constraint Termination")) {
name = "sim-rep";
}
else if (name.equals("Bifurcation Statistics")) {
name = "bifurcation";
}
name += "." + printer_id.substring(0, printer_id.length() - 8);
File dir = new File(outDir + separator + name);
if (dir.isDirectory()) {
biomodelsim.deleteDir(dir);
}
else {
dir.delete();
}
simDir.remove(i);
}
}
boolean checked = false;
for (int i = 0; i < simDir.getChildCount(); i++) {
if (((IconNode) simDir.getChildAt(i)).getIconName().equals("" + (char) 10003)) {
checked = true;
}
}
if (!checked) {
simDir.setIcon(MetalIconFactory.getTreeFolderIcon());
simDir.setIconName("");
}
ArrayList<String> rows = new ArrayList<String>();
for (int i = 0; i < tree.getRowCount(); i++) {
if (tree.isExpanded(i)) {
tree.setSelectionRow(i);
rows.add(node.getName());
}
}
scrollpane = new JScrollPane();
refreshTree();
scrollpane.getViewport().add(tree);
scrollpane.setPreferredSize(new Dimension(175, 100));
all.removeAll();
all.add(titlePanel, "North");
all.add(scroll, "Center");
all.add(scrollpane, "West");
all.revalidate();
all.repaint();
TreeSelectionListener t = new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
node = (IconNode) e.getPath().getLastPathComponent();
}
};
tree.addTreeSelectionListener(t);
for (int i = 0; i < tree.getRowCount(); i++) {
tree.setSelectionRow(i);
if (rows.contains(node.getName())) {
tree.expandRow(i);
}
}
tree.removeTreeSelectionListener(t);
addTreeListener();
}
else if (e.getActionCommand().equals("delete all")) {
for (int i = simDir.getChildCount() - 1; i >= 0; i--) {
if (((IconNode) simDir.getChildAt(i)).getChildCount() == 0) {
String name = ((IconNode) simDir.getChildAt(i)).getName();
if (name.equals("Average")) {
name = "mean";
}
else if (name.equals("Variance")) {
name = "variance";
}
else if (name.equals("Standard Deviation")) {
name = "standard_deviation";
}
else if (name.equals("Percent Termination")) {
name = "percent-term-time";
}
else if (name.equals("Termination Time")) {
name = "term-time";
}
else if (name.equals("Constraint Termination")) {
name = "sim-rep";
}
else if (name.equals("Bifurcation Statistics")) {
name = "bifurcation";
}
name += "." + printer_id.substring(0, printer_id.length() - 8);
File dir = new File(outDir + separator + name);
if (dir.isDirectory()) {
biomodelsim.deleteDir(dir);
}
else {
dir.delete();
}
simDir.remove(i);
}
else {
File dir = new File(outDir + separator + ((IconNode) simDir.getChildAt(i)).getName());
if (dir.isDirectory()) {
biomodelsim.deleteDir(dir);
}
else {
dir.delete();
}
simDir.remove(i);
}
}
boolean checked = false;
for (int i = 0; i < simDir.getChildCount(); i++) {
if (((IconNode) simDir.getChildAt(i)).getIconName().equals("" + (char) 10003)) {
checked = true;
}
}
if (!checked) {
simDir.setIcon(MetalIconFactory.getTreeFolderIcon());
simDir.setIconName("");
}
ArrayList<String> rows = new ArrayList<String>();
for (int i = 0; i < tree.getRowCount(); i++) {
if (tree.isExpanded(i)) {
tree.setSelectionRow(i);
rows.add(node.getName());
}
}
scrollpane = new JScrollPane();
refreshTree();
scrollpane.getViewport().add(tree);
scrollpane.setPreferredSize(new Dimension(175, 100));
all.removeAll();
all.add(titlePanel, "North");
all.add(scroll, "Center");
all.add(scrollpane, "West");
all.revalidate();
all.repaint();
TreeSelectionListener t = new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
node = (IconNode) e.getPath().getLastPathComponent();
}
};
tree.addTreeSelectionListener(t);
for (int i = 0; i < tree.getRowCount(); i++) {
tree.setSelectionRow(i);
if (rows.contains(node.getName())) {
tree.expandRow(i);
}
}
tree.removeTreeSelectionListener(t);
addTreeListener();
}
// // if the export as jpeg button is clicked
// else if (e.getSource() == exportJPeg) {
// export(0);
// }
// // if the export as png button is clicked
// else if (e.getSource() == exportPng) {
// export(1);
// }
// // if the export as pdf button is clicked
// else if (e.getSource() == exportPdf) {
// export(2);
// }
// // if the export as eps button is clicked
// else if (e.getSource() == exportEps) {
// export(3);
// }
// // if the export as svg button is clicked
// else if (e.getSource() == exportSvg) {
// export(4);
// } else if (e.getSource() == exportCsv) {
// export(5);
// }
}
/**
* Private method used to auto resize the graph.
*/
private void resize(XYSeriesCollection dataset) {
NumberFormat num = NumberFormat.getInstance();
num.setMaximumFractionDigits(4);
num.setGroupingUsed(false);
XYPlot plot = chart.getXYPlot();
XYItemRenderer rend = plot.getRenderer();
double minY = Double.MAX_VALUE;
double maxY = Double.MIN_VALUE;
double minX = Double.MAX_VALUE;
double maxX = Double.MIN_VALUE;
for (int j = 0; j < dataset.getSeriesCount(); j++) {
XYSeries series = dataset.getSeries(j);
double[][] seriesArray = series.toArray();
Boolean visible = rend.getSeriesVisible(j);
if (visible == null || visible.equals(true)) {
for (int k = 0; k < series.getItemCount(); k++) {
maxY = Math.max(seriesArray[1][k], maxY);
minY = Math.min(seriesArray[1][k], minY);
maxX = Math.max(seriesArray[0][k], maxX);
minX = Math.min(seriesArray[0][k], minX);
}
}
}
NumberAxis axis = (NumberAxis) plot.getRangeAxis();
if (minY == Double.MAX_VALUE || maxY == Double.MIN_VALUE) {
axis.setRange(-1, 1);
}
// else if ((maxY - minY) < .001) {
// axis.setRange(minY - 1, maxY + 1);
// }
else {
/*
* axis.setRange(Double.parseDouble(num.format(minY -
* (Math.abs(minY) .1))), Double .parseDouble(num.format(maxY +
* (Math.abs(maxY) .1))));
*/
if ((maxY - minY) < .001) {
axis.setStandardTickUnits(new StandardTickUnitSource());
}
else {
axis.setStandardTickUnits(NumberAxis.createStandardTickUnits());
}
axis.setRange(minY - (Math.abs(minY) * .1), maxY + (Math.abs(maxY) * .1));
}
axis.setAutoTickUnitSelection(true);
if (LogY.isSelected()) {
try {
LogarithmicAxis rangeAxis = new LogarithmicAxis(chart.getXYPlot().getRangeAxis().getLabel());
rangeAxis.setStrictValuesFlag(false);
plot.setRangeAxis(rangeAxis);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(Gui.frame, "Log plots are not allowed with data\nvalues less than or equal to zero.", "Error",
JOptionPane.ERROR_MESSAGE);
NumberAxis rangeAxis = new NumberAxis(chart.getXYPlot().getRangeAxis().getLabel());
plot.setRangeAxis(rangeAxis);
LogY.setSelected(false);
}
}
if (visibleLegend.isSelected()) {
if (chart.getLegend() == null) {
chart.addLegend(legend);
}
}
else {
if (chart.getLegend() != null) {
legend = chart.getLegend();
}
chart.removeLegend();
}
axis = (NumberAxis) plot.getDomainAxis();
if (minX == Double.MAX_VALUE || maxX == Double.MIN_VALUE) {
axis.setRange(-1, 1);
}
// else if ((maxX - minX) < .001) {
// axis.setRange(minX - 1, maxX + 1);
// }
else {
if ((maxX - minX) < .001) {
axis.setStandardTickUnits(new StandardTickUnitSource());
}
else {
axis.setStandardTickUnits(NumberAxis.createStandardTickUnits());
}
axis.setRange(minX, maxX);
}
axis.setAutoTickUnitSelection(true);
if (LogX.isSelected()) {
try {
LogarithmicAxis domainAxis = new LogarithmicAxis(chart.getXYPlot().getDomainAxis().getLabel());
domainAxis.setStrictValuesFlag(false);
plot.setDomainAxis(domainAxis);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(Gui.frame, "Log plots are not allowed with data\nvalues less than or equal to zero.", "Error",
JOptionPane.ERROR_MESSAGE);
NumberAxis domainAxis = new NumberAxis(chart.getXYPlot().getDomainAxis().getLabel());
plot.setRangeAxis(domainAxis);
LogX.setSelected(false);
}
}
}
/**
* After the chart is redrawn, this method calculates the x and y scale and
* updates those text fields.
*/
public void chartProgress(ChartProgressEvent e) {
// if the chart drawing is started
if (e.getType() == ChartProgressEvent.DRAWING_STARTED) {
this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
}
// if the chart drawing is finished
else if (e.getType() == ChartProgressEvent.DRAWING_FINISHED) {
this.setCursor(null);
JFreeChart chart = e.getChart();
XYPlot plot = (XYPlot) chart.getXYPlot();
NumberAxis axis = (NumberAxis) plot.getRangeAxis();
YMin.setText("" + axis.getLowerBound());
YMax.setText("" + axis.getUpperBound());
YScale.setText("" + axis.getTickUnit().getSize());
axis = (NumberAxis) plot.getDomainAxis();
XMin.setText("" + axis.getLowerBound());
XMax.setText("" + axis.getUpperBound());
XScale.setText("" + axis.getTickUnit().getSize());
}
}
/**
* Invoked when the mouse is clicked on the chart. Allows the user to edit
* the title and labels of the chart.
*/
public void mouseClicked(MouseEvent e) {
if (e.getSource() != tree) {
if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() == 2) {
if (timeSeries) {
editGraph();
}
else {
editProbGraph();
}
}
}
}
public void mousePressed(MouseEvent e) {
if (e.getSource() == tree) {
int selRow = tree.getRowForLocation(e.getX(), e.getY());
if (selRow < 0)
return;
TreePath selPath = tree.getPathForLocation(e.getX(), e.getY());
boolean set = true;
for (TreePath p : tree.getSelectionPaths()) {
if (p.equals(selPath)) {
tree.addSelectionPath(selPath);
set = false;
}
}
if (set) {
tree.setSelectionPath(selPath);
}
if (e.isPopupTrigger()) {
popup.removeAll();
if (node.getChildCount() != 0) {
JMenuItem recalculate = new JMenuItem("Recalculate Statistics");
recalculate.addActionListener(this);
recalculate.setActionCommand("recalculate");
popup.add(recalculate);
}
if (node.getChildCount() != 0 && node.getParent() != null) {
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.setActionCommand("rename");
popup.add(rename);
}
if (node.getParent() != null) {
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.setActionCommand("delete");
popup.add(delete);
}
else {
JMenuItem delete = new JMenuItem("Delete All Runs");
delete.addActionListener(this);
delete.setActionCommand("delete runs");
popup.add(delete);
JMenuItem deleteAll = new JMenuItem("Delete Recursive");
deleteAll.addActionListener(this);
deleteAll.setActionCommand("delete all");
popup.add(deleteAll);
}
if (popup.getComponentCount() != 0) {
popup.show(e.getComponent(), e.getX(), e.getY());
}
}
}
}
public void mouseReleased(MouseEvent e) {
if (e.getSource() == tree) {
int selRow = tree.getRowForLocation(e.getX(), e.getY());
if (selRow < 0)
return;
TreePath selPath = tree.getPathForLocation(e.getX(), e.getY());
boolean set = true;
for (TreePath p : tree.getSelectionPaths()) {
if (p.equals(selPath)) {
tree.addSelectionPath(selPath);
set = false;
}
}
if (set) {
tree.setSelectionPath(selPath);
}
if (e.isPopupTrigger()) {
popup.removeAll();
if (node.getChildCount() != 0) {
JMenuItem recalculate = new JMenuItem("Recalculate Statistics");
recalculate.addActionListener(this);
recalculate.setActionCommand("recalculate");
popup.add(recalculate);
}
if (node.getChildCount() != 0 && node.getParent() != null) {
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.setActionCommand("rename");
popup.add(rename);
}
if (node.getParent() != null) {
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.setActionCommand("delete");
popup.add(delete);
}
else {
JMenuItem delete = new JMenuItem("Delete All Runs");
delete.addActionListener(this);
delete.setActionCommand("delete runs");
popup.add(delete);
JMenuItem deleteAll = new JMenuItem("Delete Recursive");
deleteAll.addActionListener(this);
deleteAll.setActionCommand("delete all");
popup.add(deleteAll);
}
if (popup.getComponentCount() != 0) {
popup.show(e.getComponent(), e.getX(), e.getY());
}
}
}
}
/**
* This method currently does nothing.
*/
public void mouseEntered(MouseEvent e) {
}
/**
* This method currently does nothing.
*/
public void mouseExited(MouseEvent e) {
}
private void setUpShapesAndColors() {
DefaultDrawingSupplier draw = new DefaultDrawingSupplier();
colors = new HashMap<String, Paint>();
shapes = new HashMap<String, Shape>();
colors.put("Red", draw.getNextPaint());
colors.put("Blue", draw.getNextPaint());
colors.put("Green", draw.getNextPaint());
colors.put("Yellow", draw.getNextPaint());
colors.put("Magenta", draw.getNextPaint());
colors.put("Cyan", draw.getNextPaint());
colors.put("Tan", draw.getNextPaint());
colors.put("Gray (Dark)", draw.getNextPaint());
colors.put("Red (Dark)", draw.getNextPaint());
colors.put("Blue (Dark)", draw.getNextPaint());
colors.put("Green (Dark)", draw.getNextPaint());
colors.put("Yellow (Dark)", draw.getNextPaint());
colors.put("Magenta (Dark)", draw.getNextPaint());
colors.put("Cyan (Dark)", draw.getNextPaint());
colors.put("Black", draw.getNextPaint());
draw.getNextPaint();
draw.getNextPaint();
draw.getNextPaint();
draw.getNextPaint();
draw.getNextPaint();
draw.getNextPaint();
// colors.put("Red ", draw.getNextPaint());
// colors.put("Blue ", draw.getNextPaint());
// colors.put("Green ", draw.getNextPaint());
// colors.put("Yellow ", draw.getNextPaint());
// colors.put("Magenta ", draw.getNextPaint());
// colors.put("Cyan ", draw.getNextPaint());
colors.put("Gray", draw.getNextPaint());
colors.put("Red (Extra Dark)", draw.getNextPaint());
colors.put("Blue (Extra Dark)", draw.getNextPaint());
colors.put("Green (Extra Dark)", draw.getNextPaint());
colors.put("Yellow (Extra Dark)", draw.getNextPaint());
colors.put("Magenta (Extra Dark)", draw.getNextPaint());
colors.put("Cyan (Extra Dark)", draw.getNextPaint());
colors.put("Red (Light)", draw.getNextPaint());
colors.put("Blue (Light)", draw.getNextPaint());
colors.put("Green (Light)", draw.getNextPaint());
colors.put("Yellow (Light)", draw.getNextPaint());
colors.put("Magenta (Light)", draw.getNextPaint());
colors.put("Cyan (Light)", draw.getNextPaint());
colors.put("Gray (Light)", new java.awt.Color(238, 238, 238));
shapes.put("Square", draw.getNextShape());
shapes.put("Circle", draw.getNextShape());
shapes.put("Triangle", draw.getNextShape());
shapes.put("Diamond", draw.getNextShape());
shapes.put("Rectangle (Horizontal)", draw.getNextShape());
shapes.put("Triangle (Upside Down)", draw.getNextShape());
shapes.put("Circle (Half)", draw.getNextShape());
shapes.put("Arrow", draw.getNextShape());
shapes.put("Rectangle (Vertical)", draw.getNextShape());
shapes.put("Arrow (Backwards)", draw.getNextShape());
}
public void editGraph() {
final ArrayList<GraphSpecies> old = new ArrayList<GraphSpecies>();
for (GraphSpecies g : graphed) {
old.add(g);
}
titlePanel = new JPanel(new BorderLayout());
JLabel titleLabel = new JLabel("Title:");
JLabel xLabel = new JLabel("X-Axis Label:");
JLabel yLabel = new JLabel("Y-Axis Label:");
final JTextField title = new JTextField(chart.getTitle().getText(), 5);
final JTextField x = new JTextField(chart.getXYPlot().getDomainAxis().getLabel(), 5);
final JTextField y = new JTextField(chart.getXYPlot().getRangeAxis().getLabel(), 5);
final JLabel xMin = new JLabel("X-Min:");
final JLabel xMax = new JLabel("X-Max:");
final JLabel xScale = new JLabel("X-Step:");
final JLabel yMin = new JLabel("Y-Min:");
final JLabel yMax = new JLabel("Y-Max:");
final JLabel yScale = new JLabel("Y-Step:");
LogX.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (((JCheckBox) e.getSource()).isSelected()) {
XYPlot plot = (XYPlot) chart.getXYPlot();
try {
LogarithmicAxis domainAxis = new LogarithmicAxis(chart.getXYPlot().getDomainAxis().getLabel());
domainAxis.setStrictValuesFlag(false);
plot.setRangeAxis(domainAxis);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(Gui.frame, "Log plots are not allowed with data\nvalues less than or equal to zero.", "Error",
JOptionPane.ERROR_MESSAGE);
NumberAxis domainAxis = new NumberAxis(chart.getXYPlot().getDomainAxis().getLabel());
plot.setRangeAxis(domainAxis);
LogX.setSelected(false);
}
}
}
});
LogY.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (((JCheckBox) e.getSource()).isSelected()) {
XYPlot plot = (XYPlot) chart.getXYPlot();
try {
LogarithmicAxis rangeAxis = new LogarithmicAxis(chart.getXYPlot().getRangeAxis().getLabel());
rangeAxis.setStrictValuesFlag(false);
plot.setRangeAxis(rangeAxis);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(Gui.frame, "Semilog plots are not allowed with data\nvalues less than or equal to zero.",
"Error", JOptionPane.ERROR_MESSAGE);
NumberAxis rangeAxis = new NumberAxis(chart.getXYPlot().getRangeAxis().getLabel());
plot.setRangeAxis(rangeAxis);
LogY.setSelected(false);
}
}
}
});
visibleLegend.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (((JCheckBox) e.getSource()).isSelected()) {
if (chart.getLegend() == null) {
chart.addLegend(legend);
}
}
else {
if (chart.getLegend() != null) {
legend = chart.getLegend();
}
chart.removeLegend();
}
}
});
resize.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (((JCheckBox) e.getSource()).isSelected()) {
xMin.setEnabled(false);
XMin.setEnabled(false);
xMax.setEnabled(false);
XMax.setEnabled(false);
xScale.setEnabled(false);
XScale.setEnabled(false);
yMin.setEnabled(false);
YMin.setEnabled(false);
yMax.setEnabled(false);
YMax.setEnabled(false);
yScale.setEnabled(false);
YScale.setEnabled(false);
}
else {
xMin.setEnabled(true);
XMin.setEnabled(true);
xMax.setEnabled(true);
XMax.setEnabled(true);
xScale.setEnabled(true);
XScale.setEnabled(true);
yMin.setEnabled(true);
YMin.setEnabled(true);
yMax.setEnabled(true);
YMax.setEnabled(true);
yScale.setEnabled(true);
YScale.setEnabled(true);
}
}
});
if (resize.isSelected()) {
xMin.setEnabled(false);
XMin.setEnabled(false);
xMax.setEnabled(false);
XMax.setEnabled(false);
xScale.setEnabled(false);
XScale.setEnabled(false);
yMin.setEnabled(false);
YMin.setEnabled(false);
yMax.setEnabled(false);
YMax.setEnabled(false);
yScale.setEnabled(false);
YScale.setEnabled(false);
}
else {
xMin.setEnabled(true);
XMin.setEnabled(true);
xMax.setEnabled(true);
XMax.setEnabled(true);
xScale.setEnabled(true);
XScale.setEnabled(true);
yMin.setEnabled(true);
YMin.setEnabled(true);
yMax.setEnabled(true);
YMax.setEnabled(true);
yScale.setEnabled(true);
YScale.setEnabled(true);
}
Properties p = null;
if (learnSpecs != null) {
try {
String[] split = outDir.split(separator);
p = new Properties();
FileInputStream load = new FileInputStream(new File(outDir + separator + split[split.length - 1] + ".lrn"));
p.load(load);
load.close();
}
catch (Exception e) {
}
}
String simDirString = outDir.split(separator)[outDir.split(separator).length - 1];
simDir = new IconNode(simDirString, simDirString);
simDir.setIconName("");
String[] files = new File(outDir).list();
// for (int i = 1; i < files.length; i++) {
// String index = files[i];
// int j = i;
// while ((j > 0) && files[j - 1].compareToIgnoreCase(index) > 0) {
// files[j] = files[j - 1];
// j = j - 1;
// }
// files[j] = index;
// }
boolean addMean = false;
boolean addVar = false;
boolean addDev = false;
boolean addTerm = false;
boolean addPercent = false;
boolean addConst = false;
boolean addBif = false;
directories = new ArrayList<String>();
for (String file : files) {
if ((file.length() > 3 && (file.substring(file.length() - 4).equals("." + printer_id.substring(0, printer_id.length() - 8))))
|| (file.length() > 4 && file.substring(file.length() - 5).equals(".dtsd"))) {
if (file.contains("run-") || file.contains("mean")) {
addMean = true;
}
else if (file.contains("run-") || file.contains("variance")) {
addVar = true;
}
else if (file.contains("run-") || file.contains("standard_deviation")) {
addDev = true;
}
else if (file.startsWith("term-time")) {
addTerm = true;
}
else if (file.contains("percent-term-time")) {
addPercent = true;
}
else if (file.contains("sim-rep")) {
addConst = true;
}
else if (file.contains("bifurcation")) {
addBif = true;
}
else {
IconNode n = new IconNode(file.substring(0, file.length() - 4), file.substring(0, file.length() - 4));
boolean added = false;
for (int j = 0; j < simDir.getChildCount(); j++) {
if (simDir.getChildAt(j).toString().compareToIgnoreCase(n.toString()) > 0) {
simDir.insert(n, j);
added = true;
break;
}
}
if (!added) {
simDir.add(n);
}
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(file.substring(0, file.length() - 4)) && g.getDirectory().equals("")) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
}
else if (new File(outDir + separator + file).isDirectory()) {
boolean addIt = false;
String[] files3 = new File(outDir + separator + file).list();
// for (int i = 1; i < files3.length; i++) {
// String index = files3[i];
// int j = i;
// while ((j > 0) && files3[j - 1].compareToIgnoreCase(index) >
// 0) {
// files3[j] = files3[j - 1];
// j = j - 1;
// }
// files3[j] = index;
// }
for (String getFile : files3) {
if ((getFile.length() > 3
&& (getFile.substring(getFile.length() - 4).equals("." + printer_id.substring(0, printer_id.length() - 8))))
|| (getFile.length() > 4 && getFile.substring(getFile.length() - 5).equals(".dtsd"))) {
addIt = true;
}
else if (new File(outDir + separator + file + separator + getFile).isDirectory()) {
for (String getFile2 : new File(outDir + separator + file + separator + getFile).list()) {
if ((getFile2.length() > 3
&& (getFile2.substring(getFile2.length() - 4).equals("." + printer_id.substring(0, printer_id.length() - 8))))
|| (getFile2.length() > 4 && getFile2.substring(getFile2.length() - 5).equals(".dtsd"))) {
addIt = true;
}
}
}
}
if (addIt) {
directories.add(file);
IconNode d = new IconNode(file, file);
d.setIconName("");
boolean addMean2 = false;
boolean addVar2 = false;
boolean addDev2 = false;
boolean addTerm2 = false;
boolean addPercent2 = false;
boolean addConst2 = false;
boolean addBif2 = false;
for (String f : files3) {
if (f.contains(printer_id.substring(0, printer_id.length() - 8)) ||
f.contains(".dtsd")) {
if (f.contains("run-") || f.contains("mean")) {
addMean2 = true;
}
else if (f.contains("run-") || f.contains("variance")) {
addVar2 = true;
}
else if (f.contains("run-") || f.contains("standard_deviation")) {
addDev2 = true;
}
else if (f.startsWith("term-time")) {
addTerm2 = true;
}
else if (f.contains("percent-term-time")) {
addPercent2 = true;
}
else if (f.contains("sim-rep")) {
addConst2 = true;
}
else if (f.contains("bifurcation")) {
addBif2 = true;
}
else {
IconNode n = new IconNode(f.substring(0, f.length() - 4), f.substring(0, f.length() - 4));
boolean added = false;
for (int j = 0; j < d.getChildCount(); j++) {
if (d.getChildAt(j).toString().compareToIgnoreCase(n.toString()) > 0) {
d.insert(n, j);
added = true;
break;
}
}
if (!added) {
d.add(n);
}
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(f.substring(0, f.length() - 4)) && g.getDirectory().equals(d.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
}
else if (new File(outDir + separator + file + separator + f).isDirectory()) {
boolean addIt2 = false;
String[] files2 = new File(outDir + separator + file + separator + f).list();
// for (int i = 1; i < files2.length; i++) {
// String index = files2[i];
// int j = i;
// while ((j > 0) && files2[j -
// 1].compareToIgnoreCase(index) > 0) {
// files2[j] = files2[j - 1];
// j = j - 1;
// }
// files2[j] = index;
// }
for (String getFile2 : files2) {
if (getFile2.length() > 3
&& (getFile2.substring(getFile2.length() - 4).equals("." + printer_id.substring(0, printer_id.length() - 8))
|| getFile2.substring(getFile2.length() - 5).equals(".dtsd"))) {
addIt2 = true;
}
}
if (addIt2) {
directories.add(file + separator + f);
IconNode d2 = new IconNode(f, f);
d2.setIconName("");
boolean addMean3 = false;
boolean addVar3 = false;
boolean addDev3 = false;
boolean addTerm3 = false;
boolean addPercent3 = false;
boolean addConst3 = false;
boolean addBif3 = false;
for (String f2 : files2) {
if (f2.contains(printer_id.substring(0, printer_id.length() - 8))
|| f2.contains(".dtsd")) {
if (f2.contains("run-") || f2.contains("mean")) {
addMean3 = true;
}
else if (f2.contains("run-") || f2.contains("variance")) {
addVar3 = true;
}
else if (f2.contains("run-") || f2.contains("standard_deviation")) {
addDev3 = true;
}
else if (f2.startsWith("term-time")) {
addTerm3 = true;
}
else if (f2.contains("percent-term-time")) {
addPercent3 = true;
}
else if (f2.contains("sim-rep")) {
addConst3 = true;
}
else if (f2.contains("bifurcation")) {
addBif3 = true;
}
else {
IconNode n = new IconNode(f2.substring(0, f2.length() - 4), f2.substring(0, f2.length() - 4));
boolean added = false;
for (int j = 0; j < d2.getChildCount(); j++) {
if (d2.getChildAt(j).toString().compareToIgnoreCase(n.toString()) > 0) {
d2.insert(n, j);
added = true;
break;
}
}
if (!added) {
d2.add(n);
}
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(f2.substring(0, f2.length() - 4))
&& g.getDirectory().equals(d.getName() + separator + d2.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d2.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d2.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
}
}
if (addMean3) {
IconNode n = new IconNode("Average", "Average");
d2.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Average") && g.getDirectory().equals(d.getName() + separator + d2.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d2.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d2.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addDev3) {
IconNode n = new IconNode("Standard Deviation", "Standard Deviation");
d2.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Standard Deviation")
&& g.getDirectory().equals(d.getName() + separator + d2.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d2.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d2.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addVar3) {
IconNode n = new IconNode("Variance", "Variance");
d2.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Variance") && g.getDirectory().equals(d.getName() + separator + d2.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d2.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d2.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addTerm3) {
IconNode n = new IconNode("Termination Time", "Termination Time");
d2.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Termination Time")
&& g.getDirectory().equals(d.getName() + separator + d2.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d2.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d2.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addPercent3) {
IconNode n = new IconNode("Percent Termination", "Percent Termination");
d2.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Percent Termination")
&& g.getDirectory().equals(d.getName() + separator + d2.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d2.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d2.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addConst3) {
IconNode n = new IconNode("Constraint Termination", "Constraint Termination");
d2.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Constraint Termination")
&& g.getDirectory().equals(d.getName() + separator + d2.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d2.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d2.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addBif3) {
IconNode n = new IconNode("Bifurcation Statistics", "Bifurcation Statistics");
d2.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Bifurcation Statistics")
&& g.getDirectory().equals(d.getName() + separator + d2.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d2.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d2.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
int run = 1;
String r2 = null;
for (String s : files2) {
if (s.contains("run-")) {
r2 = s;
}
}
if (r2 != null) {
for (String s : files2) {
if (s.length() > 4) {
String end = "";
for (int j = 1; j < 5; j++) {
end = s.charAt(s.length() - j) + end;
}
if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv") || end.equals(".dtsd")) {
if (s.contains("run-")) {
run = Math.max(run, Integer.parseInt(s.substring(4, s.length() - end.length())));
}
}
}
}
for (int i = 0; i < run; i++) {
if (new File(outDir + separator + file + separator + f + separator + "run-" + (i + 1) + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists() ||
new File(outDir + separator + file + separator + f
+ separator + "run-" + (i + 1) + ".dtsd").exists()) {
IconNode n;
if (learnSpecs != null) {
n = new IconNode(p.get("run-" + (i + 1) + "." + printer_id.substring(0, printer_id.length() - 8)),
"run-" + (i + 1));
if (d2.getChildCount() > 3) {
boolean added = false;
for (int j = 3; j < d2.getChildCount(); j++) {
if (d2.getChildAt(j)
.toString()
.compareToIgnoreCase(
(String) p.get("run-" + (i + 1) + "."
+ printer_id.substring(0, printer_id.length() - 8))) > 0) {
d2.insert(n, j);
added = true;
break;
}
}
if (!added) {
d2.add(n);
}
}
else {
d2.add(n);
}
}
else {
n = new IconNode("run-" + (i + 1), "run-" + (i + 1));
d2.add(n);
}
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("run-" + (i + 1))
&& g.getDirectory().equals(d.getName() + separator + d2.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d2.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d2.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
}
}
boolean added = false;
for (int j = 0; j < d.getChildCount(); j++) {
if ((d.getChildAt(j).toString().compareToIgnoreCase(d2.toString()) > 0)
|| new File(outDir + separator + d.toString() + separator
+ (d.getChildAt(j).toString() + "." + printer_id.substring(0, printer_id.length() - 8))).isFile()) {
d.insert(d2, j);
added = true;
break;
}
}
if (!added) {
d.add(d2);
}
}
}
}
if (addMean2) {
IconNode n = new IconNode("Average", "Average");
d.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Average") && g.getDirectory().equals(d.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addDev2) {
IconNode n = new IconNode("Standard Deviation", "Standard Deviation");
d.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Standard Deviation") && g.getDirectory().equals(d.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addVar2) {
IconNode n = new IconNode("Variance", "Variance");
d.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Variance") && g.getDirectory().equals(d.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addTerm2) {
IconNode n = new IconNode("Termination Time", "Termination Time");
d.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Termination Time") && g.getDirectory().equals(d.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addPercent2) {
IconNode n = new IconNode("Percent Termination", "Percent Termination");
d.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Percent Termination") && g.getDirectory().equals(d.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addConst2) {
IconNode n = new IconNode("Constraint Termination", "Constraint Termination");
d.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Constraint Termination") && g.getDirectory().equals(d.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addBif2) {
IconNode n = new IconNode("Bifurcation Statistics", "Bifurcation Statistics");
d.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Bifurcation Statistics") && g.getDirectory().equals(d.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
int run = 1;
String r = null;
for (String s : files3) {
if (s.contains("run-")) {
r = s;
}
}
if (r != null) {
for (String s : files3) {
if (s.length() > 4) {
String end = "";
for (int j = 1; j < 5; j++) {
end = s.charAt(s.length() - j) + end;
}
if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv") || end.equals(".dtsd")) {
if (s.contains("run-")) {
run = Math.max(run, Integer.parseInt(s.substring(4, s.length() - end.length())));
}
}
}
}
for (int i = 0; i < run; i++) {
if (new File(outDir + separator + file + separator + "run-" + (i + 1) + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
IconNode n;
if (learnSpecs != null) {
n = new IconNode(p.get("run-" + (i + 1) + "." + printer_id.substring(0, printer_id.length() - 8)), "run-"
+ (i + 1));
if (d.getChildCount() > 3) {
boolean added = false;
for (int j = 3; j < d.getChildCount(); j++) {
if (d.getChildAt(j)
.toString()
.compareToIgnoreCase(
(String) p.get("run-" + (i + 1) + "." + printer_id.substring(0, printer_id.length() - 8))) > 0) {
d.insert(n, j);
added = true;
break;
}
}
if (!added) {
d.add(n);
}
}
else {
d.add(n);
}
}
else {
n = new IconNode("run-" + (i + 1), "run-" + (i + 1));
d.add(n);
}
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("run-" + (i + 1)) && g.getDirectory().equals(d.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
}
}
boolean added = false;
for (int j = 0; j < simDir.getChildCount(); j++) {
if ((simDir.getChildAt(j).toString().compareToIgnoreCase(d.toString()) > 0)
|| new File(outDir + separator
+ (simDir.getChildAt(j).toString() + "." + printer_id.substring(0, printer_id.length() - 8))).isFile()) {
simDir.insert(d, j);
added = true;
break;
}
}
if (!added) {
simDir.add(d);
}
}
}
}
if (addMean) {
IconNode n = new IconNode("Average", "Average");
simDir.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Average") && g.getDirectory().equals("")) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addDev) {
IconNode n = new IconNode("Standard Deviation", "Standard Deviation");
simDir.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Standard Deviation") && g.getDirectory().equals("")) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addVar) {
IconNode n = new IconNode("Variance", "Variance");
simDir.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Variance") && g.getDirectory().equals("")) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addTerm) {
IconNode n = new IconNode("Termination Time", "Termination Time");
simDir.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Termination Time") && g.getDirectory().equals("")) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addPercent) {
IconNode n = new IconNode("Percent Termination", "Percent Termination");
simDir.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Percent Termination") && g.getDirectory().equals("")) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addConst) {
IconNode n = new IconNode("Constraint Termination", "Constraint Termination");
simDir.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Constraint Termination") && g.getDirectory().equals("")) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addBif) {
IconNode n = new IconNode("Bifurcation Statistics", "Bifurcation Statistics");
simDir.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Bifurcation Statistics") && g.getDirectory().equals("")) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
int run = 1;
String runs = null;
for (String s : new File(outDir).list()) {
if (s.contains("run-")) {
runs = s;
}
}
if (runs != null) {
for (String s : new File(outDir).list()) {
if (s.length() > 4) {
String end = "";
for (int j = 1; j < 5; j++) {
end = s.charAt(s.length() - j) + end;
}
if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv") || end.equals(".dtsd")) {
if (s.contains("run-")) {
run = Math.max(run, Integer.parseInt(s.substring(4, s.length() - end.length())));
}
}
}
}
for (int i = 0; i < run; i++) {
if (new File(outDir + separator + "run-" + (i + 1) + "." + printer_id.substring(0, printer_id.length() - 8)).exists()
|| new File(outDir + separator + "run-" + (i + 1) + ".dtsd").exists()) {
IconNode n;
if (learnSpecs != null) {
n = new IconNode(p.get("run-" + (i + 1) + "." + printer_id.substring(0, printer_id.length() - 8)), "run-" + (i + 1));
if (simDir.getChildCount() > 3) {
boolean added = false;
for (int j = 3; j < simDir.getChildCount(); j++) {
if (simDir
.getChildAt(j)
.toString()
.compareToIgnoreCase(
(String) p.get("run-" + (i + 1) + "." + printer_id.substring(0, printer_id.length() - 8))) > 0) {
simDir.insert(n, j);
added = true;
break;
}
}
if (!added) {
simDir.add(n);
}
}
else {
simDir.add(n);
}
}
else {
n = new IconNode("run-" + (i + 1), "run-" + (i + 1));
simDir.add(n);
}
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("run-" + (i + 1)) && g.getDirectory().equals("")) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
}
}
if (simDir.getChildCount() == 0) {
JOptionPane.showMessageDialog(Gui.frame, "No data to graph." + "\nPerform some simulations to create some data first.", "No Data",
JOptionPane.PLAIN_MESSAGE);
}
else {
all = new JPanel(new BorderLayout());
specPanel = new JPanel();
scrollpane = new JScrollPane();
refreshTree();
addTreeListener();
scrollpane.getViewport().add(tree);
scrollpane.setPreferredSize(new Dimension(175, 100));
scroll = new JScrollPane();
scroll.setPreferredSize(new Dimension(1050, 500));
JPanel editPanel = new JPanel(new BorderLayout());
editPanel.add(specPanel, "Center");
scroll.setViewportView(editPanel);
scroll.getVerticalScrollBar().setUnitIncrement(10);
// JButton ok = new JButton("Ok");
/*
* ok.addActionListener(new ActionListener() { public void
* actionPerformed(ActionEvent e) { double minY; double maxY; double
* scaleY; double minX; double maxX; double scaleX; change = true;
* try { minY = Double.parseDouble(YMin.getText().trim()); maxY =
* Double.parseDouble(YMax.getText().trim()); scaleY =
* Double.parseDouble(YScale.getText().trim()); minX =
* Double.parseDouble(XMin.getText().trim()); maxX =
* Double.parseDouble(XMax.getText().trim()); scaleX =
* Double.parseDouble(XScale.getText().trim()); NumberFormat num =
* NumberFormat.getInstance(); num.setMaximumFractionDigits(4);
* num.setGroupingUsed(false); minY =
* Double.parseDouble(num.format(minY)); maxY =
* Double.parseDouble(num.format(maxY)); scaleY =
* Double.parseDouble(num.format(scaleY)); minX =
* Double.parseDouble(num.format(minX)); maxX =
* Double.parseDouble(num.format(maxX)); scaleX =
* Double.parseDouble(num.format(scaleX)); } catch (Exception e1) {
* JOptionPane.showMessageDialog(BioSim.frame, "Must enter doubles
* into the inputs " + "to change the graph's dimensions!", "Error",
* JOptionPane.ERROR_MESSAGE); return; } lastSelected = selected;
* selected = ""; ArrayList<XYSeries> graphData = new
* ArrayList<XYSeries>(); XYLineAndShapeRenderer rend =
* (XYLineAndShapeRenderer) chart.getXYPlot().getRenderer(); int
* thisOne = -1; for (int i = 1; i < graphed.size(); i++) {
* GraphSpecies index = graphed.get(i); int j = i; while ((j > 0) &&
* (graphed.get(j -
* 1).getSpecies().compareToIgnoreCase(index.getSpecies()) > 0)) {
* graphed.set(j, graphed.get(j - 1)); j = j - 1; } graphed.set(j,
* index); } ArrayList<GraphSpecies> unableToGraph = new
* ArrayList<GraphSpecies>(); HashMap<String,
* ArrayList<ArrayList<Double>>> allData = new HashMap<String,
* ArrayList<ArrayList<Double>>>(); for (GraphSpecies g : graphed) {
* if (g.getDirectory().equals("")) { thisOne++;
* rend.setSeriesVisible(thisOne, true);
* rend.setSeriesLinesVisible(thisOne, g.getConnected());
* rend.setSeriesShapesFilled(thisOne, g.getFilled());
* rend.setSeriesShapesVisible(thisOne, g.getVisible());
* rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint());
* rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape()); if
* (!g.getRunNumber().equals("Average") &&
* !g.getRunNumber().equals("Variance") &&
* !g.getRunNumber().equals("Standard Deviation")) { if (new
* File(outDir + separator + g.getRunNumber() + "." +
* printer_id.substring(0, printer_id.length() - 8)).exists()) {
* readGraphSpecies(outDir + separator + g.getRunNumber() + "." +
* printer_id.substring(0, printer_id.length() - 8), BioSim.frame);
* ArrayList<ArrayList<Double>> data; if
* (allData.containsKey(g.getRunNumber() + " " + g.getDirectory()))
* { data = allData.get(g.getRunNumber() + " " + g.getDirectory());
* } else { data = readData(outDir + separator + g.getRunNumber() +
* "." + printer_id.substring(0, printer_id.length() - 8),
* BioSim.frame, y.getText().trim(), g.getRunNumber(), null); for
* (int i = 2; i < graphSpecies.size(); i++) { String index =
* graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int
* j = i; while ((j > 1) && graphSpecies.get(j -
* 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j,
* graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j -
* 1; } graphSpecies.set(j, index); data.set(j, index2); }
* allData.put(g.getRunNumber() + " " + g.getDirectory(), data); }
* graphData.add(new XYSeries(g.getSpecies())); if (data.size() !=
* 0) { for (int i = 0; i < (data.get(0)).size(); i++) {
* graphData.get(graphData.size() - 1).add((data.get(0)).get(i),
* (data.get(g.getNumber() + 1)).get(i)); } } } else {
* unableToGraph.add(g); thisOne--; } } else { boolean ableToGraph =
* false; try { for (String s : new File(outDir).list()) { if
* (s.length() > 3 && s.substring(0, 4).equals("run-")) {
* ableToGraph = true; } } } catch (Exception e1) { ableToGraph =
* false; } if (ableToGraph) { int next = 1; while (!new File(outDir
* + separator + "run-" + next + "." + printer_id.substring(0,
* printer_id.length() - 8)).exists()) { next++; }
* readGraphSpecies(outDir + separator + "run-" + next + "." +
* printer_id.substring(0, printer_id.length() - 8), BioSim.frame);
* ArrayList<ArrayList<Double>> data; if
* (allData.containsKey(g.getRunNumber() + " " + g.getDirectory()))
* { data = allData.get(g.getRunNumber() + " " + g.getDirectory());
* } else { data = readData(outDir + separator + "run-1." +
* printer_id.substring(0, printer_id.length() - 8), BioSim.frame,
* y.getText().trim(), g.getRunNumber().toLowerCase(), null); for
* (int i = 2; i < graphSpecies.size(); i++) { String index =
* graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int
* j = i; while ((j > 1) && graphSpecies.get(j -
* 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j,
* graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j -
* 1; } graphSpecies.set(j, index); data.set(j, index2); }
* allData.put(g.getRunNumber() + " " + g.getDirectory(), data); }
* graphData.add(new XYSeries(g.getSpecies())); if (data.size() !=
* 0) { for (int i = 0; i < (data.get(0)).size(); i++) {
* graphData.get(graphData.size() - 1).add((data.get(0)).get(i),
* (data.get(g.getNumber() + 1)).get(i)); } } } else {
* unableToGraph.add(g); thisOne--; } } } else { thisOne++;
* rend.setSeriesVisible(thisOne, true);
* rend.setSeriesLinesVisible(thisOne, g.getConnected());
* rend.setSeriesShapesFilled(thisOne, g.getFilled());
* rend.setSeriesShapesVisible(thisOne, g.getVisible());
* rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint());
* rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape()); if
* (!g.getRunNumber().equals("Average") &&
* !g.getRunNumber().equals("Variance") &&
* !g.getRunNumber().equals("Standard Deviation")) { if (new
* File(outDir + separator + g.getDirectory() + separator +
* g.getRunNumber() + "." + printer_id.substring(0,
* printer_id.length() - 8)).exists()) { readGraphSpecies( outDir +
* separator + g.getDirectory() + separator + g.getRunNumber() + "."
* + printer_id.substring(0, printer_id.length() - 8),
* BioSim.frame); ArrayList<ArrayList<Double>> data; if
* (allData.containsKey(g.getRunNumber() + " " + g.getDirectory()))
* { data = allData.get(g.getRunNumber() + " " + g.getDirectory());
* } else { data = readData(outDir + separator + g.getDirectory() +
* separator + g.getRunNumber() + "." + printer_id.substring(0,
* printer_id.length() - 8), BioSim.frame, y.getText().trim(),
* g.getRunNumber(), g.getDirectory()); for (int i = 2; i <
* graphSpecies.size(); i++) { String index = graphSpecies.get(i);
* ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1)
* && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
* graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j,
* data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index);
* data.set(j, index2); } allData.put(g.getRunNumber() + " " +
* g.getDirectory(), data); } graphData.add(new
* XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i =
* 0; i < (data.get(0)).size(); i++) {
* graphData.get(graphData.size() - 1).add((data.get(0)).get(i),
* (data.get(g.getNumber() + 1)).get(i)); } } } else {
* unableToGraph.add(g); thisOne--; } } else { boolean ableToGraph =
* false; try { for (String s : new File(outDir + separator +
* g.getDirectory()).list()) { if (s.length() > 3 && s.substring(0,
* 4).equals("run-")) { ableToGraph = true; } } } catch (Exception
* e1) { ableToGraph = false; } if (ableToGraph) { int next = 1;
* while (!new File(outDir + separator + g.getDirectory() +
* separator + "run-" + next + "." + printer_id.substring(0,
* printer_id.length() - 8)).exists()) { next++; }
* readGraphSpecies(outDir + separator + g.getDirectory() +
* separator + "run-" + next + "." + printer_id.substring(0,
* printer_id.length() - 8), BioSim.frame);
* ArrayList<ArrayList<Double>> data; if
* (allData.containsKey(g.getRunNumber() + " " + g.getDirectory()))
* { data = allData.get(g.getRunNumber() + " " + g.getDirectory());
* } else { data = readData(outDir + separator + g.getDirectory() +
* separator + "run-1." + printer_id.substring(0,
* printer_id.length() - 8), BioSim.frame, y.getText().trim(),
* g.getRunNumber().toLowerCase(), g.getDirectory()); for (int i =
* 2; i < graphSpecies.size(); i++) { String index =
* graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int
* j = i; while ((j > 1) && graphSpecies.get(j -
* 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j,
* graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j -
* 1; } graphSpecies.set(j, index); data.set(j, index2); }
* allData.put(g.getRunNumber() + " " + g.getDirectory(), data); }
* graphData.add(new XYSeries(g.getSpecies())); if (data.size() !=
* 0) { for (int i = 0; i < (data.get(0)).size(); i++) {
* graphData.get(graphData.size() - 1).add((data.get(0)).get(i),
* (data.get(g.getNumber() + 1)).get(i)); } } } else {
* unableToGraph.add(g); thisOne--; } } } } for (GraphSpecies g :
* unableToGraph) { graphed.remove(g); } XYSeriesCollection dataset
* = new XYSeriesCollection(); for (int i = 0; i < graphData.size();
* i++) { dataset.addSeries(graphData.get(i)); }
* fixGraph(title.getText().trim(), x.getText().trim(),
* y.getText().trim(), dataset);
* chart.getXYPlot().setRenderer(rend); XYPlot plot =
* chart.getXYPlot(); if (resize.isSelected()) { resize(dataset); }
* else { NumberAxis axis = (NumberAxis) plot.getRangeAxis();
* axis.setAutoTickUnitSelection(false); axis.setRange(minY, maxY);
* axis.setTickUnit(new NumberTickUnit(scaleY)); axis = (NumberAxis)
* plot.getDomainAxis(); axis.setAutoTickUnitSelection(false);
* axis.setRange(minX, maxX); axis.setTickUnit(new
* NumberTickUnit(scaleX)); } //f.dispose(); } });
*/
// final JButton cancel = new JButton("Cancel");
// cancel.addActionListener(new ActionListener() {
// public void actionPerformed(ActionEvent e) {
// selected = "";
// int size = graphed.size();
// for (int i = 0; i < size; i++) {
// graphed.remove();
// }
// for (GraphSpecies g : old) {
// graphed.add(g);
// }
// f.dispose();
// }
// });
final JButton deselect = new JButton("Deselect All");
deselect.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// selected = "";
int size = graphed.size();
for (int i = 0; i < size; i++) {
graphed.remove();
}
IconNode n = simDir;
while (n != null) {
if (n.isLeaf()) {
n.setIcon(MetalIconFactory.getTreeLeafIcon());
n.setIconName("");
IconNode check = (IconNode) ((DefaultMutableTreeNode) n.getParent()).getChildAfter(n);
if (check == null) {
n = (IconNode) n.getParent();
if (n.getParent() == null) {
n = null;
}
else {
IconNode check2 = (IconNode) ((DefaultMutableTreeNode) n.getParent()).getChildAfter(n);
if (check2 == null) {
n = (IconNode) n.getParent();
if (n.getParent() == null) {
n = null;
}
else {
n = (IconNode) ((DefaultMutableTreeNode) n.getParent()).getChildAfter(n);
}
}
else {
n = check2;
}
}
}
else {
n = check;
}
}
else {
n.setIcon(MetalIconFactory.getTreeFolderIcon());
n.setIconName("");
n = (IconNode) n.getChildAt(0);
}
}
tree.revalidate();
tree.repaint();
if (tree.getSelectionCount() > 0) {
int selectedRow = tree.getSelectionRows()[0];
tree.setSelectionRow(0);
tree.setSelectionRow(selectedRow);
}
}
});
JPanel titlePanel1 = new JPanel(new GridLayout(3, 6));
JPanel titlePanel2 = new JPanel(new GridLayout(1, 6));
titlePanel1.add(titleLabel);
titlePanel1.add(title);
titlePanel1.add(xMin);
titlePanel1.add(XMin);
titlePanel1.add(yMin);
titlePanel1.add(YMin);
titlePanel1.add(xLabel);
titlePanel1.add(x);
titlePanel1.add(xMax);
titlePanel1.add(XMax);
titlePanel1.add(yMax);
titlePanel1.add(YMax);
titlePanel1.add(yLabel);
titlePanel1.add(y);
titlePanel1.add(xScale);
titlePanel1.add(XScale);
titlePanel1.add(yScale);
titlePanel1.add(YScale);
JPanel deselectPanel = new JPanel();
deselectPanel.add(deselect);
titlePanel2.add(deselectPanel);
titlePanel2.add(resize);
titlePanel2.add(XVariable);
titlePanel2.add(LogX);
titlePanel2.add(LogY);
titlePanel2.add(visibleLegend);
titlePanel.add(titlePanel1, "Center");
titlePanel.add(titlePanel2, "South");
// JPanel buttonPanel = new JPanel();
// buttonPanel.add(ok);
// buttonPanel.add(deselect);
// buttonPanel.add(cancel);
all.add(titlePanel, "North");
all.add(scroll, "Center");
all.add(scrollpane, "West");
// all.add(buttonPanel, "South");
Object[] options = { "Ok", "Cancel" };
int value = JOptionPane.showOptionDialog(Gui.frame, all, "Edit Graph", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null,
options, options[0]);
if (value == JOptionPane.YES_OPTION) {
double minY;
double maxY;
double scaleY;
double minX;
double maxX;
double scaleX;
change = true;
try {
minY = Double.parseDouble(YMin.getText().trim());
maxY = Double.parseDouble(YMax.getText().trim());
scaleY = Double.parseDouble(YScale.getText().trim());
minX = Double.parseDouble(XMin.getText().trim());
maxX = Double.parseDouble(XMax.getText().trim());
scaleX = Double.parseDouble(XScale.getText().trim());
/*
* NumberFormat num = NumberFormat.getInstance();
* num.setMaximumFractionDigits(4);
* num.setGroupingUsed(false); minY =
* Double.parseDouble(num.format(minY)); maxY =
* Double.parseDouble(num.format(maxY)); scaleY =
* Double.parseDouble(num.format(scaleY)); minX =
* Double.parseDouble(num.format(minX)); maxX =
* Double.parseDouble(num.format(maxX)); scaleX =
* Double.parseDouble(num.format(scaleX));
*/
}
catch (Exception e1) {
JOptionPane.showMessageDialog(Gui.frame, "Must enter doubles into the inputs " + "to change the graph's dimensions!", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
lastSelected = selected;
selected = "";
ArrayList<XYSeries> graphData = new ArrayList<XYSeries>();
XYLineAndShapeRenderer rend = (XYLineAndShapeRenderer) chart.getXYPlot().getRenderer();
int thisOne = -1;
for (int i = 1; i < graphed.size(); i++) {
GraphSpecies index = graphed.get(i);
int j = i;
while ((j > 0) &&
(graphed.get(j - 1).getSpecies().compareToIgnoreCase(index.getSpecies()) > 0)) {
graphed.set(j, graphed.get(j - 1));
j = j - 1;
}
graphed.set(j, index);
}
ArrayList<GraphSpecies> unableToGraph = new ArrayList<GraphSpecies>();
HashMap<String, ArrayList<ArrayList<Double>>> allData = new HashMap<String, ArrayList<ArrayList<Double>>>();
for (GraphSpecies g : graphed) {
if (g.getDirectory().equals("")) {
thisOne++;
rend.setSeriesVisible(thisOne, true);
rend.setSeriesLinesVisible(thisOne, g.getConnected());
rend.setSeriesShapesFilled(thisOne, g.getFilled());
rend.setSeriesShapesVisible(thisOne, g.getVisible());
rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint());
rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape());
if (!g.getRunNumber().equals("Average") && !g.getRunNumber().equals("Variance")
&& !g.getRunNumber().equals("Standard Deviation") && !g.getRunNumber().equals("Termination Time")
&& !g.getRunNumber().equals("Percent Termination") && !g.getRunNumber().equals("Constraint Termination")
&& !g.getRunNumber().equals("Bifurcation Statistics")) {
if (new File(outDir + separator + g.getRunNumber() + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists() ||
new File(outDir + separator + g.getRunNumber() + ".dtsd").exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
String extension = printer_id.substring(0, printer_id.length() - 8);
if (new File(outDir + separator + g.getRunNumber() + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists() == false
&& new File(outDir + separator + g.getRunNumber() + ".dtsd").exists()) {
extension = "dtsd";
}
data = readData(outDir + separator + g.getRunNumber() + "." + extension,
g.getRunNumber(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
}
else {
unableToGraph.add(g);
thisOne--;
}
}
else {
if (g.getRunNumber().equals("Average")
&& new File(outDir + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(outDir + separator + "mean." + printer_id.substring(0, printer_id.length() - 8), g.getRunNumber()
.toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
}
else if (g.getRunNumber().equals("Variance")
&& new File(outDir + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(outDir + separator + "variance." + printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
}
else if (g.getRunNumber().equals("Standard Deviation")
&& new File(outDir + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(outDir + separator + "standard_deviation." + printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
}
else if (g.getRunNumber().equals("Termination Time")
&& new File(outDir + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(outDir + separator + "term-time." + printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
}
else if (g.getRunNumber().equals("Percent Termination")
&& new File(outDir + separator + "percent-term-time" + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(outDir + separator + "percent-term-time." + printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
}
else if (g.getRunNumber().equals("Constraint Termination")
&& new File(outDir + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(outDir + separator + "sim-rep." + printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
}
else if (g.getRunNumber().equals("Bifurcation Statistics")
&& new File(outDir + separator + "bifurcation" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(outDir + separator + "bifurcation." + printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
}
else {
boolean ableToGraph = false;
try {
for (String s : new File(outDir).list()) {
if (s.length() > 3 && s.substring(0, 4).equals("run-")) {
ableToGraph = true;
}
}
}
catch (Exception e1) {
ableToGraph = false;
}
if (ableToGraph) {
int next = 1;
while (!new File(outDir + separator + "run-" + next + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
next++;
}
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(outDir + separator + "run-1." + printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
}
else {
unableToGraph.add(g);
thisOne--;
}
}
}
}
else {
thisOne++;
rend.setSeriesVisible(thisOne, true);
rend.setSeriesLinesVisible(thisOne, g.getConnected());
rend.setSeriesShapesFilled(thisOne, g.getFilled());
rend.setSeriesShapesVisible(thisOne, g.getVisible());
rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint());
rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape());
if (!g.getRunNumber().equals("Average") && !g.getRunNumber().equals("Variance")
&& !g.getRunNumber().equals("Standard Deviation") && !g.getRunNumber().equals("Termination Time")
&& !g.getRunNumber().equals("Percent Termination") && !g.getRunNumber().equals("Constraint Termination")
&& !g.getRunNumber().equals("Bifurcation Statistics")) {
if (new File(outDir + separator + g.getDirectory() + separator + g.getRunNumber() + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()
|| new File(outDir + separator + g.getDirectory() + separator + g.getRunNumber() + ".dtsd").exists()) {
ArrayList<ArrayList<Double>> data;
//if the data has already been put into the data structure
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
String extension = printer_id.substring(0, printer_id.length() - 8);
if (new File(outDir + separator + g.getDirectory() + separator + g.getRunNumber() + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists() == false
&& new File(outDir + separator + g.getDirectory() + separator
+ g.getRunNumber() + ".dtsd").exists()) {
extension = "dtsd";
}
data = readData(
outDir + separator + g.getDirectory() + separator + g.getRunNumber() + "."
+ extension, g.getRunNumber(), g.getDirectory(), false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
}
else {
unableToGraph.add(g);
thisOne--;
}
}
//if it's one of the stats/termination files
else {
if (g.getRunNumber().equals("Average")
&& new File(outDir + separator + g.getDirectory() + separator + "mean" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(
outDir + separator + g.getDirectory() + separator + "mean."
+ printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
} //end average
else if (g.getRunNumber().equals("Variance")
&& new File(outDir + separator + g.getDirectory() + separator + "variance" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(
outDir + separator + g.getDirectory() + separator + "variance."
+ printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
} //end variance
else if (g.getRunNumber().equals("Standard Deviation")
&& new File(outDir + separator + g.getDirectory() + separator + "standard_deviation" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(
outDir + separator + g.getDirectory() + separator + "standard_deviation."
+ printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
} //end standard deviation
else if (g.getRunNumber().equals("Termination Time")
&& new File(outDir + separator + g.getDirectory() + separator + "term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(
outDir + separator + g.getDirectory() + separator + "term-time."
+ printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
} //end termination time
else if (g.getRunNumber().equals("Percent Termination")
&& new File(outDir + separator + g.getDirectory() + separator + "percent-term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(
outDir + separator + g.getDirectory() + separator + "percent-term-time."
+ printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
} //end percent termination
else if (g.getRunNumber().equals("Constraint Termination")
&& new File(outDir + separator + g.getDirectory() + separator + "sim-rep" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(
outDir + separator + g.getDirectory() + separator + "sim-rep."
+ printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
} //end constraint termination
else if (g.getRunNumber().equals("Bifurcation Statistics")
&& new File(outDir + separator + g.getDirectory() + separator + "bifurcation" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(
outDir + separator + g.getDirectory() + separator + "bifurcation."
+ printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
}
else {
boolean ableToGraph = false;
try {
for (String s : new File(outDir + separator + g.getDirectory()).list()) {
if (s.length() > 3 && s.substring(0, 4).equals("run-")) {
ableToGraph = true;
}
}
}
catch (Exception e1) {
ableToGraph = false;
}
if (ableToGraph) {
int next = 1;
while (!new File(outDir + separator + g.getDirectory() + separator + "run-" + next + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
next++;
}
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(
outDir + separator + g.getDirectory() + separator + "run-1."
+ printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(),
g.getDirectory(), false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
}
else {
unableToGraph.add(g);
thisOne--;
}
}
}
}
}
for (GraphSpecies g : unableToGraph) {
graphed.remove(g);
}
XYSeriesCollection dataset = new XYSeriesCollection();
for (int i = 0; i < graphData.size(); i++) {
dataset.addSeries(graphData.get(i));
}
fixGraph(title.getText().trim(), x.getText().trim(), y.getText().trim(), dataset);
chart.getXYPlot().setRenderer(rend);
XYPlot plot = chart.getXYPlot();
if (resize.isSelected()) {
resize(dataset);
}
else {
NumberAxis axis = (NumberAxis) plot.getRangeAxis();
axis.setAutoTickUnitSelection(false);
axis.setRange(minY, maxY);
axis.setTickUnit(new NumberTickUnit(scaleY));
axis = (NumberAxis) plot.getDomainAxis();
axis.setAutoTickUnitSelection(false);
axis.setRange(minX, maxX);
axis.setTickUnit(new NumberTickUnit(scaleX));
}
} //end of "Ok" option being true
else {
selected = "";
int size = graphed.size();
for (int i = 0; i < size; i++) {
graphed.remove();
}
for (GraphSpecies g : old) {
graphed.add(g);
}
}
// WindowListener w = new WindowListener() {
// public void windowClosing(WindowEvent arg0) {
// cancel.doClick();
// }
// 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) {
// }
// };
// f.addWindowListener(w);
// f.setContentPane(all);
// f.pack();
// Dimension screenSize;
// try {
// Toolkit tk = Toolkit.getDefaultToolkit();
// screenSize = tk.getScreenSize();
// }
// catch (AWTError awe) {
// screenSize = new Dimension(640, 480);
// }
// Dimension frameSize = f.getSize();
// if (frameSize.height > screenSize.height) {
// frameSize.height = screenSize.height;
// }
// if (frameSize.width > screenSize.width) {
// frameSize.width = screenSize.width;
// }
// int xx = screenSize.width / 2 - frameSize.width / 2;
// int yy = screenSize.height / 2 - frameSize.height / 2;
// f.setLocation(xx, yy);
// f.setVisible(true);
}
}
private void refreshTree() {
tree = new JTree(simDir);
if (!topLevel && learnSpecs == null) {
tree.addMouseListener(this);
}
tree.putClientProperty("JTree.icons", makeIcons());
tree.setCellRenderer(new IconNodeRenderer());
DefaultTreeCellRenderer renderer = (DefaultTreeCellRenderer) tree.getCellRenderer();
renderer.setLeafIcon(MetalIconFactory.getTreeLeafIcon());
renderer.setClosedIcon(MetalIconFactory.getTreeFolderIcon());
renderer.setOpenIcon(MetalIconFactory.getTreeFolderIcon());
}
private void addTreeListener() {
boolean stop = false;
int selectionRow = 1;
for (int i = 1; i < tree.getRowCount(); i++) {
tree.setSelectionRow(i);
if (selected.equals(lastSelected)) {
stop = true;
selectionRow = i;
break;
}
}
tree.addTreeSelectionListener(new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
node = (IconNode) e.getPath().getLastPathComponent();
if (!directories.contains(node.getName()) && node.getParent() != null
&& !directories.contains(((IconNode) node.getParent()).getName() + separator + node.getName())) {
selected = node.getName();
int select;
if (selected.equals("Average")) {
select = 0;
}
else if (selected.equals("Variance")) {
select = 1;
}
else if (selected.equals("Standard Deviation")) {
select = 2;
}
else if (selected.contains("-run")) {
select = 0;
}
else if (selected.equals("Termination Time")) {
select = 0;
}
else if (selected.equals("Percent Termination")) {
select = 0;
}
else if (selected.equals("Constraint Termination")) {
select = 0;
}
else if (selected.equals("Bifurcation Statistics")) {
select = 0;
}
else {
try {
if (selected.contains("run-")) {
select = Integer.parseInt(selected.substring(4)) + 2;
}
else {
select = -1;
}
}
catch (Exception e1) {
select = -1;
}
}
if (select != -1) {
specPanel.removeAll();
if (node.getParent().getParent() != null
&& directories.contains(((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName())) {
specPanel.add(fixGraphChoices(((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName()));
}
else if (directories.contains(((IconNode) node.getParent()).getName())) {
specPanel.add(fixGraphChoices(((IconNode) node.getParent()).getName()));
}
else {
specPanel.add(fixGraphChoices(""));
}
specPanel.revalidate();
specPanel.repaint();
for (int i = 0; i < series.size(); i++) {
series.get(i).setText(graphSpecies.get(i + 1));
series.get(i).setSelectionStart(0);
series.get(i).setSelectionEnd(0);
}
for (int i = 0; i < boxes.size(); i++) {
boxes.get(i).setSelected(false);
}
if (node.getParent().getParent() != null
&& directories.contains(((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName())) {
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected)
&& g.getDirectory().equals(
((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName())) {
XVariable.setSelectedIndex(g.getXNumber());
boxes.get(g.getNumber()).setSelected(true);
series.get(g.getNumber()).setText(g.getSpecies());
series.get(g.getNumber()).setSelectionStart(0);
series.get(g.getNumber()).setSelectionEnd(0);
colorsButtons.get(g.getNumber()).setBackground((Color) g.getShapeAndPaint().getPaint());
colorsButtons.get(g.getNumber()).setForeground((Color) g.getShapeAndPaint().getPaint());
colorsCombo.get(g.getNumber()).setSelectedItem(g.getShapeAndPaint().getPaintName().split("_")[0]);
shapesCombo.get(g.getNumber()).setSelectedItem(g.getShapeAndPaint().getShapeName());
connected.get(g.getNumber()).setSelected(g.getConnected());
visible.get(g.getNumber()).setSelected(g.getVisible());
filled.get(g.getNumber()).setSelected(g.getFilled());
}
}
}
else if (directories.contains(((IconNode) node.getParent()).getName())) {
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getDirectory().equals(((IconNode) node.getParent()).getName())) {
XVariable.setSelectedIndex(g.getXNumber());
boxes.get(g.getNumber()).setSelected(true);
series.get(g.getNumber()).setText(g.getSpecies());
series.get(g.getNumber()).setSelectionStart(0);
series.get(g.getNumber()).setSelectionEnd(0);
colorsButtons.get(g.getNumber()).setBackground((Color) g.getShapeAndPaint().getPaint());
colorsButtons.get(g.getNumber()).setForeground((Color) g.getShapeAndPaint().getPaint());
colorsCombo.get(g.getNumber()).setSelectedItem(g.getShapeAndPaint().getPaintName().split("_")[0]);
shapesCombo.get(g.getNumber()).setSelectedItem(g.getShapeAndPaint().getShapeName());
connected.get(g.getNumber()).setSelected(g.getConnected());
visible.get(g.getNumber()).setSelected(g.getVisible());
filled.get(g.getNumber()).setSelected(g.getFilled());
}
}
}
else {
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getDirectory().equals("")) {
XVariable.setSelectedIndex(g.getXNumber());
boxes.get(g.getNumber()).setSelected(true);
series.get(g.getNumber()).setText(g.getSpecies());
series.get(g.getNumber()).setSelectionStart(0);
series.get(g.getNumber()).setSelectionEnd(0);
colorsButtons.get(g.getNumber()).setBackground((Color) g.getShapeAndPaint().getPaint());
colorsButtons.get(g.getNumber()).setForeground((Color) g.getShapeAndPaint().getPaint());
colorsCombo.get(g.getNumber()).setSelectedItem(g.getShapeAndPaint().getPaintName().split("_")[0]);
shapesCombo.get(g.getNumber()).setSelectedItem(g.getShapeAndPaint().getShapeName());
connected.get(g.getNumber()).setSelected(g.getConnected());
visible.get(g.getNumber()).setSelected(g.getVisible());
filled.get(g.getNumber()).setSelected(g.getFilled());
}
}
}
boolean allChecked = true;
boolean allCheckedVisible = true;
boolean allCheckedFilled = true;
boolean allCheckedConnected = true;
for (int i = 0; i < boxes.size(); i++) {
if (!boxes.get(i).isSelected()) {
allChecked = false;
String s = "";
s = ((IconNode) e.getPath().getLastPathComponent()).toString();
if (node.getParent().getParent() != null
&& directories.contains(((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName())) {
if (s.equals("Average")) {
s = "(" + ((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName() + ", " + (char) 967 + ")";
}
else if (s.equals("Variance")) {
s = "(" + ((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName() + ", " + (char) 948 + (char) 178 + ")";
}
else if (s.equals("Standard Deviation")) {
s = "(" + ((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName() + ", " + (char) 948 + ")";
}
else {
if (s.endsWith("-run")) {
s = s.substring(0, s.length() - 4);
}
else if (s.startsWith("run-")) {
s = s.substring(4);
}
s = "(" + ((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName() + ", " + s + ")";
}
}
else if (directories.contains(((IconNode) node.getParent()).getName())) {
if (s.equals("Average")) {
s = "(" + ((IconNode) node.getParent()).getName() + ", " + (char) 967 + ")";
}
else if (s.equals("Variance")) {
s = "(" + ((IconNode) node.getParent()).getName() + ", " + (char) 948 + (char) 178 + ")";
}
else if (s.equals("Standard Deviation")) {
s = "(" + ((IconNode) node.getParent()).getName() + ", " + (char) 948 + ")";
}
else {
if (s.endsWith("-run")) {
s = s.substring(0, s.length() - 4);
}
else if (s.startsWith("run-")) {
s = s.substring(4);
}
s = "(" + ((IconNode) node.getParent()).getName() + ", " + s + ")";
}
}
else {
if (s.equals("Average")) {
s = "(" + (char) 967 + ")";
}
else if (s.equals("Variance")) {
s = "(" + (char) 948 + (char) 178 + ")";
}
else if (s.equals("Standard Deviation")) {
s = "(" + (char) 948 + ")";
}
else {
if (s.endsWith("-run")) {
s = s.substring(0, s.length() - 4);
}
else if (s.startsWith("run-")) {
s = s.substring(4);
}
s = "(" + s + ")";
}
}
String text = graphSpecies.get(i + 1);
String end = "";
if (text.length() >= s.length()) {
for (int j = 0; j < s.length(); j++) {
end = text.charAt(text.length() - 1 - j) + end;
}
if (!s.equals(end)) {
text += " " + s;
}
}
else {
text += " " + s;
}
boxes.get(i).setName(text);
series.get(i).setText(text);
series.get(i).setSelectionStart(0);
series.get(i).setSelectionEnd(0);
colorsCombo.get(i).setSelectedIndex(0);
colorsButtons.get(i).setBackground((Color) colors.get("Black"));
colorsButtons.get(i).setForeground((Color) colors.get("Black"));
shapesCombo.get(i).setSelectedIndex(0);
}
else {
String s = "";
s = ((IconNode) e.getPath().getLastPathComponent()).toString();
if (node.getParent().getParent() != null
&& directories.contains(((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName())) {
if (s.equals("Average")) {
s = "(" + ((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName() + ", " + (char) 967 + ")";
}
else if (s.equals("Variance")) {
s = "(" + ((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName() + ", " + (char) 948 + (char) 178 + ")";
}
else if (s.equals("Standard Deviation")) {
s = "(" + ((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName() + ", " + (char) 948 + ")";
}
else {
if (s.endsWith("-run")) {
s = s.substring(0, s.length() - 4);
}
else if (s.startsWith("run-")) {
s = s.substring(4);
}
s = "(" + ((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName() + ", " + s + ")";
}
}
else if (directories.contains(((IconNode) node.getParent()).getName())) {
if (s.equals("Average")) {
s = "(" + ((IconNode) node.getParent()).getName() + ", " + (char) 967 + ")";
}
else if (s.equals("Variance")) {
s = "(" + ((IconNode) node.getParent()).getName() + ", " + (char) 948 + (char) 178 + ")";
}
else if (s.equals("Standard Deviation")) {
s = "(" + ((IconNode) node.getParent()).getName() + ", " + (char) 948 + ")";
}
else {
if (s.endsWith("-run")) {
s = s.substring(0, s.length() - 4);
}
else if (s.startsWith("run-")) {
s = s.substring(4);
}
s = "(" + ((IconNode) node.getParent()).getName() + ", " + s + ")";
}
}
else {
if (s.equals("Average")) {
s = "(" + (char) 967 + ")";
}
else if (s.equals("Variance")) {
s = "(" + (char) 948 + (char) 178 + ")";
}
else if (s.equals("Standard Deviation")) {
s = "(" + (char) 948 + ")";
}
else {
if (s.endsWith("-run")) {
s = s.substring(0, s.length() - 4);
}
else if (s.startsWith("run-")) {
s = s.substring(4);
}
s = "(" + s + ")";
}
}
String text = series.get(i).getText();
String end = "";
if (text.length() >= s.length()) {
for (int j = 0; j < s.length(); j++) {
end = text.charAt(text.length() - 1 - j) + end;
}
if (!s.equals(end)) {
text += " " + s;
}
}
else {
text += " " + s;
}
boxes.get(i).setName(text);
}
if (!visible.get(i).isSelected()) {
allCheckedVisible = false;
}
if (!connected.get(i).isSelected()) {
allCheckedConnected = false;
}
if (!filled.get(i).isSelected()) {
allCheckedFilled = false;
}
}
if (allChecked) {
use.setSelected(true);
}
else {
use.setSelected(false);
}
if (allCheckedVisible) {
visibleLabel.setSelected(true);
}
else {
visibleLabel.setSelected(false);
}
if (allCheckedFilled) {
filledLabel.setSelected(true);
}
else {
filledLabel.setSelected(false);
}
if (allCheckedConnected) {
connectedLabel.setSelected(true);
}
else {
connectedLabel.setSelected(false);
}
}
}
else {
specPanel.removeAll();
specPanel.revalidate();
specPanel.repaint();
}
}
});
if (!stop) {
tree.setSelectionRow(0);
tree.setSelectionRow(1);
}
else {
tree.setSelectionRow(0);
tree.setSelectionRow(selectionRow);
}
}
private JPanel fixGraphChoices(final String directory) {
if (directory.equals("")) {
if (selected.equals("Average") || selected.equals("Variance") || selected.equals("Standard Deviation")
|| selected.equals("Termination Time") || selected.equals("Percent Termination") || selected.equals("Constraint Termination")
|| selected.equals("Bifurcation Statistics")) {
if (selected.equals("Average")
&& new File(outDir + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8));
}
else if (selected.equals("Variance")
&& new File(outDir + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8));
}
else if (selected.equals("Standard Deviation")
&& new File(outDir + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8));
}
else if (selected.equals("Termination Time")
&& new File(outDir + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8));
}
else if (selected.equals("Percent Termination")
&& new File(outDir + separator + "percent-term-time" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + "percent-term-time" + "." + printer_id.substring(0, printer_id.length() - 8));
}
else if (selected.equals("Constraint Termination")
&& new File(outDir + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8));
}
else if (selected.equals("Bifurcation Statistics")
&& new File(outDir + separator + "bifurcation" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + "bifurcation" + "." + printer_id.substring(0, printer_id.length() - 8));
}
else {
int nextOne = 1;
while (!new File(outDir + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
nextOne++;
}
readGraphSpecies(outDir + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8));
}
}
else {
String extension = printer_id.substring(0, printer_id.length() - 8);
if (new File(outDir + separator + selected + "." + extension).exists() == false)
extension = "dtsd";
readGraphSpecies(outDir + separator + selected + "." + extension);
}
}
else {
if (selected.equals("Average") || selected.equals("Variance") || selected.equals("Standard Deviation")
|| selected.equals("Termination Time") || selected.equals("Percent Termination") || selected.equals("Constraint Termination")
|| selected.equals("Bifurcation Statistics")) {
if (selected.equals("Average")
&& new File(outDir + separator + directory + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
readGraphSpecies(outDir + separator + directory + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8));
}
else if (selected.equals("Variance")
&& new File(outDir + separator + directory + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
readGraphSpecies(outDir + separator + directory + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8));
}
else if (selected.equals("Standard Deviation")
&& new File(outDir + separator + directory + separator + "standard_deviation" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + directory + separator + "standard_deviation" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (selected.equals("Termination Time")
&& new File(outDir + separator + directory + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
readGraphSpecies(outDir + separator + directory + separator + "term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (selected.equals("Percent Termination")
&& new File(outDir + separator + directory + separator + "percent-term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + directory + separator + "percent-term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (selected.equals("Constraint Termination")
&& new File(outDir + separator + directory + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
readGraphSpecies(outDir + separator + directory + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8));
}
else if (selected.equals("Bifurcation Statistics")
&& new File(outDir + separator + directory + separator + "bifurcation" + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
readGraphSpecies(outDir + separator + directory + separator + "bifurcation" + "." + printer_id.substring(0, printer_id.length() - 8));
}
else {
int nextOne = 1;
while (!new File(outDir + separator + directory + separator + "run-" + nextOne + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
nextOne++;
}
readGraphSpecies(outDir + separator + directory + separator + "run-" + nextOne + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
}
else {
readGraphSpecies(outDir + separator + directory + separator + selected + "." + printer_id.substring(0, printer_id.length() - 8));
}
}
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
}
updateXNumber = false;
XVariable.removeAllItems();
for (int i = 0; i < graphSpecies.size(); i++) {
XVariable.addItem(graphSpecies.get(i));
}
updateXNumber = true;
JPanel speciesPanel1 = new JPanel(new GridLayout(graphSpecies.size(), 1));
JPanel speciesPanel2 = new JPanel(new GridLayout(graphSpecies.size(), 3));
JPanel speciesPanel3 = new JPanel(new GridLayout(graphSpecies.size(), 3));
use = new JCheckBox("Use");
JLabel specs;
specs = new JLabel("Variables");
JLabel color = new JLabel("Color");
JLabel shape = new JLabel("Shape");
connectedLabel = new JCheckBox("Connect");
visibleLabel = new JCheckBox("Visible");
filledLabel = new JCheckBox("Fill");
connectedLabel.setSelected(true);
visibleLabel.setSelected(true);
filledLabel.setSelected(true);
boxes = new ArrayList<JCheckBox>();
series = new ArrayList<JTextField>();
colorsCombo = new ArrayList<JComboBox>();
colorsButtons = new ArrayList<JButton>();
shapesCombo = new ArrayList<JComboBox>();
connected = new ArrayList<JCheckBox>();
visible = new ArrayList<JCheckBox>();
filled = new ArrayList<JCheckBox>();
use.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (use.isSelected()) {
for (JCheckBox box : boxes) {
if (!box.isSelected()) {
box.doClick();
}
}
}
else {
for (JCheckBox box : boxes) {
if (box.isSelected()) {
box.doClick();
}
}
}
}
});
connectedLabel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (connectedLabel.isSelected()) {
for (JCheckBox box : connected) {
if (!box.isSelected()) {
box.doClick();
}
}
}
else {
for (JCheckBox box : connected) {
if (box.isSelected()) {
box.doClick();
}
}
}
}
});
visibleLabel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (visibleLabel.isSelected()) {
for (JCheckBox box : visible) {
if (!box.isSelected()) {
box.doClick();
}
}
}
else {
for (JCheckBox box : visible) {
if (box.isSelected()) {
box.doClick();
}
}
}
}
});
filledLabel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (filledLabel.isSelected()) {
for (JCheckBox box : filled) {
if (!box.isSelected()) {
box.doClick();
}
}
}
else {
for (JCheckBox box : filled) {
if (box.isSelected()) {
box.doClick();
}
}
}
}
});
speciesPanel1.add(use);
speciesPanel2.add(specs);
speciesPanel2.add(color);
speciesPanel2.add(shape);
speciesPanel3.add(connectedLabel);
speciesPanel3.add(visibleLabel);
speciesPanel3.add(filledLabel);
final HashMap<String, Shape> shapey = this.shapes;
final HashMap<String, Paint> colory = this.colors;
for (int i = 0; i < graphSpecies.size() - 1; i++) {
JCheckBox temp = new JCheckBox();
temp.setActionCommand("" + i);
temp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
if (((JCheckBox) e.getSource()).isSelected()) {
node.setIcon(TextIcons.getIcon("g"));
node.setIconName("" + (char) 10003);
IconNode n = ((IconNode) node.getParent());
while (n != null) {
n.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
n.setIconName("" + (char) 10003);
if (n.getParent() == null) {
n = null;
}
else {
n = ((IconNode) n.getParent());
}
}
tree.revalidate();
tree.repaint();
String s = series.get(i).getText();
((JCheckBox) e.getSource()).setSelected(false);
int[] cols = new int[35];
int[] shaps = new int[10];
for (int k = 0; k < boxes.size(); k++) {
if (boxes.get(k).isSelected()) {
if (colorsCombo.get(k).getSelectedItem().equals("Red")) {
cols[0]++;
colorsButtons.get(k).setBackground((Color) colory.get("Red"));
colorsButtons.get(k).setForeground((Color) colory.get("Red"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Blue")) {
cols[1]++;
colorsButtons.get(k).setBackground((Color) colory.get("Blue"));
colorsButtons.get(k).setForeground((Color) colory.get("Blue"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Green")) {
cols[2]++;
colorsButtons.get(k).setBackground((Color) colory.get("Green"));
colorsButtons.get(k).setForeground((Color) colory.get("Green"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Yellow")) {
cols[3]++;
colorsButtons.get(k).setBackground((Color) colory.get("Yellow"));
colorsButtons.get(k).setForeground((Color) colory.get("Yellow"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Magenta")) {
cols[4]++;
colorsButtons.get(k).setBackground((Color) colory.get("Magenta"));
colorsButtons.get(k).setForeground((Color) colory.get("Magenta"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Cyan")) {
cols[5]++;
colorsButtons.get(k).setBackground((Color) colory.get("Cyan"));
colorsButtons.get(k).setForeground((Color) colory.get("Cyan"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Tan")) {
cols[6]++;
colorsButtons.get(k).setBackground((Color) colory.get("Tan"));
colorsButtons.get(k).setForeground((Color) colory.get("Tan"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Gray (Dark)")) {
cols[7]++;
colorsButtons.get(k).setBackground((Color) colory.get("Gray (Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Gray (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Red (Dark)")) {
cols[8]++;
colorsButtons.get(k).setBackground((Color) colory.get("Red (Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Red (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Blue (Dark)")) {
cols[9]++;
colorsButtons.get(k).setBackground((Color) colory.get("Blue (Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Blue (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Green (Dark)")) {
cols[10]++;
colorsButtons.get(k).setBackground((Color) colory.get("Green (Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Green (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Yellow (Dark)")) {
cols[11]++;
colorsButtons.get(k).setBackground((Color) colory.get("Yellow (Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Yellow (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Magenta (Dark)")) {
cols[12]++;
colorsButtons.get(k).setBackground((Color) colory.get("Magenta (Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Magenta (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Cyan (Dark)")) {
cols[13]++;
colorsButtons.get(k).setBackground((Color) colory.get("Cyan (Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Cyan (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Black")) {
cols[14]++;
colorsButtons.get(k).setBackground((Color) colory.get("Black"));
colorsButtons.get(k).setForeground((Color) colory.get("Black"));
}
/*
* else if
* (colorsCombo.get(k).getSelectedItem().
* equals("Red ")) { cols[15]++; } else if
* (colorsCombo
* .get(k).getSelectedItem().equals("Blue ")) {
* cols[16]++; } else if
* (colorsCombo.get(k).getSelectedItem
* ().equals("Green ")) { cols[17]++; } else if
* (colorsCombo.get(k).getSelectedItem().equals(
* "Yellow ")) { cols[18]++; } else if
* (colorsCombo
* .get(k).getSelectedItem().equals("Magenta "))
* { cols[19]++; } else if
* (colorsCombo.get(k).getSelectedItem
* ().equals("Cyan ")) { cols[20]++; }
*/
else if (colorsCombo.get(k).getSelectedItem().equals("Gray")) {
cols[21]++;
colorsButtons.get(k).setBackground((Color) colory.get("Gray"));
colorsButtons.get(k).setForeground((Color) colory.get("Gray"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Red (Extra Dark)")) {
cols[22]++;
colorsButtons.get(k).setBackground((Color) colory.get("Red (Extra Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Red (Extra Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Blue (Extra Dark)")) {
cols[23]++;
colorsButtons.get(k).setBackground((Color) colory.get("Blue (Extra Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Blue (Extra Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Green (Extra Dark)")) {
cols[24]++;
colorsButtons.get(k).setBackground((Color) colory.get("Green (Extra Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Green (Extra Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Yellow (Extra Dark)")) {
cols[25]++;
colorsButtons.get(k).setBackground((Color) colory.get("Yellow (Extra Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Yellow (Extra Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Magenta (Extra Dark)")) {
cols[26]++;
colorsButtons.get(k).setBackground((Color) colory.get("Magenta (Extra Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Magenta (Extra Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Cyan (Extra Dark)")) {
cols[27]++;
colorsButtons.get(k).setBackground((Color) colory.get("Cyan (Extra Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Cyan (Extra Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Red (Light)")) {
cols[28]++;
colorsButtons.get(k).setBackground((Color) colory.get("Red (Light)"));
colorsButtons.get(k).setForeground((Color) colory.get("Red (Light)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Blue (Light)")) {
cols[29]++;
colorsButtons.get(k).setBackground((Color) colory.get("Blue (Light)"));
colorsButtons.get(k).setForeground((Color) colory.get("Blue (Light)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Green (Light)")) {
cols[30]++;
colorsButtons.get(k).setBackground((Color) colory.get("Green (Light)"));
colorsButtons.get(k).setForeground((Color) colory.get("Green (Light)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Yellow (Light)")) {
cols[31]++;
colorsButtons.get(k).setBackground((Color) colory.get("Yellow (Light)"));
colorsButtons.get(k).setForeground((Color) colory.get("Yellow (Light)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Magenta (Light)")) {
cols[32]++;
colorsButtons.get(k).setBackground((Color) colory.get("Magenta (Light)"));
colorsButtons.get(k).setForeground((Color) colory.get("Magenta (Light)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Cyan (Light)")) {
cols[33]++;
colorsButtons.get(k).setBackground((Color) colory.get("Cyan (Light)"));
colorsButtons.get(k).setForeground((Color) colory.get("Cyan (Light)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Gray (Light)")) {
cols[34]++;
colorsButtons.get(k).setBackground((Color) colory.get("Gray (Light)"));
colorsButtons.get(k).setForeground((Color) colory.get("Gray (Light)"));
}
if (shapesCombo.get(k).getSelectedItem().equals("Square")) {
shaps[0]++;
}
else if (shapesCombo.get(k).getSelectedItem().equals("Circle")) {
shaps[1]++;
}
else if (shapesCombo.get(k).getSelectedItem().equals("Triangle")) {
shaps[2]++;
}
else if (shapesCombo.get(k).getSelectedItem().equals("Diamond")) {
shaps[3]++;
}
else if (shapesCombo.get(k).getSelectedItem().equals("Rectangle (Horizontal)")) {
shaps[4]++;
}
else if (shapesCombo.get(k).getSelectedItem().equals("Triangle (Upside Down)")) {
shaps[5]++;
}
else if (shapesCombo.get(k).getSelectedItem().equals("Circle (Half)")) {
shaps[6]++;
}
else if (shapesCombo.get(k).getSelectedItem().equals("Arrow")) {
shaps[7]++;
}
else if (shapesCombo.get(k).getSelectedItem().equals("Rectangle (Vertical)")) {
shaps[8]++;
}
else if (shapesCombo.get(k).getSelectedItem().equals("Arrow (Backwards)")) {
shaps[9]++;
}
}
}
for (GraphSpecies graph : graphed) {
if (graph.getShapeAndPaint().getPaintName().equals("Red")) {
cols[0]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Blue")) {
cols[1]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Green")) {
cols[2]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Yellow")) {
cols[3]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Magenta")) {
cols[4]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Cyan")) {
cols[5]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Tan")) {
cols[6]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Gray (Dark)")) {
cols[7]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Red (Dark)")) {
cols[8]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Blue (Dark)")) {
cols[9]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Green (Dark)")) {
cols[10]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Yellow (Dark)")) {
cols[11]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Magenta (Dark)")) {
cols[12]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Cyan (Dark)")) {
cols[13]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Black")) {
cols[14]++;
}
/*
* else if
* (graph.getShapeAndPaint().getPaintName().equals
* ("Red ")) { cols[15]++; } else if
* (graph.getShapeAndPaint
* ().getPaintName().equals("Blue ")) { cols[16]++;
* } else if
* (graph.getShapeAndPaint().getPaintName()
* .equals("Green ")) { cols[17]++; } else if
* (graph.
* getShapeAndPaint().getPaintName().equals("Yellow "
* )) { cols[18]++; } else if
* (graph.getShapeAndPaint
* ().getPaintName().equals("Magenta ")) {
* cols[19]++; } else if
* (graph.getShapeAndPaint().getPaintName
* ().equals("Cyan ")) { cols[20]++; }
*/
else if (graph.getShapeAndPaint().getPaintName().equals("Gray")) {
cols[21]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Red (Extra Dark)")) {
cols[22]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Blue (Extra Dark)")) {
cols[23]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Green (Extra Dark)")) {
cols[24]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Yellow (Extra Dark)")) {
cols[25]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Magenta (Extra Dark)")) {
cols[26]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Cyan (Extra Dark)")) {
cols[27]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Red (Light)")) {
cols[28]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Blue (Light)")) {
cols[29]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Green (Light)")) {
cols[30]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Yellow (Light)")) {
cols[31]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Magenta (Light)")) {
cols[32]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Cyan (Light)")) {
cols[33]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Gray (Light)")) {
cols[34]++;
}
if (graph.getShapeAndPaint().getShapeName().equals("Square")) {
shaps[0]++;
}
else if (graph.getShapeAndPaint().getShapeName().equals("Circle")) {
shaps[1]++;
}
else if (graph.getShapeAndPaint().getShapeName().equals("Triangle")) {
shaps[2]++;
}
else if (graph.getShapeAndPaint().getShapeName().equals("Diamond")) {
shaps[3]++;
}
else if (graph.getShapeAndPaint().getShapeName().equals("Rectangle (Horizontal)")) {
shaps[4]++;
}
else if (graph.getShapeAndPaint().getShapeName().equals("Triangle (Upside Down)")) {
shaps[5]++;
}
else if (graph.getShapeAndPaint().getShapeName().equals("Circle (Half)")) {
shaps[6]++;
}
else if (graph.getShapeAndPaint().getShapeName().equals("Arrow")) {
shaps[7]++;
}
else if (graph.getShapeAndPaint().getShapeName().equals("Rectangle (Vertical)")) {
shaps[8]++;
}
else if (graph.getShapeAndPaint().getShapeName().equals("Arrow (Backwards)")) {
shaps[9]++;
}
}
((JCheckBox) e.getSource()).setSelected(true);
series.get(i).setText(s);
series.get(i).setSelectionStart(0);
series.get(i).setSelectionEnd(0);
int colorSet = 0;
for (int j = 1; j < cols.length; j++) {
if ((j < 15 || j > 20) && cols[j] < cols[colorSet]) {
colorSet = j;
}
}
int shapeSet = 0;
for (int j = 1; j < shaps.length; j++) {
if (shaps[j] < shaps[shapeSet]) {
shapeSet = j;
}
}
DefaultDrawingSupplier draw = new DefaultDrawingSupplier();
Paint paint;
if (colorSet == 34) {
paint = colors.get("Gray (Light)");
}
else {
for (int j = 0; j < colorSet; j++) {
draw.getNextPaint();
}
paint = draw.getNextPaint();
}
Object[] set = colory.keySet().toArray();
for (int j = 0; j < set.length; j++) {
if (paint == colory.get(set[j])) {
colorsCombo.get(i).setSelectedItem(set[j]);
colorsButtons.get(i).setBackground((Color) paint);
colorsButtons.get(i).setForeground((Color) paint);
}
}
for (int j = 0; j < shapeSet; j++) {
draw.getNextShape();
}
Shape shape = draw.getNextShape();
set = shapey.keySet().toArray();
for (int j = 0; j < set.length; j++) {
if (shape == shapey.get(set[j])) {
shapesCombo.get(i).setSelectedItem(set[j]);
}
}
boolean allChecked = true;
for (JCheckBox temp : boxes) {
if (!temp.isSelected()) {
allChecked = false;
}
}
if (allChecked) {
use.setSelected(true);
}
String color = (String) colorsCombo.get(i).getSelectedItem();
if (color.equals("Custom")) {
color += "_" + colorsButtons.get(i).getBackground().getRGB();
}
graphed.add(new GraphSpecies(shapey.get(shapesCombo.get(i).getSelectedItem()), color, filled.get(i).isSelected(), visible
.get(i).isSelected(), connected.get(i).isSelected(), selected, boxes.get(i).getName(),
series.get(i).getText().trim(), XVariable.getSelectedIndex(), i, directory));
}
else {
boolean check = false;
for (JCheckBox b : boxes) {
if (b.isSelected()) {
check = true;
}
}
if (!check) {
node.setIcon(MetalIconFactory.getTreeLeafIcon());
node.setIconName("");
boolean check2 = false;
IconNode parent = ((IconNode) node.getParent());
while (parent != null) {
for (int j = 0; j < parent.getChildCount(); j++) {
if (((IconNode) parent.getChildAt(j)).getIconName().equals("" + (char) 10003)) {
check2 = true;
}
}
if (!check2) {
parent.setIcon(MetalIconFactory.getTreeFolderIcon());
parent.setIconName("");
}
check2 = false;
if (parent.getParent() == null) {
parent = null;
}
else {
parent = ((IconNode) parent.getParent());
}
}
tree.revalidate();
tree.repaint();
}
ArrayList<GraphSpecies> remove = new ArrayList<GraphSpecies>();
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) {
remove.add(g);
}
}
for (GraphSpecies g : remove) {
graphed.remove(g);
}
use.setSelected(false);
colorsCombo.get(i).setSelectedIndex(0);
colorsButtons.get(i).setBackground((Color) colory.get("Black"));
colorsButtons.get(i).setForeground((Color) colory.get("Black"));
shapesCombo.get(i).setSelectedIndex(0);
}
}
});
boxes.add(temp);
temp = new JCheckBox();
temp.setActionCommand("" + i);
temp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
if (((JCheckBox) e.getSource()).isSelected()) {
boolean allChecked = true;
for (JCheckBox temp : visible) {
if (!temp.isSelected()) {
allChecked = false;
}
}
if (allChecked) {
visibleLabel.setSelected(true);
}
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setVisible(true);
}
}
}
else {
visibleLabel.setSelected(false);
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setVisible(false);
}
}
}
}
});
visible.add(temp);
visible.get(i).setSelected(true);
temp = new JCheckBox();
temp.setActionCommand("" + i);
temp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
if (((JCheckBox) e.getSource()).isSelected()) {
boolean allChecked = true;
for (JCheckBox temp : filled) {
if (!temp.isSelected()) {
allChecked = false;
}
}
if (allChecked) {
filledLabel.setSelected(true);
}
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setFilled(true);
}
}
}
else {
filledLabel.setSelected(false);
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setFilled(false);
}
}
}
}
});
filled.add(temp);
filled.get(i).setSelected(true);
temp = new JCheckBox();
temp.setActionCommand("" + i);
temp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
if (((JCheckBox) e.getSource()).isSelected()) {
boolean allChecked = true;
for (JCheckBox temp : connected) {
if (!temp.isSelected()) {
allChecked = false;
}
}
if (allChecked) {
connectedLabel.setSelected(true);
}
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setConnected(true);
}
}
}
else {
connectedLabel.setSelected(false);
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setConnected(false);
}
}
}
}
});
connected.add(temp);
connected.get(i).setSelected(true);
JTextField seriesName = new JTextField(graphSpecies.get(i + 1), 20);
seriesName.setName("" + i);
seriesName.addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) {
int i = Integer.parseInt(((JTextField) e.getSource()).getName());
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setSpecies(((JTextField) e.getSource()).getText());
}
}
}
public void keyReleased(KeyEvent e) {
int i = Integer.parseInt(((JTextField) e.getSource()).getName());
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setSpecies(((JTextField) e.getSource()).getText());
}
}
}
public void keyTyped(KeyEvent e) {
int i = Integer.parseInt(((JTextField) e.getSource()).getName());
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setSpecies(((JTextField) e.getSource()).getText());
}
}
}
});
series.add(seriesName);
ArrayList<String> allColors = new ArrayList<String>();
for (String c : this.colors.keySet()) {
allColors.add(c);
}
allColors.add("Custom");
Object[] col = allColors.toArray();
Arrays.sort(col);
Object[] shap = this.shapes.keySet().toArray();
Arrays.sort(shap);
JComboBox colBox = new JComboBox(col);
colBox.setActionCommand("" + i);
colBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
if (!((JComboBox) (e.getSource())).getSelectedItem().equals("Custom")) {
colorsButtons.get(i).setBackground((Color) colors.get(((JComboBox) (e.getSource())).getSelectedItem()));
colorsButtons.get(i).setForeground((Color) colors.get(((JComboBox) (e.getSource())).getSelectedItem()));
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setPaint((String) ((JComboBox) e.getSource()).getSelectedItem());
}
}
}
else {
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setPaint("Custom_" + colorsButtons.get(i).getBackground().getRGB());
}
}
}
}
});
JComboBox shapBox = new JComboBox(shap);
shapBox.setActionCommand("" + i);
shapBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setShape((String) ((JComboBox) e.getSource()).getSelectedItem());
}
}
}
});
colorsCombo.add(colBox);
JButton colorButton = new JButton();
colorButton.setPreferredSize(new Dimension(30, 20));
colorButton.setBorder(BorderFactory.createLineBorder(Color.darkGray));
colorButton.setBackground((Color) colory.get("Black"));
colorButton.setForeground((Color) colory.get("Black"));
colorButton.setUI(new MetalButtonUI());
colorButton.setActionCommand("" + i);
colorButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
Color newColor = JColorChooser.showDialog(Gui.frame, "Choose Color", ((JButton) e.getSource()).getBackground());
if (newColor != null) {
((JButton) e.getSource()).setBackground(newColor);
((JButton) e.getSource()).setForeground(newColor);
colorsCombo.get(i).setSelectedItem("Custom");
}
}
});
colorsButtons.add(colorButton);
JPanel colorPanel = new JPanel(new BorderLayout());
colorPanel.add(colorsCombo.get(i), "Center");
colorPanel.add(colorsButtons.get(i), "East");
shapesCombo.add(shapBox);
speciesPanel1.add(boxes.get(i));
speciesPanel2.add(series.get(i));
speciesPanel2.add(colorPanel);
speciesPanel2.add(shapesCombo.get(i));
speciesPanel3.add(connected.get(i));
speciesPanel3.add(visible.get(i));
speciesPanel3.add(filled.get(i));
}
JPanel speciesPanel = new JPanel(new BorderLayout());
speciesPanel.add(speciesPanel1, "West");
speciesPanel.add(speciesPanel2, "Center");
speciesPanel.add(speciesPanel3, "East");
return speciesPanel;
}
private void fixGraph(String title, String x, String y, XYSeriesCollection dataset) {
curData = dataset;
// chart = ChartFactory.createXYLineChart(title, x, y, dataset,
// PlotOrientation.VERTICAL,
// true, true, false);
chart.getXYPlot().setDataset(dataset);
chart.setTitle(title);
chart.getXYPlot().getDomainAxis().setLabel(x);
chart.getXYPlot().getRangeAxis().setLabel(y);
// chart.setBackgroundPaint(new java.awt.Color(238, 238, 238));
// chart.getPlot().setBackgroundPaint(java.awt.Color.WHITE);
// chart.getXYPlot().setDomainGridlinePaint(java.awt.Color.LIGHT_GRAY);
// chart.getXYPlot().setRangeGridlinePaint(java.awt.Color.LIGHT_GRAY);
// chart.addProgressListener(this);
ChartPanel graph = new ChartPanel(chart);
if (graphed.isEmpty()) {
graph.setLayout(new GridLayout(1, 1));
JLabel edit = new JLabel("Double click here to create graph");
edit.addMouseListener(this);
Font font = edit.getFont();
font = font.deriveFont(Font.BOLD, 42.0f);
edit.setFont(font);
edit.setHorizontalAlignment(SwingConstants.CENTER);
graph.add(edit);
}
graph.addMouseListener(this);
JPanel ButtonHolder = new JPanel();
run = new JButton("Save and Run");
save = new JButton("Save Graph");
saveAs = new JButton("Save As");
saveAs.addActionListener(this);
export = new JButton("Export");
refresh = new JButton("Refresh");
// exportJPeg = new JButton("Export As JPEG");
// exportPng = new JButton("Export As PNG");
// exportPdf = new JButton("Export As PDF");
// exportEps = new JButton("Export As EPS");
// exportSvg = new JButton("Export As SVG");
// exportCsv = new JButton("Export As CSV");
run.addActionListener(this);
save.addActionListener(this);
export.addActionListener(this);
refresh.addActionListener(this);
// exportJPeg.addActionListener(this);
// exportPng.addActionListener(this);
// exportPdf.addActionListener(this);
// exportEps.addActionListener(this);
// exportSvg.addActionListener(this);
// exportCsv.addActionListener(this);
if (reb2sac != null) {
ButtonHolder.add(run);
}
ButtonHolder.add(save);
ButtonHolder.add(saveAs);
ButtonHolder.add(export);
ButtonHolder.add(refresh);
// ButtonHolder.add(exportJPeg);
// ButtonHolder.add(exportPng);
// ButtonHolder.add(exportPdf);
// ButtonHolder.add(exportEps);
// ButtonHolder.add(exportSvg);
// ButtonHolder.add(exportCsv);
// JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
// ButtonHolder, null);
// splitPane.setDividerSize(0);
this.removeAll();
this.setLayout(new BorderLayout());
this.add(graph, "Center");
// this.add(splitPane, "South");
this.revalidate();
}
/**
* This method saves the graph as a jpeg or as a png file.
*/
public void export() {
try {
int output = 2; /* Default is currently pdf */
int width = -1;
int height = -1;
JPanel sizePanel = new JPanel(new GridLayout(2, 2));
JLabel heightLabel = new JLabel("Desired pixel height:");
JLabel widthLabel = new JLabel("Desired pixel width:");
JTextField heightField = new JTextField("400");
JTextField widthField = new JTextField("650");
sizePanel.add(widthLabel);
sizePanel.add(widthField);
sizePanel.add(heightLabel);
sizePanel.add(heightField);
Object[] options2 = { "Export", "Cancel" };
int value;
String export = "Export";
if (timeSeries) {
export += " TSD";
}
else {
export += " Probability";
}
File file;
Preferences biosimrc = Preferences.userRoot();
if (biosimrc.get("biosim.general.export_dir", "").equals("")) {
file = null;
}
else {
file = new File(biosimrc.get("biosim.general.export_dir", ""));
}
String filename = Utility.browse(Gui.frame, file, null, JFileChooser.FILES_ONLY, export, output);
if ((filename.length() > 4) && (filename.substring((filename.length() - 4), filename.length()).equals(".jpg"))) {
output = 0;
}
else if ((filename.length() > 4) && (filename.substring((filename.length() - 4), filename.length()).equals(".png"))) {
output = 1;
}
else if ((filename.length() > 4) && (filename.substring((filename.length() - 4), filename.length()).equals(".pdf"))) {
output = 2;
}
else if ((filename.length() > 4) && (filename.substring((filename.length() - 4), filename.length()).equals(".eps"))) {
output = 3;
}
else if ((filename.length() > 4) && (filename.substring((filename.length() - 4), filename.length()).equals(".svg"))) {
output = 4;
}
else if ((filename.length() > 4) && (filename.substring((filename.length() - 4), filename.length()).equals(".csv"))) {
output = 5;
}
else if ((filename.length() > 4) && (filename.substring((filename.length() - 4), filename.length()).equals(".dat"))) {
output = 6;
}
else if ((filename.length() > 4) && (filename.substring((filename.length() - 4), filename.length()).equals(".tsd"))) {
output = 7;
}
if (!filename.equals("")) {
file = new File(filename);
biosimrc.put("biosim.general.export_dir", filename);
boolean exportIt = true;
if (file.exists()) {
Object[] options = { "Overwrite", "Cancel" };
value = JOptionPane.showOptionDialog(Gui.frame, "File already exists." + " Overwrite?", "File Already Exists",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
exportIt = false;
if (value == JOptionPane.YES_OPTION) {
exportIt = true;
}
}
if (exportIt) {
if ((output != 5) && (output != 6) && (output != 7)) {
value = JOptionPane.showOptionDialog(Gui.frame, sizePanel, "Enter Size Of File", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options2, options2[0]);
if (value == JOptionPane.YES_OPTION) {
while (value == JOptionPane.YES_OPTION && (width == -1 || height == -1))
try {
width = Integer.parseInt(widthField.getText().trim());
height = Integer.parseInt(heightField.getText().trim());
if (width < 1 || height < 1) {
JOptionPane.showMessageDialog(Gui.frame, "Width and height must be positive integers!", "Error",
JOptionPane.ERROR_MESSAGE);
width = -1;
height = -1;
value = JOptionPane.showOptionDialog(Gui.frame, sizePanel, "Enter Size Of File", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options2, options2[0]);
}
}
catch (Exception e2) {
JOptionPane.showMessageDialog(Gui.frame, "Width and height must be positive integers!", "Error",
JOptionPane.ERROR_MESSAGE);
width = -1;
height = -1;
value = JOptionPane.showOptionDialog(Gui.frame, sizePanel, "Enter Size Of File", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options2, options2[0]);
}
}
if (value == JOptionPane.NO_OPTION) {
return;
}
}
if (output == 0) {
ChartUtilities.saveChartAsJPEG(file, chart, width, height);
}
else if (output == 1) {
ChartUtilities.saveChartAsPNG(file, chart, width, height);
}
else if (output == 2) {
Rectangle pagesize = new Rectangle(width, height);
Document document = new Document(pagesize, 50, 50, 50, 50);
FileOutputStream out = new FileOutputStream(file);
PdfWriter writer = PdfWriter.getInstance(document, out);
document.open();
PdfContentByte cb = writer.getDirectContent();
PdfTemplate tp = cb.createTemplate(width, height);
Graphics2D g2 = tp.createGraphics(width, height, new DefaultFontMapper());
chart.draw(g2, new java.awt.Rectangle(width, height));
g2.dispose();
cb.addTemplate(tp, 0, 0);
document.close();
out.close();
}
else if (output == 3) {
Graphics2D g = new EpsGraphics2D();
chart.draw(g, new java.awt.Rectangle(width, height));
Writer out = new FileWriter(file);
out.write(g.toString());
out.close();
}
else if (output == 4) {
DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation();
org.w3c.dom.Document document = domImpl.createDocument(null, "svg", null);
SVGGraphics2D svgGenerator = new SVGGraphics2D(document);
chart.draw(svgGenerator, new java.awt.Rectangle(width, height));
boolean useCSS = true;
FileOutputStream outStream = new FileOutputStream(file);
Writer out = new OutputStreamWriter(outStream, "UTF-8");
svgGenerator.stream(out, useCSS);
out.close();
outStream.close();
}
else if ((output == 5) || (output == 6) || (output == 7)) {
exportDataFile(file, output);
}
}
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(Gui.frame, "Unable To Export File!", "Error", JOptionPane.ERROR_MESSAGE);
}
}
public void export(int output) {
// jpg = 0
// png = 1
// pdf = 2
// eps = 3
// svg = 4
// csv = 5 (data)
// dat = 6 (data)
// tsd = 7 (data)
try {
int width = -1;
int height = -1;
JPanel sizePanel = new JPanel(new GridLayout(2, 2));
JLabel heightLabel = new JLabel("Desired pixel height:");
JLabel widthLabel = new JLabel("Desired pixel width:");
JTextField heightField = new JTextField("400");
JTextField widthField = new JTextField("650");
sizePanel.add(widthLabel);
sizePanel.add(widthField);
sizePanel.add(heightLabel);
sizePanel.add(heightField);
Object[] options2 = { "Export", "Cancel" };
int value;
String export = "Export";
if (timeSeries) {
export += " TSD";
}
else {
export += " Probability";
}
File file;
Preferences biosimrc = Preferences.userRoot();
if (biosimrc.get("biosim.general.export_dir", "").equals("")) {
file = null;
}
else {
file = new File(biosimrc.get("biosim.general.export_dir", ""));
}
String filename = Utility.browse(Gui.frame, file, null, JFileChooser.FILES_ONLY, export, output);
if (!filename.equals("")) {
file = new File(filename);
biosimrc.put("biosim.general.export_dir", filename);
boolean exportIt = true;
if (file.exists()) {
Object[] options = { "Overwrite", "Cancel" };
value = JOptionPane.showOptionDialog(Gui.frame, "File already exists." + " Overwrite?", "File Already Exists",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
exportIt = false;
if (value == JOptionPane.YES_OPTION) {
exportIt = true;
}
}
if (exportIt) {
if ((output != 5) && (output != 6) && (output != 7)) {
value = JOptionPane.showOptionDialog(Gui.frame, sizePanel, "Enter Size Of File", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options2, options2[0]);
if (value == JOptionPane.YES_OPTION) {
while (value == JOptionPane.YES_OPTION && (width == -1 || height == -1))
try {
width = Integer.parseInt(widthField.getText().trim());
height = Integer.parseInt(heightField.getText().trim());
if (width < 1 || height < 1) {
JOptionPane.showMessageDialog(Gui.frame, "Width and height must be positive integers!", "Error",
JOptionPane.ERROR_MESSAGE);
width = -1;
height = -1;
value = JOptionPane.showOptionDialog(Gui.frame, sizePanel, "Enter Size Of File", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options2, options2[0]);
}
}
catch (Exception e2) {
JOptionPane.showMessageDialog(Gui.frame, "Width and height must be positive integers!", "Error",
JOptionPane.ERROR_MESSAGE);
width = -1;
height = -1;
value = JOptionPane.showOptionDialog(Gui.frame, sizePanel, "Enter Size Of File", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options2, options2[0]);
}
}
if (value == JOptionPane.NO_OPTION) {
return;
}
}
if (output == 0) {
ChartUtilities.saveChartAsJPEG(file, chart, width, height);
}
else if (output == 1) {
ChartUtilities.saveChartAsPNG(file, chart, width, height);
}
else if (output == 2) {
Rectangle pagesize = new Rectangle(width, height);
Document document = new Document(pagesize, 50, 50, 50, 50);
FileOutputStream out = new FileOutputStream(file);
PdfWriter writer = PdfWriter.getInstance(document, out);
document.open();
PdfContentByte cb = writer.getDirectContent();
PdfTemplate tp = cb.createTemplate(width, height);
Graphics2D g2 = tp.createGraphics(width, height, new DefaultFontMapper());
chart.draw(g2, new java.awt.Rectangle(width, height));
g2.dispose();
cb.addTemplate(tp, 0, 0);
document.close();
out.close();
}
else if (output == 3) {
Graphics2D g = new EpsGraphics2D();
chart.draw(g, new java.awt.Rectangle(width, height));
Writer out = new FileWriter(file);
out.write(g.toString());
out.close();
}
else if (output == 4) {
DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation();
org.w3c.dom.Document document = domImpl.createDocument(null, "svg", null);
SVGGraphics2D svgGenerator = new SVGGraphics2D(document);
chart.draw(svgGenerator, new java.awt.Rectangle(width, height));
boolean useCSS = true;
FileOutputStream outStream = new FileOutputStream(file);
Writer out = new OutputStreamWriter(outStream, "UTF-8");
svgGenerator.stream(out, useCSS);
out.close();
outStream.close();
}
else if ((output == 5) || (output == 6) || (output == 7)) {
exportDataFile(file, output);
}
}
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(Gui.frame, "Unable To Export File!", "Error", JOptionPane.ERROR_MESSAGE);
}
}
public void exportDataFile(File file, int output) {
try {
int count = curData.getSeries(0).getItemCount();
for (int i = 1; i < curData.getSeriesCount(); i++) {
if (curData.getSeries(i).getItemCount() != count) {
JOptionPane.showMessageDialog(Gui.frame, "Data series do not have the same number of points!", "Unable to Export Data File",
JOptionPane.ERROR_MESSAGE);
return;
}
}
for (int j = 0; j < count; j++) {
Number Xval = curData.getSeries(0).getDataItem(j).getX();
for (int i = 1; i < curData.getSeriesCount(); i++) {
if (!curData.getSeries(i).getDataItem(j).getX().equals(Xval)) {
JOptionPane.showMessageDialog(Gui.frame, "Data series time points are not the same!", "Unable to Export Data File",
JOptionPane.ERROR_MESSAGE);
return;
}
}
}
FileOutputStream csvFile = new FileOutputStream(file);
PrintWriter csvWriter = new PrintWriter(csvFile);
if (output == 7) {
csvWriter.print("((");
}
else if (output == 6) {
csvWriter.print("#");
}
csvWriter.print("\"Time\"");
count = curData.getSeries(0).getItemCount();
int pos = 0;
for (int i = 0; i < curData.getSeriesCount(); i++) {
if (output == 6) {
csvWriter.print(" ");
}
else {
csvWriter.print(",");
}
csvWriter.print("\"" + curData.getSeriesKey(i) + "\"");
if (curData.getSeries(i).getItemCount() > count) {
count = curData.getSeries(i).getItemCount();
pos = i;
}
}
if (output == 7) {
csvWriter.print(")");
}
else {
csvWriter.println("");
}
for (int j = 0; j < count; j++) {
if (output == 7) {
csvWriter.print(",");
}
for (int i = 0; i < curData.getSeriesCount(); i++) {
if (i == 0) {
if (output == 7) {
csvWriter.print("(");
}
csvWriter.print(curData.getSeries(pos).getDataItem(j).getX());
}
XYSeries data = curData.getSeries(i);
if (j < data.getItemCount()) {
XYDataItem item = data.getDataItem(j);
if (output == 6) {
csvWriter.print(" ");
}
else {
csvWriter.print(",");
}
csvWriter.print(item.getY());
}
else {
if (output == 6) {
csvWriter.print(" ");
}
else {
csvWriter.print(",");
}
}
}
if (output == 7) {
csvWriter.print(")");
}
else {
csvWriter.println("");
}
}
if (output == 7) {
csvWriter.println(")");
}
csvWriter.close();
csvFile.close();
}
catch (Exception e1) {
JOptionPane.showMessageDialog(Gui.frame, "Unable To Export File!", "Error", JOptionPane.ERROR_MESSAGE);
}
}
public ArrayList<ArrayList<Double>> calculateAverageVarianceDeviation(ArrayList<String> files, int choice, String directory, boolean warning,
boolean output) {
if (files.size() > 0) {
ArrayList<ArrayList<Double>> average = new ArrayList<ArrayList<Double>>();
ArrayList<ArrayList<Double>> variance = new ArrayList<ArrayList<Double>>();
ArrayList<ArrayList<Double>> deviation = new ArrayList<ArrayList<Double>>();
lock.lock();
try {
warn = warning;
// TSDParser p = new TSDParser(startFile, biomodelsim, false);
ArrayList<ArrayList<Double>> data;
if (directory == null) {
data = readData(outDir + separator + files.get(0), "", directory, warn);
}
else {
data = readData(outDir + separator + directory + separator + files.get(0), "", directory, warn);
}
averageOrder = graphSpecies;
boolean first = true;
for (int i = 0; i < graphSpecies.size(); i++) {
average.add(new ArrayList<Double>());
variance.add(new ArrayList<Double>());
}
HashMap<Double, Integer> dataCounts = new HashMap<Double, Integer>();
// int count = 0;
for (String run : files) {
if (directory == null) {
if (new File(outDir + separator + run).exists()) {
ArrayList<ArrayList<Double>> newData = readData(outDir + separator + run, "", directory, warn);
data = new ArrayList<ArrayList<Double>>();
for (int i = 0; i < averageOrder.size(); i++) {
for (int k = 0; k < graphSpecies.size(); k++) {
if (averageOrder.get(i).equals(graphSpecies.get(k))) {
data.add(newData.get(k));
break;
}
}
}
}
}
else {
if (new File(outDir + separator + directory + separator + run).exists()) {
ArrayList<ArrayList<Double>> newData = readData(outDir + separator + directory + separator + run, "", directory, warn);
data = new ArrayList<ArrayList<Double>>();
for (int i = 0; i < averageOrder.size(); i++) {
for (int k = 0; k < graphSpecies.size(); k++) {
if (averageOrder.get(i).equals(graphSpecies.get(k))) {
data.add(newData.get(k));
break;
}
}
}
}
}
// ArrayList<ArrayList<Double>> data = p.getData();
for (int k = 0; k < data.get(0).size(); k++) {
if (first) {
double put;
if (k == data.get(0).size() - 1 && k >= 2) {
if (data.get(0).get(k) - data.get(0).get(k - 1) != data.get(0).get(k - 1) - data.get(0).get(k - 2)) {
put = data.get(0).get(k - 1) + (data.get(0).get(k - 1) - data.get(0).get(k - 2));
dataCounts.put(put, 1);
}
else {
put = (data.get(0)).get(k);
dataCounts.put(put, 1);
}
}
else {
put = (data.get(0)).get(k);
dataCounts.put(put, 1);
}
for (int i = 0; i < data.size(); i++) {
if (i == 0) {
variance.get(i).add((data.get(i)).get(k));
average.get(i).add(put);
}
else {
variance.get(i).add(0.0);
average.get(i).add((data.get(i)).get(k));
}
}
}
else {
int index = -1;
double put;
if (k == data.get(0).size() - 1 && k >= 2) {
if (data.get(0).get(k) - data.get(0).get(k - 1) != data.get(0).get(k - 1) - data.get(0).get(k - 2)) {
put = data.get(0).get(k - 1) + (data.get(0).get(k - 1) - data.get(0).get(k - 2));
}
else {
put = (data.get(0)).get(k);
}
}
else if (k == data.get(0).size() - 1 && k == 1) {
if (average.get(0).size() > 1) {
put = (average.get(0)).get(k);
}
else {
put = (data.get(0)).get(k);
}
}
else {
put = (data.get(0)).get(k);
}
if (average.get(0).contains(put)) {
index = average.get(0).indexOf(put);
int count = dataCounts.get(put);
dataCounts.put(put, count + 1);
for (int i = 1; i < data.size(); i++) {
double old = (average.get(i)).get(index);
(average.get(i)).set(index, old + (((data.get(i)).get(k) - old) / (count + 1)));
double newMean = (average.get(i)).get(index);
double vary = (((count - 1) * (variance.get(i)).get(index)) + ((data.get(i)).get(k) - newMean)
* ((data.get(i)).get(k) - old))
/ count;
(variance.get(i)).set(index, vary);
}
}
else {
dataCounts.put(put, 1);
for (int a = 0; a < average.get(0).size(); a++) {
if (average.get(0).get(a) > put) {
index = a;
break;
}
}
if (index == -1) {
index = average.get(0).size() - 1;
}
average.get(0).add(put);
variance.get(0).add(put);
for (int a = 1; a < average.size(); a++) {
average.get(a).add(data.get(a).get(k));
variance.get(a).add(0.0);
}
if (index != average.get(0).size() - 1) {
for (int a = average.get(0).size() - 2; a >= 0; a--) {
if (average.get(0).get(a) > average.get(0).get(a + 1)) {
for (int b = 0; b < average.size(); b++) {
double temp = average.get(b).get(a);
average.get(b).set(a, average.get(b).get(a + 1));
average.get(b).set(a + 1, temp);
temp = variance.get(b).get(a);
variance.get(b).set(a, variance.get(b).get(a + 1));
variance.get(b).set(a + 1, temp);
}
}
else {
break;
}
}
}
}
}
}
first = false;
}
deviation = new ArrayList<ArrayList<Double>>();
for (int i = 0; i < variance.size(); i++) {
deviation.add(new ArrayList<Double>());
for (int j = 0; j < variance.get(i).size(); j++) {
deviation.get(i).add(variance.get(i).get(j));
}
}
for (int i = 1; i < deviation.size(); i++) {
for (int j = 0; j < deviation.get(i).size(); j++) {
deviation.get(i).set(j, Math.sqrt(deviation.get(i).get(j)));
}
}
averageOrder = null;
}
catch (Exception e) {
JOptionPane.showMessageDialog(Gui.frame, "Unable to output average, variance, and standard deviation!", "Error",
JOptionPane.ERROR_MESSAGE);
}
lock.unlock();
if (output) {
DataParser m = new DataParser(graphSpecies, average);
DataParser d = new DataParser(graphSpecies, deviation);
DataParser v = new DataParser(graphSpecies, variance);
if (directory == null) {
m.outputTSD(outDir + separator + "mean.tsd");
v.outputTSD(outDir + separator + "variance.tsd");
d.outputTSD(outDir + separator + "standard_deviation.tsd");
}
else {
m.outputTSD(outDir + separator + directory + separator + "mean.tsd");
v.outputTSD(outDir + separator + directory + separator + "variance.tsd");
d.outputTSD(outDir + separator + directory + separator + "standard_deviation.tsd");
}
}
if (choice == 0) {
return average;
}
else if (choice == 1) {
return variance;
}
else {
return deviation;
}
}
return null;
}
public void run() {
reb2sac.getRunButton().doClick();
}
public void save() {
if (timeSeries) {
Properties graph = new Properties();
graph.setProperty("title", chart.getTitle().getText());
graph.setProperty("chart.background.paint", "" + ((Color) chart.getBackgroundPaint()).getRGB());
graph.setProperty("plot.background.paint", "" + ((Color) chart.getPlot().getBackgroundPaint()).getRGB());
graph.setProperty("plot.domain.grid.line.paint", "" + ((Color) chart.getXYPlot().getDomainGridlinePaint()).getRGB());
graph.setProperty("plot.range.grid.line.paint", "" + ((Color) chart.getXYPlot().getRangeGridlinePaint()).getRGB());
graph.setProperty("x.axis", chart.getXYPlot().getDomainAxis().getLabel());
graph.setProperty("y.axis", chart.getXYPlot().getRangeAxis().getLabel());
graph.setProperty("x.min", XMin.getText());
graph.setProperty("x.max", XMax.getText());
graph.setProperty("x.scale", XScale.getText());
graph.setProperty("y.min", YMin.getText());
graph.setProperty("y.max", YMax.getText());
graph.setProperty("y.scale", YScale.getText());
graph.setProperty("auto.resize", "" + resize.isSelected());
graph.setProperty("LogX", "" + LogX.isSelected());
graph.setProperty("LogY", "" + LogY.isSelected());
graph.setProperty("visibleLegend", "" + visibleLegend.isSelected());
for (int i = 0; i < graphed.size(); i++) {
graph.setProperty("species.connected." + i, "" + graphed.get(i).getConnected());
graph.setProperty("species.filled." + i, "" + graphed.get(i).getFilled());
graph.setProperty("species.xnumber." + i, "" + graphed.get(i).getXNumber());
graph.setProperty("species.number." + i, "" + graphed.get(i).getNumber());
graph.setProperty("species.run.number." + i, graphed.get(i).getRunNumber());
graph.setProperty("species.name." + i, graphed.get(i).getSpecies());
graph.setProperty("species.id." + i, graphed.get(i).getID());
graph.setProperty("species.visible." + i, "" + graphed.get(i).getVisible());
graph.setProperty("species.paint." + i, graphed.get(i).getShapeAndPaint().getPaintName());
graph.setProperty("species.shape." + i, graphed.get(i).getShapeAndPaint().getShapeName());
graph.setProperty("species.directory." + i, graphed.get(i).getDirectory());
}
try {
FileOutputStream store = new FileOutputStream(new File(outDir + separator + graphName));
graph.store(store, "Graph Data");
store.close();
log.addText("Creating graph file:\n" + outDir + separator + graphName + "\n");
change = false;
}
catch (Exception except) {
JOptionPane.showMessageDialog(Gui.frame, "Unable To Save Graph!", "Error", JOptionPane.ERROR_MESSAGE);
}
}
else {
Properties graph = new Properties();
graph.setProperty("title", chart.getTitle().getText());
graph.setProperty("chart.background.paint", "" + ((Color) chart.getBackgroundPaint()).getRGB());
graph.setProperty("plot.background.paint", "" + ((Color) chart.getPlot().getBackgroundPaint()).getRGB());
graph.setProperty("plot.range.grid.line.paint", "" + ((Color) chart.getCategoryPlot().getRangeGridlinePaint()).getRGB());
graph.setProperty("x.axis", chart.getCategoryPlot().getDomainAxis().getLabel());
graph.setProperty("y.axis", chart.getCategoryPlot().getRangeAxis().getLabel());
graph.setProperty("gradient", "" + (((BarRenderer) chart.getCategoryPlot().getRenderer()).getBarPainter() instanceof GradientBarPainter));
graph.setProperty("shadow", "" + ((BarRenderer) chart.getCategoryPlot().getRenderer()).getShadowsVisible());
graph.setProperty("visibleLegend", "" + visibleLegend.isSelected());
for (int i = 0; i < probGraphed.size(); i++) {
graph.setProperty("species.number." + i, "" + probGraphed.get(i).getNumber());
graph.setProperty("species.name." + i, probGraphed.get(i).getSpecies());
graph.setProperty("species.id." + i, probGraphed.get(i).getID());
graph.setProperty("species.paint." + i, probGraphed.get(i).getPaintName());
graph.setProperty("species.directory." + i, probGraphed.get(i).getDirectory());
}
try {
FileOutputStream store = new FileOutputStream(new File(outDir + separator + graphName));
graph.store(store, "Probability Data");
store.close();
log.addText("Creating graph file:\n" + outDir + separator + graphName + "\n");
change = false;
}
catch (Exception except) {
JOptionPane.showMessageDialog(Gui.frame, "Unable To Save Graph!", "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
public void saveAs() {
if (timeSeries) {
String graphName = JOptionPane.showInputDialog(Gui.frame, "Enter Graph Name:", "Graph Name", JOptionPane.PLAIN_MESSAGE);
if (graphName != null && !graphName.trim().equals("")) {
graphName = graphName.trim();
if (graphName.length() > 3) {
if (!graphName.substring(graphName.length() - 4).equals(".grf")) {
graphName += ".grf";
}
}
else {
graphName += ".grf";
}
File f;
if (topLevel) {
f = new File(outDir + separator + graphName);
}
else {
f = new File(outDir.substring(0, outDir.length() - outDir.split(separator)[outDir.split(separator).length - 1].length())
+ separator + graphName);
}
if (f.exists()) {
Object[] options = { "Overwrite", "Cancel" };
int value = JOptionPane.showOptionDialog(Gui.frame, "File already exists." + "\nDo you want to overwrite?", "Overwrite",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
if (value == JOptionPane.YES_OPTION) {
File del;
if (topLevel) {
del = new File(outDir + separator + graphName);
}
else {
del = new File(
outDir.substring(0, outDir.length() - outDir.split(separator)[outDir.split(separator).length - 1].length())
+ separator + graphName);
}
if (del.isDirectory()) {
biomodelsim.deleteDir(del);
}
else {
del.delete();
}
for (int i = 0; i < biomodelsim.getTab().getTabCount(); i++) {
if (biomodelsim.getTab().getTitleAt(i).equals(graphName)) {
biomodelsim.getTab().remove(i);
}
}
}
else {
return;
}
}
Properties graph = new Properties();
graph.setProperty("title", chart.getTitle().getText());
graph.setProperty("x.axis", chart.getXYPlot().getDomainAxis().getLabel());
graph.setProperty("y.axis", chart.getXYPlot().getRangeAxis().getLabel());
graph.setProperty("x.min", XMin.getText());
graph.setProperty("x.max", XMax.getText());
graph.setProperty("x.scale", XScale.getText());
graph.setProperty("y.min", YMin.getText());
graph.setProperty("y.max", YMax.getText());
graph.setProperty("y.scale", YScale.getText());
graph.setProperty("auto.resize", "" + resize.isSelected());
graph.setProperty("LogX", "" + LogX.isSelected());
graph.setProperty("LogY", "" + LogY.isSelected());
graph.setProperty("visibleLegend", "" + visibleLegend.isSelected());
for (int i = 0; i < graphed.size(); i++) {
graph.setProperty("species.connected." + i, "" + graphed.get(i).getConnected());
graph.setProperty("species.filled." + i, "" + graphed.get(i).getFilled());
graph.setProperty("species.number." + i, "" + graphed.get(i).getNumber());
graph.setProperty("species.run.number." + i, graphed.get(i).getRunNumber());
graph.setProperty("species.name." + i, graphed.get(i).getSpecies());
graph.setProperty("species.id." + i, graphed.get(i).getID());
graph.setProperty("species.visible." + i, "" + graphed.get(i).getVisible());
graph.setProperty("species.paint." + i, graphed.get(i).getShapeAndPaint().getPaintName());
graph.setProperty("species.shape." + i, graphed.get(i).getShapeAndPaint().getShapeName());
if (topLevel) {
graph.setProperty("species.directory." + i, graphed.get(i).getDirectory());
}
else {
if (graphed.get(i).getDirectory().equals("")) {
graph.setProperty("species.directory." + i, outDir.split(separator)[outDir.split(separator).length - 1]);
}
else {
graph.setProperty("species.directory." + i, outDir.split(separator)[outDir.split(separator).length - 1] + "/"
+ graphed.get(i).getDirectory());
}
}
}
try {
FileOutputStream store = new FileOutputStream(f);
graph.store(store, "Graph Data");
store.close();
log.addText("Creating graph file:\n" + f.getAbsolutePath() + "\n");
change = false;
biomodelsim.addToTree(f.getName());
}
catch (Exception except) {
JOptionPane.showMessageDialog(Gui.frame, "Unable To Save Graph!", "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
else {
String graphName = JOptionPane.showInputDialog(Gui.frame, "Enter Probability Graph Name:", "Probability Graph Name",
JOptionPane.PLAIN_MESSAGE);
if (graphName != null && !graphName.trim().equals("")) {
graphName = graphName.trim();
if (graphName.length() > 3) {
if (!graphName.substring(graphName.length() - 4).equals(".prb")) {
graphName += ".prb";
}
}
else {
graphName += ".prb";
}
File f;
if (topLevel) {
f = new File(outDir + separator + graphName);
}
else {
f = new File(outDir.substring(0, outDir.length() - outDir.split(separator)[outDir.split(separator).length - 1].length())
+ separator + graphName);
}
if (f.exists()) {
Object[] options = { "Overwrite", "Cancel" };
int value = JOptionPane.showOptionDialog(Gui.frame, "File already exists." + "\nDo you want to overwrite?", "Overwrite",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
if (value == JOptionPane.YES_OPTION) {
File del;
if (topLevel) {
del = new File(outDir + separator + graphName);
}
else {
del = new File(
outDir.substring(0, outDir.length() - outDir.split(separator)[outDir.split(separator).length - 1].length())
+ separator + graphName);
}
if (del.isDirectory()) {
biomodelsim.deleteDir(del);
}
else {
del.delete();
}
for (int i = 0; i < biomodelsim.getTab().getTabCount(); i++) {
if (biomodelsim.getTab().getTitleAt(i).equals(graphName)) {
biomodelsim.getTab().remove(i);
}
}
}
else {
return;
}
}
Properties graph = new Properties();
graph.setProperty("title", chart.getTitle().getText());
graph.setProperty("x.axis", chart.getCategoryPlot().getDomainAxis().getLabel());
graph.setProperty("y.axis", chart.getCategoryPlot().getRangeAxis().getLabel());
graph.setProperty("gradient", ""
+ (((BarRenderer) chart.getCategoryPlot().getRenderer()).getBarPainter() instanceof GradientBarPainter));
graph.setProperty("shadow", "" + ((BarRenderer) chart.getCategoryPlot().getRenderer()).getShadowsVisible());
graph.setProperty("visibleLegend", "" + visibleLegend.isSelected());
for (int i = 0; i < probGraphed.size(); i++) {
graph.setProperty("species.number." + i, "" + probGraphed.get(i).getNumber());
graph.setProperty("species.name." + i, probGraphed.get(i).getSpecies());
graph.setProperty("species.id." + i, probGraphed.get(i).getID());
graph.setProperty("species.paint." + i, probGraphed.get(i).getPaintName());
if (topLevel) {
graph.setProperty("species.directory." + i, probGraphed.get(i).getDirectory());
}
else {
if (probGraphed.get(i).getDirectory().equals("")) {
graph.setProperty("species.directory." + i, outDir.split(separator)[outDir.split(separator).length - 1]);
}
else {
graph.setProperty("species.directory." + i, outDir.split(separator)[outDir.split(separator).length - 1] + "/"
+ probGraphed.get(i).getDirectory());
}
}
}
try {
FileOutputStream store = new FileOutputStream(f);
graph.store(store, "Probability Graph Data");
store.close();
log.addText("Creating probability graph file:\n" + f.getAbsolutePath() + "\n");
change = false;
biomodelsim.addToTree(f.getName());
}
catch (Exception except) {
JOptionPane.showMessageDialog(Gui.frame, "Unable To Save Probability Graph!", "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
}
private void open(String filename) {
if (timeSeries) {
Properties graph = new Properties();
try {
FileInputStream load = new FileInputStream(new File(filename));
graph.load(load);
load.close();
XMin.setText(graph.getProperty("x.min"));
XMax.setText(graph.getProperty("x.max"));
XScale.setText(graph.getProperty("x.scale"));
YMin.setText(graph.getProperty("y.min"));
YMax.setText(graph.getProperty("y.max"));
YScale.setText(graph.getProperty("y.scale"));
chart.setTitle(graph.getProperty("title"));
if (graph.containsKey("chart.background.paint")) {
chart.setBackgroundPaint(new Color(Integer.parseInt(graph.getProperty("chart.background.paint"))));
}
if (graph.containsKey("plot.background.paint")) {
chart.getPlot().setBackgroundPaint(new Color(Integer.parseInt(graph.getProperty("plot.background.paint"))));
}
if (graph.containsKey("plot.domain.grid.line.paint")) {
chart.getXYPlot().setDomainGridlinePaint(new Color(Integer.parseInt(graph.getProperty("plot.domain.grid.line.paint"))));
}
if (graph.containsKey("plot.range.grid.line.paint")) {
chart.getXYPlot().setRangeGridlinePaint(new Color(Integer.parseInt(graph.getProperty("plot.range.grid.line.paint"))));
}
chart.getXYPlot().getDomainAxis().setLabel(graph.getProperty("x.axis"));
chart.getXYPlot().getRangeAxis().setLabel(graph.getProperty("y.axis"));
if (graph.getProperty("auto.resize").equals("true")) {
resize.setSelected(true);
}
else {
resize.setSelected(false);
}
if (graph.containsKey("LogX") && graph.getProperty("LogX").equals("true")) {
LogX.setSelected(true);
}
else {
LogX.setSelected(false);
}
if (graph.containsKey("LogY") && graph.getProperty("LogY").equals("true")) {
LogY.setSelected(true);
}
else {
LogY.setSelected(false);
}
if (graph.containsKey("visibleLegend") && graph.getProperty("visibleLegend").equals("false")) {
visibleLegend.setSelected(false);
}
else {
visibleLegend.setSelected(true);
}
int next = 0;
while (graph.containsKey("species.name." + next)) {
boolean connected, filled, visible;
if (graph.getProperty("species.connected." + next).equals("true")) {
connected = true;
}
else {
connected = false;
}
if (graph.getProperty("species.filled." + next).equals("true")) {
filled = true;
}
else {
filled = false;
}
if (graph.getProperty("species.visible." + next).equals("true")) {
visible = true;
}
else {
visible = false;
}
int xnumber = 0;
if (graph.containsKey("species.xnumber." + next)) {
xnumber = Integer.parseInt(graph.getProperty("species.xnumber." + next));
}
graphed.add(new GraphSpecies(shapes.get(graph.getProperty("species.shape." + next)), graph.getProperty("species.paint." + next)
.trim(), filled, visible, connected, graph.getProperty("species.run.number." + next), graph.getProperty("species.id."
+ next), graph.getProperty("species.name." + next), xnumber,
Integer.parseInt(graph.getProperty("species.number." + next)), graph.getProperty("species.directory." + next)));
next++;
}
updateXNumber = false;
XVariable.addItem("time");
refresh();
}
catch (IOException except) {
JOptionPane.showMessageDialog(Gui.frame, "Unable To Load Graph!", "Error", JOptionPane.ERROR_MESSAGE);
}
}
else {
Properties graph = new Properties();
try {
FileInputStream load = new FileInputStream(new File(filename));
graph.load(load);
load.close();
chart.setTitle(graph.getProperty("title"));
if (graph.containsKey("chart.background.paint")) {
chart.setBackgroundPaint(new Color(Integer.parseInt(graph.getProperty("chart.background.paint"))));
}
if (graph.containsKey("plot.background.paint")) {
chart.getPlot().setBackgroundPaint(new Color(Integer.parseInt(graph.getProperty("plot.background.paint"))));
}
if (graph.containsKey("plot.range.grid.line.paint")) {
chart.getCategoryPlot().setRangeGridlinePaint(new Color(Integer.parseInt(graph.getProperty("plot.range.grid.line.paint"))));
}
chart.getCategoryPlot().getDomainAxis().setLabel(graph.getProperty("x.axis"));
chart.getCategoryPlot().getRangeAxis().setLabel(graph.getProperty("y.axis"));
if (graph.containsKey("gradient") && graph.getProperty("gradient").equals("true")) {
((BarRenderer) chart.getCategoryPlot().getRenderer()).setBarPainter(new GradientBarPainter());
}
else {
((BarRenderer) chart.getCategoryPlot().getRenderer()).setBarPainter(new StandardBarPainter());
}
if (graph.containsKey("shadow") && graph.getProperty("shadow").equals("false")) {
((BarRenderer) chart.getCategoryPlot().getRenderer()).setShadowVisible(false);
}
else {
((BarRenderer) chart.getCategoryPlot().getRenderer()).setShadowVisible(true);
}
if (graph.containsKey("visibleLegend") && graph.getProperty("visibleLegend").equals("false")) {
visibleLegend.setSelected(false);
}
else {
visibleLegend.setSelected(true);
}
int next = 0;
while (graph.containsKey("species.name." + next)) {
String color = graph.getProperty("species.paint." + next).trim();
Paint paint;
if (color.startsWith("Custom_")) {
paint = new Color(Integer.parseInt(color.replace("Custom_", "")));
}
else {
paint = colors.get(color);
}
probGraphed.add(new GraphProbs(paint, color, graph.getProperty("species.id." + next), graph.getProperty("species.name." + next),
Integer.parseInt(graph.getProperty("species.number." + next)), graph.getProperty("species.directory." + next)));
next++;
}
refreshProb();
}
catch (Exception except) {
JOptionPane.showMessageDialog(Gui.frame, "Unable To Load Graph!", "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
public boolean isTSDGraph() {
return timeSeries;
}
public void refresh() {
lock2.lock();
if (timeSeries) {
if (learnSpecs != null) {
updateSpecies();
}
double minY = 0;
double maxY = 0;
double scaleY = 0;
double minX = 0;
double maxX = 0;
double scaleX = 0;
try {
minY = Double.parseDouble(YMin.getText().trim());
maxY = Double.parseDouble(YMax.getText().trim());
scaleY = Double.parseDouble(YScale.getText().trim());
minX = Double.parseDouble(XMin.getText().trim());
maxX = Double.parseDouble(XMax.getText().trim());
scaleX = Double.parseDouble(XScale.getText().trim());
/*
* NumberFormat num = NumberFormat.getInstance();
* num.setMaximumFractionDigits(4); num.setGroupingUsed(false);
* minY = Double.parseDouble(num.format(minY)); maxY =
* Double.parseDouble(num.format(maxY)); scaleY =
* Double.parseDouble(num.format(scaleY)); minX =
* Double.parseDouble(num.format(minX)); maxX =
* Double.parseDouble(num.format(maxX)); scaleX =
* Double.parseDouble(num.format(scaleX));
*/
}
catch (Exception e1) {
}
ArrayList<XYSeries> graphData = new ArrayList<XYSeries>();
XYLineAndShapeRenderer rend = (XYLineAndShapeRenderer) chart.getXYPlot().getRenderer();
int thisOne = -1;
for (int i = 1; i < graphed.size(); i++) {
GraphSpecies index = graphed.get(i);
int j = i;
while ((j > 0) && (graphed.get(j - 1).getSpecies().compareToIgnoreCase(index.getSpecies()) > 0)) {
graphed.set(j, graphed.get(j - 1));
j = j - 1;
}
graphed.set(j, index);
}
ArrayList<GraphSpecies> unableToGraph = new ArrayList<GraphSpecies>();
HashMap<String, ArrayList<ArrayList<Double>>> allData = new HashMap<String, ArrayList<ArrayList<Double>>>();
for (GraphSpecies g : graphed) {
if (g.getDirectory().equals("")) {
thisOne++;
rend.setSeriesVisible(thisOne, true);
rend.setSeriesLinesVisible(thisOne, g.getConnected());
rend.setSeriesShapesFilled(thisOne, g.getFilled());
rend.setSeriesShapesVisible(thisOne, g.getVisible());
rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint());
rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape());
if (!g.getRunNumber().equals("Average") && !g.getRunNumber().equals("Variance") && !g.getRunNumber().equals("Standard Deviation")
&& !g.getRunNumber().equals("Termination Time") && !g.getRunNumber().equals("Percent Termination")
&& !g.getRunNumber().equals("Constraint Termination")) {
if (new File(outDir + separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
readGraphSpecies(outDir + separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8));
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
}
updateXNumber = false;
XVariable.removeAllItems();
for (int i = 0; i < graphSpecies.size(); i++) {
XVariable.addItem(graphSpecies.get(i));
}
updateXNumber = true;
}
else {
data = readData(outDir + separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8),
g.getRunNumber(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
boolean set = false;
for (int i = 1; i < graphSpecies.size(); i++) {
String compare = g.getID().replace(" (", "~");
if (graphSpecies.get(i).equals(compare.split("~")[0].trim())) {
g.setNumber(i - 1);
set = true;
}
}
if (g.getNumber() + 1 < graphSpecies.size() && set) {
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
}
else {
unableToGraph.add(g);
thisOne--;
}
}
else {
unableToGraph.add(g);
thisOne--;
}
}
else {
boolean ableToGraph = false;
try {
for (String s : new File(outDir).list()) {
if (s.length() > 3 && s.substring(0, 4).equals("run-")) {
ableToGraph = true;
}
}
}
catch (Exception e) {
ableToGraph = false;
}
if (!ableToGraph) {
if (g.getRunNumber().equals("Average")
&& new File(outDir + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
ableToGraph = true;
}
else if (g.getRunNumber().equals("Variance")
&& new File(outDir + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
ableToGraph = true;
}
else if (g.getRunNumber().equals("Standard Deviation")
&& new File(outDir + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
ableToGraph = true;
}
else if (g.getRunNumber().equals("Termination Time")
&& new File(outDir + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
ableToGraph = true;
}
else if (g.getRunNumber().equals("Percent Termination")
&& new File(outDir + separator + "percent-term-time" + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
ableToGraph = true;
}
else if (g.getRunNumber().equals("Constraint Termination")
&& new File(outDir + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
ableToGraph = true;
}
else if (g.getRunNumber().equals("Bifurcation Statistics")
&& new File(outDir + separator + "bifurcation" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
ableToGraph = true;
}
}
if (ableToGraph) {
int nextOne = 1;
// while (!new File(outDir + separator + "run-" +
// nextOne + "."
// + printer_id.substring(0, printer_id.length() -
// 8)).exists()) {
// nextOne++;
// }
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
if (g.getRunNumber().equals("Average")
&& new File(outDir + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8));
}
else if (g.getRunNumber().equals("Variance")
&& new File(outDir + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
readGraphSpecies(outDir + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8));
}
else if (g.getRunNumber().equals("Standard Deviation")
&& new File(outDir + separator + "standard_deviation" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + "standard_deviation" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (g.getRunNumber().equals("Termination Time")
&& new File(outDir + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
readGraphSpecies(outDir + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8));
}
else if (g.getRunNumber().equals("Percent Termination")
&& new File(outDir + separator + "percent-term-time" + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
readGraphSpecies(outDir + separator + "percent-term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (g.getRunNumber().equals("Constraint Termination")
&& new File(outDir + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8));
}
else if (g.getRunNumber().equals("Bifurcation Statistics")
&& new File(outDir + separator + "bifurcation" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + "bifurcation" + "." + printer_id.substring(0, printer_id.length() - 8));
}
else {
while (!new File(outDir + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
nextOne++;
}
readGraphSpecies(outDir + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8));
}
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
}
updateXNumber = false;
XVariable.removeAllItems();
for (int i = 0; i < graphSpecies.size(); i++) {
XVariable.addItem(graphSpecies.get(i));
}
updateXNumber = true;
}
else {
if (g.getRunNumber().equals("Average")
&& new File(outDir + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
data = readData(outDir + separator + "mean." + printer_id.substring(0, printer_id.length() - 8), g.getRunNumber()
.toLowerCase(), null, false);
}
else if (g.getRunNumber().equals("Variance")
&& new File(outDir + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
data = readData(outDir + separator + "variance." + printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
}
else if (g.getRunNumber().equals("Standard Deviation")
&& new File(outDir + separator + "standard_deviation" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
data = readData(outDir + separator + "standard_deviation." + printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
}
else if (g.getRunNumber().equals("Termination Time")
&& new File(outDir + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
data = readData(outDir + separator + "term-time." + printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
}
else if (g.getRunNumber().equals("Percent Termination")
&& new File(outDir + separator + "percent-term-time" + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
data = readData(outDir + separator + "percent-term-time." + printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
}
else if (g.getRunNumber().equals("Constraint Termination")
&& new File(outDir + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
data = readData(outDir + separator + "sim-rep." + printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
}
else if (g.getRunNumber().equals("Bifurcation Statistics")
&& new File(outDir + separator + "bifurcation" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
data = readData(outDir + separator + "bifurcation." + printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
}
else {
while (!new File(outDir + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
nextOne++;
}
data = readData(outDir + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
}
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
boolean set = false;
for (int i = 1; i < graphSpecies.size(); i++) {
String compare = g.getID().replace(" (", "~");
if (graphSpecies.get(i).equals(compare.split("~")[0].trim())) {
g.setNumber(i - 1);
set = true;
}
}
if (g.getNumber() + 1 < graphSpecies.size() && set) {
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
}
else {
unableToGraph.add(g);
thisOne--;
}
}
else {
unableToGraph.add(g);
thisOne--;
}
}
}
else {
thisOne++;
rend.setSeriesVisible(thisOne, true);
rend.setSeriesLinesVisible(thisOne, g.getConnected());
rend.setSeriesShapesFilled(thisOne, g.getFilled());
rend.setSeriesShapesVisible(thisOne, g.getVisible());
rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint());
rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape());
if (!g.getRunNumber().equals("Average") && !g.getRunNumber().equals("Variance") && !g.getRunNumber().equals("Standard Deviation")
&& !g.getRunNumber().equals("Termination Time") && !g.getRunNumber().equals("Percent Termination")
&& !g.getRunNumber().equals("Constraint Termination")) {
if (new File(outDir + separator + g.getDirectory() + separator + g.getRunNumber() + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
readGraphSpecies(outDir + separator + g.getDirectory() + separator + g.getRunNumber() + "."
+ printer_id.substring(0, printer_id.length() - 8));
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
}
updateXNumber = false;
XVariable.removeAllItems();
for (int i = 0; i < graphSpecies.size(); i++) {
XVariable.addItem(graphSpecies.get(i));
}
updateXNumber = true;
}
else {
data = readData(
outDir + separator + g.getDirectory() + separator + g.getRunNumber() + "."
+ printer_id.substring(0, printer_id.length() - 8), g.getRunNumber(), g.getDirectory(), false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
boolean set = false;
for (int i = 1; i < graphSpecies.size(); i++) {
String compare = g.getID().replace(" (", "~");
if (graphSpecies.get(i).equals(compare.split("~")[0].trim())) {
g.setNumber(i - 1);
set = true;
}
}
if (g.getNumber() + 1 < graphSpecies.size() && set) {
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
}
else {
unableToGraph.add(g);
thisOne--;
}
}
else {
unableToGraph.add(g);
thisOne--;
}
}
else {
boolean ableToGraph = false;
try {
for (String s : new File(outDir + separator + g.getDirectory()).list()) {
if (s.length() > 3 && s.substring(0, 4).equals("run-")) {
ableToGraph = true;
}
}
}
catch (Exception e) {
ableToGraph = false;
}
if (!ableToGraph) {
if (g.getRunNumber().equals("Average")
&& new File(outDir + separator + g.getDirectory() + separator + "mean" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
ableToGraph = true;
}
else if (g.getRunNumber().equals("Variance")
&& new File(outDir + separator + g.getDirectory() + separator + "variance" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
ableToGraph = true;
}
else if (g.getRunNumber().equals("Standard Deviation")
&& new File(outDir + separator + g.getDirectory() + separator + "standard_deviation" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
ableToGraph = true;
}
else if (g.getRunNumber().equals("Termination Time")
&& new File(outDir + separator + g.getDirectory() + separator + "term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
ableToGraph = true;
}
else if (g.getRunNumber().equals("Percent Termination")
&& new File(outDir + separator + g.getDirectory() + separator + "percent-term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
ableToGraph = true;
}
else if (g.getRunNumber().equals("Constraint Termination")
&& new File(outDir + separator + g.getDirectory() + separator + "sim-rep" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
ableToGraph = true;
}
else if (g.getRunNumber().equals("Bifurcation Statistics")
&& new File(outDir + separator + g.getDirectory() + separator + "bifurcation" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
ableToGraph = true;
}
}
if (ableToGraph) {
int nextOne = 1;
// while (!new File(outDir + separator +
// g.getDirectory() + separator
// + "run-" + nextOne + "."
// + printer_id.substring(0, printer_id.length() -
// 8)).exists()) {
// nextOne++;
// }
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
if (g.getRunNumber().equals("Average")
&& new File(outDir + separator + g.getDirectory() + separator + "mean" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + g.getDirectory() + separator + "mean" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (g.getRunNumber().equals("Variance")
&& new File(outDir + separator + g.getDirectory() + separator + "variance" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + g.getDirectory() + separator + "variance" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (g.getRunNumber().equals("Standard Deviation")
&& new File(outDir + separator + g.getDirectory() + separator + "standard_deviation" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + g.getDirectory() + separator + "standard_deviation" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (g.getRunNumber().equals("Termination Time")
&& new File(outDir + separator + g.getDirectory() + separator + "term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + g.getDirectory() + separator + "term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (g.getRunNumber().equals("Percent Termination")
&& new File(outDir + separator + g.getDirectory() + separator + "percent-term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + g.getDirectory() + separator + "percent-term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (g.getRunNumber().equals("Constraint Termination")
&& new File(outDir + separator + g.getDirectory() + separator + "sim-rep" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + g.getDirectory() + separator + "sim-rep" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (g.getRunNumber().equals("Bifurcation Statistics")
&& new File(outDir + separator + g.getDirectory() + separator + "bifurcation" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + g.getDirectory() + separator + "bifurcation" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else {
while (!new File(outDir + separator + g.getDirectory() + separator + "run-" + nextOne + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
nextOne++;
}
readGraphSpecies(outDir + separator + g.getDirectory() + separator + "run-" + nextOne + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
}
updateXNumber = false;
XVariable.removeAllItems();
for (int i = 0; i < graphSpecies.size(); i++) {
XVariable.addItem(graphSpecies.get(i));
}
updateXNumber = true;
}
else {
if (g.getRunNumber().equals("Average")
&& new File(outDir + separator + g.getDirectory() + separator + "mean" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
data = readData(
outDir + separator + g.getDirectory() + separator + "mean."
+ printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false);
}
else if (g.getRunNumber().equals("Variance")
&& new File(outDir + separator + g.getDirectory() + separator + "variance" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
data = readData(
outDir + separator + g.getDirectory() + separator + "variance."
+ printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false);
}
else if (g.getRunNumber().equals("Standard Deviation")
&& new File(outDir + separator + g.getDirectory() + separator + "standard_deviation" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
data = readData(
outDir + separator + g.getDirectory() + separator + "standard_deviation."
+ printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false);
}
else if (g.getRunNumber().equals("Termination Time")
&& new File(outDir + separator + g.getDirectory() + separator + "term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
data = readData(
outDir + separator + g.getDirectory() + separator + "term-time."
+ printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false);
}
else if (g.getRunNumber().equals("Percent Termination")
&& new File(outDir + separator + g.getDirectory() + separator + "percent-term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
data = readData(
outDir + separator + g.getDirectory() + separator + "percent-term-time."
+ printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false);
}
else if (g.getRunNumber().equals("Constraint Termination")
&& new File(outDir + separator + g.getDirectory() + separator + "sim-rep" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
data = readData(
outDir + separator + g.getDirectory() + separator + "sim-rep."
+ printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false);
}
else if (g.getRunNumber().equals("Bifurcation Statistics")
&& new File(outDir + separator + g.getDirectory() + separator + "bifurcation" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
data = readData(
outDir + separator + g.getDirectory() + separator + "bifurcation."
+ printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false);
}
else {
while (!new File(outDir + separator + g.getDirectory() + separator + "run-" + nextOne + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
nextOne++;
}
data = readData(
outDir + separator + g.getDirectory() + separator + "run-" + nextOne + "."
+ printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(),
g.getDirectory(), false);
}
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
boolean set = false;
for (int i = 1; i < graphSpecies.size(); i++) {
String compare = g.getID().replace(" (", "~");
if (graphSpecies.get(i).equals(compare.split("~")[0].trim())) {
g.setNumber(i - 1);
set = true;
}
}
if (g.getNumber() + 1 < graphSpecies.size() && set) {
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
}
else {
unableToGraph.add(g);
thisOne--;
}
}
else {
unableToGraph.add(g);
thisOne--;
}
}
}
}
for (GraphSpecies g : unableToGraph) {
graphed.remove(g);
}
XYSeriesCollection dataset = new XYSeriesCollection();
for (int i = 0; i < graphData.size(); i++) {
dataset.addSeries(graphData.get(i));
}
fixGraph(chart.getTitle().getText(), chart.getXYPlot().getDomainAxis().getLabel(), chart.getXYPlot().getRangeAxis().getLabel(), dataset);
chart.getXYPlot().setRenderer(rend);
XYPlot plot = chart.getXYPlot();
if (resize.isSelected()) {
resize(dataset);
}
else {
NumberAxis axis = (NumberAxis) plot.getRangeAxis();
axis.setAutoTickUnitSelection(false);
axis.setRange(minY, maxY);
axis.setTickUnit(new NumberTickUnit(scaleY));
axis = (NumberAxis) plot.getDomainAxis();
axis.setAutoTickUnitSelection(false);
axis.setRange(minX, maxX);
axis.setTickUnit(new NumberTickUnit(scaleX));
}
}
else {
BarRenderer rend = (BarRenderer) chart.getCategoryPlot().getRenderer();
int thisOne = -1;
for (int i = 1; i < probGraphed.size(); i++) {
GraphProbs index = probGraphed.get(i);
int j = i;
while ((j > 0) && (probGraphed.get(j - 1).getSpecies().compareToIgnoreCase(index.getSpecies()) > 0)) {
probGraphed.set(j, probGraphed.get(j - 1));
j = j - 1;
}
probGraphed.set(j, index);
}
ArrayList<GraphProbs> unableToGraph = new ArrayList<GraphProbs>();
DefaultCategoryDataset histDataset = new DefaultCategoryDataset();
for (GraphProbs g : probGraphed) {
if (g.getDirectory().equals("")) {
thisOne++;
rend.setSeriesPaint(thisOne, g.getPaint());
if (new File(outDir + separator + "sim-rep.txt").exists()) {
readProbSpecies(outDir + separator + "sim-rep.txt");
double[] data = readProbs(outDir + separator + "sim-rep.txt");
for (int i = 1; i < graphProbs.size(); i++) {
String index = graphProbs.get(i);
double index2 = data[i];
int j = i;
while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) {
graphProbs.set(j, graphProbs.get(j - 1));
data[j] = data[j - 1];
j = j - 1;
}
graphProbs.set(j, index);
data[j] = index2;
}
if (graphProbs.size() != 0) {
if (graphProbs.contains(g.getID())) {
for (int i = 0; i < graphProbs.size(); i++) {
if (g.getID().equals(graphProbs.get(i))) {
g.setNumber(i);
histDataset.setValue(data[i], g.getSpecies(), "");
}
}
}
else {
unableToGraph.add(g);
thisOne--;
}
}
}
else {
unableToGraph.add(g);
thisOne--;
}
}
else {
thisOne++;
rend.setSeriesPaint(thisOne, g.getPaint());
if (new File(outDir + separator + g.getDirectory() + separator + "sim-rep.txt").exists()) {
readProbSpecies(outDir + separator + g.getDirectory() + separator + "sim-rep.txt");
double[] data = readProbs(outDir + separator + g.getDirectory() + separator + "sim-rep.txt");
for (int i = 1; i < graphProbs.size(); i++) {
String index = graphProbs.get(i);
double index2 = data[i];
int j = i;
while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) {
graphProbs.set(j, graphProbs.get(j - 1));
data[j] = data[j - 1];
j = j - 1;
}
graphProbs.set(j, index);
data[j] = index2;
}
if (graphProbs.size() != 0) {
String compare = g.getID().replace(" (", "~");
if (graphProbs.contains(compare.split("~")[0].trim())) {
for (int i = 0; i < graphProbs.size(); i++) {
if (compare.split("~")[0].trim().equals(graphProbs.get(i))) {
g.setNumber(i);
histDataset.setValue(data[i], g.getSpecies(), "");
}
}
}
else {
unableToGraph.add(g);
thisOne--;
}
}
}
else {
unableToGraph.add(g);
thisOne--;
}
}
}
for (GraphProbs g : unableToGraph) {
probGraphed.remove(g);
}
fixProbGraph(chart.getTitle().getText(), chart.getCategoryPlot().getDomainAxis().getLabel(), chart.getCategoryPlot().getRangeAxis()
.getLabel(), histDataset, rend);
}
lock2.unlock();
}
private class ShapeAndPaint {
private Shape shape;
private Paint paint;
private ShapeAndPaint(Shape s, String p) {
shape = s;
if (p.startsWith("Custom_")) {
paint = new Color(Integer.parseInt(p.replace("Custom_", "")));
}
else {
paint = colors.get(p);
}
}
private Shape getShape() {
return shape;
}
private Paint getPaint() {
return paint;
}
private String getShapeName() {
Object[] set = shapes.keySet().toArray();
for (int i = 0; i < set.length; i++) {
if (shape == shapes.get(set[i])) {
return (String) set[i];
}
}
return "Unknown Shape";
}
private String getPaintName() {
Object[] set = colors.keySet().toArray();
for (int i = 0; i < set.length; i++) {
if (paint == colors.get(set[i])) {
return (String) set[i];
}
}
return "Custom_" + ((Color) paint).getRGB();
}
public void setPaint(String paint) {
if (paint.startsWith("Custom_")) {
this.paint = new Color(Integer.parseInt(paint.replace("Custom_", "")));
}
else {
this.paint = colors.get(paint);
}
}
public void setShape(String shape) {
this.shape = shapes.get(shape);
}
}
private class GraphSpecies {
private ShapeAndPaint sP;
private boolean filled, visible, connected;
private String runNumber, species, directory, id;
private int xnumber, number;
private GraphSpecies(Shape s, String p, boolean filled, boolean visible, boolean connected, String runNumber, String id, String species,
int xnumber, int number, String directory) {
sP = new ShapeAndPaint(s, p);
this.filled = filled;
this.visible = visible;
this.connected = connected;
this.runNumber = runNumber;
this.species = species;
this.xnumber = xnumber;
this.number = number;
this.directory = directory;
this.id = id;
}
private void setDirectory(String directory) {
this.directory = directory;
}
private void setXNumber(int xnumber) {
this.xnumber = xnumber;
}
private void setNumber(int number) {
this.number = number;
}
private void setSpecies(String species) {
this.species = species;
}
private void setPaint(String paint) {
sP.setPaint(paint);
}
private void setShape(String shape) {
sP.setShape(shape);
}
private void setVisible(boolean b) {
visible = b;
}
private void setFilled(boolean b) {
filled = b;
}
private void setConnected(boolean b) {
connected = b;
}
private int getXNumber() {
return xnumber;
}
private int getNumber() {
return number;
}
private String getSpecies() {
return species;
}
private ShapeAndPaint getShapeAndPaint() {
return sP;
}
private boolean getFilled() {
return filled;
}
private boolean getVisible() {
return visible;
}
private boolean getConnected() {
return connected;
}
private String getRunNumber() {
return runNumber;
}
private String getDirectory() {
return directory;
}
private String getID() {
return id;
}
}
public void setDirectory(String newDirectory) {
outDir = newDirectory;
}
public void setGraphName(String graphName) {
this.graphName = graphName;
}
public boolean hasChanged() {
return change;
}
private void probGraph(String label) {
chart = ChartFactory.createBarChart(label, "", "Percent", new DefaultCategoryDataset(), PlotOrientation.VERTICAL, true, true, false);
((BarRenderer) chart.getCategoryPlot().getRenderer()).setBarPainter(new StandardBarPainter());
chart.setBackgroundPaint(new java.awt.Color(238, 238, 238));
chart.getPlot().setBackgroundPaint(java.awt.Color.WHITE);
chart.getCategoryPlot().setRangeGridlinePaint(java.awt.Color.LIGHT_GRAY);
legend = chart.getLegend();
visibleLegend = new JCheckBox("Visible Legend");
visibleLegend.setSelected(true);
ChartPanel graph = new ChartPanel(chart);
graph.setLayout(new GridLayout(1, 1));
JLabel edit = new JLabel("Double click here to create graph");
edit.addMouseListener(this);
Font font = edit.getFont();
font = font.deriveFont(Font.BOLD, 42.0f);
edit.setFont(font);
edit.setHorizontalAlignment(SwingConstants.CENTER);
graph.add(edit);
graph.addMouseListener(this);
change = false;
// creates the buttons for the graph frame
JPanel ButtonHolder = new JPanel();
run = new JButton("Save and Run");
save = new JButton("Save Graph");
saveAs = new JButton("Save As");
export = new JButton("Export");
refresh = new JButton("Refresh");
run.addActionListener(this);
save.addActionListener(this);
saveAs.addActionListener(this);
export.addActionListener(this);
refresh.addActionListener(this);
if (reb2sac != null) {
ButtonHolder.add(run);
}
ButtonHolder.add(save);
ButtonHolder.add(saveAs);
ButtonHolder.add(export);
ButtonHolder.add(refresh);
// puts all the components of the graph gui into a display panel
// JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
// ButtonHolder, null);
// splitPane.setDividerSize(0);
this.removeAll();
this.setLayout(new BorderLayout());
this.add(graph, "Center");
// this.add(splitPane, "South");
}
private void editProbGraph() {
final ArrayList<GraphProbs> old = new ArrayList<GraphProbs>();
for (GraphProbs g : probGraphed) {
old.add(g);
}
final JPanel titlePanel = new JPanel(new BorderLayout());
JLabel titleLabel = new JLabel("Title:");
JLabel xLabel = new JLabel("X-Axis Label:");
JLabel yLabel = new JLabel("Y-Axis Label:");
final JCheckBox gradient = new JCheckBox("Paint In Gradient Style");
gradient.setSelected(!(((BarRenderer) chart.getCategoryPlot().getRenderer()).getBarPainter() instanceof StandardBarPainter));
final JCheckBox shadow = new JCheckBox("Paint Bar Shadows");
shadow.setSelected(((BarRenderer) chart.getCategoryPlot().getRenderer()).getShadowsVisible());
visibleLegend.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (((JCheckBox) e.getSource()).isSelected()) {
if (chart.getLegend() == null) {
chart.addLegend(legend);
}
}
else {
if (chart.getLegend() != null) {
legend = chart.getLegend();
}
chart.removeLegend();
}
}
});
final JTextField title = new JTextField(chart.getTitle().getText(), 5);
final JTextField x = new JTextField(chart.getCategoryPlot().getDomainAxis().getLabel(), 5);
final JTextField y = new JTextField(chart.getCategoryPlot().getRangeAxis().getLabel(), 5);
String simDirString = outDir.split(separator)[outDir.split(separator).length - 1];
simDir = new IconNode(simDirString, simDirString);
simDir.setIconName("");
String[] files = new File(outDir).list();
// for (int i = 1; i < files.length; i++) {
// String index = files[i];
// int j = i;
// while ((j > 0) && files[j - 1].compareToIgnoreCase(index) > 0) {
// files[j] = files[j - 1];
// j = j - 1;
// }
// files[j] = index;
// }
boolean add = false;
final ArrayList<String> directories = new ArrayList<String>();
for (String file : files) {
if (file.length() > 3 && file.substring(file.length() - 4).equals(".txt")) {
if (file.contains("sim-rep")) {
add = true;
}
}
else if (new File(outDir + separator + file).isDirectory()) {
boolean addIt = false;
for (String getFile : new File(outDir + separator + file).list()) {
if (getFile.length() > 3 && getFile.substring(getFile.length() - 4).equals(".txt") && getFile.contains("sim-rep")) {
addIt = true;
}
else if (new File(outDir + separator + file + separator + getFile).isDirectory()) {
for (String getFile2 : new File(outDir + separator + file + separator + getFile).list()) {
if (getFile2.length() > 3 && getFile2.substring(getFile2.length() - 4).equals(".txt") && getFile2.contains("sim-rep")) {
addIt = true;
}
}
}
}
if (addIt) {
directories.add(file);
IconNode d = new IconNode(file, file);
d.setIconName("");
String[] files2 = new File(outDir + separator + file).list();
// for (int i = 1; i < files2.length; i++) {
// String index = files2[i];
// int j = i;
// while ((j > 0) && files2[j -
// 1].compareToIgnoreCase(index) > 0) {
// files2[j] = files2[j - 1];
// j = j - 1;
// }
// files2[j] = index;
// }
boolean add2 = false;
for (String f : files2) {
if (f.equals("sim-rep.txt")) {
add2 = true;
}
else if (new File(outDir + separator + file + separator + f).isDirectory()) {
boolean addIt2 = false;
for (String getFile : new File(outDir + separator + file + separator + f).list()) {
if (getFile.length() > 3 && getFile.substring(getFile.length() - 4).equals(".txt") && getFile.contains("sim-rep")) {
addIt2 = true;
}
}
if (addIt2) {
directories.add(file + separator + f);
IconNode d2 = new IconNode(f, f);
d2.setIconName("");
for (String f2 : new File(outDir + separator + file + separator + f).list()) {
if (f2.equals("sim-rep.txt")) {
IconNode n = new IconNode(f2.substring(0, f2.length() - 4), f2.substring(0, f2.length() - 4));
d2.add(n);
n.setIconName("");
for (GraphProbs g : probGraphed) {
if (g.getDirectory().equals(d.getName() + separator + d2.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d2.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d2.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
}
boolean added = false;
for (int j = 0; j < d.getChildCount(); j++) {
if ((d.getChildAt(j).toString().compareToIgnoreCase(d2.toString()) > 0)
|| new File(outDir + separator + d.toString() + separator + (d.getChildAt(j).toString() + ".txt"))
.isFile()) {
d.insert(d2, j);
added = true;
break;
}
}
if (!added) {
d.add(d2);
}
}
}
}
if (add2) {
IconNode n = new IconNode("sim-rep", "sim-rep");
d.add(n);
n.setIconName("");
for (GraphProbs g : probGraphed) {
if (g.getDirectory().equals(d.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
boolean added = false;
for (int j = 0; j < simDir.getChildCount(); j++) {
if ((simDir.getChildAt(j).toString().compareToIgnoreCase(d.toString()) > 0)
|| new File(outDir + separator + (simDir.getChildAt(j).toString() + ".txt")).isFile()) {
simDir.insert(d, j);
added = true;
break;
}
}
if (!added) {
simDir.add(d);
}
}
}
}
if (add) {
IconNode n = new IconNode("sim-rep", "sim-rep");
simDir.add(n);
n.setIconName("");
for (GraphProbs g : probGraphed) {
if (g.getDirectory().equals("")) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (simDir.getChildCount() == 0) {
JOptionPane.showMessageDialog(Gui.frame, "No data to graph." + "\nPerform some simulations to create some data first.", "No Data",
JOptionPane.PLAIN_MESSAGE);
}
else {
tree = new JTree(simDir);
tree.putClientProperty("JTree.icons", makeIcons());
tree.setCellRenderer(new IconNodeRenderer());
DefaultTreeCellRenderer renderer = (DefaultTreeCellRenderer) tree.getCellRenderer();
renderer.setLeafIcon(MetalIconFactory.getTreeLeafIcon());
renderer.setClosedIcon(MetalIconFactory.getTreeFolderIcon());
renderer.setOpenIcon(MetalIconFactory.getTreeFolderIcon());
final JPanel all = new JPanel(new BorderLayout());
final JScrollPane scroll = new JScrollPane();
tree.addTreeExpansionListener(new TreeExpansionListener() {
public void treeCollapsed(TreeExpansionEvent e) {
JScrollPane scrollpane = new JScrollPane();
scrollpane.getViewport().add(tree);
all.removeAll();
all.add(titlePanel, "North");
all.add(scroll, "Center");
all.add(scrollpane, "West");
all.revalidate();
all.repaint();
}
public void treeExpanded(TreeExpansionEvent e) {
JScrollPane scrollpane = new JScrollPane();
scrollpane.getViewport().add(tree);
all.removeAll();
all.add(titlePanel, "North");
all.add(scroll, "Center");
all.add(scrollpane, "West");
all.revalidate();
all.repaint();
}
});
// for (int i = 0; i < tree.getRowCount(); i++) {
// tree.expandRow(i);
// }
JScrollPane scrollpane = new JScrollPane();
scrollpane.getViewport().add(tree);
scrollpane.setPreferredSize(new Dimension(175, 100));
final JPanel specPanel = new JPanel();
boolean stop = false;
int selectionRow = 1;
for (int i = 1; i < tree.getRowCount(); i++) {
tree.setSelectionRow(i);
if (selected.equals(lastSelected)) {
stop = true;
selectionRow = i;
break;
}
}
tree.addTreeSelectionListener(new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
node = (IconNode) e.getPath().getLastPathComponent();
if (!directories.contains(node.getName())) {
selected = node.getName();
int select;
if (selected.equals("sim-rep")) {
select = 0;
}
else {
select = -1;
}
if (select != -1) {
specPanel.removeAll();
if (node.getParent().getParent() != null
&& directories.contains(((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName())) {
specPanel.add(fixProbChoices(((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName()));
}
else if (directories.contains(((IconNode) node.getParent()).getName())) {
specPanel.add(fixProbChoices(((IconNode) node.getParent()).getName()));
}
else {
specPanel.add(fixProbChoices(""));
}
specPanel.revalidate();
specPanel.repaint();
for (int i = 0; i < series.size(); i++) {
series.get(i).setText(graphProbs.get(i));
series.get(i).setSelectionStart(0);
series.get(i).setSelectionEnd(0);
}
for (int i = 0; i < boxes.size(); i++) {
boxes.get(i).setSelected(false);
}
if (node.getParent().getParent() != null
&& directories.contains(((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName())) {
for (GraphProbs g : probGraphed) {
if (g.getDirectory()
.equals(((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName())) {
boxes.get(g.getNumber()).setSelected(true);
series.get(g.getNumber()).setText(g.getSpecies());
series.get(g.getNumber()).setSelectionStart(0);
series.get(g.getNumber()).setSelectionEnd(0);
colorsButtons.get(g.getNumber()).setBackground((Color) g.getPaint());
colorsButtons.get(g.getNumber()).setForeground((Color) g.getPaint());
colorsCombo.get(g.getNumber()).setSelectedItem(g.getPaintName().split("_")[0]);
}
}
}
else if (directories.contains(((IconNode) node.getParent()).getName())) {
for (GraphProbs g : probGraphed) {
if (g.getDirectory().equals(((IconNode) node.getParent()).getName())) {
boxes.get(g.getNumber()).setSelected(true);
series.get(g.getNumber()).setText(g.getSpecies());
series.get(g.getNumber()).setSelectionStart(0);
series.get(g.getNumber()).setSelectionEnd(0);
colorsButtons.get(g.getNumber()).setBackground((Color) g.getPaint());
colorsButtons.get(g.getNumber()).setForeground((Color) g.getPaint());
colorsCombo.get(g.getNumber()).setSelectedItem(g.getPaintName().split("_")[0]);
}
}
}
else {
for (GraphProbs g : probGraphed) {
if (g.getDirectory().equals("")) {
boxes.get(g.getNumber()).setSelected(true);
series.get(g.getNumber()).setText(g.getSpecies());
series.get(g.getNumber()).setSelectionStart(0);
series.get(g.getNumber()).setSelectionEnd(0);
colorsButtons.get(g.getNumber()).setBackground((Color) g.getPaint());
colorsButtons.get(g.getNumber()).setForeground((Color) g.getPaint());
colorsCombo.get(g.getNumber()).setSelectedItem(g.getPaintName().split("_")[0]);
}
}
}
boolean allChecked = true;
for (int i = 0; i < boxes.size(); i++) {
if (!boxes.get(i).isSelected()) {
allChecked = false;
String s = "";
if (node.getParent().getParent() != null
&& directories.contains(((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName())) {
s = "(" + ((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName() + ")";
}
else if (directories.contains(((IconNode) node.getParent()).getName())) {
s = "(" + ((IconNode) node.getParent()).getName() + ")";
}
String text = series.get(i).getText();
String end = "";
if (!s.equals("")) {
if (text.length() >= s.length()) {
for (int j = 0; j < s.length(); j++) {
end = text.charAt(text.length() - 1 - j) + end;
}
if (!s.equals(end)) {
text += " " + s;
}
}
else {
text += " " + s;
}
}
boxes.get(i).setName(text);
series.get(i).setText(text);
series.get(i).setSelectionStart(0);
series.get(i).setSelectionEnd(0);
colorsCombo.get(i).setSelectedIndex(0);
colorsButtons.get(i).setBackground((Color) colors.get("Black"));
colorsButtons.get(i).setForeground((Color) colors.get("Black"));
}
else {
String s = "";
if (node.getParent().getParent() != null
&& directories.contains(((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName())) {
s = "(" + ((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName() + ")";
}
else if (directories.contains(((IconNode) node.getParent()).getName())) {
s = "(" + ((IconNode) node.getParent()).getName() + ")";
}
String text = graphProbs.get(i);
String end = "";
if (!s.equals("")) {
if (text.length() >= s.length()) {
for (int j = 0; j < s.length(); j++) {
end = text.charAt(text.length() - 1 - j) + end;
}
if (!s.equals(end)) {
text += " " + s;
}
}
else {
text += " " + s;
}
}
boxes.get(i).setName(text);
}
}
if (allChecked) {
use.setSelected(true);
}
else {
use.setSelected(false);
}
}
}
else {
specPanel.removeAll();
specPanel.revalidate();
specPanel.repaint();
}
}
});
if (!stop) {
tree.setSelectionRow(0);
tree.setSelectionRow(1);
}
else {
tree.setSelectionRow(0);
tree.setSelectionRow(selectionRow);
}
scroll.setPreferredSize(new Dimension(1050, 500));
JPanel editPanel = new JPanel(new BorderLayout());
editPanel.add(specPanel, "Center");
scroll.setViewportView(editPanel);
final JButton deselect = new JButton("Deselect All");
deselect.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int size = probGraphed.size();
for (int i = 0; i < size; i++) {
probGraphed.remove();
}
IconNode n = simDir;
while (n != null) {
if (n.isLeaf()) {
n.setIcon(MetalIconFactory.getTreeLeafIcon());
n.setIconName("");
IconNode check = (IconNode) ((DefaultMutableTreeNode) n.getParent()).getChildAfter(n);
if (check == null) {
n = (IconNode) n.getParent();
if (n.getParent() == null) {
n = null;
}
else {
IconNode check2 = (IconNode) ((DefaultMutableTreeNode) n.getParent()).getChildAfter(n);
if (check2 == null) {
n = (IconNode) n.getParent();
if (n.getParent() == null) {
n = null;
}
else {
n = (IconNode) ((DefaultMutableTreeNode) n.getParent()).getChildAfter(n);
}
}
else {
n = check2;
}
}
}
else {
n = check;
}
}
else {
n.setIcon(MetalIconFactory.getTreeFolderIcon());
n.setIconName("");
n = (IconNode) n.getChildAt(0);
}
}
tree.revalidate();
tree.repaint();
if (tree.getSelectionCount() > 0) {
int selectedRow = tree.getSelectionRows()[0];
tree.setSelectionRow(0);
tree.setSelectionRow(selectedRow);
}
}
});
JPanel titlePanel1 = new JPanel(new GridLayout(1, 6));
JPanel titlePanel2 = new JPanel(new GridLayout(1, 6));
titlePanel1.add(titleLabel);
titlePanel1.add(title);
titlePanel1.add(xLabel);
titlePanel1.add(x);
titlePanel1.add(yLabel);
titlePanel1.add(y);
JPanel deselectPanel = new JPanel();
deselectPanel.add(deselect);
titlePanel2.add(deselectPanel);
titlePanel2.add(gradient);
titlePanel2.add(shadow);
titlePanel2.add(visibleLegend);
titlePanel2.add(new JPanel());
titlePanel2.add(new JPanel());
titlePanel.add(titlePanel1, "Center");
titlePanel.add(titlePanel2, "South");
all.add(titlePanel, "North");
all.add(scroll, "Center");
all.add(scrollpane, "West");
Object[] options = { "Ok", "Cancel" };
int value = JOptionPane.showOptionDialog(Gui.frame, all, "Edit Probability Graph", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE,
null, options, options[0]);
if (value == JOptionPane.YES_OPTION) {
change = true;
lastSelected = selected;
selected = "";
BarRenderer rend = (BarRenderer) chart.getCategoryPlot().getRenderer();
if (gradient.isSelected()) {
rend.setBarPainter(new GradientBarPainter());
}
else {
rend.setBarPainter(new StandardBarPainter());
}
if (shadow.isSelected()) {
rend.setShadowVisible(true);
}
else {
rend.setShadowVisible(false);
}
int thisOne = -1;
for (int i = 1; i < probGraphed.size(); i++) {
GraphProbs index = probGraphed.get(i);
int j = i;
while ((j > 0) && (probGraphed.get(j - 1).getSpecies().compareToIgnoreCase(index.getSpecies()) > 0)) {
probGraphed.set(j, probGraphed.get(j - 1));
j = j - 1;
}
probGraphed.set(j, index);
}
ArrayList<GraphProbs> unableToGraph = new ArrayList<GraphProbs>();
DefaultCategoryDataset histDataset = new DefaultCategoryDataset();
for (GraphProbs g : probGraphed) {
if (g.getDirectory().equals("")) {
thisOne++;
rend.setSeriesPaint(thisOne, g.getPaint());
if (new File(outDir + separator + "sim-rep.txt").exists()) {
readProbSpecies(outDir + separator + "sim-rep.txt");
double[] data = readProbs(outDir + separator + "sim-rep.txt");
for (int i = 1; i < graphProbs.size(); i++) {
String index = graphProbs.get(i);
double index2 = data[i];
int j = i;
while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) {
graphProbs.set(j, graphProbs.get(j - 1));
data[j] = data[j - 1];
j = j - 1;
}
graphProbs.set(j, index);
data[j] = index2;
}
if (graphProbs.size() != 0) {
for (int i = 0; i < graphProbs.size(); i++) {
if (g.getID().equals(graphProbs.get(i))) {
histDataset.setValue(data[i], g.getSpecies(), "");
}
}
}
}
else {
unableToGraph.add(g);
thisOne--;
}
}
else {
thisOne++;
rend.setSeriesPaint(thisOne, g.getPaint());
if (new File(outDir + separator + g.getDirectory() + separator + "sim-rep.txt").exists()) {
readProbSpecies(outDir + separator + g.getDirectory() + separator + "sim-rep.txt");
double[] data = readProbs(outDir + separator + g.getDirectory() + separator + "sim-rep.txt");
for (int i = 1; i < graphProbs.size(); i++) {
String index = graphProbs.get(i);
double index2 = data[i];
int j = i;
while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) {
graphProbs.set(j, graphProbs.get(j - 1));
data[j] = data[j - 1];
j = j - 1;
}
graphProbs.set(j, index);
data[j] = index2;
}
if (graphProbs.size() != 0) {
for (int i = 0; i < graphProbs.size(); i++) {
String compare = g.getID().replace(" (", "~");
if (compare.split("~")[0].trim().equals(graphProbs.get(i))) {
histDataset.setValue(data[i], g.getSpecies(), "");
}
}
}
}
else {
unableToGraph.add(g);
thisOne--;
}
}
}
for (GraphProbs g : unableToGraph) {
probGraphed.remove(g);
}
fixProbGraph(title.getText().trim(), x.getText().trim(), y.getText().trim(), histDataset, rend);
}
else {
selected = "";
int size = probGraphed.size();
for (int i = 0; i < size; i++) {
probGraphed.remove();
}
for (GraphProbs g : old) {
probGraphed.add(g);
}
}
}
}
private JPanel fixProbChoices(final String directory) {
if (directory.equals("")) {
readProbSpecies(outDir + separator + "sim-rep.txt");
}
else {
readProbSpecies(outDir + separator + directory + separator + "sim-rep.txt");
}
for (int i = 1; i < graphProbs.size(); i++) {
String index = graphProbs.get(i);
int j = i;
while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) {
graphProbs.set(j, graphProbs.get(j - 1));
j = j - 1;
}
graphProbs.set(j, index);
}
JPanel speciesPanel1 = new JPanel(new GridLayout(graphProbs.size() + 1, 1));
JPanel speciesPanel2 = new JPanel(new GridLayout(graphProbs.size() + 1, 2));
use = new JCheckBox("Use");
JLabel specs = new JLabel("Constraint");
JLabel color = new JLabel("Color");
boxes = new ArrayList<JCheckBox>();
series = new ArrayList<JTextField>();
colorsCombo = new ArrayList<JComboBox>();
colorsButtons = new ArrayList<JButton>();
use.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (use.isSelected()) {
for (JCheckBox box : boxes) {
if (!box.isSelected()) {
box.doClick();
}
}
}
else {
for (JCheckBox box : boxes) {
if (box.isSelected()) {
box.doClick();
}
}
}
}
});
speciesPanel1.add(use);
speciesPanel2.add(specs);
speciesPanel2.add(color);
final HashMap<String, Paint> colory = this.colors;
for (int i = 0; i < graphProbs.size(); i++) {
JCheckBox temp = new JCheckBox();
temp.setActionCommand("" + i);
temp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
if (((JCheckBox) e.getSource()).isSelected()) {
node.setIcon(TextIcons.getIcon("g"));
node.setIconName("" + (char) 10003);
IconNode n = ((IconNode) node.getParent());
while (n != null) {
n.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
n.setIconName("" + (char) 10003);
if (n.getParent() == null) {
n = null;
}
else {
n = ((IconNode) n.getParent());
}
}
tree.revalidate();
tree.repaint();
String s = series.get(i).getText();
((JCheckBox) e.getSource()).setSelected(false);
int[] cols = new int[35];
for (int k = 0; k < boxes.size(); k++) {
if (boxes.get(k).isSelected()) {
if (colorsCombo.get(k).getSelectedItem().equals("Red")) {
cols[0]++;
colorsButtons.get(k).setBackground((Color) colory.get("Red"));
colorsButtons.get(k).setForeground((Color) colory.get("Red"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Blue")) {
cols[1]++;
colorsButtons.get(k).setBackground((Color) colory.get("Blue"));
colorsButtons.get(k).setForeground((Color) colory.get("Blue"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Green")) {
cols[2]++;
colorsButtons.get(k).setBackground((Color) colory.get("Green"));
colorsButtons.get(k).setForeground((Color) colory.get("Green"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Yellow")) {
cols[3]++;
colorsButtons.get(k).setBackground((Color) colory.get("Yellow"));
colorsButtons.get(k).setForeground((Color) colory.get("Yellow"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Magenta")) {
cols[4]++;
colorsButtons.get(k).setBackground((Color) colory.get("Magenta"));
colorsButtons.get(k).setForeground((Color) colory.get("Magenta"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Cyan")) {
cols[5]++;
colorsButtons.get(k).setBackground((Color) colory.get("Cyan"));
colorsButtons.get(k).setForeground((Color) colory.get("Cyan"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Tan")) {
cols[6]++;
colorsButtons.get(k).setBackground((Color) colory.get("Tan"));
colorsButtons.get(k).setForeground((Color) colory.get("Tan"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Gray (Dark)")) {
cols[7]++;
colorsButtons.get(k).setBackground((Color) colory.get("Gray (Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Gray (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Red (Dark)")) {
cols[8]++;
colorsButtons.get(k).setBackground((Color) colory.get("Red (Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Red (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Blue (Dark)")) {
cols[9]++;
colorsButtons.get(k).setBackground((Color) colory.get("Blue (Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Blue (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Green (Dark)")) {
cols[10]++;
colorsButtons.get(k).setBackground((Color) colory.get("Green (Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Green (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Yellow (Dark)")) {
cols[11]++;
colorsButtons.get(k).setBackground((Color) colory.get("Yellow (Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Yellow (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Magenta (Dark)")) {
cols[12]++;
colorsButtons.get(k).setBackground((Color) colory.get("Magenta (Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Magenta (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Cyan (Dark)")) {
cols[13]++;
colorsButtons.get(k).setBackground((Color) colory.get("Cyan (Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Cyan (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Black")) {
cols[14]++;
colorsButtons.get(k).setBackground((Color) colory.get("Black"));
colorsButtons.get(k).setForeground((Color) colory.get("Black"));
}
/*
* else if
* (colorsCombo.get(k).getSelectedItem().
* equals("Red ")) { cols[15]++; } else if
* (colorsCombo
* .get(k).getSelectedItem().equals("Blue ")) {
* cols[16]++; } else if
* (colorsCombo.get(k).getSelectedItem
* ().equals("Green ")) { cols[17]++; } else if
* (colorsCombo.get(k).getSelectedItem().equals(
* "Yellow ")) { cols[18]++; } else if
* (colorsCombo
* .get(k).getSelectedItem().equals("Magenta "))
* { cols[19]++; } else if
* (colorsCombo.get(k).getSelectedItem
* ().equals("Cyan ")) { cols[20]++; }
*/
else if (colorsCombo.get(k).getSelectedItem().equals("Gray")) {
cols[21]++;
colorsButtons.get(k).setBackground((Color) colory.get("Gray"));
colorsButtons.get(k).setForeground((Color) colory.get("Gray"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Red (Extra Dark)")) {
cols[22]++;
colorsButtons.get(k).setBackground((Color) colory.get("Red (Extra Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Red (Extra Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Blue (Extra Dark)")) {
cols[23]++;
colorsButtons.get(k).setBackground((Color) colory.get("Blue (Extra Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Blue (Extra Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Green (Extra Dark)")) {
cols[24]++;
colorsButtons.get(k).setBackground((Color) colory.get("Green (Extra Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Green (Extra Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Yellow (Extra Dark)")) {
cols[25]++;
colorsButtons.get(k).setBackground((Color) colory.get("Yellow (Extra Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Yellow (Extra Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Magenta (Extra Dark)")) {
cols[26]++;
colorsButtons.get(k).setBackground((Color) colory.get("Magenta (Extra Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Magenta (Extra Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Cyan (Extra Dark)")) {
cols[27]++;
colorsButtons.get(k).setBackground((Color) colory.get("Cyan (Extra Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Cyan (Extra Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Red (Light)")) {
cols[28]++;
colorsButtons.get(k).setBackground((Color) colory.get("Red (Light)"));
colorsButtons.get(k).setForeground((Color) colory.get("Red (Light)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Blue (Light)")) {
cols[29]++;
colorsButtons.get(k).setBackground((Color) colory.get("Blue (Light)"));
colorsButtons.get(k).setForeground((Color) colory.get("Blue (Light)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Green (Light)")) {
cols[30]++;
colorsButtons.get(k).setBackground((Color) colory.get("Green (Light)"));
colorsButtons.get(k).setForeground((Color) colory.get("Green (Light)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Yellow (Light)")) {
cols[31]++;
colorsButtons.get(k).setBackground((Color) colory.get("Yellow (Light)"));
colorsButtons.get(k).setForeground((Color) colory.get("Yellow (Light)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Magenta (Light)")) {
cols[32]++;
colorsButtons.get(k).setBackground((Color) colory.get("Magenta (Light)"));
colorsButtons.get(k).setForeground((Color) colory.get("Magenta (Light)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Cyan (Light)")) {
cols[33]++;
colorsButtons.get(k).setBackground((Color) colory.get("Cyan (Light)"));
colorsButtons.get(k).setForeground((Color) colory.get("Cyan (Light)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Gray (Light)")) {
cols[34]++;
colorsButtons.get(k).setBackground((Color) colory.get("Gray (Light)"));
colorsButtons.get(k).setForeground((Color) colory.get("Gray (Light)"));
}
}
}
for (GraphProbs graph : probGraphed) {
if (graph.getPaintName().equals("Red")) {
cols[0]++;
}
else if (graph.getPaintName().equals("Blue")) {
cols[1]++;
}
else if (graph.getPaintName().equals("Green")) {
cols[2]++;
}
else if (graph.getPaintName().equals("Yellow")) {
cols[3]++;
}
else if (graph.getPaintName().equals("Magenta")) {
cols[4]++;
}
else if (graph.getPaintName().equals("Cyan")) {
cols[5]++;
}
else if (graph.getPaintName().equals("Tan")) {
cols[6]++;
}
else if (graph.getPaintName().equals("Gray (Dark)")) {
cols[7]++;
}
else if (graph.getPaintName().equals("Red (Dark)")) {
cols[8]++;
}
else if (graph.getPaintName().equals("Blue (Dark)")) {
cols[9]++;
}
else if (graph.getPaintName().equals("Green (Dark)")) {
cols[10]++;
}
else if (graph.getPaintName().equals("Yellow (Dark)")) {
cols[11]++;
}
else if (graph.getPaintName().equals("Magenta (Dark)")) {
cols[12]++;
}
else if (graph.getPaintName().equals("Cyan (Dark)")) {
cols[13]++;
}
else if (graph.getPaintName().equals("Black")) {
cols[14]++;
}
/*
* else if (graph.getPaintName().equals("Red ")) {
* cols[15]++; } else if
* (graph.getPaintName().equals("Blue ")) {
* cols[16]++; } else if
* (graph.getPaintName().equals("Green ")) {
* cols[17]++; } else if
* (graph.getPaintName().equals("Yellow ")) {
* cols[18]++; } else if
* (graph.getPaintName().equals("Magenta ")) {
* cols[19]++; } else if
* (graph.getPaintName().equals("Cyan ")) {
* cols[20]++; }
*/
else if (graph.getPaintName().equals("Gray")) {
cols[21]++;
}
else if (graph.getPaintName().equals("Red (Extra Dark)")) {
cols[22]++;
}
else if (graph.getPaintName().equals("Blue (Extra Dark)")) {
cols[23]++;
}
else if (graph.getPaintName().equals("Green (Extra Dark)")) {
cols[24]++;
}
else if (graph.getPaintName().equals("Yellow (Extra Dark)")) {
cols[25]++;
}
else if (graph.getPaintName().equals("Magenta (Extra Dark)")) {
cols[26]++;
}
else if (graph.getPaintName().equals("Cyan (Extra Dark)")) {
cols[27]++;
}
else if (graph.getPaintName().equals("Red (Light)")) {
cols[28]++;
}
else if (graph.getPaintName().equals("Blue (Light)")) {
cols[29]++;
}
else if (graph.getPaintName().equals("Green (Light)")) {
cols[30]++;
}
else if (graph.getPaintName().equals("Yellow (Light)")) {
cols[31]++;
}
else if (graph.getPaintName().equals("Magenta (Light)")) {
cols[32]++;
}
else if (graph.getPaintName().equals("Cyan (Light)")) {
cols[33]++;
}
else if (graph.getPaintName().equals("Gray (Light)")) {
cols[34]++;
}
}
((JCheckBox) e.getSource()).setSelected(true);
series.get(i).setText(s);
series.get(i).setSelectionStart(0);
series.get(i).setSelectionEnd(0);
int colorSet = 0;
for (int j = 1; j < cols.length; j++) {
if ((j < 15 || j > 20) && cols[j] < cols[colorSet]) {
colorSet = j;
}
}
DefaultDrawingSupplier draw = new DefaultDrawingSupplier();
Paint paint;
if (colorSet == 34) {
paint = colors.get("Gray (Light)");
}
else {
for (int j = 0; j < colorSet; j++) {
draw.getNextPaint();
}
paint = draw.getNextPaint();
}
Object[] set = colory.keySet().toArray();
for (int j = 0; j < set.length; j++) {
if (paint == colory.get(set[j])) {
colorsCombo.get(i).setSelectedItem(set[j]);
colorsButtons.get(i).setBackground((Color) paint);
colorsButtons.get(i).setForeground((Color) paint);
}
}
boolean allChecked = true;
for (JCheckBox temp : boxes) {
if (!temp.isSelected()) {
allChecked = false;
}
}
if (allChecked) {
use.setSelected(true);
}
String color = (String) colorsCombo.get(i).getSelectedItem();
if (color.equals("Custom")) {
color += "_" + colorsButtons.get(i).getBackground().getRGB();
}
probGraphed.add(new GraphProbs(colorsButtons.get(i).getBackground(), color, boxes.get(i).getName(), series.get(i).getText()
.trim(), i, directory));
}
else {
boolean check = false;
for (JCheckBox b : boxes) {
if (b.isSelected()) {
check = true;
}
}
if (!check) {
node.setIcon(MetalIconFactory.getTreeLeafIcon());
node.setIconName("");
boolean check2 = false;
IconNode parent = ((IconNode) node.getParent());
while (parent != null) {
for (int j = 0; j < parent.getChildCount(); j++) {
if (((IconNode) parent.getChildAt(j)).getIconName().equals("" + (char) 10003)) {
check2 = true;
}
}
if (!check2) {
parent.setIcon(MetalIconFactory.getTreeFolderIcon());
parent.setIconName("");
}
check2 = false;
if (parent.getParent() == null) {
parent = null;
}
else {
parent = ((IconNode) parent.getParent());
}
}
tree.revalidate();
tree.repaint();
}
ArrayList<GraphProbs> remove = new ArrayList<GraphProbs>();
for (GraphProbs g : probGraphed) {
if (g.getNumber() == i && g.getDirectory().equals(directory)) {
remove.add(g);
}
}
for (GraphProbs g : remove) {
probGraphed.remove(g);
}
use.setSelected(false);
colorsCombo.get(i).setSelectedIndex(0);
colorsButtons.get(i).setBackground((Color) colory.get("Black"));
colorsButtons.get(i).setForeground((Color) colory.get("Black"));
}
}
});
boxes.add(temp);
JTextField seriesName = new JTextField(graphProbs.get(i));
seriesName.setName("" + i);
seriesName.addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) {
int i = Integer.parseInt(((JTextField) e.getSource()).getName());
for (GraphProbs g : probGraphed) {
if (g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setSpecies(((JTextField) e.getSource()).getText());
}
}
}
public void keyReleased(KeyEvent e) {
int i = Integer.parseInt(((JTextField) e.getSource()).getName());
for (GraphProbs g : probGraphed) {
if (g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setSpecies(((JTextField) e.getSource()).getText());
}
}
}
public void keyTyped(KeyEvent e) {
int i = Integer.parseInt(((JTextField) e.getSource()).getName());
for (GraphProbs g : probGraphed) {
if (g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setSpecies(((JTextField) e.getSource()).getText());
}
}
}
});
series.add(seriesName);
ArrayList<String> allColors = new ArrayList<String>();
for (String c : this.colors.keySet()) {
allColors.add(c);
}
allColors.add("Custom");
Object[] col = allColors.toArray();
Arrays.sort(col);
JComboBox colBox = new JComboBox(col);
colBox.setActionCommand("" + i);
colBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
if (!((JComboBox) (e.getSource())).getSelectedItem().equals("Custom")) {
colorsButtons.get(i).setBackground((Color) colors.get(((JComboBox) (e.getSource())).getSelectedItem()));
colorsButtons.get(i).setForeground((Color) colors.get(((JComboBox) (e.getSource())).getSelectedItem()));
for (GraphProbs g : probGraphed) {
if (g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setPaintName((String) ((JComboBox) e.getSource()).getSelectedItem());
g.setPaint(colory.get(((JComboBox) e.getSource()).getSelectedItem()));
}
}
}
else {
for (GraphProbs g : probGraphed) {
if (g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setPaintName("Custom_" + colorsButtons.get(i).getBackground().getRGB());
g.setPaint(colorsButtons.get(i).getBackground());
}
}
}
}
});
colorsCombo.add(colBox);
JButton colorButton = new JButton();
colorButton.setPreferredSize(new Dimension(30, 20));
colorButton.setBorder(BorderFactory.createLineBorder(Color.darkGray));
colorButton.setBackground((Color) colory.get("Black"));
colorButton.setForeground((Color) colory.get("Black"));
colorButton.setUI(new MetalButtonUI());
colorButton.setActionCommand("" + i);
colorButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
Color newColor = JColorChooser.showDialog(Gui.frame, "Choose Color", ((JButton) e.getSource()).getBackground());
if (newColor != null) {
((JButton) e.getSource()).setBackground(newColor);
((JButton) e.getSource()).setForeground(newColor);
colorsCombo.get(i).setSelectedItem("Custom");
}
}
});
colorsButtons.add(colorButton);
JPanel colorPanel = new JPanel(new BorderLayout());
colorPanel.add(colorsCombo.get(i), "Center");
colorPanel.add(colorsButtons.get(i), "East");
speciesPanel1.add(boxes.get(i));
speciesPanel2.add(series.get(i));
speciesPanel2.add(colorPanel);
}
JPanel speciesPanel = new JPanel(new BorderLayout());
speciesPanel.add(speciesPanel1, "West");
speciesPanel.add(speciesPanel2, "Center");
return speciesPanel;
}
private void readProbSpecies(String file) {
graphProbs = new ArrayList<String>();
ArrayList<String> data = new ArrayList<String>();
try {
Scanner s = new Scanner(new File(file));
while (s.hasNextLine()) {
String[] ss = s.nextLine().split(" ");
if (ss[0].equals("The") && ss[1].equals("total") && ss[2].equals("termination") && ss[3].equals("count:") && ss[4].equals("0")) {
return;
}
if (data.size() == 0) {
for (String add : ss) {
data.add(add);
}
}
else {
for (int i = 0; i < ss.length; i++) {
data.set(i, data.get(i) + " " + ss[i]);
}
}
}
}
catch (Exception e) {
}
for (String s : data) {
if (!s.split(" ")[0].equals("#total")) {
graphProbs.add(s.split(" ")[0]);
}
}
}
private double[] readProbs(String file) {
ArrayList<String> data = new ArrayList<String>();
try {
Scanner s = new Scanner(new File(file));
while (s.hasNextLine()) {
String[] ss = s.nextLine().split(" ");
if (ss[0].equals("The") && ss[1].equals("total") && ss[2].equals("termination") && ss[3].equals("count:") && ss[4].equals("0")) {
return new double[0];
}
if (data.size() == 0) {
for (String add : ss) {
data.add(add);
}
}
else {
for (int i = 0; i < ss.length; i++) {
data.set(i, data.get(i) + " " + ss[i]);
}
}
}
}
catch (Exception e) {
}
double[] dataSet = new double[data.size()];
double total = 0;
int i = 0;
if (data.get(0).split(" ")[0].equals("#total")) {
total = Double.parseDouble(data.get(0).split(" ")[1]);
i = 1;
}
for (; i < data.size(); i++) {
if (total == 0) {
dataSet[i] = Double.parseDouble(data.get(i).split(" ")[1]);
}
else {
dataSet[i - 1] = 100 * ((Double.parseDouble(data.get(i).split(" ")[1])) / total);
}
}
return dataSet;
}
private void fixProbGraph(String label, String xLabel, String yLabel, DefaultCategoryDataset dataset, BarRenderer rend) {
Paint chartBackground = chart.getBackgroundPaint();
Paint plotBackground = chart.getPlot().getBackgroundPaint();
Paint plotRangeGridLine = chart.getCategoryPlot().getRangeGridlinePaint();
chart = ChartFactory.createBarChart(label, xLabel, yLabel, dataset, PlotOrientation.VERTICAL, true, true, false);
chart.getCategoryPlot().setRenderer(rend);
chart.setBackgroundPaint(chartBackground);
chart.getPlot().setBackgroundPaint(plotBackground);
chart.getCategoryPlot().setRangeGridlinePaint(plotRangeGridLine);
ChartPanel graph = new ChartPanel(chart);
legend = chart.getLegend();
if (visibleLegend.isSelected()) {
if (chart.getLegend() == null) {
chart.addLegend(legend);
}
}
else {
if (chart.getLegend() != null) {
legend = chart.getLegend();
}
chart.removeLegend();
}
if (probGraphed.isEmpty()) {
graph.setLayout(new GridLayout(1, 1));
JLabel edit = new JLabel("Double click here to create graph");
edit.addMouseListener(this);
Font font = edit.getFont();
font = font.deriveFont(Font.BOLD, 42.0f);
edit.setFont(font);
edit.setHorizontalAlignment(SwingConstants.CENTER);
graph.add(edit);
}
graph.addMouseListener(this);
JPanel ButtonHolder = new JPanel();
run = new JButton("Save and Run");
save = new JButton("Save Graph");
saveAs = new JButton("Save As");
export = new JButton("Export");
refresh = new JButton("Refresh");
run.addActionListener(this);
save.addActionListener(this);
saveAs.addActionListener(this);
export.addActionListener(this);
refresh.addActionListener(this);
if (reb2sac != null) {
ButtonHolder.add(run);
}
ButtonHolder.add(save);
ButtonHolder.add(saveAs);
ButtonHolder.add(export);
ButtonHolder.add(refresh);
// JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
// ButtonHolder, null);
// splitPane.setDividerSize(0);
this.removeAll();
this.setLayout(new BorderLayout());
this.add(graph, "Center");
// this.add(splitPane, "South");
this.revalidate();
}
public void refreshProb() {
BarRenderer rend = (BarRenderer) chart.getCategoryPlot().getRenderer();
int thisOne = -1;
for (int i = 1; i < probGraphed.size(); i++) {
GraphProbs index = probGraphed.get(i);
int j = i;
while ((j > 0) && (probGraphed.get(j - 1).getSpecies().compareToIgnoreCase(index.getSpecies()) > 0)) {
probGraphed.set(j, probGraphed.get(j - 1));
j = j - 1;
}
probGraphed.set(j, index);
}
ArrayList<GraphProbs> unableToGraph = new ArrayList<GraphProbs>();
DefaultCategoryDataset histDataset = new DefaultCategoryDataset();
for (GraphProbs g : probGraphed) {
if (g.getDirectory().equals("")) {
thisOne++;
rend.setSeriesPaint(thisOne, g.getPaint());
if (new File(outDir + separator + "sim-rep.txt").exists()) {
readProbSpecies(outDir + separator + "sim-rep.txt");
double[] data = readProbs(outDir + separator + "sim-rep.txt");
for (int i = 1; i < graphProbs.size(); i++) {
String index = graphProbs.get(i);
double index2 = data[i];
int j = i;
while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) {
graphProbs.set(j, graphProbs.get(j - 1));
data[j] = data[j - 1];
j = j - 1;
}
graphProbs.set(j, index);
data[j] = index2;
}
if (graphProbs.size() != 0) {
for (int i = 0; i < graphProbs.size(); i++) {
if (g.getID().equals(graphProbs.get(i))) {
g.setNumber(i);
histDataset.setValue(data[i], g.getSpecies(), "");
}
}
}
}
else {
unableToGraph.add(g);
thisOne--;
}
}
else {
thisOne++;
rend.setSeriesPaint(thisOne, g.getPaint());
if (new File(outDir + separator + g.getDirectory() + separator + "sim-rep.txt").exists()) {
readProbSpecies(outDir + separator + g.getDirectory() + separator + "sim-rep.txt");
double[] data = readProbs(outDir + separator + g.getDirectory() + separator + "sim-rep.txt");
for (int i = 1; i < graphProbs.size(); i++) {
String index = graphProbs.get(i);
double index2 = data[i];
int j = i;
while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) {
graphProbs.set(j, graphProbs.get(j - 1));
data[j] = data[j - 1];
j = j - 1;
}
graphProbs.set(j, index);
data[j] = index2;
}
if (graphProbs.size() != 0) {
for (int i = 0; i < graphProbs.size(); i++) {
String compare = g.getID().replace(" (", "~");
if (compare.split("~")[0].trim().equals(graphProbs.get(i))) {
histDataset.setValue(data[i], g.getSpecies(), "");
}
}
}
}
else {
unableToGraph.add(g);
thisOne--;
}
}
}
for (GraphProbs g : unableToGraph) {
probGraphed.remove(g);
}
fixProbGraph(chart.getTitle().getText(), chart.getCategoryPlot().getDomainAxis().getLabel(), chart.getCategoryPlot().getRangeAxis()
.getLabel(), histDataset, rend);
}
private void updateSpecies() {
String background;
try {
Properties p = new Properties();
String[] split = outDir.split(separator);
FileInputStream load = new FileInputStream(new File(outDir + separator + split[split.length - 1] + ".lrn"));
p.load(load);
load.close();
if (p.containsKey("genenet.file")) {
String[] getProp = p.getProperty("genenet.file").split(separator);
background = outDir.substring(0, outDir.length() - split[split.length - 1].length()) + separator + getProp[getProp.length - 1];
}
else if (p.containsKey("learn.file")) {
String[] getProp = p.getProperty("learn.file").split(separator);
background = outDir.substring(0, outDir.length() - split[split.length - 1].length()) + separator + getProp[getProp.length - 1];
}
else {
background = null;
}
}
catch (Exception e) {
JOptionPane.showMessageDialog(Gui.frame, "Unable to load background file.", "Error", JOptionPane.ERROR_MESSAGE);
background = null;
}
learnSpecs = new ArrayList<String>();
if (background != null) {
if (background.contains(".gcm")) {
BioModel gcm = new BioModel(biomodelsim.getRoot());
gcm.load(background);
learnSpecs = gcm.getSpecies();
}
else if (background.contains(".lpn")) {
LhpnFile lhpn = new LhpnFile(biomodelsim.log);
lhpn.load(background);
/*
HashMap<String, Properties> speciesMap = lhpn.getContinuous();
* for (String s : speciesMap.keySet()) { learnSpecs.add(s); }
*/
// ADDED BY SB.
TSDParser extractVars;
ArrayList<String> datFileVars = new ArrayList<String>();
// ArrayList<String> allVars = new ArrayList<String>();
Boolean varPresent = false;
// Finding the intersection of all the variables present in all
// data files.
for (int i = 1; (new File(outDir + separator + "run-" + i + ".tsd")).exists(); i++) {
extractVars = new TSDParser(outDir + separator + "run-" + i + ".tsd", false);
datFileVars = extractVars.getSpecies();
if (i == 1) {
learnSpecs.addAll(datFileVars);
}
for (String s : learnSpecs) {
varPresent = false;
for (String t : datFileVars) {
if (s.equalsIgnoreCase(t)) {
varPresent = true;
break;
}
}
if (!varPresent) {
learnSpecs.remove(s);
}
}
}
// END ADDED BY SB.
}
else {
SBMLDocument document = Gui.readSBML(background);
Model model = document.getModel();
ListOf ids = model.getListOfSpecies();
for (int i = 0; i < model.getNumSpecies(); i++) {
learnSpecs.add(((Species) ids.get(i)).getId());
}
}
}
for (int i = 0; i < learnSpecs.size(); i++) {
String index = learnSpecs.get(i);
int j = i;
while ((j > 0) && learnSpecs.get(j - 1).compareToIgnoreCase(index) > 0) {
learnSpecs.set(j, learnSpecs.get(j - 1));
j = j - 1;
}
learnSpecs.set(j, index);
}
}
public boolean getWarning() {
return warn;
}
private class GraphProbs {
private Paint paint;
private String species, directory, id, paintName;
private int number;
private GraphProbs(Paint paint, String paintName, String id, String species, int number, String directory) {
this.paint = paint;
this.paintName = paintName;
this.species = species;
this.number = number;
this.directory = directory;
this.id = id;
}
private Paint getPaint() {
return paint;
}
private void setPaint(Paint p) {
paint = p;
}
private String getPaintName() {
return paintName;
}
private void setPaintName(String p) {
paintName = p;
}
private String getSpecies() {
return species;
}
private void setSpecies(String s) {
species = s;
}
private String getDirectory() {
return directory;
}
private String getID() {
return id;
}
private int getNumber() {
return number;
}
private void setNumber(int n) {
number = n;
}
}
private Hashtable makeIcons() {
Hashtable<String, Icon> icons = new Hashtable<String, Icon>();
icons.put("floppyDrive", MetalIconFactory.getTreeFloppyDriveIcon());
icons.put("hardDrive", MetalIconFactory.getTreeHardDriveIcon());
icons.put("computer", MetalIconFactory.getTreeComputerIcon());
icons.put("c", TextIcons.getIcon("c"));
icons.put("java", TextIcons.getIcon("java"));
icons.put("html", TextIcons.getIcon("html"));
return icons;
}
}
class IconNodeRenderer extends DefaultTreeCellRenderer {
/**
*
*/
private static final long serialVersionUID = -940588131120912851L;
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) {
super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
Icon icon = ((IconNode) value).getIcon();
if (icon == null) {
Hashtable icons = (Hashtable) tree.getClientProperty("JTree.icons");
String name = ((IconNode) value).getIconName();
if ((icons != null) && (name != null)) {
icon = (Icon) icons.get(name);
if (icon != null) {
setIcon(icon);
}
}
}
else {
setIcon(icon);
}
return this;
}
}
class IconNode extends DefaultMutableTreeNode {
/**
*
*/
private static final long serialVersionUID = 2887169888272379817L;
protected Icon icon;
protected String iconName;
private String hiddenName;
public IconNode() {
this(null, "");
}
public IconNode(Object userObject, String name) {
this(userObject, true, null, name);
}
public IconNode(Object userObject, boolean allowsChildren, Icon icon, String name) {
super(userObject, allowsChildren);
this.icon = icon;
hiddenName = name;
}
public String getName() {
return hiddenName;
}
public void setName(String name) {
hiddenName = name;
}
public void setIcon(Icon icon) {
this.icon = icon;
}
public Icon getIcon() {
return icon;
}
public String getIconName() {
if (iconName != null) {
return iconName;
}
else {
String str = userObject.toString();
int index = str.lastIndexOf(".");
if (index != -1) {
return str.substring(++index);
}
else {
return null;
}
}
}
public void setIconName(String name) {
iconName = name;
}
}
class TextIcons extends MetalIconFactory.TreeLeafIcon {
/**
*
*/
private static final long serialVersionUID = 1623303213056273064L;
protected String label;
private static Hashtable<String, String> labels;
protected TextIcons() {
}
public void paintIcon(Component c, Graphics g, int x, int y) {
super.paintIcon(c, g, x, y);
if (label != null) {
FontMetrics fm = g.getFontMetrics();
int offsetX = (getIconWidth() - fm.stringWidth(label)) / 2;
int offsetY = (getIconHeight() - fm.getHeight()) / 2 - 2;
g.drawString(label, x + offsetX, y + offsetY + fm.getHeight());
}
}
public static Icon getIcon(String str) {
if (labels == null) {
labels = new Hashtable<String, String>();
setDefaultSet();
}
TextIcons icon = new TextIcons();
icon.label = (String) labels.get(str);
return icon;
}
public static void setLabelSet(String ext, String label) {
if (labels == null) {
labels = new Hashtable<String, String>();
setDefaultSet();
}
labels.put(ext, label);
}
private static void setDefaultSet() {
labels.put("c", "C");
labels.put("java", "J");
labels.put("html", "H");
labels.put("htm", "H");
labels.put("g", "" + (char) 10003);
// and so on
/*
* labels.put("txt" ,"TXT"); labels.put("TXT" ,"TXT"); labels.put("cc"
* ,"C++"); labels.put("C" ,"C++"); labels.put("cpp" ,"C++");
* labels.put("exe" ,"BIN"); labels.put("class" ,"BIN");
* labels.put("gif" ,"GIF"); labels.put("GIF" ,"GIF");
*
* labels.put("", "");
*/
}
}
|
gui/src/graph/Graph.java
|
package graph;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.Paint;
import java.awt.Shape;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.Properties;
import java.util.Scanner;
import java.util.concurrent.locks.ReentrantLock;
import java.util.prefs.Preferences;
import javax.swing.BorderFactory;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JColorChooser;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JTree;
import javax.swing.SwingConstants;
import javax.swing.event.TreeExpansionEvent;
import javax.swing.event.TreeExpansionListener;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.plaf.metal.MetalButtonUI;
import javax.swing.plaf.metal.MetalIconFactory;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.TreePath;
import lpn.parser.LhpnFile;
import main.Gui;
import main.Log;
import main.util.Utility;
import main.util.dataparser.DTSDParser;
import main.util.dataparser.DataParser;
import main.util.dataparser.TSDParser;
import org.apache.batik.dom.GenericDOMImplementation;
import org.apache.batik.svggen.SVGGraphics2D;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.axis.LogarithmicAxis;
import org.jfree.chart.axis.NumberTickUnit;
import org.jfree.chart.axis.StandardTickUnitSource;
import org.jfree.chart.event.ChartProgressEvent;
import org.jfree.chart.event.ChartProgressListener;
import org.jfree.chart.plot.DefaultDrawingSupplier;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.category.BarRenderer;
import org.jfree.chart.renderer.category.GradientBarPainter;
import org.jfree.chart.renderer.category.StandardBarPainter;
import org.jfree.chart.renderer.xy.XYItemRenderer;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.chart.title.LegendTitle;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.xy.XYDataItem;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
import org.jibble.epsgraphics.EpsGraphics2D;
import org.sbml.libsbml.ListOf;
import org.sbml.libsbml.Model;
import org.sbml.libsbml.SBMLDocument;
import org.sbml.libsbml.Species;
import org.w3c.dom.DOMImplementation;
import analysis.AnalysisView;
import biomodel.parser.BioModel;
import com.lowagie.text.Document;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.DefaultFontMapper;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfTemplate;
import com.lowagie.text.pdf.PdfWriter;
/**
* This is the Graph class. It takes in data and draws a graph of that data. The
* Graph class implements the ActionListener class, the ChartProgressListener
* class, and the MouseListener class. This allows the Graph class to perform
* actions when buttons are pressed, when the chart is drawn, or when the chart
* is clicked.
*
* @author Curtis Madsen
*/
public class Graph extends JPanel implements ActionListener, MouseListener, ChartProgressListener {
private static final long serialVersionUID = 4350596002373546900L;
private JFreeChart chart; // Graph of the output data
private XYSeriesCollection curData; // Data in the current graph
private String outDir; // output directory
private String printer_id; // printer id
/*
* Text fields used to change the graph window
*/
private JTextField XMin, XMax, XScale, YMin, YMax, YScale;
private ArrayList<String> graphSpecies; // names of species in the graph
private Gui biomodelsim; // tstubd gui
private JButton save, run, saveAs;
private JButton export, refresh; // buttons
// private JButton exportJPeg, exportPng, exportPdf, exportEps, exportSvg,
// exportCsv; // buttons
private HashMap<String, Paint> colors;
private HashMap<String, Shape> shapes;
private String selected, lastSelected;
private LinkedList<GraphSpecies> graphed;
private LinkedList<GraphProbs> probGraphed;
private JCheckBox resize;
private JComboBox XVariable;
private JCheckBox LogX, LogY;
private JCheckBox visibleLegend;
private LegendTitle legend;
private Log log;
private ArrayList<JCheckBox> boxes;
private ArrayList<JTextField> series;
private ArrayList<JComboBox> colorsCombo;
private ArrayList<JButton> colorsButtons;
private ArrayList<JComboBox> shapesCombo;
private ArrayList<JCheckBox> connected;
private ArrayList<JCheckBox> visible;
private ArrayList<JCheckBox> filled;
private JCheckBox use;
private JCheckBox connectedLabel;
private JCheckBox visibleLabel;
private JCheckBox filledLabel;
private String graphName;
private String separator;
private boolean change;
private boolean timeSeries;
private boolean topLevel;
private ArrayList<String> graphProbs;
private JTree tree;
private IconNode node, simDir;
private AnalysisView reb2sac; // reb2sac options
private ArrayList<String> learnSpecs;
private boolean warn;
private ArrayList<String> averageOrder;
private JPopupMenu popup; // popup menu
private ArrayList<String> directories;
private JPanel specPanel;
private JScrollPane scrollpane;
private JPanel all;
private JPanel titlePanel;
private JScrollPane scroll;
private boolean updateXNumber;
private final ReentrantLock lock, lock2;
/**
* Creates a Graph Object from the data given and calls the private graph
* helper method.
*/
public Graph(AnalysisView reb2sac, String printer_track_quantity, String label, String printer_id, String outDir, String time, Gui biomodelsim,
String open, Log log, String graphName, boolean timeSeries, boolean learnGraph) {
lock = new ReentrantLock(true);
lock2 = new ReentrantLock(true);
this.reb2sac = reb2sac;
averageOrder = null;
popup = new JPopupMenu();
warn = false;
if (File.separator.equals("\\")) {
separator = "\\\\";
}
else {
separator = File.separator;
}
// initializes member variables
this.log = log;
this.timeSeries = timeSeries;
if (graphName != null) {
this.graphName = graphName;
topLevel = true;
}
else {
if (timeSeries) {
this.graphName = outDir.split(separator)[outDir.split(separator).length - 1] + ".grf";
}
else {
this.graphName = outDir.split(separator)[outDir.split(separator).length - 1] + ".prb";
}
topLevel = false;
}
this.outDir = outDir;
this.printer_id = printer_id;
this.biomodelsim = biomodelsim;
XYSeriesCollection data = new XYSeriesCollection();
if (learnGraph) {
updateSpecies();
}
else {
learnSpecs = null;
}
// graph the output data
if (timeSeries) {
setUpShapesAndColors();
graphed = new LinkedList<GraphSpecies>();
selected = "";
lastSelected = "";
graph(printer_track_quantity, label, data, time);
if (open != null) {
open(open);
}
}
else {
setUpShapesAndColors();
probGraphed = new LinkedList<GraphProbs>();
selected = "";
lastSelected = "";
probGraph(label);
if (open != null) {
open(open);
}
}
}
/**
* This private helper method calls the private readData method, sets up a
* graph frame, and graphs the data.
*
* @param dataset
* @param time
*/
private void graph(String printer_track_quantity, String label, XYSeriesCollection dataset, String time) {
chart = ChartFactory.createXYLineChart(label, time, printer_track_quantity, dataset, PlotOrientation.VERTICAL, true, true, false);
chart.setBackgroundPaint(new java.awt.Color(238, 238, 238));
chart.getPlot().setBackgroundPaint(java.awt.Color.WHITE);
chart.getXYPlot().setDomainGridlinePaint(java.awt.Color.LIGHT_GRAY);
chart.getXYPlot().setRangeGridlinePaint(java.awt.Color.LIGHT_GRAY);
chart.addProgressListener(this);
legend = chart.getLegend();
ChartPanel graph = new ChartPanel(chart);
graph.setLayout(new GridLayout(1, 1));
JLabel edit = new JLabel("Double click here to create graph");
edit.addMouseListener(this);
Font font = edit.getFont();
font = font.deriveFont(Font.BOLD, 42.0f);
edit.setFont(font);
edit.setHorizontalAlignment(SwingConstants.CENTER);
graph.add(edit);
graph.addMouseListener(this);
change = false;
// creates text fields for changing the graph's dimensions
resize = new JCheckBox("Auto Resize");
resize.setSelected(true);
XVariable = new JComboBox();
Dimension dim = new Dimension(1,1);
XVariable.setPreferredSize(dim);
updateXNumber = false;
XVariable.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (updateXNumber && node != null) {
String curDir = "";
if (node.getParent().getParent() != null
&& directories.contains(((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName())) {
curDir = ((IconNode) node.getParent().getParent()).getName() + separator + ((IconNode) node.getParent()).getName();
}
else if (directories.contains(((IconNode) node.getParent()).getName())) {
curDir = ((IconNode) node.getParent()).getName();
}
else {
curDir = "";
}
for (int i = 0; i < graphed.size(); i++) {
if (graphed.get(i).getDirectory().equals(curDir)) {
graphed.get(i).setXNumber(XVariable.getSelectedIndex());
}
}
}
}
});
LogX = new JCheckBox("LogX");
LogX.setSelected(false);
LogY = new JCheckBox("LogY");
LogY.setSelected(false);
visibleLegend = new JCheckBox("Visible Legend");
visibleLegend.setSelected(true);
XMin = new JTextField();
XMax = new JTextField();
XScale = new JTextField();
YMin = new JTextField();
YMax = new JTextField();
YScale = new JTextField();
// creates the buttons for the graph frame
JPanel ButtonHolder = new JPanel();
run = new JButton("Save and Run");
save = new JButton("Save Graph");
saveAs = new JButton("Save As");
saveAs.addActionListener(this);
export = new JButton("Export");
refresh = new JButton("Refresh");
// exportJPeg = new JButton("Export As JPEG");
// exportPng = new JButton("Export As PNG");
// exportPdf = new JButton("Export As PDF");
// exportEps = new JButton("Export As EPS");
// exportSvg = new JButton("Export As SVG");
// exportCsv = new JButton("Export As CSV");
run.addActionListener(this);
save.addActionListener(this);
export.addActionListener(this);
refresh.addActionListener(this);
// exportJPeg.addActionListener(this);
// exportPng.addActionListener(this);
// exportPdf.addActionListener(this);
// exportEps.addActionListener(this);
// exportSvg.addActionListener(this);
// exportCsv.addActionListener(this);
if (reb2sac != null) {
ButtonHolder.add(run);
}
ButtonHolder.add(save);
ButtonHolder.add(saveAs);
ButtonHolder.add(export);
ButtonHolder.add(refresh);
// ButtonHolder.add(exportJPeg);
// ButtonHolder.add(exportPng);
// ButtonHolder.add(exportPdf);
// ButtonHolder.add(exportEps);
// ButtonHolder.add(exportSvg);
// ButtonHolder.add(exportCsv);
// puts all the components of the graph gui into a display panel
// JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
// ButtonHolder, null);
// splitPane.setDividerSize(0);
this.removeAll();
this.setLayout(new BorderLayout());
this.add(graph, "Center");
// this.add(splitPane, "South");
// determines maximum and minimum values and resizes
resize(dataset);
this.revalidate();
}
private void readGraphSpecies(String file) {
Gui.frame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
if (file.contains(".dtsd"))
graphSpecies = (new DTSDParser(file)).getSpecies();
else
graphSpecies = new TSDParser(file, true).getSpecies();
Gui.frame.setCursor(null);
if (learnSpecs != null) {
for (String spec : learnSpecs) {
if (!graphSpecies.contains(spec)) {
graphSpecies.add(spec);
}
}
for (int i = 1; i < graphSpecies.size(); i++) {
if (!learnSpecs.contains(graphSpecies.get(i))) {
graphSpecies.remove(i);
i--;
}
}
}
}
/**
* This public helper method parses the output file of ODE, monte carlo, and
* markov abstractions.
*/
public ArrayList<ArrayList<Double>> readData(String file, String label, String directory, boolean warning) {
warn = warning;
String[] s = file.split(separator);
String getLast = s[s.length - 1];
String stem = "";
int t = 0;
try {
while (!Character.isDigit(getLast.charAt(t))) {
stem += getLast.charAt(t);
t++;
}
}
catch (Exception e) {
}
if ((label.contains("average") && file.contains("mean")) || (label.contains("variance") && file.contains("variance"))
|| (label.contains("deviation") && file.contains("standard_deviation"))) {
Gui.frame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
TSDParser p = new TSDParser(file, warn);
Gui.frame.setCursor(null);
warn = p.getWarning();
graphSpecies = p.getSpecies();
ArrayList<ArrayList<Double>> data = p.getData();
if (learnSpecs != null) {
for (String spec : learnSpecs) {
if (!graphSpecies.contains(spec)) {
graphSpecies.add(spec);
ArrayList<Double> d = new ArrayList<Double>();
for (int i = 0; i < data.get(0).size(); i++) {
d.add(0.0);
}
data.add(d);
}
}
for (int i = 1; i < graphSpecies.size(); i++) {
if (!learnSpecs.contains(graphSpecies.get(i))) {
graphSpecies.remove(i);
data.remove(i);
i--;
}
}
}
else if (averageOrder != null) {
for (String spec : averageOrder) {
if (!graphSpecies.contains(spec)) {
graphSpecies.add(spec);
ArrayList<Double> d = new ArrayList<Double>();
for (int i = 0; i < data.get(0).size(); i++) {
d.add(0.0);
}
data.add(d);
}
}
for (int i = 1; i < graphSpecies.size(); i++) {
if (!averageOrder.contains(graphSpecies.get(i))) {
graphSpecies.remove(i);
data.remove(i);
i--;
}
}
}
return data;
}
if (label.contains("average") || label.contains("variance") || label.contains("deviation")) {
ArrayList<String> runs = new ArrayList<String>();
if (directory == null) {
String[] files = new File(outDir).list();
for (String f : files) {
if (f.contains(stem) && f.endsWith("." + printer_id.substring(0, printer_id.length() - 8))) {
runs.add(f);
}
}
}
else {
String[] files = new File(outDir + separator + directory).list();
for (String f : files) {
if (f.contains(stem) && f.endsWith("." + printer_id.substring(0, printer_id.length() - 8))) {
runs.add(f);
}
}
}
if (label.contains("average")) {
return calculateAverageVarianceDeviation(runs, 0, directory, warn, false);
}
else if (label.contains("variance")) {
return calculateAverageVarianceDeviation(runs, 1, directory, warn, false);
}
else {
return calculateAverageVarianceDeviation(runs, 2, directory, warn, false);
}
}
//if it's not a stats file
else {
Gui.frame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
DTSDParser dtsdParser;
TSDParser p;
ArrayList<ArrayList<Double>> data;
if (file.contains(".dtsd")) {
dtsdParser = new DTSDParser(file);
Gui.frame.setCursor(null);
warn = false;
graphSpecies = dtsdParser.getSpecies();
data = dtsdParser.getData();
}
else {
p = new TSDParser(file, warn);
Gui.frame.setCursor(null);
warn = p.getWarning();
graphSpecies = p.getSpecies();
data = p.getData();
}
if (learnSpecs != null) {
for (String spec : learnSpecs) {
if (!graphSpecies.contains(spec)) {
graphSpecies.add(spec);
ArrayList<Double> d = new ArrayList<Double>();
for (int i = 0; i < data.get(0).size(); i++) {
d.add(0.0);
}
data.add(d);
}
}
for (int i = 1; i < graphSpecies.size(); i++) {
if (!learnSpecs.contains(graphSpecies.get(i))) {
graphSpecies.remove(i);
data.remove(i);
i--;
}
}
}
else if (averageOrder != null) {
for (String spec : averageOrder) {
if (!graphSpecies.contains(spec)) {
graphSpecies.add(spec);
ArrayList<Double> d = new ArrayList<Double>();
for (int i = 0; i < data.get(0).size(); i++) {
d.add(0.0);
}
data.add(d);
}
}
for (int i = 1; i < graphSpecies.size(); i++) {
if (!averageOrder.contains(graphSpecies.get(i))) {
graphSpecies.remove(i);
data.remove(i);
i--;
}
}
}
return data;
}
}
/**
* This method adds and removes plots from the graph depending on what check
* boxes are selected.
*/
public void actionPerformed(ActionEvent e) {
// if the save button is clicked
if (e.getSource() == run) {
reb2sac.getRunButton().doClick();
}
if (e.getSource() == save) {
save();
}
// if the save as button is clicked
if (e.getSource() == saveAs) {
saveAs();
}
// if the export button is clicked
else if (e.getSource() == export) {
export();
}
else if (e.getSource() == refresh) {
refresh();
}
else if (e.getActionCommand().equals("rename")) {
String rename = JOptionPane.showInputDialog(Gui.frame, "Enter A New Filename:", "Rename", JOptionPane.PLAIN_MESSAGE);
if (rename != null) {
rename = rename.trim();
}
else {
return;
}
if (!rename.equals("")) {
boolean write = true;
if (rename.equals(node.getName())) {
write = false;
}
else if (new File(outDir + separator + rename).exists()) {
Object[] options = { "Overwrite", "Cancel" };
int value = JOptionPane.showOptionDialog(Gui.frame, "File already exists." + "\nDo you want to overwrite?", "Overwrite",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
if (value == JOptionPane.YES_OPTION) {
File dir = new File(outDir + separator + rename);
if (dir.isDirectory()) {
biomodelsim.deleteDir(dir);
}
else {
dir.delete();
}
for (int i = 0; i < simDir.getChildCount(); i++) {
if (((IconNode) simDir.getChildAt(i)).getChildCount() > 0 && ((IconNode) simDir.getChildAt(i)).getName().equals(rename)) {
simDir.remove(i);
}
}
boolean checked = false;
for (int i = 0; i < simDir.getChildCount(); i++) {
if (((IconNode) simDir.getChildAt(i)).getIconName().equals("" + (char) 10003)) {
checked = true;
}
}
if (!checked) {
simDir.setIcon(MetalIconFactory.getTreeFolderIcon());
simDir.setIconName("");
}
for (int i = 0; i < graphed.size(); i++) {
if (graphed.get(i).getDirectory().equals(rename)) {
graphed.remove(i);
i--;
}
}
}
else {
write = false;
}
}
if (write) {
String getFile = node.getName();
IconNode s = node;
while (s.getParent().getParent() != null) {
getFile = s.getName() + separator + getFile;
s = (IconNode) s.getParent();
}
getFile = outDir + separator + getFile;
new File(getFile).renameTo(new File(outDir + separator + rename));
for (GraphSpecies spec : graphed) {
if (spec.getDirectory().equals(node.getName())) {
spec.setDirectory(rename);
}
}
directories.remove(node.getName());
directories.add(rename);
node.setUserObject(rename);
node.setName(rename);
simDir.remove(node);
int i;
for (i = 0; i < simDir.getChildCount(); i++) {
if (((IconNode) simDir.getChildAt(i)).getChildCount() != 0) {
if (((IconNode) simDir.getChildAt(i)).getName().compareToIgnoreCase(rename) > 0) {
simDir.insert(node, i);
break;
}
}
else {
break;
}
}
simDir.insert(node, i);
ArrayList<String> rows = new ArrayList<String>();
for (i = 0; i < tree.getRowCount(); i++) {
if (tree.isExpanded(i)) {
tree.setSelectionRow(i);
rows.add(node.getName());
}
}
scrollpane = new JScrollPane();
refreshTree();
scrollpane.getViewport().add(tree);
scrollpane.setPreferredSize(new Dimension(175, 100));
all.removeAll();
all.add(titlePanel, "North");
all.add(scroll, "Center");
all.add(scrollpane, "West");
all.revalidate();
all.repaint();
TreeSelectionListener t = new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
node = (IconNode) e.getPath().getLastPathComponent();
}
};
tree.addTreeSelectionListener(t);
int select = 0;
for (i = 0; i < tree.getRowCount(); i++) {
tree.setSelectionRow(i);
if (rows.contains(node.getName())) {
tree.expandRow(i);
}
if (rename.equals(node.getName())) {
select = i;
}
}
tree.removeTreeSelectionListener(t);
addTreeListener();
tree.setSelectionRow(select);
}
}
}
else if (e.getActionCommand().equals("recalculate")) {
TreePath select = tree.getSelectionPath();
String[] files;
if (((IconNode) select.getLastPathComponent()).getParent() != null) {
files = new File(outDir + separator + ((IconNode) select.getLastPathComponent()).getName()).list();
}
else {
files = new File(outDir).list();
}
ArrayList<String> runs = new ArrayList<String>();
for (String file : files) {
if (file.contains("run-") && file.endsWith("." + printer_id.substring(0, printer_id.length() - 8))) {
runs.add(file);
}
}
if (((IconNode) select.getLastPathComponent()).getParent() != null) {
calculateAverageVarianceDeviation(runs, 0, ((IconNode) select.getLastPathComponent()).getName(), warn, true);
}
else {
calculateAverageVarianceDeviation(runs, 0, null, warn, true);
}
}
else if (e.getActionCommand().equals("delete")) {
TreePath[] selected = tree.getSelectionPaths();
TreeSelectionListener t = new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
node = (IconNode) e.getPath().getLastPathComponent();
}
};
for (TreeSelectionListener listen : tree.getTreeSelectionListeners()) {
tree.removeTreeSelectionListener(listen);
}
tree.addTreeSelectionListener(t);
for (TreePath select : selected) {
tree.setSelectionPath(select);
if (((IconNode) select.getLastPathComponent()).getParent() != null) {
for (int i = 0; i < simDir.getChildCount(); i++) {
if (((IconNode) simDir.getChildAt(i)) == ((IconNode) select.getLastPathComponent())) {
if (((IconNode) simDir.getChildAt(i)).getChildCount() != 0) {
simDir.remove(i);
File dir = new File(outDir + separator + ((IconNode) select.getLastPathComponent()).getName());
if (dir.isDirectory()) {
biomodelsim.deleteDir(dir);
}
else {
dir.delete();
}
directories.remove(((IconNode) select.getLastPathComponent()).getName());
for (int j = 0; j < graphed.size(); j++) {
if (graphed.get(j).getDirectory().equals(((IconNode) select.getLastPathComponent()).getName())) {
graphed.remove(j);
j--;
}
}
}
else {
String name = ((IconNode) select.getLastPathComponent()).getName();
if (name.equals("Average")) {
name = "mean";
}
else if (name.equals("Variance")) {
name = "variance";
}
else if (name.equals("Standard Deviation")) {
name = "standard_deviation";
}
else if (name.equals("Percent Termination")) {
name = "percent-term-time";
simDir.remove(i);
}
else if (name.equals("Termination Time")) {
name = "term-time";
simDir.remove(i);
}
else if (name.equals("Constraint Termination")) {
name = "sim-rep";
simDir.remove(i);
}
else if (name.equals("Bifurcation Statistics")) {
name = "bifurcation";
simDir.remove(i);
}
else {
simDir.remove(i);
}
name += "." + printer_id.substring(0, printer_id.length() - 8);
File dir = new File(outDir + separator + name);
if (dir.isDirectory()) {
biomodelsim.deleteDir(dir);
}
else {
dir.delete();
}
int count = 0;
boolean m = false;
if (new File(outDir + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
m = true;
}
boolean v = false;
if (new File(outDir + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
v = true;
}
boolean d = false;
if (new File(outDir + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
d = true;
}
for (int j = 0; j < simDir.getChildCount(); j++) {
if (((IconNode) simDir.getChildAt(j)).getChildCount() == 0) {
if (((IconNode) simDir.getChildAt(j)).getName().contains("run-")) {
count++;
}
}
}
if (count == 0) {
for (int j = 0; j < simDir.getChildCount(); j++) {
if (((IconNode) simDir.getChildAt(j)).getChildCount() == 0) {
if (((IconNode) simDir.getChildAt(j)).getName().contains("Average") && !m) {
simDir.remove(j);
j--;
}
else if (((IconNode) simDir.getChildAt(j)).getName().contains("Variance") && !v) {
simDir.remove(j);
j--;
}
else if (((IconNode) simDir.getChildAt(j)).getName().contains("Deviation") && !d) {
simDir.remove(j);
j--;
}
}
}
}
}
}
else if (((IconNode) simDir.getChildAt(i)).getChildCount() != 0) {
for (int j = 0; j < simDir.getChildAt(i).getChildCount(); j++) {
if (((IconNode) ((IconNode) simDir.getChildAt(i)).getChildAt(j)) == ((IconNode) select.getLastPathComponent())) {
String name = ((IconNode) select.getLastPathComponent()).getName();
if (name.equals("Average")) {
name = "mean";
}
else if (name.equals("Variance")) {
name = "variance";
}
else if (name.equals("Standard Deviation")) {
name = "standard_deviation";
}
else if (name.equals("Percent Termination")) {
name = "percent-term-time";
((IconNode) simDir.getChildAt(i)).remove(j);
}
else if (name.equals("Termination Time")) {
name = "term-time";
((IconNode) simDir.getChildAt(i)).remove(j);
}
else if (name.equals("Constraint Termination")) {
name = "sim-rep";
((IconNode) simDir.getChildAt(i)).remove(j);
}
else if (name.equals("Bifurcation Statistics")) {
name = "bifurcation";
((IconNode) simDir.getChildAt(i)).remove(j);
}
else {
((IconNode) simDir.getChildAt(i)).remove(j);
}
name += "." + printer_id.substring(0, printer_id.length() - 8);
File dir = new File(outDir + separator + ((IconNode) simDir.getChildAt(i)).getName() + separator + name);
if (dir.isDirectory()) {
biomodelsim.deleteDir(dir);
}
else {
dir.delete();
}
boolean checked = false;
for (int k = 0; k < simDir.getChildAt(i).getChildCount(); k++) {
if (((IconNode) simDir.getChildAt(i).getChildAt(k)).getIconName().equals("" + (char) 10003)) {
checked = true;
}
}
if (!checked) {
((IconNode) simDir.getChildAt(i)).setIcon(MetalIconFactory.getTreeFolderIcon());
((IconNode) simDir.getChildAt(i)).setIconName("");
}
int count = 0;
boolean m = false;
if (new File(outDir + separator + ((IconNode) simDir.getChildAt(i)).getName() + separator + "mean" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
m = true;
}
boolean v = false;
if (new File(outDir + separator + ((IconNode) simDir.getChildAt(i)).getName() + separator + "variance" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
v = true;
}
boolean d = false;
if (new File(outDir + separator + ((IconNode) simDir.getChildAt(i)).getName() + separator + "standard_deviation"
+ "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
d = true;
}
for (int k = 0; k < simDir.getChildAt(i).getChildCount(); k++) {
if (((IconNode) simDir.getChildAt(i).getChildAt(k)).getChildCount() == 0) {
if (((IconNode) simDir.getChildAt(i).getChildAt(k)).getName().contains("run-")) {
count++;
}
}
}
if (count == 0) {
for (int k = 0; k < simDir.getChildAt(i).getChildCount(); k++) {
if (((IconNode) simDir.getChildAt(i).getChildAt(k)).getChildCount() == 0) {
if (((IconNode) simDir.getChildAt(i).getChildAt(k)).getName().contains("Average") && !m) {
((IconNode) simDir.getChildAt(i)).remove(k);
k--;
}
else if (((IconNode) simDir.getChildAt(i).getChildAt(k)).getName().contains("Variance") && !v) {
((IconNode) simDir.getChildAt(i)).remove(k);
k--;
}
else if (((IconNode) simDir.getChildAt(i).getChildAt(k)).getName().contains("Deviation") && !d) {
((IconNode) simDir.getChildAt(i)).remove(k);
k--;
}
}
}
}
}
}
}
}
}
}
boolean checked = false;
for (int i = 0; i < simDir.getChildCount(); i++) {
if (((IconNode) simDir.getChildAt(i)).getIconName().equals("" + (char) 10003)) {
checked = true;
}
}
if (!checked) {
simDir.setIcon(MetalIconFactory.getTreeFolderIcon());
simDir.setIconName("");
}
ArrayList<String> rows = new ArrayList<String>();
for (int i = 0; i < tree.getRowCount(); i++) {
if (tree.isExpanded(i)) {
tree.setSelectionRow(i);
rows.add(node.getName());
}
}
scrollpane = new JScrollPane();
refreshTree();
scrollpane.getViewport().add(tree);
scrollpane.setPreferredSize(new Dimension(175, 100));
all.removeAll();
all.add(titlePanel, "North");
all.add(scroll, "Center");
all.add(scrollpane, "West");
all.revalidate();
all.repaint();
t = new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
node = (IconNode) e.getPath().getLastPathComponent();
}
};
tree.addTreeSelectionListener(t);
for (int i = 0; i < tree.getRowCount(); i++) {
tree.setSelectionRow(i);
if (rows.contains(node.getName())) {
tree.expandRow(i);
}
}
tree.removeTreeSelectionListener(t);
addTreeListener();
}
else if (e.getActionCommand().equals("delete runs")) {
for (int i = simDir.getChildCount() - 1; i >= 0; i--) {
if (((IconNode) simDir.getChildAt(i)).getChildCount() == 0) {
String name = ((IconNode) simDir.getChildAt(i)).getName();
if (name.equals("Average")) {
name = "mean";
}
else if (name.equals("Variance")) {
name = "variance";
}
else if (name.equals("Standard Deviation")) {
name = "standard_deviation";
}
else if (name.equals("Percent Termination")) {
name = "percent-term-time";
}
else if (name.equals("Termination Time")) {
name = "term-time";
}
else if (name.equals("Constraint Termination")) {
name = "sim-rep";
}
else if (name.equals("Bifurcation Statistics")) {
name = "bifurcation";
}
name += "." + printer_id.substring(0, printer_id.length() - 8);
File dir = new File(outDir + separator + name);
if (dir.isDirectory()) {
biomodelsim.deleteDir(dir);
}
else {
dir.delete();
}
simDir.remove(i);
}
}
boolean checked = false;
for (int i = 0; i < simDir.getChildCount(); i++) {
if (((IconNode) simDir.getChildAt(i)).getIconName().equals("" + (char) 10003)) {
checked = true;
}
}
if (!checked) {
simDir.setIcon(MetalIconFactory.getTreeFolderIcon());
simDir.setIconName("");
}
ArrayList<String> rows = new ArrayList<String>();
for (int i = 0; i < tree.getRowCount(); i++) {
if (tree.isExpanded(i)) {
tree.setSelectionRow(i);
rows.add(node.getName());
}
}
scrollpane = new JScrollPane();
refreshTree();
scrollpane.getViewport().add(tree);
scrollpane.setPreferredSize(new Dimension(175, 100));
all.removeAll();
all.add(titlePanel, "North");
all.add(scroll, "Center");
all.add(scrollpane, "West");
all.revalidate();
all.repaint();
TreeSelectionListener t = new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
node = (IconNode) e.getPath().getLastPathComponent();
}
};
tree.addTreeSelectionListener(t);
for (int i = 0; i < tree.getRowCount(); i++) {
tree.setSelectionRow(i);
if (rows.contains(node.getName())) {
tree.expandRow(i);
}
}
tree.removeTreeSelectionListener(t);
addTreeListener();
}
else if (e.getActionCommand().equals("delete all")) {
for (int i = simDir.getChildCount() - 1; i >= 0; i--) {
if (((IconNode) simDir.getChildAt(i)).getChildCount() == 0) {
String name = ((IconNode) simDir.getChildAt(i)).getName();
if (name.equals("Average")) {
name = "mean";
}
else if (name.equals("Variance")) {
name = "variance";
}
else if (name.equals("Standard Deviation")) {
name = "standard_deviation";
}
else if (name.equals("Percent Termination")) {
name = "percent-term-time";
}
else if (name.equals("Termination Time")) {
name = "term-time";
}
else if (name.equals("Constraint Termination")) {
name = "sim-rep";
}
else if (name.equals("Bifurcation Statistics")) {
name = "bifurcation";
}
name += "." + printer_id.substring(0, printer_id.length() - 8);
File dir = new File(outDir + separator + name);
if (dir.isDirectory()) {
biomodelsim.deleteDir(dir);
}
else {
dir.delete();
}
simDir.remove(i);
}
else {
File dir = new File(outDir + separator + ((IconNode) simDir.getChildAt(i)).getName());
if (dir.isDirectory()) {
biomodelsim.deleteDir(dir);
}
else {
dir.delete();
}
simDir.remove(i);
}
}
boolean checked = false;
for (int i = 0; i < simDir.getChildCount(); i++) {
if (((IconNode) simDir.getChildAt(i)).getIconName().equals("" + (char) 10003)) {
checked = true;
}
}
if (!checked) {
simDir.setIcon(MetalIconFactory.getTreeFolderIcon());
simDir.setIconName("");
}
ArrayList<String> rows = new ArrayList<String>();
for (int i = 0; i < tree.getRowCount(); i++) {
if (tree.isExpanded(i)) {
tree.setSelectionRow(i);
rows.add(node.getName());
}
}
scrollpane = new JScrollPane();
refreshTree();
scrollpane.getViewport().add(tree);
scrollpane.setPreferredSize(new Dimension(175, 100));
all.removeAll();
all.add(titlePanel, "North");
all.add(scroll, "Center");
all.add(scrollpane, "West");
all.revalidate();
all.repaint();
TreeSelectionListener t = new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
node = (IconNode) e.getPath().getLastPathComponent();
}
};
tree.addTreeSelectionListener(t);
for (int i = 0; i < tree.getRowCount(); i++) {
tree.setSelectionRow(i);
if (rows.contains(node.getName())) {
tree.expandRow(i);
}
}
tree.removeTreeSelectionListener(t);
addTreeListener();
}
// // if the export as jpeg button is clicked
// else if (e.getSource() == exportJPeg) {
// export(0);
// }
// // if the export as png button is clicked
// else if (e.getSource() == exportPng) {
// export(1);
// }
// // if the export as pdf button is clicked
// else if (e.getSource() == exportPdf) {
// export(2);
// }
// // if the export as eps button is clicked
// else if (e.getSource() == exportEps) {
// export(3);
// }
// // if the export as svg button is clicked
// else if (e.getSource() == exportSvg) {
// export(4);
// } else if (e.getSource() == exportCsv) {
// export(5);
// }
}
/**
* Private method used to auto resize the graph.
*/
private void resize(XYSeriesCollection dataset) {
NumberFormat num = NumberFormat.getInstance();
num.setMaximumFractionDigits(4);
num.setGroupingUsed(false);
XYPlot plot = chart.getXYPlot();
XYItemRenderer rend = plot.getRenderer();
double minY = Double.MAX_VALUE;
double maxY = Double.MIN_VALUE;
double minX = Double.MAX_VALUE;
double maxX = Double.MIN_VALUE;
for (int j = 0; j < dataset.getSeriesCount(); j++) {
XYSeries series = dataset.getSeries(j);
double[][] seriesArray = series.toArray();
Boolean visible = rend.getSeriesVisible(j);
if (visible == null || visible.equals(true)) {
for (int k = 0; k < series.getItemCount(); k++) {
maxY = Math.max(seriesArray[1][k], maxY);
minY = Math.min(seriesArray[1][k], minY);
maxX = Math.max(seriesArray[0][k], maxX);
minX = Math.min(seriesArray[0][k], minX);
}
}
}
NumberAxis axis = (NumberAxis) plot.getRangeAxis();
if (minY == Double.MAX_VALUE || maxY == Double.MIN_VALUE) {
axis.setRange(-1, 1);
}
// else if ((maxY - minY) < .001) {
// axis.setRange(minY - 1, maxY + 1);
// }
else {
/*
* axis.setRange(Double.parseDouble(num.format(minY -
* (Math.abs(minY) .1))), Double .parseDouble(num.format(maxY +
* (Math.abs(maxY) .1))));
*/
if ((maxY - minY) < .001) {
axis.setStandardTickUnits(new StandardTickUnitSource());
}
else {
axis.setStandardTickUnits(NumberAxis.createStandardTickUnits());
}
axis.setRange(minY - (Math.abs(minY) * .1), maxY + (Math.abs(maxY) * .1));
}
axis.setAutoTickUnitSelection(true);
if (LogY.isSelected()) {
try {
LogarithmicAxis rangeAxis = new LogarithmicAxis(chart.getXYPlot().getRangeAxis().getLabel());
rangeAxis.setStrictValuesFlag(false);
plot.setRangeAxis(rangeAxis);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(Gui.frame, "Log plots are not allowed with data\nvalues less than or equal to zero.", "Error",
JOptionPane.ERROR_MESSAGE);
NumberAxis rangeAxis = new NumberAxis(chart.getXYPlot().getRangeAxis().getLabel());
plot.setRangeAxis(rangeAxis);
LogY.setSelected(false);
}
}
if (visibleLegend.isSelected()) {
if (chart.getLegend() == null) {
chart.addLegend(legend);
}
}
else {
if (chart.getLegend() != null) {
legend = chart.getLegend();
}
chart.removeLegend();
}
axis = (NumberAxis) plot.getDomainAxis();
if (minX == Double.MAX_VALUE || maxX == Double.MIN_VALUE) {
axis.setRange(-1, 1);
}
// else if ((maxX - minX) < .001) {
// axis.setRange(minX - 1, maxX + 1);
// }
else {
if ((maxX - minX) < .001) {
axis.setStandardTickUnits(new StandardTickUnitSource());
}
else {
axis.setStandardTickUnits(NumberAxis.createStandardTickUnits());
}
axis.setRange(minX, maxX);
}
axis.setAutoTickUnitSelection(true);
if (LogX.isSelected()) {
try {
LogarithmicAxis domainAxis = new LogarithmicAxis(chart.getXYPlot().getDomainAxis().getLabel());
domainAxis.setStrictValuesFlag(false);
plot.setDomainAxis(domainAxis);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(Gui.frame, "Log plots are not allowed with data\nvalues less than or equal to zero.", "Error",
JOptionPane.ERROR_MESSAGE);
NumberAxis domainAxis = new NumberAxis(chart.getXYPlot().getDomainAxis().getLabel());
plot.setRangeAxis(domainAxis);
LogX.setSelected(false);
}
}
}
/**
* After the chart is redrawn, this method calculates the x and y scale and
* updates those text fields.
*/
public void chartProgress(ChartProgressEvent e) {
// if the chart drawing is started
if (e.getType() == ChartProgressEvent.DRAWING_STARTED) {
this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
}
// if the chart drawing is finished
else if (e.getType() == ChartProgressEvent.DRAWING_FINISHED) {
this.setCursor(null);
JFreeChart chart = e.getChart();
XYPlot plot = (XYPlot) chart.getXYPlot();
NumberAxis axis = (NumberAxis) plot.getRangeAxis();
YMin.setText("" + axis.getLowerBound());
YMax.setText("" + axis.getUpperBound());
YScale.setText("" + axis.getTickUnit().getSize());
axis = (NumberAxis) plot.getDomainAxis();
XMin.setText("" + axis.getLowerBound());
XMax.setText("" + axis.getUpperBound());
XScale.setText("" + axis.getTickUnit().getSize());
}
}
/**
* Invoked when the mouse is clicked on the chart. Allows the user to edit
* the title and labels of the chart.
*/
public void mouseClicked(MouseEvent e) {
if (e.getSource() != tree) {
if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() == 2) {
if (timeSeries) {
editGraph();
}
else {
editProbGraph();
}
}
}
}
public void mousePressed(MouseEvent e) {
if (e.getSource() == tree) {
int selRow = tree.getRowForLocation(e.getX(), e.getY());
if (selRow < 0)
return;
TreePath selPath = tree.getPathForLocation(e.getX(), e.getY());
boolean set = true;
for (TreePath p : tree.getSelectionPaths()) {
if (p.equals(selPath)) {
tree.addSelectionPath(selPath);
set = false;
}
}
if (set) {
tree.setSelectionPath(selPath);
}
if (e.isPopupTrigger()) {
popup.removeAll();
if (node.getChildCount() != 0) {
JMenuItem recalculate = new JMenuItem("Recalculate Statistics");
recalculate.addActionListener(this);
recalculate.setActionCommand("recalculate");
popup.add(recalculate);
}
if (node.getChildCount() != 0 && node.getParent() != null) {
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.setActionCommand("rename");
popup.add(rename);
}
if (node.getParent() != null) {
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.setActionCommand("delete");
popup.add(delete);
}
else {
JMenuItem delete = new JMenuItem("Delete All Runs");
delete.addActionListener(this);
delete.setActionCommand("delete runs");
popup.add(delete);
JMenuItem deleteAll = new JMenuItem("Delete Recursive");
deleteAll.addActionListener(this);
deleteAll.setActionCommand("delete all");
popup.add(deleteAll);
}
if (popup.getComponentCount() != 0) {
popup.show(e.getComponent(), e.getX(), e.getY());
}
}
}
}
public void mouseReleased(MouseEvent e) {
if (e.getSource() == tree) {
int selRow = tree.getRowForLocation(e.getX(), e.getY());
if (selRow < 0)
return;
TreePath selPath = tree.getPathForLocation(e.getX(), e.getY());
boolean set = true;
for (TreePath p : tree.getSelectionPaths()) {
if (p.equals(selPath)) {
tree.addSelectionPath(selPath);
set = false;
}
}
if (set) {
tree.setSelectionPath(selPath);
}
if (e.isPopupTrigger()) {
popup.removeAll();
if (node.getChildCount() != 0) {
JMenuItem recalculate = new JMenuItem("Recalculate Statistics");
recalculate.addActionListener(this);
recalculate.setActionCommand("recalculate");
popup.add(recalculate);
}
if (node.getChildCount() != 0 && node.getParent() != null) {
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.setActionCommand("rename");
popup.add(rename);
}
if (node.getParent() != null) {
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.setActionCommand("delete");
popup.add(delete);
}
else {
JMenuItem delete = new JMenuItem("Delete All Runs");
delete.addActionListener(this);
delete.setActionCommand("delete runs");
popup.add(delete);
JMenuItem deleteAll = new JMenuItem("Delete Recursive");
deleteAll.addActionListener(this);
deleteAll.setActionCommand("delete all");
popup.add(deleteAll);
}
if (popup.getComponentCount() != 0) {
popup.show(e.getComponent(), e.getX(), e.getY());
}
}
}
}
/**
* This method currently does nothing.
*/
public void mouseEntered(MouseEvent e) {
}
/**
* This method currently does nothing.
*/
public void mouseExited(MouseEvent e) {
}
private void setUpShapesAndColors() {
DefaultDrawingSupplier draw = new DefaultDrawingSupplier();
colors = new HashMap<String, Paint>();
shapes = new HashMap<String, Shape>();
colors.put("Red", draw.getNextPaint());
colors.put("Blue", draw.getNextPaint());
colors.put("Green", draw.getNextPaint());
colors.put("Yellow", draw.getNextPaint());
colors.put("Magenta", draw.getNextPaint());
colors.put("Cyan", draw.getNextPaint());
colors.put("Tan", draw.getNextPaint());
colors.put("Gray (Dark)", draw.getNextPaint());
colors.put("Red (Dark)", draw.getNextPaint());
colors.put("Blue (Dark)", draw.getNextPaint());
colors.put("Green (Dark)", draw.getNextPaint());
colors.put("Yellow (Dark)", draw.getNextPaint());
colors.put("Magenta (Dark)", draw.getNextPaint());
colors.put("Cyan (Dark)", draw.getNextPaint());
colors.put("Black", draw.getNextPaint());
draw.getNextPaint();
draw.getNextPaint();
draw.getNextPaint();
draw.getNextPaint();
draw.getNextPaint();
draw.getNextPaint();
// colors.put("Red ", draw.getNextPaint());
// colors.put("Blue ", draw.getNextPaint());
// colors.put("Green ", draw.getNextPaint());
// colors.put("Yellow ", draw.getNextPaint());
// colors.put("Magenta ", draw.getNextPaint());
// colors.put("Cyan ", draw.getNextPaint());
colors.put("Gray", draw.getNextPaint());
colors.put("Red (Extra Dark)", draw.getNextPaint());
colors.put("Blue (Extra Dark)", draw.getNextPaint());
colors.put("Green (Extra Dark)", draw.getNextPaint());
colors.put("Yellow (Extra Dark)", draw.getNextPaint());
colors.put("Magenta (Extra Dark)", draw.getNextPaint());
colors.put("Cyan (Extra Dark)", draw.getNextPaint());
colors.put("Red (Light)", draw.getNextPaint());
colors.put("Blue (Light)", draw.getNextPaint());
colors.put("Green (Light)", draw.getNextPaint());
colors.put("Yellow (Light)", draw.getNextPaint());
colors.put("Magenta (Light)", draw.getNextPaint());
colors.put("Cyan (Light)", draw.getNextPaint());
colors.put("Gray (Light)", new java.awt.Color(238, 238, 238));
shapes.put("Square", draw.getNextShape());
shapes.put("Circle", draw.getNextShape());
shapes.put("Triangle", draw.getNextShape());
shapes.put("Diamond", draw.getNextShape());
shapes.put("Rectangle (Horizontal)", draw.getNextShape());
shapes.put("Triangle (Upside Down)", draw.getNextShape());
shapes.put("Circle (Half)", draw.getNextShape());
shapes.put("Arrow", draw.getNextShape());
shapes.put("Rectangle (Vertical)", draw.getNextShape());
shapes.put("Arrow (Backwards)", draw.getNextShape());
}
public void editGraph() {
final ArrayList<GraphSpecies> old = new ArrayList<GraphSpecies>();
for (GraphSpecies g : graphed) {
old.add(g);
}
titlePanel = new JPanel(new BorderLayout());
JLabel titleLabel = new JLabel("Title:");
JLabel xLabel = new JLabel("X-Axis Label:");
JLabel yLabel = new JLabel("Y-Axis Label:");
final JTextField title = new JTextField(chart.getTitle().getText(), 5);
final JTextField x = new JTextField(chart.getXYPlot().getDomainAxis().getLabel(), 5);
final JTextField y = new JTextField(chart.getXYPlot().getRangeAxis().getLabel(), 5);
final JLabel xMin = new JLabel("X-Min:");
final JLabel xMax = new JLabel("X-Max:");
final JLabel xScale = new JLabel("X-Step:");
final JLabel yMin = new JLabel("Y-Min:");
final JLabel yMax = new JLabel("Y-Max:");
final JLabel yScale = new JLabel("Y-Step:");
LogX.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (((JCheckBox) e.getSource()).isSelected()) {
XYPlot plot = (XYPlot) chart.getXYPlot();
try {
LogarithmicAxis domainAxis = new LogarithmicAxis(chart.getXYPlot().getDomainAxis().getLabel());
domainAxis.setStrictValuesFlag(false);
plot.setRangeAxis(domainAxis);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(Gui.frame, "Log plots are not allowed with data\nvalues less than or equal to zero.", "Error",
JOptionPane.ERROR_MESSAGE);
NumberAxis domainAxis = new NumberAxis(chart.getXYPlot().getDomainAxis().getLabel());
plot.setRangeAxis(domainAxis);
LogX.setSelected(false);
}
}
}
});
LogY.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (((JCheckBox) e.getSource()).isSelected()) {
XYPlot plot = (XYPlot) chart.getXYPlot();
try {
LogarithmicAxis rangeAxis = new LogarithmicAxis(chart.getXYPlot().getRangeAxis().getLabel());
rangeAxis.setStrictValuesFlag(false);
plot.setRangeAxis(rangeAxis);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(Gui.frame, "Semilog plots are not allowed with data\nvalues less than or equal to zero.",
"Error", JOptionPane.ERROR_MESSAGE);
NumberAxis rangeAxis = new NumberAxis(chart.getXYPlot().getRangeAxis().getLabel());
plot.setRangeAxis(rangeAxis);
LogY.setSelected(false);
}
}
}
});
visibleLegend.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (((JCheckBox) e.getSource()).isSelected()) {
if (chart.getLegend() == null) {
chart.addLegend(legend);
}
}
else {
if (chart.getLegend() != null) {
legend = chart.getLegend();
}
chart.removeLegend();
}
}
});
resize.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (((JCheckBox) e.getSource()).isSelected()) {
xMin.setEnabled(false);
XMin.setEnabled(false);
xMax.setEnabled(false);
XMax.setEnabled(false);
xScale.setEnabled(false);
XScale.setEnabled(false);
yMin.setEnabled(false);
YMin.setEnabled(false);
yMax.setEnabled(false);
YMax.setEnabled(false);
yScale.setEnabled(false);
YScale.setEnabled(false);
}
else {
xMin.setEnabled(true);
XMin.setEnabled(true);
xMax.setEnabled(true);
XMax.setEnabled(true);
xScale.setEnabled(true);
XScale.setEnabled(true);
yMin.setEnabled(true);
YMin.setEnabled(true);
yMax.setEnabled(true);
YMax.setEnabled(true);
yScale.setEnabled(true);
YScale.setEnabled(true);
}
}
});
if (resize.isSelected()) {
xMin.setEnabled(false);
XMin.setEnabled(false);
xMax.setEnabled(false);
XMax.setEnabled(false);
xScale.setEnabled(false);
XScale.setEnabled(false);
yMin.setEnabled(false);
YMin.setEnabled(false);
yMax.setEnabled(false);
YMax.setEnabled(false);
yScale.setEnabled(false);
YScale.setEnabled(false);
}
else {
xMin.setEnabled(true);
XMin.setEnabled(true);
xMax.setEnabled(true);
XMax.setEnabled(true);
xScale.setEnabled(true);
XScale.setEnabled(true);
yMin.setEnabled(true);
YMin.setEnabled(true);
yMax.setEnabled(true);
YMax.setEnabled(true);
yScale.setEnabled(true);
YScale.setEnabled(true);
}
Properties p = null;
if (learnSpecs != null) {
try {
String[] split = outDir.split(separator);
p = new Properties();
FileInputStream load = new FileInputStream(new File(outDir + separator + split[split.length - 1] + ".lrn"));
p.load(load);
load.close();
}
catch (Exception e) {
}
}
String simDirString = outDir.split(separator)[outDir.split(separator).length - 1];
simDir = new IconNode(simDirString, simDirString);
simDir.setIconName("");
String[] files = new File(outDir).list();
// for (int i = 1; i < files.length; i++) {
// String index = files[i];
// int j = i;
// while ((j > 0) && files[j - 1].compareToIgnoreCase(index) > 0) {
// files[j] = files[j - 1];
// j = j - 1;
// }
// files[j] = index;
// }
boolean addMean = false;
boolean addVar = false;
boolean addDev = false;
boolean addTerm = false;
boolean addPercent = false;
boolean addConst = false;
boolean addBif = false;
directories = new ArrayList<String>();
for (String file : files) {
if ((file.length() > 3 && (file.substring(file.length() - 4).equals("." + printer_id.substring(0, printer_id.length() - 8))))
|| (file.length() > 4 && file.substring(file.length() - 5).equals(".dtsd"))) {
if (file.contains("run-") || file.contains("mean")) {
addMean = true;
}
else if (file.contains("run-") || file.contains("variance")) {
addVar = true;
}
else if (file.contains("run-") || file.contains("standard_deviation")) {
addDev = true;
}
else if (file.startsWith("term-time")) {
addTerm = true;
}
else if (file.contains("percent-term-time")) {
addPercent = true;
}
else if (file.contains("sim-rep")) {
addConst = true;
}
else if (file.contains("bifurcation")) {
addBif = true;
}
else {
IconNode n = new IconNode(file.substring(0, file.length() - 4), file.substring(0, file.length() - 4));
boolean added = false;
for (int j = 0; j < simDir.getChildCount(); j++) {
if (simDir.getChildAt(j).toString().compareToIgnoreCase(n.toString()) > 0) {
simDir.insert(n, j);
added = true;
break;
}
}
if (!added) {
simDir.add(n);
}
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(file.substring(0, file.length() - 4)) && g.getDirectory().equals("")) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
}
else if (new File(outDir + separator + file).isDirectory()) {
boolean addIt = false;
String[] files3 = new File(outDir + separator + file).list();
// for (int i = 1; i < files3.length; i++) {
// String index = files3[i];
// int j = i;
// while ((j > 0) && files3[j - 1].compareToIgnoreCase(index) >
// 0) {
// files3[j] = files3[j - 1];
// j = j - 1;
// }
// files3[j] = index;
// }
for (String getFile : files3) {
if ((getFile.length() > 3
&& (getFile.substring(getFile.length() - 4).equals("." + printer_id.substring(0, printer_id.length() - 8))))
|| (getFile.length() > 4 && getFile.substring(getFile.length() - 5).equals(".dtsd"))) {
addIt = true;
}
else if (new File(outDir + separator + file + separator + getFile).isDirectory()) {
for (String getFile2 : new File(outDir + separator + file + separator + getFile).list()) {
if ((getFile2.length() > 3
&& (getFile2.substring(getFile2.length() - 4).equals("." + printer_id.substring(0, printer_id.length() - 8))))
|| (getFile2.length() > 4 && getFile2.substring(getFile2.length() - 5).equals(".dtsd"))) {
addIt = true;
}
}
}
}
if (addIt) {
directories.add(file);
IconNode d = new IconNode(file, file);
d.setIconName("");
boolean addMean2 = false;
boolean addVar2 = false;
boolean addDev2 = false;
boolean addTerm2 = false;
boolean addPercent2 = false;
boolean addConst2 = false;
boolean addBif2 = false;
for (String f : files3) {
if (f.contains(printer_id.substring(0, printer_id.length() - 8)) ||
f.contains(".dtsd")) {
if (f.contains("run-") || f.contains("mean")) {
addMean2 = true;
}
else if (f.contains("run-") || f.contains("variance")) {
addVar2 = true;
}
else if (f.contains("run-") || f.contains("standard_deviation")) {
addDev2 = true;
}
else if (f.startsWith("term-time")) {
addTerm2 = true;
}
else if (f.contains("percent-term-time")) {
addPercent2 = true;
}
else if (f.contains("sim-rep")) {
addConst2 = true;
}
else if (f.contains("bifurcation")) {
addBif2 = true;
}
else {
IconNode n = new IconNode(f.substring(0, f.length() - 4), f.substring(0, f.length() - 4));
boolean added = false;
for (int j = 0; j < d.getChildCount(); j++) {
if (d.getChildAt(j).toString().compareToIgnoreCase(n.toString()) > 0) {
d.insert(n, j);
added = true;
break;
}
}
if (!added) {
d.add(n);
}
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(f.substring(0, f.length() - 4)) && g.getDirectory().equals(d.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
}
else if (new File(outDir + separator + file + separator + f).isDirectory()) {
boolean addIt2 = false;
String[] files2 = new File(outDir + separator + file + separator + f).list();
// for (int i = 1; i < files2.length; i++) {
// String index = files2[i];
// int j = i;
// while ((j > 0) && files2[j -
// 1].compareToIgnoreCase(index) > 0) {
// files2[j] = files2[j - 1];
// j = j - 1;
// }
// files2[j] = index;
// }
for (String getFile2 : files2) {
if (getFile2.length() > 3
&& (getFile2.substring(getFile2.length() - 4).equals("." + printer_id.substring(0, printer_id.length() - 8))
|| getFile2.substring(getFile2.length() - 5).equals(".dtsd"))) {
addIt2 = true;
}
}
if (addIt2) {
directories.add(file + separator + f);
IconNode d2 = new IconNode(f, f);
d2.setIconName("");
boolean addMean3 = false;
boolean addVar3 = false;
boolean addDev3 = false;
boolean addTerm3 = false;
boolean addPercent3 = false;
boolean addConst3 = false;
boolean addBif3 = false;
for (String f2 : files2) {
if (f2.contains(printer_id.substring(0, printer_id.length() - 8))
|| f2.contains(".dtsd")) {
if (f2.contains("run-") || f2.contains("mean")) {
addMean3 = true;
}
else if (f2.contains("run-") || f2.contains("variance")) {
addVar3 = true;
}
else if (f2.contains("run-") || f2.contains("standard_deviation")) {
addDev3 = true;
}
else if (f2.startsWith("term-time")) {
addTerm3 = true;
}
else if (f2.contains("percent-term-time")) {
addPercent3 = true;
}
else if (f2.contains("sim-rep")) {
addConst3 = true;
}
else if (f2.contains("bifurcation")) {
addBif3 = true;
}
else {
IconNode n = new IconNode(f2.substring(0, f2.length() - 4), f2.substring(0, f2.length() - 4));
boolean added = false;
for (int j = 0; j < d2.getChildCount(); j++) {
if (d2.getChildAt(j).toString().compareToIgnoreCase(n.toString()) > 0) {
d2.insert(n, j);
added = true;
break;
}
}
if (!added) {
d2.add(n);
}
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(f2.substring(0, f2.length() - 4))
&& g.getDirectory().equals(d.getName() + separator + d2.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d2.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d2.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
}
}
if (addMean3) {
IconNode n = new IconNode("Average", "Average");
d2.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Average") && g.getDirectory().equals(d.getName() + separator + d2.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d2.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d2.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addDev3) {
IconNode n = new IconNode("Standard Deviation", "Standard Deviation");
d2.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Standard Deviation")
&& g.getDirectory().equals(d.getName() + separator + d2.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d2.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d2.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addVar3) {
IconNode n = new IconNode("Variance", "Variance");
d2.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Variance") && g.getDirectory().equals(d.getName() + separator + d2.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d2.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d2.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addTerm3) {
IconNode n = new IconNode("Termination Time", "Termination Time");
d2.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Termination Time")
&& g.getDirectory().equals(d.getName() + separator + d2.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d2.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d2.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addPercent3) {
IconNode n = new IconNode("Percent Termination", "Percent Termination");
d2.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Percent Termination")
&& g.getDirectory().equals(d.getName() + separator + d2.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d2.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d2.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addConst3) {
IconNode n = new IconNode("Constraint Termination", "Constraint Termination");
d2.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Constraint Termination")
&& g.getDirectory().equals(d.getName() + separator + d2.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d2.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d2.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addBif3) {
IconNode n = new IconNode("Bifurcation Statistics", "Bifurcation Statistics");
d2.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Bifurcation Statistics")
&& g.getDirectory().equals(d.getName() + separator + d2.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d2.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d2.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
int run = 1;
String r2 = null;
for (String s : files2) {
if (s.contains("run-")) {
r2 = s;
}
}
if (r2 != null) {
for (String s : files2) {
if (s.length() > 4) {
String end = "";
for (int j = 1; j < 5; j++) {
end = s.charAt(s.length() - j) + end;
}
if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv") || end.equals(".dtsd")) {
if (s.contains("run-")) {
run = Math.max(run, Integer.parseInt(s.substring(4, s.length() - end.length())));
}
}
}
}
for (int i = 0; i < run; i++) {
if (new File(outDir + separator + file + separator + f + separator + "run-" + (i + 1) + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists() ||
new File(outDir + separator + file + separator + f
+ separator + "run-" + (i + 1) + ".dtsd").exists()) {
IconNode n;
if (learnSpecs != null) {
n = new IconNode(p.get("run-" + (i + 1) + "." + printer_id.substring(0, printer_id.length() - 8)),
"run-" + (i + 1));
if (d2.getChildCount() > 3) {
boolean added = false;
for (int j = 3; j < d2.getChildCount(); j++) {
if (d2.getChildAt(j)
.toString()
.compareToIgnoreCase(
(String) p.get("run-" + (i + 1) + "."
+ printer_id.substring(0, printer_id.length() - 8))) > 0) {
d2.insert(n, j);
added = true;
break;
}
}
if (!added) {
d2.add(n);
}
}
else {
d2.add(n);
}
}
else {
n = new IconNode("run-" + (i + 1), "run-" + (i + 1));
d2.add(n);
}
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("run-" + (i + 1))
&& g.getDirectory().equals(d.getName() + separator + d2.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d2.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d2.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
}
}
boolean added = false;
for (int j = 0; j < d.getChildCount(); j++) {
if ((d.getChildAt(j).toString().compareToIgnoreCase(d2.toString()) > 0)
|| new File(outDir + separator + d.toString() + separator
+ (d.getChildAt(j).toString() + "." + printer_id.substring(0, printer_id.length() - 8))).isFile()) {
d.insert(d2, j);
added = true;
break;
}
}
if (!added) {
d.add(d2);
}
}
}
}
if (addMean2) {
IconNode n = new IconNode("Average", "Average");
d.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Average") && g.getDirectory().equals(d.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addDev2) {
IconNode n = new IconNode("Standard Deviation", "Standard Deviation");
d.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Standard Deviation") && g.getDirectory().equals(d.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addVar2) {
IconNode n = new IconNode("Variance", "Variance");
d.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Variance") && g.getDirectory().equals(d.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addTerm2) {
IconNode n = new IconNode("Termination Time", "Termination Time");
d.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Termination Time") && g.getDirectory().equals(d.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addPercent2) {
IconNode n = new IconNode("Percent Termination", "Percent Termination");
d.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Percent Termination") && g.getDirectory().equals(d.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addConst2) {
IconNode n = new IconNode("Constraint Termination", "Constraint Termination");
d.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Constraint Termination") && g.getDirectory().equals(d.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addBif2) {
IconNode n = new IconNode("Bifurcation Statistics", "Bifurcation Statistics");
d.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Bifurcation Statistics") && g.getDirectory().equals(d.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
int run = 1;
String r = null;
for (String s : files3) {
if (s.contains("run-")) {
r = s;
}
}
if (r != null) {
for (String s : files3) {
if (s.length() > 4) {
String end = "";
for (int j = 1; j < 5; j++) {
end = s.charAt(s.length() - j) + end;
}
if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv") || end.equals(".dtsd")) {
if (s.contains("run-")) {
run = Math.max(run, Integer.parseInt(s.substring(4, s.length() - end.length())));
}
}
}
}
for (int i = 0; i < run; i++) {
if (new File(outDir + separator + file + separator + "run-" + (i + 1) + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
IconNode n;
if (learnSpecs != null) {
n = new IconNode(p.get("run-" + (i + 1) + "." + printer_id.substring(0, printer_id.length() - 8)), "run-"
+ (i + 1));
if (d.getChildCount() > 3) {
boolean added = false;
for (int j = 3; j < d.getChildCount(); j++) {
if (d.getChildAt(j)
.toString()
.compareToIgnoreCase(
(String) p.get("run-" + (i + 1) + "." + printer_id.substring(0, printer_id.length() - 8))) > 0) {
d.insert(n, j);
added = true;
break;
}
}
if (!added) {
d.add(n);
}
}
else {
d.add(n);
}
}
else {
n = new IconNode("run-" + (i + 1), "run-" + (i + 1));
d.add(n);
}
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("run-" + (i + 1)) && g.getDirectory().equals(d.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
}
}
boolean added = false;
for (int j = 0; j < simDir.getChildCount(); j++) {
if ((simDir.getChildAt(j).toString().compareToIgnoreCase(d.toString()) > 0)
|| new File(outDir + separator
+ (simDir.getChildAt(j).toString() + "." + printer_id.substring(0, printer_id.length() - 8))).isFile()) {
simDir.insert(d, j);
added = true;
break;
}
}
if (!added) {
simDir.add(d);
}
}
}
}
if (addMean) {
IconNode n = new IconNode("Average", "Average");
simDir.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Average") && g.getDirectory().equals("")) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addDev) {
IconNode n = new IconNode("Standard Deviation", "Standard Deviation");
simDir.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Standard Deviation") && g.getDirectory().equals("")) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addVar) {
IconNode n = new IconNode("Variance", "Variance");
simDir.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Variance") && g.getDirectory().equals("")) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addTerm) {
IconNode n = new IconNode("Termination Time", "Termination Time");
simDir.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Termination Time") && g.getDirectory().equals("")) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addPercent) {
IconNode n = new IconNode("Percent Termination", "Percent Termination");
simDir.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Percent Termination") && g.getDirectory().equals("")) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addConst) {
IconNode n = new IconNode("Constraint Termination", "Constraint Termination");
simDir.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Constraint Termination") && g.getDirectory().equals("")) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addBif) {
IconNode n = new IconNode("Bifurcation Statistics", "Bifurcation Statistics");
simDir.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Bifurcation Statistics") && g.getDirectory().equals("")) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
int run = 1;
String runs = null;
for (String s : new File(outDir).list()) {
if (s.contains("run-")) {
runs = s;
}
}
if (runs != null) {
for (String s : new File(outDir).list()) {
if (s.length() > 4) {
String end = "";
for (int j = 1; j < 5; j++) {
end = s.charAt(s.length() - j) + end;
}
if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv") || end.equals(".dtsd")) {
if (s.contains("run-")) {
run = Math.max(run, Integer.parseInt(s.substring(4, s.length() - end.length())));
}
}
}
}
for (int i = 0; i < run; i++) {
if (new File(outDir + separator + "run-" + (i + 1) + "." + printer_id.substring(0, printer_id.length() - 8)).exists()
|| new File(outDir + separator + "run-" + (i + 1) + ".dtsd").exists()) {
IconNode n;
if (learnSpecs != null) {
n = new IconNode(p.get("run-" + (i + 1) + "." + printer_id.substring(0, printer_id.length() - 8)), "run-" + (i + 1));
if (simDir.getChildCount() > 3) {
boolean added = false;
for (int j = 3; j < simDir.getChildCount(); j++) {
if (simDir
.getChildAt(j)
.toString()
.compareToIgnoreCase(
(String) p.get("run-" + (i + 1) + "." + printer_id.substring(0, printer_id.length() - 8))) > 0) {
simDir.insert(n, j);
added = true;
break;
}
}
if (!added) {
simDir.add(n);
}
}
else {
simDir.add(n);
}
}
else {
n = new IconNode("run-" + (i + 1), "run-" + (i + 1));
simDir.add(n);
}
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("run-" + (i + 1)) && g.getDirectory().equals("")) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
}
}
if (simDir.getChildCount() == 0) {
JOptionPane.showMessageDialog(Gui.frame, "No data to graph." + "\nPerform some simulations to create some data first.", "No Data",
JOptionPane.PLAIN_MESSAGE);
}
else {
all = new JPanel(new BorderLayout());
specPanel = new JPanel();
scrollpane = new JScrollPane();
refreshTree();
addTreeListener();
scrollpane.getViewport().add(tree);
scrollpane.setPreferredSize(new Dimension(175, 100));
scroll = new JScrollPane();
scroll.setPreferredSize(new Dimension(1050, 500));
JPanel editPanel = new JPanel(new BorderLayout());
editPanel.add(specPanel, "Center");
scroll.setViewportView(editPanel);
scroll.getVerticalScrollBar().setUnitIncrement(10);
// JButton ok = new JButton("Ok");
/*
* ok.addActionListener(new ActionListener() { public void
* actionPerformed(ActionEvent e) { double minY; double maxY; double
* scaleY; double minX; double maxX; double scaleX; change = true;
* try { minY = Double.parseDouble(YMin.getText().trim()); maxY =
* Double.parseDouble(YMax.getText().trim()); scaleY =
* Double.parseDouble(YScale.getText().trim()); minX =
* Double.parseDouble(XMin.getText().trim()); maxX =
* Double.parseDouble(XMax.getText().trim()); scaleX =
* Double.parseDouble(XScale.getText().trim()); NumberFormat num =
* NumberFormat.getInstance(); num.setMaximumFractionDigits(4);
* num.setGroupingUsed(false); minY =
* Double.parseDouble(num.format(minY)); maxY =
* Double.parseDouble(num.format(maxY)); scaleY =
* Double.parseDouble(num.format(scaleY)); minX =
* Double.parseDouble(num.format(minX)); maxX =
* Double.parseDouble(num.format(maxX)); scaleX =
* Double.parseDouble(num.format(scaleX)); } catch (Exception e1) {
* JOptionPane.showMessageDialog(BioSim.frame, "Must enter doubles
* into the inputs " + "to change the graph's dimensions!", "Error",
* JOptionPane.ERROR_MESSAGE); return; } lastSelected = selected;
* selected = ""; ArrayList<XYSeries> graphData = new
* ArrayList<XYSeries>(); XYLineAndShapeRenderer rend =
* (XYLineAndShapeRenderer) chart.getXYPlot().getRenderer(); int
* thisOne = -1; for (int i = 1; i < graphed.size(); i++) {
* GraphSpecies index = graphed.get(i); int j = i; while ((j > 0) &&
* (graphed.get(j -
* 1).getSpecies().compareToIgnoreCase(index.getSpecies()) > 0)) {
* graphed.set(j, graphed.get(j - 1)); j = j - 1; } graphed.set(j,
* index); } ArrayList<GraphSpecies> unableToGraph = new
* ArrayList<GraphSpecies>(); HashMap<String,
* ArrayList<ArrayList<Double>>> allData = new HashMap<String,
* ArrayList<ArrayList<Double>>>(); for (GraphSpecies g : graphed) {
* if (g.getDirectory().equals("")) { thisOne++;
* rend.setSeriesVisible(thisOne, true);
* rend.setSeriesLinesVisible(thisOne, g.getConnected());
* rend.setSeriesShapesFilled(thisOne, g.getFilled());
* rend.setSeriesShapesVisible(thisOne, g.getVisible());
* rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint());
* rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape()); if
* (!g.getRunNumber().equals("Average") &&
* !g.getRunNumber().equals("Variance") &&
* !g.getRunNumber().equals("Standard Deviation")) { if (new
* File(outDir + separator + g.getRunNumber() + "." +
* printer_id.substring(0, printer_id.length() - 8)).exists()) {
* readGraphSpecies(outDir + separator + g.getRunNumber() + "." +
* printer_id.substring(0, printer_id.length() - 8), BioSim.frame);
* ArrayList<ArrayList<Double>> data; if
* (allData.containsKey(g.getRunNumber() + " " + g.getDirectory()))
* { data = allData.get(g.getRunNumber() + " " + g.getDirectory());
* } else { data = readData(outDir + separator + g.getRunNumber() +
* "." + printer_id.substring(0, printer_id.length() - 8),
* BioSim.frame, y.getText().trim(), g.getRunNumber(), null); for
* (int i = 2; i < graphSpecies.size(); i++) { String index =
* graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int
* j = i; while ((j > 1) && graphSpecies.get(j -
* 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j,
* graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j -
* 1; } graphSpecies.set(j, index); data.set(j, index2); }
* allData.put(g.getRunNumber() + " " + g.getDirectory(), data); }
* graphData.add(new XYSeries(g.getSpecies())); if (data.size() !=
* 0) { for (int i = 0; i < (data.get(0)).size(); i++) {
* graphData.get(graphData.size() - 1).add((data.get(0)).get(i),
* (data.get(g.getNumber() + 1)).get(i)); } } } else {
* unableToGraph.add(g); thisOne--; } } else { boolean ableToGraph =
* false; try { for (String s : new File(outDir).list()) { if
* (s.length() > 3 && s.substring(0, 4).equals("run-")) {
* ableToGraph = true; } } } catch (Exception e1) { ableToGraph =
* false; } if (ableToGraph) { int next = 1; while (!new File(outDir
* + separator + "run-" + next + "." + printer_id.substring(0,
* printer_id.length() - 8)).exists()) { next++; }
* readGraphSpecies(outDir + separator + "run-" + next + "." +
* printer_id.substring(0, printer_id.length() - 8), BioSim.frame);
* ArrayList<ArrayList<Double>> data; if
* (allData.containsKey(g.getRunNumber() + " " + g.getDirectory()))
* { data = allData.get(g.getRunNumber() + " " + g.getDirectory());
* } else { data = readData(outDir + separator + "run-1." +
* printer_id.substring(0, printer_id.length() - 8), BioSim.frame,
* y.getText().trim(), g.getRunNumber().toLowerCase(), null); for
* (int i = 2; i < graphSpecies.size(); i++) { String index =
* graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int
* j = i; while ((j > 1) && graphSpecies.get(j -
* 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j,
* graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j -
* 1; } graphSpecies.set(j, index); data.set(j, index2); }
* allData.put(g.getRunNumber() + " " + g.getDirectory(), data); }
* graphData.add(new XYSeries(g.getSpecies())); if (data.size() !=
* 0) { for (int i = 0; i < (data.get(0)).size(); i++) {
* graphData.get(graphData.size() - 1).add((data.get(0)).get(i),
* (data.get(g.getNumber() + 1)).get(i)); } } } else {
* unableToGraph.add(g); thisOne--; } } } else { thisOne++;
* rend.setSeriesVisible(thisOne, true);
* rend.setSeriesLinesVisible(thisOne, g.getConnected());
* rend.setSeriesShapesFilled(thisOne, g.getFilled());
* rend.setSeriesShapesVisible(thisOne, g.getVisible());
* rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint());
* rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape()); if
* (!g.getRunNumber().equals("Average") &&
* !g.getRunNumber().equals("Variance") &&
* !g.getRunNumber().equals("Standard Deviation")) { if (new
* File(outDir + separator + g.getDirectory() + separator +
* g.getRunNumber() + "." + printer_id.substring(0,
* printer_id.length() - 8)).exists()) { readGraphSpecies( outDir +
* separator + g.getDirectory() + separator + g.getRunNumber() + "."
* + printer_id.substring(0, printer_id.length() - 8),
* BioSim.frame); ArrayList<ArrayList<Double>> data; if
* (allData.containsKey(g.getRunNumber() + " " + g.getDirectory()))
* { data = allData.get(g.getRunNumber() + " " + g.getDirectory());
* } else { data = readData(outDir + separator + g.getDirectory() +
* separator + g.getRunNumber() + "." + printer_id.substring(0,
* printer_id.length() - 8), BioSim.frame, y.getText().trim(),
* g.getRunNumber(), g.getDirectory()); for (int i = 2; i <
* graphSpecies.size(); i++) { String index = graphSpecies.get(i);
* ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1)
* && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
* graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j,
* data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index);
* data.set(j, index2); } allData.put(g.getRunNumber() + " " +
* g.getDirectory(), data); } graphData.add(new
* XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i =
* 0; i < (data.get(0)).size(); i++) {
* graphData.get(graphData.size() - 1).add((data.get(0)).get(i),
* (data.get(g.getNumber() + 1)).get(i)); } } } else {
* unableToGraph.add(g); thisOne--; } } else { boolean ableToGraph =
* false; try { for (String s : new File(outDir + separator +
* g.getDirectory()).list()) { if (s.length() > 3 && s.substring(0,
* 4).equals("run-")) { ableToGraph = true; } } } catch (Exception
* e1) { ableToGraph = false; } if (ableToGraph) { int next = 1;
* while (!new File(outDir + separator + g.getDirectory() +
* separator + "run-" + next + "." + printer_id.substring(0,
* printer_id.length() - 8)).exists()) { next++; }
* readGraphSpecies(outDir + separator + g.getDirectory() +
* separator + "run-" + next + "." + printer_id.substring(0,
* printer_id.length() - 8), BioSim.frame);
* ArrayList<ArrayList<Double>> data; if
* (allData.containsKey(g.getRunNumber() + " " + g.getDirectory()))
* { data = allData.get(g.getRunNumber() + " " + g.getDirectory());
* } else { data = readData(outDir + separator + g.getDirectory() +
* separator + "run-1." + printer_id.substring(0,
* printer_id.length() - 8), BioSim.frame, y.getText().trim(),
* g.getRunNumber().toLowerCase(), g.getDirectory()); for (int i =
* 2; i < graphSpecies.size(); i++) { String index =
* graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int
* j = i; while ((j > 1) && graphSpecies.get(j -
* 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j,
* graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j -
* 1; } graphSpecies.set(j, index); data.set(j, index2); }
* allData.put(g.getRunNumber() + " " + g.getDirectory(), data); }
* graphData.add(new XYSeries(g.getSpecies())); if (data.size() !=
* 0) { for (int i = 0; i < (data.get(0)).size(); i++) {
* graphData.get(graphData.size() - 1).add((data.get(0)).get(i),
* (data.get(g.getNumber() + 1)).get(i)); } } } else {
* unableToGraph.add(g); thisOne--; } } } } for (GraphSpecies g :
* unableToGraph) { graphed.remove(g); } XYSeriesCollection dataset
* = new XYSeriesCollection(); for (int i = 0; i < graphData.size();
* i++) { dataset.addSeries(graphData.get(i)); }
* fixGraph(title.getText().trim(), x.getText().trim(),
* y.getText().trim(), dataset);
* chart.getXYPlot().setRenderer(rend); XYPlot plot =
* chart.getXYPlot(); if (resize.isSelected()) { resize(dataset); }
* else { NumberAxis axis = (NumberAxis) plot.getRangeAxis();
* axis.setAutoTickUnitSelection(false); axis.setRange(minY, maxY);
* axis.setTickUnit(new NumberTickUnit(scaleY)); axis = (NumberAxis)
* plot.getDomainAxis(); axis.setAutoTickUnitSelection(false);
* axis.setRange(minX, maxX); axis.setTickUnit(new
* NumberTickUnit(scaleX)); } //f.dispose(); } });
*/
// final JButton cancel = new JButton("Cancel");
// cancel.addActionListener(new ActionListener() {
// public void actionPerformed(ActionEvent e) {
// selected = "";
// int size = graphed.size();
// for (int i = 0; i < size; i++) {
// graphed.remove();
// }
// for (GraphSpecies g : old) {
// graphed.add(g);
// }
// f.dispose();
// }
// });
final JButton deselect = new JButton("Deselect All");
deselect.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// selected = "";
int size = graphed.size();
for (int i = 0; i < size; i++) {
graphed.remove();
}
IconNode n = simDir;
while (n != null) {
if (n.isLeaf()) {
n.setIcon(MetalIconFactory.getTreeLeafIcon());
n.setIconName("");
IconNode check = (IconNode) ((DefaultMutableTreeNode) n.getParent()).getChildAfter(n);
if (check == null) {
n = (IconNode) n.getParent();
if (n.getParent() == null) {
n = null;
}
else {
IconNode check2 = (IconNode) ((DefaultMutableTreeNode) n.getParent()).getChildAfter(n);
if (check2 == null) {
n = (IconNode) n.getParent();
if (n.getParent() == null) {
n = null;
}
else {
n = (IconNode) ((DefaultMutableTreeNode) n.getParent()).getChildAfter(n);
}
}
else {
n = check2;
}
}
}
else {
n = check;
}
}
else {
n.setIcon(MetalIconFactory.getTreeFolderIcon());
n.setIconName("");
n = (IconNode) n.getChildAt(0);
}
}
tree.revalidate();
tree.repaint();
if (tree.getSelectionCount() > 0) {
int selectedRow = tree.getSelectionRows()[0];
tree.setSelectionRow(0);
tree.setSelectionRow(selectedRow);
}
}
});
JPanel titlePanel1 = new JPanel(new GridLayout(3, 6));
JPanel titlePanel2 = new JPanel(new GridLayout(1, 6));
titlePanel1.add(titleLabel);
titlePanel1.add(title);
titlePanel1.add(xMin);
titlePanel1.add(XMin);
titlePanel1.add(yMin);
titlePanel1.add(YMin);
titlePanel1.add(xLabel);
titlePanel1.add(x);
titlePanel1.add(xMax);
titlePanel1.add(XMax);
titlePanel1.add(yMax);
titlePanel1.add(YMax);
titlePanel1.add(yLabel);
titlePanel1.add(y);
titlePanel1.add(xScale);
titlePanel1.add(XScale);
titlePanel1.add(yScale);
titlePanel1.add(YScale);
JPanel deselectPanel = new JPanel();
deselectPanel.add(deselect);
titlePanel2.add(deselectPanel);
titlePanel2.add(resize);
titlePanel2.add(XVariable);
titlePanel2.add(LogX);
titlePanel2.add(LogY);
titlePanel2.add(visibleLegend);
titlePanel.add(titlePanel1, "Center");
titlePanel.add(titlePanel2, "South");
// JPanel buttonPanel = new JPanel();
// buttonPanel.add(ok);
// buttonPanel.add(deselect);
// buttonPanel.add(cancel);
all.add(titlePanel, "North");
all.add(scroll, "Center");
all.add(scrollpane, "West");
// all.add(buttonPanel, "South");
Object[] options = { "Ok", "Cancel" };
int value = JOptionPane.showOptionDialog(Gui.frame, all, "Edit Graph", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null,
options, options[0]);
if (value == JOptionPane.YES_OPTION) {
double minY;
double maxY;
double scaleY;
double minX;
double maxX;
double scaleX;
change = true;
try {
minY = Double.parseDouble(YMin.getText().trim());
maxY = Double.parseDouble(YMax.getText().trim());
scaleY = Double.parseDouble(YScale.getText().trim());
minX = Double.parseDouble(XMin.getText().trim());
maxX = Double.parseDouble(XMax.getText().trim());
scaleX = Double.parseDouble(XScale.getText().trim());
/*
* NumberFormat num = NumberFormat.getInstance();
* num.setMaximumFractionDigits(4);
* num.setGroupingUsed(false); minY =
* Double.parseDouble(num.format(minY)); maxY =
* Double.parseDouble(num.format(maxY)); scaleY =
* Double.parseDouble(num.format(scaleY)); minX =
* Double.parseDouble(num.format(minX)); maxX =
* Double.parseDouble(num.format(maxX)); scaleX =
* Double.parseDouble(num.format(scaleX));
*/
}
catch (Exception e1) {
JOptionPane.showMessageDialog(Gui.frame, "Must enter doubles into the inputs " + "to change the graph's dimensions!", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
lastSelected = selected;
selected = "";
ArrayList<XYSeries> graphData = new ArrayList<XYSeries>();
XYLineAndShapeRenderer rend = (XYLineAndShapeRenderer) chart.getXYPlot().getRenderer();
int thisOne = -1;
for (int i = 1; i < graphed.size(); i++) {
GraphSpecies index = graphed.get(i);
int j = i;
while ((j > 0) &&
(graphed.get(j - 1).getSpecies().compareToIgnoreCase(index.getSpecies()) > 0)) {
graphed.set(j, graphed.get(j - 1));
j = j - 1;
}
graphed.set(j, index);
}
ArrayList<GraphSpecies> unableToGraph = new ArrayList<GraphSpecies>();
HashMap<String, ArrayList<ArrayList<Double>>> allData = new HashMap<String, ArrayList<ArrayList<Double>>>();
for (GraphSpecies g : graphed) {
if (g.getDirectory().equals("")) {
thisOne++;
rend.setSeriesVisible(thisOne, true);
rend.setSeriesLinesVisible(thisOne, g.getConnected());
rend.setSeriesShapesFilled(thisOne, g.getFilled());
rend.setSeriesShapesVisible(thisOne, g.getVisible());
rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint());
rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape());
if (!g.getRunNumber().equals("Average") && !g.getRunNumber().equals("Variance")
&& !g.getRunNumber().equals("Standard Deviation") && !g.getRunNumber().equals("Termination Time")
&& !g.getRunNumber().equals("Percent Termination") && !g.getRunNumber().equals("Constraint Termination")
&& !g.getRunNumber().equals("Bifurcation Statistics")) {
if (new File(outDir + separator + g.getRunNumber() + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists() ||
new File(outDir + separator + g.getRunNumber() + ".dtsd").exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
String extension = printer_id.substring(0, printer_id.length() - 8);
if (new File(outDir + separator + g.getRunNumber() + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists() == false
&& new File(outDir + separator + g.getRunNumber() + ".dtsd").exists()) {
extension = "dtsd";
}
data = readData(outDir + separator + g.getRunNumber() + "." + extension,
g.getRunNumber(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
}
else {
unableToGraph.add(g);
thisOne--;
}
}
else {
if (g.getRunNumber().equals("Average")
&& new File(outDir + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(outDir + separator + "mean." + printer_id.substring(0, printer_id.length() - 8), g.getRunNumber()
.toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
}
else if (g.getRunNumber().equals("Variance")
&& new File(outDir + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(outDir + separator + "variance." + printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
}
else if (g.getRunNumber().equals("Standard Deviation")
&& new File(outDir + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(outDir + separator + "standard_deviation." + printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
}
else if (g.getRunNumber().equals("Termination Time")
&& new File(outDir + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(outDir + separator + "term-time." + printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
}
else if (g.getRunNumber().equals("Percent Termination")
&& new File(outDir + separator + "percent-term-time" + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(outDir + separator + "percent-term-time." + printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
}
else if (g.getRunNumber().equals("Constraint Termination")
&& new File(outDir + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(outDir + separator + "sim-rep." + printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
}
else if (g.getRunNumber().equals("Bifurcation Statistics")
&& new File(outDir + separator + "bifurcation" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(outDir + separator + "bifurcation." + printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
}
else {
boolean ableToGraph = false;
try {
for (String s : new File(outDir).list()) {
if (s.length() > 3 && s.substring(0, 4).equals("run-")) {
ableToGraph = true;
}
}
}
catch (Exception e1) {
ableToGraph = false;
}
if (ableToGraph) {
int next = 1;
while (!new File(outDir + separator + "run-" + next + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
next++;
}
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(outDir + separator + "run-1." + printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
}
else {
unableToGraph.add(g);
thisOne--;
}
}
}
}
else {
thisOne++;
rend.setSeriesVisible(thisOne, true);
rend.setSeriesLinesVisible(thisOne, g.getConnected());
rend.setSeriesShapesFilled(thisOne, g.getFilled());
rend.setSeriesShapesVisible(thisOne, g.getVisible());
rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint());
rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape());
if (!g.getRunNumber().equals("Average") && !g.getRunNumber().equals("Variance")
&& !g.getRunNumber().equals("Standard Deviation") && !g.getRunNumber().equals("Termination Time")
&& !g.getRunNumber().equals("Percent Termination") && !g.getRunNumber().equals("Constraint Termination")
&& !g.getRunNumber().equals("Bifurcation Statistics")) {
if (new File(outDir + separator + g.getDirectory() + separator + g.getRunNumber() + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()
|| new File(outDir + separator + g.getDirectory() + separator + g.getRunNumber() + ".dtsd").exists()) {
ArrayList<ArrayList<Double>> data;
//if the data has already been put into the data structure
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
String extension = printer_id.substring(0, printer_id.length() - 8);
if (new File(outDir + separator + g.getDirectory() + separator + g.getRunNumber() + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists() == false
&& new File(outDir + separator + g.getDirectory() + separator
+ g.getRunNumber() + ".dtsd").exists()) {
extension = "dtsd";
}
data = readData(
outDir + separator + g.getDirectory() + separator + g.getRunNumber() + "."
+ extension, g.getRunNumber(), g.getDirectory(), false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
}
else {
unableToGraph.add(g);
thisOne--;
}
}
//if it's one of the stats/termination files
else {
if (g.getRunNumber().equals("Average")
&& new File(outDir + separator + g.getDirectory() + separator + "mean" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(
outDir + separator + g.getDirectory() + separator + "mean."
+ printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
} //end average
else if (g.getRunNumber().equals("Variance")
&& new File(outDir + separator + g.getDirectory() + separator + "variance" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(
outDir + separator + g.getDirectory() + separator + "variance."
+ printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
} //end variance
else if (g.getRunNumber().equals("Standard Deviation")
&& new File(outDir + separator + g.getDirectory() + separator + "standard_deviation" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(
outDir + separator + g.getDirectory() + separator + "standard_deviation."
+ printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
} //end standard deviation
else if (g.getRunNumber().equals("Termination Time")
&& new File(outDir + separator + g.getDirectory() + separator + "term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(
outDir + separator + g.getDirectory() + separator + "term-time."
+ printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
} //end termination time
else if (g.getRunNumber().equals("Percent Termination")
&& new File(outDir + separator + g.getDirectory() + separator + "percent-term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(
outDir + separator + g.getDirectory() + separator + "percent-term-time."
+ printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
} //end percent termination
else if (g.getRunNumber().equals("Constraint Termination")
&& new File(outDir + separator + g.getDirectory() + separator + "sim-rep" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(
outDir + separator + g.getDirectory() + separator + "sim-rep."
+ printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
} //end constraint termination
else if (g.getRunNumber().equals("Bifurcation Statistics")
&& new File(outDir + separator + g.getDirectory() + separator + "bifurcation" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(
outDir + separator + g.getDirectory() + separator + "bifurcation."
+ printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
}
else {
boolean ableToGraph = false;
try {
for (String s : new File(outDir + separator + g.getDirectory()).list()) {
if (s.length() > 3 && s.substring(0, 4).equals("run-")) {
ableToGraph = true;
}
}
}
catch (Exception e1) {
ableToGraph = false;
}
if (ableToGraph) {
int next = 1;
while (!new File(outDir + separator + g.getDirectory() + separator + "run-" + next + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
next++;
}
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(
outDir + separator + g.getDirectory() + separator + "run-1."
+ printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(),
g.getDirectory(), false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
}
else {
unableToGraph.add(g);
thisOne--;
}
}
}
}
}
for (GraphSpecies g : unableToGraph) {
graphed.remove(g);
}
XYSeriesCollection dataset = new XYSeriesCollection();
for (int i = 0; i < graphData.size(); i++) {
dataset.addSeries(graphData.get(i));
}
fixGraph(title.getText().trim(), x.getText().trim(), y.getText().trim(), dataset);
chart.getXYPlot().setRenderer(rend);
XYPlot plot = chart.getXYPlot();
if (resize.isSelected()) {
resize(dataset);
}
else {
NumberAxis axis = (NumberAxis) plot.getRangeAxis();
axis.setAutoTickUnitSelection(false);
axis.setRange(minY, maxY);
axis.setTickUnit(new NumberTickUnit(scaleY));
axis = (NumberAxis) plot.getDomainAxis();
axis.setAutoTickUnitSelection(false);
axis.setRange(minX, maxX);
axis.setTickUnit(new NumberTickUnit(scaleX));
}
} //end of "Ok" option being true
else {
selected = "";
int size = graphed.size();
for (int i = 0; i < size; i++) {
graphed.remove();
}
for (GraphSpecies g : old) {
graphed.add(g);
}
}
// WindowListener w = new WindowListener() {
// public void windowClosing(WindowEvent arg0) {
// cancel.doClick();
// }
// 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) {
// }
// };
// f.addWindowListener(w);
// f.setContentPane(all);
// f.pack();
// Dimension screenSize;
// try {
// Toolkit tk = Toolkit.getDefaultToolkit();
// screenSize = tk.getScreenSize();
// }
// catch (AWTError awe) {
// screenSize = new Dimension(640, 480);
// }
// Dimension frameSize = f.getSize();
// if (frameSize.height > screenSize.height) {
// frameSize.height = screenSize.height;
// }
// if (frameSize.width > screenSize.width) {
// frameSize.width = screenSize.width;
// }
// int xx = screenSize.width / 2 - frameSize.width / 2;
// int yy = screenSize.height / 2 - frameSize.height / 2;
// f.setLocation(xx, yy);
// f.setVisible(true);
}
}
private void refreshTree() {
tree = new JTree(simDir);
if (!topLevel && learnSpecs == null) {
tree.addMouseListener(this);
}
tree.putClientProperty("JTree.icons", makeIcons());
tree.setCellRenderer(new IconNodeRenderer());
DefaultTreeCellRenderer renderer = (DefaultTreeCellRenderer) tree.getCellRenderer();
renderer.setLeafIcon(MetalIconFactory.getTreeLeafIcon());
renderer.setClosedIcon(MetalIconFactory.getTreeFolderIcon());
renderer.setOpenIcon(MetalIconFactory.getTreeFolderIcon());
}
private void addTreeListener() {
boolean stop = false;
int selectionRow = 1;
for (int i = 1; i < tree.getRowCount(); i++) {
tree.setSelectionRow(i);
if (selected.equals(lastSelected)) {
stop = true;
selectionRow = i;
break;
}
}
tree.addTreeSelectionListener(new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
node = (IconNode) e.getPath().getLastPathComponent();
if (!directories.contains(node.getName()) && node.getParent() != null
&& !directories.contains(((IconNode) node.getParent()).getName() + separator + node.getName())) {
selected = node.getName();
int select;
if (selected.equals("Average")) {
select = 0;
}
else if (selected.equals("Variance")) {
select = 1;
}
else if (selected.equals("Standard Deviation")) {
select = 2;
}
else if (selected.contains("-run")) {
select = 0;
}
else if (selected.equals("Termination Time")) {
select = 0;
}
else if (selected.equals("Percent Termination")) {
select = 0;
}
else if (selected.equals("Constraint Termination")) {
select = 0;
}
else if (selected.equals("Bifurcation Statistics")) {
select = 0;
}
else {
try {
if (selected.contains("run-")) {
select = Integer.parseInt(selected.substring(4)) + 2;
}
else {
select = -1;
}
}
catch (Exception e1) {
select = -1;
}
}
if (select != -1) {
specPanel.removeAll();
if (node.getParent().getParent() != null
&& directories.contains(((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName())) {
specPanel.add(fixGraphChoices(((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName()));
}
else if (directories.contains(((IconNode) node.getParent()).getName())) {
specPanel.add(fixGraphChoices(((IconNode) node.getParent()).getName()));
}
else {
specPanel.add(fixGraphChoices(""));
}
specPanel.revalidate();
specPanel.repaint();
for (int i = 0; i < series.size(); i++) {
series.get(i).setText(graphSpecies.get(i + 1));
series.get(i).setSelectionStart(0);
series.get(i).setSelectionEnd(0);
}
for (int i = 0; i < boxes.size(); i++) {
boxes.get(i).setSelected(false);
}
if (node.getParent().getParent() != null
&& directories.contains(((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName())) {
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected)
&& g.getDirectory().equals(
((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName())) {
XVariable.setSelectedIndex(g.getXNumber());
boxes.get(g.getNumber()).setSelected(true);
series.get(g.getNumber()).setText(g.getSpecies());
series.get(g.getNumber()).setSelectionStart(0);
series.get(g.getNumber()).setSelectionEnd(0);
colorsButtons.get(g.getNumber()).setBackground((Color) g.getShapeAndPaint().getPaint());
colorsButtons.get(g.getNumber()).setForeground((Color) g.getShapeAndPaint().getPaint());
colorsCombo.get(g.getNumber()).setSelectedItem(g.getShapeAndPaint().getPaintName().split("_")[0]);
shapesCombo.get(g.getNumber()).setSelectedItem(g.getShapeAndPaint().getShapeName());
connected.get(g.getNumber()).setSelected(g.getConnected());
visible.get(g.getNumber()).setSelected(g.getVisible());
filled.get(g.getNumber()).setSelected(g.getFilled());
}
}
}
else if (directories.contains(((IconNode) node.getParent()).getName())) {
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getDirectory().equals(((IconNode) node.getParent()).getName())) {
XVariable.setSelectedIndex(g.getXNumber());
boxes.get(g.getNumber()).setSelected(true);
series.get(g.getNumber()).setText(g.getSpecies());
series.get(g.getNumber()).setSelectionStart(0);
series.get(g.getNumber()).setSelectionEnd(0);
colorsButtons.get(g.getNumber()).setBackground((Color) g.getShapeAndPaint().getPaint());
colorsButtons.get(g.getNumber()).setForeground((Color) g.getShapeAndPaint().getPaint());
colorsCombo.get(g.getNumber()).setSelectedItem(g.getShapeAndPaint().getPaintName().split("_")[0]);
shapesCombo.get(g.getNumber()).setSelectedItem(g.getShapeAndPaint().getShapeName());
connected.get(g.getNumber()).setSelected(g.getConnected());
visible.get(g.getNumber()).setSelected(g.getVisible());
filled.get(g.getNumber()).setSelected(g.getFilled());
}
}
}
else {
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getDirectory().equals("")) {
XVariable.setSelectedIndex(g.getXNumber());
boxes.get(g.getNumber()).setSelected(true);
series.get(g.getNumber()).setText(g.getSpecies());
series.get(g.getNumber()).setSelectionStart(0);
series.get(g.getNumber()).setSelectionEnd(0);
colorsButtons.get(g.getNumber()).setBackground((Color) g.getShapeAndPaint().getPaint());
colorsButtons.get(g.getNumber()).setForeground((Color) g.getShapeAndPaint().getPaint());
colorsCombo.get(g.getNumber()).setSelectedItem(g.getShapeAndPaint().getPaintName().split("_")[0]);
shapesCombo.get(g.getNumber()).setSelectedItem(g.getShapeAndPaint().getShapeName());
connected.get(g.getNumber()).setSelected(g.getConnected());
visible.get(g.getNumber()).setSelected(g.getVisible());
filled.get(g.getNumber()).setSelected(g.getFilled());
}
}
}
boolean allChecked = true;
boolean allCheckedVisible = true;
boolean allCheckedFilled = true;
boolean allCheckedConnected = true;
for (int i = 0; i < boxes.size(); i++) {
if (!boxes.get(i).isSelected()) {
allChecked = false;
String s = "";
s = ((IconNode) e.getPath().getLastPathComponent()).toString();
if (node.getParent().getParent() != null
&& directories.contains(((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName())) {
if (s.equals("Average")) {
s = "(" + ((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName() + ", " + (char) 967 + ")";
}
else if (s.equals("Variance")) {
s = "(" + ((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName() + ", " + (char) 948 + (char) 178 + ")";
}
else if (s.equals("Standard Deviation")) {
s = "(" + ((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName() + ", " + (char) 948 + ")";
}
else {
if (s.endsWith("-run")) {
s = s.substring(0, s.length() - 4);
}
else if (s.startsWith("run-")) {
s = s.substring(4);
}
s = "(" + ((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName() + ", " + s + ")";
}
}
else if (directories.contains(((IconNode) node.getParent()).getName())) {
if (s.equals("Average")) {
s = "(" + ((IconNode) node.getParent()).getName() + ", " + (char) 967 + ")";
}
else if (s.equals("Variance")) {
s = "(" + ((IconNode) node.getParent()).getName() + ", " + (char) 948 + (char) 178 + ")";
}
else if (s.equals("Standard Deviation")) {
s = "(" + ((IconNode) node.getParent()).getName() + ", " + (char) 948 + ")";
}
else {
if (s.endsWith("-run")) {
s = s.substring(0, s.length() - 4);
}
else if (s.startsWith("run-")) {
s = s.substring(4);
}
s = "(" + ((IconNode) node.getParent()).getName() + ", " + s + ")";
}
}
else {
if (s.equals("Average")) {
s = "(" + (char) 967 + ")";
}
else if (s.equals("Variance")) {
s = "(" + (char) 948 + (char) 178 + ")";
}
else if (s.equals("Standard Deviation")) {
s = "(" + (char) 948 + ")";
}
else {
if (s.endsWith("-run")) {
s = s.substring(0, s.length() - 4);
}
else if (s.startsWith("run-")) {
s = s.substring(4);
}
s = "(" + s + ")";
}
}
String text = graphSpecies.get(i + 1);
String end = "";
if (text.length() >= s.length()) {
for (int j = 0; j < s.length(); j++) {
end = text.charAt(text.length() - 1 - j) + end;
}
if (!s.equals(end)) {
text += " " + s;
}
}
else {
text += " " + s;
}
boxes.get(i).setName(text);
series.get(i).setText(text);
series.get(i).setSelectionStart(0);
series.get(i).setSelectionEnd(0);
colorsCombo.get(i).setSelectedIndex(0);
colorsButtons.get(i).setBackground((Color) colors.get("Black"));
colorsButtons.get(i).setForeground((Color) colors.get("Black"));
shapesCombo.get(i).setSelectedIndex(0);
}
else {
String s = "";
s = ((IconNode) e.getPath().getLastPathComponent()).toString();
if (node.getParent().getParent() != null
&& directories.contains(((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName())) {
if (s.equals("Average")) {
s = "(" + ((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName() + ", " + (char) 967 + ")";
}
else if (s.equals("Variance")) {
s = "(" + ((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName() + ", " + (char) 948 + (char) 178 + ")";
}
else if (s.equals("Standard Deviation")) {
s = "(" + ((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName() + ", " + (char) 948 + ")";
}
else {
if (s.endsWith("-run")) {
s = s.substring(0, s.length() - 4);
}
else if (s.startsWith("run-")) {
s = s.substring(4);
}
s = "(" + ((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName() + ", " + s + ")";
}
}
else if (directories.contains(((IconNode) node.getParent()).getName())) {
if (s.equals("Average")) {
s = "(" + ((IconNode) node.getParent()).getName() + ", " + (char) 967 + ")";
}
else if (s.equals("Variance")) {
s = "(" + ((IconNode) node.getParent()).getName() + ", " + (char) 948 + (char) 178 + ")";
}
else if (s.equals("Standard Deviation")) {
s = "(" + ((IconNode) node.getParent()).getName() + ", " + (char) 948 + ")";
}
else {
if (s.endsWith("-run")) {
s = s.substring(0, s.length() - 4);
}
else if (s.startsWith("run-")) {
s = s.substring(4);
}
s = "(" + ((IconNode) node.getParent()).getName() + ", " + s + ")";
}
}
else {
if (s.equals("Average")) {
s = "(" + (char) 967 + ")";
}
else if (s.equals("Variance")) {
s = "(" + (char) 948 + (char) 178 + ")";
}
else if (s.equals("Standard Deviation")) {
s = "(" + (char) 948 + ")";
}
else {
if (s.endsWith("-run")) {
s = s.substring(0, s.length() - 4);
}
else if (s.startsWith("run-")) {
s = s.substring(4);
}
s = "(" + s + ")";
}
}
String text = series.get(i).getText();
String end = "";
if (text.length() >= s.length()) {
for (int j = 0; j < s.length(); j++) {
end = text.charAt(text.length() - 1 - j) + end;
}
if (!s.equals(end)) {
text += " " + s;
}
}
else {
text += " " + s;
}
boxes.get(i).setName(text);
}
if (!visible.get(i).isSelected()) {
allCheckedVisible = false;
}
if (!connected.get(i).isSelected()) {
allCheckedConnected = false;
}
if (!filled.get(i).isSelected()) {
allCheckedFilled = false;
}
}
if (allChecked) {
use.setSelected(true);
}
else {
use.setSelected(false);
}
if (allCheckedVisible) {
visibleLabel.setSelected(true);
}
else {
visibleLabel.setSelected(false);
}
if (allCheckedFilled) {
filledLabel.setSelected(true);
}
else {
filledLabel.setSelected(false);
}
if (allCheckedConnected) {
connectedLabel.setSelected(true);
}
else {
connectedLabel.setSelected(false);
}
}
}
else {
specPanel.removeAll();
specPanel.revalidate();
specPanel.repaint();
}
}
});
if (!stop) {
tree.setSelectionRow(0);
tree.setSelectionRow(1);
}
else {
tree.setSelectionRow(0);
tree.setSelectionRow(selectionRow);
}
}
private JPanel fixGraphChoices(final String directory) {
if (directory.equals("")) {
if (selected.equals("Average") || selected.equals("Variance") || selected.equals("Standard Deviation")
|| selected.equals("Termination Time") || selected.equals("Percent Termination") || selected.equals("Constraint Termination")
|| selected.equals("Bifurcation Statistics")) {
if (selected.equals("Average")
&& new File(outDir + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8));
}
else if (selected.equals("Variance")
&& new File(outDir + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8));
}
else if (selected.equals("Standard Deviation")
&& new File(outDir + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8));
}
else if (selected.equals("Termination Time")
&& new File(outDir + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8));
}
else if (selected.equals("Percent Termination")
&& new File(outDir + separator + "percent-term-time" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + "percent-term-time" + "." + printer_id.substring(0, printer_id.length() - 8));
}
else if (selected.equals("Constraint Termination")
&& new File(outDir + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8));
}
else if (selected.equals("Bifurcation Statistics")
&& new File(outDir + separator + "bifurcation" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + "bifurcation" + "." + printer_id.substring(0, printer_id.length() - 8));
}
else {
int nextOne = 1;
while (!new File(outDir + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
nextOne++;
}
readGraphSpecies(outDir + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8));
}
}
else {
String extension = printer_id.substring(0, printer_id.length() - 8);
if (new File(outDir + separator + selected + "." + extension).exists() == false)
extension = "dtsd";
readGraphSpecies(outDir + separator + selected + "." + extension);
}
}
else {
if (selected.equals("Average") || selected.equals("Variance") || selected.equals("Standard Deviation")
|| selected.equals("Termination Time") || selected.equals("Percent Termination") || selected.equals("Constraint Termination")) {
if (selected.equals("Average")
&& new File(outDir + separator + directory + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
readGraphSpecies(outDir + separator + directory + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8));
}
else if (selected.equals("Variance")
&& new File(outDir + separator + directory + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
readGraphSpecies(outDir + separator + directory + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8));
}
else if (selected.equals("Standard Deviation")
&& new File(outDir + separator + directory + separator + "standard_deviation" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + directory + separator + "standard_deviation" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (selected.equals("Termination Time")
&& new File(outDir + separator + directory + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
readGraphSpecies(outDir + separator + directory + separator + "term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (selected.equals("Percent Termination")
&& new File(outDir + separator + directory + separator + "percent-term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + directory + separator + "percent-term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (selected.equals("Constraint Termination")
&& new File(outDir + separator + directory + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
readGraphSpecies(outDir + separator + directory + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8));
}
else if (selected.equals("Bifurcation Statistics")
&& new File(outDir + separator + directory + separator + "bifurcation" + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
readGraphSpecies(outDir + separator + directory + separator + "bifurcation" + "." + printer_id.substring(0, printer_id.length() - 8));
}
else {
int nextOne = 1;
while (!new File(outDir + separator + directory + separator + "run-" + nextOne + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
nextOne++;
}
readGraphSpecies(outDir + separator + directory + separator + "run-" + nextOne + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
}
else {
readGraphSpecies(outDir + separator + directory + separator + selected + "." + printer_id.substring(0, printer_id.length() - 8));
}
}
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
}
updateXNumber = false;
XVariable.removeAllItems();
for (int i = 0; i < graphSpecies.size(); i++) {
XVariable.addItem(graphSpecies.get(i));
}
updateXNumber = true;
JPanel speciesPanel1 = new JPanel(new GridLayout(graphSpecies.size(), 1));
JPanel speciesPanel2 = new JPanel(new GridLayout(graphSpecies.size(), 3));
JPanel speciesPanel3 = new JPanel(new GridLayout(graphSpecies.size(), 3));
use = new JCheckBox("Use");
JLabel specs;
specs = new JLabel("Variables");
JLabel color = new JLabel("Color");
JLabel shape = new JLabel("Shape");
connectedLabel = new JCheckBox("Connect");
visibleLabel = new JCheckBox("Visible");
filledLabel = new JCheckBox("Fill");
connectedLabel.setSelected(true);
visibleLabel.setSelected(true);
filledLabel.setSelected(true);
boxes = new ArrayList<JCheckBox>();
series = new ArrayList<JTextField>();
colorsCombo = new ArrayList<JComboBox>();
colorsButtons = new ArrayList<JButton>();
shapesCombo = new ArrayList<JComboBox>();
connected = new ArrayList<JCheckBox>();
visible = new ArrayList<JCheckBox>();
filled = new ArrayList<JCheckBox>();
use.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (use.isSelected()) {
for (JCheckBox box : boxes) {
if (!box.isSelected()) {
box.doClick();
}
}
}
else {
for (JCheckBox box : boxes) {
if (box.isSelected()) {
box.doClick();
}
}
}
}
});
connectedLabel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (connectedLabel.isSelected()) {
for (JCheckBox box : connected) {
if (!box.isSelected()) {
box.doClick();
}
}
}
else {
for (JCheckBox box : connected) {
if (box.isSelected()) {
box.doClick();
}
}
}
}
});
visibleLabel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (visibleLabel.isSelected()) {
for (JCheckBox box : visible) {
if (!box.isSelected()) {
box.doClick();
}
}
}
else {
for (JCheckBox box : visible) {
if (box.isSelected()) {
box.doClick();
}
}
}
}
});
filledLabel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (filledLabel.isSelected()) {
for (JCheckBox box : filled) {
if (!box.isSelected()) {
box.doClick();
}
}
}
else {
for (JCheckBox box : filled) {
if (box.isSelected()) {
box.doClick();
}
}
}
}
});
speciesPanel1.add(use);
speciesPanel2.add(specs);
speciesPanel2.add(color);
speciesPanel2.add(shape);
speciesPanel3.add(connectedLabel);
speciesPanel3.add(visibleLabel);
speciesPanel3.add(filledLabel);
final HashMap<String, Shape> shapey = this.shapes;
final HashMap<String, Paint> colory = this.colors;
for (int i = 0; i < graphSpecies.size() - 1; i++) {
JCheckBox temp = new JCheckBox();
temp.setActionCommand("" + i);
temp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
if (((JCheckBox) e.getSource()).isSelected()) {
node.setIcon(TextIcons.getIcon("g"));
node.setIconName("" + (char) 10003);
IconNode n = ((IconNode) node.getParent());
while (n != null) {
n.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
n.setIconName("" + (char) 10003);
if (n.getParent() == null) {
n = null;
}
else {
n = ((IconNode) n.getParent());
}
}
tree.revalidate();
tree.repaint();
String s = series.get(i).getText();
((JCheckBox) e.getSource()).setSelected(false);
int[] cols = new int[35];
int[] shaps = new int[10];
for (int k = 0; k < boxes.size(); k++) {
if (boxes.get(k).isSelected()) {
if (colorsCombo.get(k).getSelectedItem().equals("Red")) {
cols[0]++;
colorsButtons.get(k).setBackground((Color) colory.get("Red"));
colorsButtons.get(k).setForeground((Color) colory.get("Red"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Blue")) {
cols[1]++;
colorsButtons.get(k).setBackground((Color) colory.get("Blue"));
colorsButtons.get(k).setForeground((Color) colory.get("Blue"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Green")) {
cols[2]++;
colorsButtons.get(k).setBackground((Color) colory.get("Green"));
colorsButtons.get(k).setForeground((Color) colory.get("Green"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Yellow")) {
cols[3]++;
colorsButtons.get(k).setBackground((Color) colory.get("Yellow"));
colorsButtons.get(k).setForeground((Color) colory.get("Yellow"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Magenta")) {
cols[4]++;
colorsButtons.get(k).setBackground((Color) colory.get("Magenta"));
colorsButtons.get(k).setForeground((Color) colory.get("Magenta"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Cyan")) {
cols[5]++;
colorsButtons.get(k).setBackground((Color) colory.get("Cyan"));
colorsButtons.get(k).setForeground((Color) colory.get("Cyan"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Tan")) {
cols[6]++;
colorsButtons.get(k).setBackground((Color) colory.get("Tan"));
colorsButtons.get(k).setForeground((Color) colory.get("Tan"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Gray (Dark)")) {
cols[7]++;
colorsButtons.get(k).setBackground((Color) colory.get("Gray (Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Gray (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Red (Dark)")) {
cols[8]++;
colorsButtons.get(k).setBackground((Color) colory.get("Red (Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Red (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Blue (Dark)")) {
cols[9]++;
colorsButtons.get(k).setBackground((Color) colory.get("Blue (Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Blue (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Green (Dark)")) {
cols[10]++;
colorsButtons.get(k).setBackground((Color) colory.get("Green (Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Green (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Yellow (Dark)")) {
cols[11]++;
colorsButtons.get(k).setBackground((Color) colory.get("Yellow (Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Yellow (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Magenta (Dark)")) {
cols[12]++;
colorsButtons.get(k).setBackground((Color) colory.get("Magenta (Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Magenta (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Cyan (Dark)")) {
cols[13]++;
colorsButtons.get(k).setBackground((Color) colory.get("Cyan (Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Cyan (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Black")) {
cols[14]++;
colorsButtons.get(k).setBackground((Color) colory.get("Black"));
colorsButtons.get(k).setForeground((Color) colory.get("Black"));
}
/*
* else if
* (colorsCombo.get(k).getSelectedItem().
* equals("Red ")) { cols[15]++; } else if
* (colorsCombo
* .get(k).getSelectedItem().equals("Blue ")) {
* cols[16]++; } else if
* (colorsCombo.get(k).getSelectedItem
* ().equals("Green ")) { cols[17]++; } else if
* (colorsCombo.get(k).getSelectedItem().equals(
* "Yellow ")) { cols[18]++; } else if
* (colorsCombo
* .get(k).getSelectedItem().equals("Magenta "))
* { cols[19]++; } else if
* (colorsCombo.get(k).getSelectedItem
* ().equals("Cyan ")) { cols[20]++; }
*/
else if (colorsCombo.get(k).getSelectedItem().equals("Gray")) {
cols[21]++;
colorsButtons.get(k).setBackground((Color) colory.get("Gray"));
colorsButtons.get(k).setForeground((Color) colory.get("Gray"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Red (Extra Dark)")) {
cols[22]++;
colorsButtons.get(k).setBackground((Color) colory.get("Red (Extra Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Red (Extra Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Blue (Extra Dark)")) {
cols[23]++;
colorsButtons.get(k).setBackground((Color) colory.get("Blue (Extra Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Blue (Extra Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Green (Extra Dark)")) {
cols[24]++;
colorsButtons.get(k).setBackground((Color) colory.get("Green (Extra Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Green (Extra Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Yellow (Extra Dark)")) {
cols[25]++;
colorsButtons.get(k).setBackground((Color) colory.get("Yellow (Extra Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Yellow (Extra Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Magenta (Extra Dark)")) {
cols[26]++;
colorsButtons.get(k).setBackground((Color) colory.get("Magenta (Extra Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Magenta (Extra Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Cyan (Extra Dark)")) {
cols[27]++;
colorsButtons.get(k).setBackground((Color) colory.get("Cyan (Extra Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Cyan (Extra Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Red (Light)")) {
cols[28]++;
colorsButtons.get(k).setBackground((Color) colory.get("Red (Light)"));
colorsButtons.get(k).setForeground((Color) colory.get("Red (Light)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Blue (Light)")) {
cols[29]++;
colorsButtons.get(k).setBackground((Color) colory.get("Blue (Light)"));
colorsButtons.get(k).setForeground((Color) colory.get("Blue (Light)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Green (Light)")) {
cols[30]++;
colorsButtons.get(k).setBackground((Color) colory.get("Green (Light)"));
colorsButtons.get(k).setForeground((Color) colory.get("Green (Light)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Yellow (Light)")) {
cols[31]++;
colorsButtons.get(k).setBackground((Color) colory.get("Yellow (Light)"));
colorsButtons.get(k).setForeground((Color) colory.get("Yellow (Light)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Magenta (Light)")) {
cols[32]++;
colorsButtons.get(k).setBackground((Color) colory.get("Magenta (Light)"));
colorsButtons.get(k).setForeground((Color) colory.get("Magenta (Light)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Cyan (Light)")) {
cols[33]++;
colorsButtons.get(k).setBackground((Color) colory.get("Cyan (Light)"));
colorsButtons.get(k).setForeground((Color) colory.get("Cyan (Light)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Gray (Light)")) {
cols[34]++;
colorsButtons.get(k).setBackground((Color) colory.get("Gray (Light)"));
colorsButtons.get(k).setForeground((Color) colory.get("Gray (Light)"));
}
if (shapesCombo.get(k).getSelectedItem().equals("Square")) {
shaps[0]++;
}
else if (shapesCombo.get(k).getSelectedItem().equals("Circle")) {
shaps[1]++;
}
else if (shapesCombo.get(k).getSelectedItem().equals("Triangle")) {
shaps[2]++;
}
else if (shapesCombo.get(k).getSelectedItem().equals("Diamond")) {
shaps[3]++;
}
else if (shapesCombo.get(k).getSelectedItem().equals("Rectangle (Horizontal)")) {
shaps[4]++;
}
else if (shapesCombo.get(k).getSelectedItem().equals("Triangle (Upside Down)")) {
shaps[5]++;
}
else if (shapesCombo.get(k).getSelectedItem().equals("Circle (Half)")) {
shaps[6]++;
}
else if (shapesCombo.get(k).getSelectedItem().equals("Arrow")) {
shaps[7]++;
}
else if (shapesCombo.get(k).getSelectedItem().equals("Rectangle (Vertical)")) {
shaps[8]++;
}
else if (shapesCombo.get(k).getSelectedItem().equals("Arrow (Backwards)")) {
shaps[9]++;
}
}
}
for (GraphSpecies graph : graphed) {
if (graph.getShapeAndPaint().getPaintName().equals("Red")) {
cols[0]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Blue")) {
cols[1]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Green")) {
cols[2]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Yellow")) {
cols[3]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Magenta")) {
cols[4]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Cyan")) {
cols[5]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Tan")) {
cols[6]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Gray (Dark)")) {
cols[7]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Red (Dark)")) {
cols[8]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Blue (Dark)")) {
cols[9]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Green (Dark)")) {
cols[10]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Yellow (Dark)")) {
cols[11]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Magenta (Dark)")) {
cols[12]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Cyan (Dark)")) {
cols[13]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Black")) {
cols[14]++;
}
/*
* else if
* (graph.getShapeAndPaint().getPaintName().equals
* ("Red ")) { cols[15]++; } else if
* (graph.getShapeAndPaint
* ().getPaintName().equals("Blue ")) { cols[16]++;
* } else if
* (graph.getShapeAndPaint().getPaintName()
* .equals("Green ")) { cols[17]++; } else if
* (graph.
* getShapeAndPaint().getPaintName().equals("Yellow "
* )) { cols[18]++; } else if
* (graph.getShapeAndPaint
* ().getPaintName().equals("Magenta ")) {
* cols[19]++; } else if
* (graph.getShapeAndPaint().getPaintName
* ().equals("Cyan ")) { cols[20]++; }
*/
else if (graph.getShapeAndPaint().getPaintName().equals("Gray")) {
cols[21]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Red (Extra Dark)")) {
cols[22]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Blue (Extra Dark)")) {
cols[23]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Green (Extra Dark)")) {
cols[24]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Yellow (Extra Dark)")) {
cols[25]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Magenta (Extra Dark)")) {
cols[26]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Cyan (Extra Dark)")) {
cols[27]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Red (Light)")) {
cols[28]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Blue (Light)")) {
cols[29]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Green (Light)")) {
cols[30]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Yellow (Light)")) {
cols[31]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Magenta (Light)")) {
cols[32]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Cyan (Light)")) {
cols[33]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Gray (Light)")) {
cols[34]++;
}
if (graph.getShapeAndPaint().getShapeName().equals("Square")) {
shaps[0]++;
}
else if (graph.getShapeAndPaint().getShapeName().equals("Circle")) {
shaps[1]++;
}
else if (graph.getShapeAndPaint().getShapeName().equals("Triangle")) {
shaps[2]++;
}
else if (graph.getShapeAndPaint().getShapeName().equals("Diamond")) {
shaps[3]++;
}
else if (graph.getShapeAndPaint().getShapeName().equals("Rectangle (Horizontal)")) {
shaps[4]++;
}
else if (graph.getShapeAndPaint().getShapeName().equals("Triangle (Upside Down)")) {
shaps[5]++;
}
else if (graph.getShapeAndPaint().getShapeName().equals("Circle (Half)")) {
shaps[6]++;
}
else if (graph.getShapeAndPaint().getShapeName().equals("Arrow")) {
shaps[7]++;
}
else if (graph.getShapeAndPaint().getShapeName().equals("Rectangle (Vertical)")) {
shaps[8]++;
}
else if (graph.getShapeAndPaint().getShapeName().equals("Arrow (Backwards)")) {
shaps[9]++;
}
}
((JCheckBox) e.getSource()).setSelected(true);
series.get(i).setText(s);
series.get(i).setSelectionStart(0);
series.get(i).setSelectionEnd(0);
int colorSet = 0;
for (int j = 1; j < cols.length; j++) {
if ((j < 15 || j > 20) && cols[j] < cols[colorSet]) {
colorSet = j;
}
}
int shapeSet = 0;
for (int j = 1; j < shaps.length; j++) {
if (shaps[j] < shaps[shapeSet]) {
shapeSet = j;
}
}
DefaultDrawingSupplier draw = new DefaultDrawingSupplier();
Paint paint;
if (colorSet == 34) {
paint = colors.get("Gray (Light)");
}
else {
for (int j = 0; j < colorSet; j++) {
draw.getNextPaint();
}
paint = draw.getNextPaint();
}
Object[] set = colory.keySet().toArray();
for (int j = 0; j < set.length; j++) {
if (paint == colory.get(set[j])) {
colorsCombo.get(i).setSelectedItem(set[j]);
colorsButtons.get(i).setBackground((Color) paint);
colorsButtons.get(i).setForeground((Color) paint);
}
}
for (int j = 0; j < shapeSet; j++) {
draw.getNextShape();
}
Shape shape = draw.getNextShape();
set = shapey.keySet().toArray();
for (int j = 0; j < set.length; j++) {
if (shape == shapey.get(set[j])) {
shapesCombo.get(i).setSelectedItem(set[j]);
}
}
boolean allChecked = true;
for (JCheckBox temp : boxes) {
if (!temp.isSelected()) {
allChecked = false;
}
}
if (allChecked) {
use.setSelected(true);
}
String color = (String) colorsCombo.get(i).getSelectedItem();
if (color.equals("Custom")) {
color += "_" + colorsButtons.get(i).getBackground().getRGB();
}
graphed.add(new GraphSpecies(shapey.get(shapesCombo.get(i).getSelectedItem()), color, filled.get(i).isSelected(), visible
.get(i).isSelected(), connected.get(i).isSelected(), selected, boxes.get(i).getName(),
series.get(i).getText().trim(), XVariable.getSelectedIndex(), i, directory));
}
else {
boolean check = false;
for (JCheckBox b : boxes) {
if (b.isSelected()) {
check = true;
}
}
if (!check) {
node.setIcon(MetalIconFactory.getTreeLeafIcon());
node.setIconName("");
boolean check2 = false;
IconNode parent = ((IconNode) node.getParent());
while (parent != null) {
for (int j = 0; j < parent.getChildCount(); j++) {
if (((IconNode) parent.getChildAt(j)).getIconName().equals("" + (char) 10003)) {
check2 = true;
}
}
if (!check2) {
parent.setIcon(MetalIconFactory.getTreeFolderIcon());
parent.setIconName("");
}
check2 = false;
if (parent.getParent() == null) {
parent = null;
}
else {
parent = ((IconNode) parent.getParent());
}
}
tree.revalidate();
tree.repaint();
}
ArrayList<GraphSpecies> remove = new ArrayList<GraphSpecies>();
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) {
remove.add(g);
}
}
for (GraphSpecies g : remove) {
graphed.remove(g);
}
use.setSelected(false);
colorsCombo.get(i).setSelectedIndex(0);
colorsButtons.get(i).setBackground((Color) colory.get("Black"));
colorsButtons.get(i).setForeground((Color) colory.get("Black"));
shapesCombo.get(i).setSelectedIndex(0);
}
}
});
boxes.add(temp);
temp = new JCheckBox();
temp.setActionCommand("" + i);
temp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
if (((JCheckBox) e.getSource()).isSelected()) {
boolean allChecked = true;
for (JCheckBox temp : visible) {
if (!temp.isSelected()) {
allChecked = false;
}
}
if (allChecked) {
visibleLabel.setSelected(true);
}
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setVisible(true);
}
}
}
else {
visibleLabel.setSelected(false);
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setVisible(false);
}
}
}
}
});
visible.add(temp);
visible.get(i).setSelected(true);
temp = new JCheckBox();
temp.setActionCommand("" + i);
temp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
if (((JCheckBox) e.getSource()).isSelected()) {
boolean allChecked = true;
for (JCheckBox temp : filled) {
if (!temp.isSelected()) {
allChecked = false;
}
}
if (allChecked) {
filledLabel.setSelected(true);
}
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setFilled(true);
}
}
}
else {
filledLabel.setSelected(false);
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setFilled(false);
}
}
}
}
});
filled.add(temp);
filled.get(i).setSelected(true);
temp = new JCheckBox();
temp.setActionCommand("" + i);
temp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
if (((JCheckBox) e.getSource()).isSelected()) {
boolean allChecked = true;
for (JCheckBox temp : connected) {
if (!temp.isSelected()) {
allChecked = false;
}
}
if (allChecked) {
connectedLabel.setSelected(true);
}
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setConnected(true);
}
}
}
else {
connectedLabel.setSelected(false);
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setConnected(false);
}
}
}
}
});
connected.add(temp);
connected.get(i).setSelected(true);
JTextField seriesName = new JTextField(graphSpecies.get(i + 1), 20);
seriesName.setName("" + i);
seriesName.addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) {
int i = Integer.parseInt(((JTextField) e.getSource()).getName());
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setSpecies(((JTextField) e.getSource()).getText());
}
}
}
public void keyReleased(KeyEvent e) {
int i = Integer.parseInt(((JTextField) e.getSource()).getName());
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setSpecies(((JTextField) e.getSource()).getText());
}
}
}
public void keyTyped(KeyEvent e) {
int i = Integer.parseInt(((JTextField) e.getSource()).getName());
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setSpecies(((JTextField) e.getSource()).getText());
}
}
}
});
series.add(seriesName);
ArrayList<String> allColors = new ArrayList<String>();
for (String c : this.colors.keySet()) {
allColors.add(c);
}
allColors.add("Custom");
Object[] col = allColors.toArray();
Arrays.sort(col);
Object[] shap = this.shapes.keySet().toArray();
Arrays.sort(shap);
JComboBox colBox = new JComboBox(col);
colBox.setActionCommand("" + i);
colBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
if (!((JComboBox) (e.getSource())).getSelectedItem().equals("Custom")) {
colorsButtons.get(i).setBackground((Color) colors.get(((JComboBox) (e.getSource())).getSelectedItem()));
colorsButtons.get(i).setForeground((Color) colors.get(((JComboBox) (e.getSource())).getSelectedItem()));
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setPaint((String) ((JComboBox) e.getSource()).getSelectedItem());
}
}
}
else {
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setPaint("Custom_" + colorsButtons.get(i).getBackground().getRGB());
}
}
}
}
});
JComboBox shapBox = new JComboBox(shap);
shapBox.setActionCommand("" + i);
shapBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setShape((String) ((JComboBox) e.getSource()).getSelectedItem());
}
}
}
});
colorsCombo.add(colBox);
JButton colorButton = new JButton();
colorButton.setPreferredSize(new Dimension(30, 20));
colorButton.setBorder(BorderFactory.createLineBorder(Color.darkGray));
colorButton.setBackground((Color) colory.get("Black"));
colorButton.setForeground((Color) colory.get("Black"));
colorButton.setUI(new MetalButtonUI());
colorButton.setActionCommand("" + i);
colorButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
Color newColor = JColorChooser.showDialog(Gui.frame, "Choose Color", ((JButton) e.getSource()).getBackground());
if (newColor != null) {
((JButton) e.getSource()).setBackground(newColor);
((JButton) e.getSource()).setForeground(newColor);
colorsCombo.get(i).setSelectedItem("Custom");
}
}
});
colorsButtons.add(colorButton);
JPanel colorPanel = new JPanel(new BorderLayout());
colorPanel.add(colorsCombo.get(i), "Center");
colorPanel.add(colorsButtons.get(i), "East");
shapesCombo.add(shapBox);
speciesPanel1.add(boxes.get(i));
speciesPanel2.add(series.get(i));
speciesPanel2.add(colorPanel);
speciesPanel2.add(shapesCombo.get(i));
speciesPanel3.add(connected.get(i));
speciesPanel3.add(visible.get(i));
speciesPanel3.add(filled.get(i));
}
JPanel speciesPanel = new JPanel(new BorderLayout());
speciesPanel.add(speciesPanel1, "West");
speciesPanel.add(speciesPanel2, "Center");
speciesPanel.add(speciesPanel3, "East");
return speciesPanel;
}
private void fixGraph(String title, String x, String y, XYSeriesCollection dataset) {
curData = dataset;
// chart = ChartFactory.createXYLineChart(title, x, y, dataset,
// PlotOrientation.VERTICAL,
// true, true, false);
chart.getXYPlot().setDataset(dataset);
chart.setTitle(title);
chart.getXYPlot().getDomainAxis().setLabel(x);
chart.getXYPlot().getRangeAxis().setLabel(y);
// chart.setBackgroundPaint(new java.awt.Color(238, 238, 238));
// chart.getPlot().setBackgroundPaint(java.awt.Color.WHITE);
// chart.getXYPlot().setDomainGridlinePaint(java.awt.Color.LIGHT_GRAY);
// chart.getXYPlot().setRangeGridlinePaint(java.awt.Color.LIGHT_GRAY);
// chart.addProgressListener(this);
ChartPanel graph = new ChartPanel(chart);
if (graphed.isEmpty()) {
graph.setLayout(new GridLayout(1, 1));
JLabel edit = new JLabel("Double click here to create graph");
edit.addMouseListener(this);
Font font = edit.getFont();
font = font.deriveFont(Font.BOLD, 42.0f);
edit.setFont(font);
edit.setHorizontalAlignment(SwingConstants.CENTER);
graph.add(edit);
}
graph.addMouseListener(this);
JPanel ButtonHolder = new JPanel();
run = new JButton("Save and Run");
save = new JButton("Save Graph");
saveAs = new JButton("Save As");
saveAs.addActionListener(this);
export = new JButton("Export");
refresh = new JButton("Refresh");
// exportJPeg = new JButton("Export As JPEG");
// exportPng = new JButton("Export As PNG");
// exportPdf = new JButton("Export As PDF");
// exportEps = new JButton("Export As EPS");
// exportSvg = new JButton("Export As SVG");
// exportCsv = new JButton("Export As CSV");
run.addActionListener(this);
save.addActionListener(this);
export.addActionListener(this);
refresh.addActionListener(this);
// exportJPeg.addActionListener(this);
// exportPng.addActionListener(this);
// exportPdf.addActionListener(this);
// exportEps.addActionListener(this);
// exportSvg.addActionListener(this);
// exportCsv.addActionListener(this);
if (reb2sac != null) {
ButtonHolder.add(run);
}
ButtonHolder.add(save);
ButtonHolder.add(saveAs);
ButtonHolder.add(export);
ButtonHolder.add(refresh);
// ButtonHolder.add(exportJPeg);
// ButtonHolder.add(exportPng);
// ButtonHolder.add(exportPdf);
// ButtonHolder.add(exportEps);
// ButtonHolder.add(exportSvg);
// ButtonHolder.add(exportCsv);
// JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
// ButtonHolder, null);
// splitPane.setDividerSize(0);
this.removeAll();
this.setLayout(new BorderLayout());
this.add(graph, "Center");
// this.add(splitPane, "South");
this.revalidate();
}
/**
* This method saves the graph as a jpeg or as a png file.
*/
public void export() {
try {
int output = 2; /* Default is currently pdf */
int width = -1;
int height = -1;
JPanel sizePanel = new JPanel(new GridLayout(2, 2));
JLabel heightLabel = new JLabel("Desired pixel height:");
JLabel widthLabel = new JLabel("Desired pixel width:");
JTextField heightField = new JTextField("400");
JTextField widthField = new JTextField("650");
sizePanel.add(widthLabel);
sizePanel.add(widthField);
sizePanel.add(heightLabel);
sizePanel.add(heightField);
Object[] options2 = { "Export", "Cancel" };
int value;
String export = "Export";
if (timeSeries) {
export += " TSD";
}
else {
export += " Probability";
}
File file;
Preferences biosimrc = Preferences.userRoot();
if (biosimrc.get("biosim.general.export_dir", "").equals("")) {
file = null;
}
else {
file = new File(biosimrc.get("biosim.general.export_dir", ""));
}
String filename = Utility.browse(Gui.frame, file, null, JFileChooser.FILES_ONLY, export, output);
if ((filename.length() > 4) && (filename.substring((filename.length() - 4), filename.length()).equals(".jpg"))) {
output = 0;
}
else if ((filename.length() > 4) && (filename.substring((filename.length() - 4), filename.length()).equals(".png"))) {
output = 1;
}
else if ((filename.length() > 4) && (filename.substring((filename.length() - 4), filename.length()).equals(".pdf"))) {
output = 2;
}
else if ((filename.length() > 4) && (filename.substring((filename.length() - 4), filename.length()).equals(".eps"))) {
output = 3;
}
else if ((filename.length() > 4) && (filename.substring((filename.length() - 4), filename.length()).equals(".svg"))) {
output = 4;
}
else if ((filename.length() > 4) && (filename.substring((filename.length() - 4), filename.length()).equals(".csv"))) {
output = 5;
}
else if ((filename.length() > 4) && (filename.substring((filename.length() - 4), filename.length()).equals(".dat"))) {
output = 6;
}
else if ((filename.length() > 4) && (filename.substring((filename.length() - 4), filename.length()).equals(".tsd"))) {
output = 7;
}
if (!filename.equals("")) {
file = new File(filename);
biosimrc.put("biosim.general.export_dir", filename);
boolean exportIt = true;
if (file.exists()) {
Object[] options = { "Overwrite", "Cancel" };
value = JOptionPane.showOptionDialog(Gui.frame, "File already exists." + " Overwrite?", "File Already Exists",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
exportIt = false;
if (value == JOptionPane.YES_OPTION) {
exportIt = true;
}
}
if (exportIt) {
if ((output != 5) && (output != 6) && (output != 7)) {
value = JOptionPane.showOptionDialog(Gui.frame, sizePanel, "Enter Size Of File", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options2, options2[0]);
if (value == JOptionPane.YES_OPTION) {
while (value == JOptionPane.YES_OPTION && (width == -1 || height == -1))
try {
width = Integer.parseInt(widthField.getText().trim());
height = Integer.parseInt(heightField.getText().trim());
if (width < 1 || height < 1) {
JOptionPane.showMessageDialog(Gui.frame, "Width and height must be positive integers!", "Error",
JOptionPane.ERROR_MESSAGE);
width = -1;
height = -1;
value = JOptionPane.showOptionDialog(Gui.frame, sizePanel, "Enter Size Of File", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options2, options2[0]);
}
}
catch (Exception e2) {
JOptionPane.showMessageDialog(Gui.frame, "Width and height must be positive integers!", "Error",
JOptionPane.ERROR_MESSAGE);
width = -1;
height = -1;
value = JOptionPane.showOptionDialog(Gui.frame, sizePanel, "Enter Size Of File", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options2, options2[0]);
}
}
if (value == JOptionPane.NO_OPTION) {
return;
}
}
if (output == 0) {
ChartUtilities.saveChartAsJPEG(file, chart, width, height);
}
else if (output == 1) {
ChartUtilities.saveChartAsPNG(file, chart, width, height);
}
else if (output == 2) {
Rectangle pagesize = new Rectangle(width, height);
Document document = new Document(pagesize, 50, 50, 50, 50);
FileOutputStream out = new FileOutputStream(file);
PdfWriter writer = PdfWriter.getInstance(document, out);
document.open();
PdfContentByte cb = writer.getDirectContent();
PdfTemplate tp = cb.createTemplate(width, height);
Graphics2D g2 = tp.createGraphics(width, height, new DefaultFontMapper());
chart.draw(g2, new java.awt.Rectangle(width, height));
g2.dispose();
cb.addTemplate(tp, 0, 0);
document.close();
out.close();
}
else if (output == 3) {
Graphics2D g = new EpsGraphics2D();
chart.draw(g, new java.awt.Rectangle(width, height));
Writer out = new FileWriter(file);
out.write(g.toString());
out.close();
}
else if (output == 4) {
DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation();
org.w3c.dom.Document document = domImpl.createDocument(null, "svg", null);
SVGGraphics2D svgGenerator = new SVGGraphics2D(document);
chart.draw(svgGenerator, new java.awt.Rectangle(width, height));
boolean useCSS = true;
FileOutputStream outStream = new FileOutputStream(file);
Writer out = new OutputStreamWriter(outStream, "UTF-8");
svgGenerator.stream(out, useCSS);
out.close();
outStream.close();
}
else if ((output == 5) || (output == 6) || (output == 7)) {
exportDataFile(file, output);
}
}
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(Gui.frame, "Unable To Export File!", "Error", JOptionPane.ERROR_MESSAGE);
}
}
public void export(int output) {
// jpg = 0
// png = 1
// pdf = 2
// eps = 3
// svg = 4
// csv = 5 (data)
// dat = 6 (data)
// tsd = 7 (data)
try {
int width = -1;
int height = -1;
JPanel sizePanel = new JPanel(new GridLayout(2, 2));
JLabel heightLabel = new JLabel("Desired pixel height:");
JLabel widthLabel = new JLabel("Desired pixel width:");
JTextField heightField = new JTextField("400");
JTextField widthField = new JTextField("650");
sizePanel.add(widthLabel);
sizePanel.add(widthField);
sizePanel.add(heightLabel);
sizePanel.add(heightField);
Object[] options2 = { "Export", "Cancel" };
int value;
String export = "Export";
if (timeSeries) {
export += " TSD";
}
else {
export += " Probability";
}
File file;
Preferences biosimrc = Preferences.userRoot();
if (biosimrc.get("biosim.general.export_dir", "").equals("")) {
file = null;
}
else {
file = new File(biosimrc.get("biosim.general.export_dir", ""));
}
String filename = Utility.browse(Gui.frame, file, null, JFileChooser.FILES_ONLY, export, output);
if (!filename.equals("")) {
file = new File(filename);
biosimrc.put("biosim.general.export_dir", filename);
boolean exportIt = true;
if (file.exists()) {
Object[] options = { "Overwrite", "Cancel" };
value = JOptionPane.showOptionDialog(Gui.frame, "File already exists." + " Overwrite?", "File Already Exists",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
exportIt = false;
if (value == JOptionPane.YES_OPTION) {
exportIt = true;
}
}
if (exportIt) {
if ((output != 5) && (output != 6) && (output != 7)) {
value = JOptionPane.showOptionDialog(Gui.frame, sizePanel, "Enter Size Of File", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options2, options2[0]);
if (value == JOptionPane.YES_OPTION) {
while (value == JOptionPane.YES_OPTION && (width == -1 || height == -1))
try {
width = Integer.parseInt(widthField.getText().trim());
height = Integer.parseInt(heightField.getText().trim());
if (width < 1 || height < 1) {
JOptionPane.showMessageDialog(Gui.frame, "Width and height must be positive integers!", "Error",
JOptionPane.ERROR_MESSAGE);
width = -1;
height = -1;
value = JOptionPane.showOptionDialog(Gui.frame, sizePanel, "Enter Size Of File", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options2, options2[0]);
}
}
catch (Exception e2) {
JOptionPane.showMessageDialog(Gui.frame, "Width and height must be positive integers!", "Error",
JOptionPane.ERROR_MESSAGE);
width = -1;
height = -1;
value = JOptionPane.showOptionDialog(Gui.frame, sizePanel, "Enter Size Of File", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options2, options2[0]);
}
}
if (value == JOptionPane.NO_OPTION) {
return;
}
}
if (output == 0) {
ChartUtilities.saveChartAsJPEG(file, chart, width, height);
}
else if (output == 1) {
ChartUtilities.saveChartAsPNG(file, chart, width, height);
}
else if (output == 2) {
Rectangle pagesize = new Rectangle(width, height);
Document document = new Document(pagesize, 50, 50, 50, 50);
FileOutputStream out = new FileOutputStream(file);
PdfWriter writer = PdfWriter.getInstance(document, out);
document.open();
PdfContentByte cb = writer.getDirectContent();
PdfTemplate tp = cb.createTemplate(width, height);
Graphics2D g2 = tp.createGraphics(width, height, new DefaultFontMapper());
chart.draw(g2, new java.awt.Rectangle(width, height));
g2.dispose();
cb.addTemplate(tp, 0, 0);
document.close();
out.close();
}
else if (output == 3) {
Graphics2D g = new EpsGraphics2D();
chart.draw(g, new java.awt.Rectangle(width, height));
Writer out = new FileWriter(file);
out.write(g.toString());
out.close();
}
else if (output == 4) {
DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation();
org.w3c.dom.Document document = domImpl.createDocument(null, "svg", null);
SVGGraphics2D svgGenerator = new SVGGraphics2D(document);
chart.draw(svgGenerator, new java.awt.Rectangle(width, height));
boolean useCSS = true;
FileOutputStream outStream = new FileOutputStream(file);
Writer out = new OutputStreamWriter(outStream, "UTF-8");
svgGenerator.stream(out, useCSS);
out.close();
outStream.close();
}
else if ((output == 5) || (output == 6) || (output == 7)) {
exportDataFile(file, output);
}
}
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(Gui.frame, "Unable To Export File!", "Error", JOptionPane.ERROR_MESSAGE);
}
}
public void exportDataFile(File file, int output) {
try {
int count = curData.getSeries(0).getItemCount();
for (int i = 1; i < curData.getSeriesCount(); i++) {
if (curData.getSeries(i).getItemCount() != count) {
JOptionPane.showMessageDialog(Gui.frame, "Data series do not have the same number of points!", "Unable to Export Data File",
JOptionPane.ERROR_MESSAGE);
return;
}
}
for (int j = 0; j < count; j++) {
Number Xval = curData.getSeries(0).getDataItem(j).getX();
for (int i = 1; i < curData.getSeriesCount(); i++) {
if (!curData.getSeries(i).getDataItem(j).getX().equals(Xval)) {
JOptionPane.showMessageDialog(Gui.frame, "Data series time points are not the same!", "Unable to Export Data File",
JOptionPane.ERROR_MESSAGE);
return;
}
}
}
FileOutputStream csvFile = new FileOutputStream(file);
PrintWriter csvWriter = new PrintWriter(csvFile);
if (output == 7) {
csvWriter.print("((");
}
else if (output == 6) {
csvWriter.print("#");
}
csvWriter.print("\"Time\"");
count = curData.getSeries(0).getItemCount();
int pos = 0;
for (int i = 0; i < curData.getSeriesCount(); i++) {
if (output == 6) {
csvWriter.print(" ");
}
else {
csvWriter.print(",");
}
csvWriter.print("\"" + curData.getSeriesKey(i) + "\"");
if (curData.getSeries(i).getItemCount() > count) {
count = curData.getSeries(i).getItemCount();
pos = i;
}
}
if (output == 7) {
csvWriter.print(")");
}
else {
csvWriter.println("");
}
for (int j = 0; j < count; j++) {
if (output == 7) {
csvWriter.print(",");
}
for (int i = 0; i < curData.getSeriesCount(); i++) {
if (i == 0) {
if (output == 7) {
csvWriter.print("(");
}
csvWriter.print(curData.getSeries(pos).getDataItem(j).getX());
}
XYSeries data = curData.getSeries(i);
if (j < data.getItemCount()) {
XYDataItem item = data.getDataItem(j);
if (output == 6) {
csvWriter.print(" ");
}
else {
csvWriter.print(",");
}
csvWriter.print(item.getY());
}
else {
if (output == 6) {
csvWriter.print(" ");
}
else {
csvWriter.print(",");
}
}
}
if (output == 7) {
csvWriter.print(")");
}
else {
csvWriter.println("");
}
}
if (output == 7) {
csvWriter.println(")");
}
csvWriter.close();
csvFile.close();
}
catch (Exception e1) {
JOptionPane.showMessageDialog(Gui.frame, "Unable To Export File!", "Error", JOptionPane.ERROR_MESSAGE);
}
}
public ArrayList<ArrayList<Double>> calculateAverageVarianceDeviation(ArrayList<String> files, int choice, String directory, boolean warning,
boolean output) {
if (files.size() > 0) {
ArrayList<ArrayList<Double>> average = new ArrayList<ArrayList<Double>>();
ArrayList<ArrayList<Double>> variance = new ArrayList<ArrayList<Double>>();
ArrayList<ArrayList<Double>> deviation = new ArrayList<ArrayList<Double>>();
lock.lock();
try {
warn = warning;
// TSDParser p = new TSDParser(startFile, biomodelsim, false);
ArrayList<ArrayList<Double>> data;
if (directory == null) {
data = readData(outDir + separator + files.get(0), "", directory, warn);
}
else {
data = readData(outDir + separator + directory + separator + files.get(0), "", directory, warn);
}
averageOrder = graphSpecies;
boolean first = true;
for (int i = 0; i < graphSpecies.size(); i++) {
average.add(new ArrayList<Double>());
variance.add(new ArrayList<Double>());
}
HashMap<Double, Integer> dataCounts = new HashMap<Double, Integer>();
// int count = 0;
for (String run : files) {
if (directory == null) {
if (new File(outDir + separator + run).exists()) {
ArrayList<ArrayList<Double>> newData = readData(outDir + separator + run, "", directory, warn);
data = new ArrayList<ArrayList<Double>>();
for (int i = 0; i < averageOrder.size(); i++) {
for (int k = 0; k < graphSpecies.size(); k++) {
if (averageOrder.get(i).equals(graphSpecies.get(k))) {
data.add(newData.get(k));
break;
}
}
}
}
}
else {
if (new File(outDir + separator + directory + separator + run).exists()) {
ArrayList<ArrayList<Double>> newData = readData(outDir + separator + directory + separator + run, "", directory, warn);
data = new ArrayList<ArrayList<Double>>();
for (int i = 0; i < averageOrder.size(); i++) {
for (int k = 0; k < graphSpecies.size(); k++) {
if (averageOrder.get(i).equals(graphSpecies.get(k))) {
data.add(newData.get(k));
break;
}
}
}
}
}
// ArrayList<ArrayList<Double>> data = p.getData();
for (int k = 0; k < data.get(0).size(); k++) {
if (first) {
double put;
if (k == data.get(0).size() - 1 && k >= 2) {
if (data.get(0).get(k) - data.get(0).get(k - 1) != data.get(0).get(k - 1) - data.get(0).get(k - 2)) {
put = data.get(0).get(k - 1) + (data.get(0).get(k - 1) - data.get(0).get(k - 2));
dataCounts.put(put, 1);
}
else {
put = (data.get(0)).get(k);
dataCounts.put(put, 1);
}
}
else {
put = (data.get(0)).get(k);
dataCounts.put(put, 1);
}
for (int i = 0; i < data.size(); i++) {
if (i == 0) {
variance.get(i).add((data.get(i)).get(k));
average.get(i).add(put);
}
else {
variance.get(i).add(0.0);
average.get(i).add((data.get(i)).get(k));
}
}
}
else {
int index = -1;
double put;
if (k == data.get(0).size() - 1 && k >= 2) {
if (data.get(0).get(k) - data.get(0).get(k - 1) != data.get(0).get(k - 1) - data.get(0).get(k - 2)) {
put = data.get(0).get(k - 1) + (data.get(0).get(k - 1) - data.get(0).get(k - 2));
}
else {
put = (data.get(0)).get(k);
}
}
else if (k == data.get(0).size() - 1 && k == 1) {
if (average.get(0).size() > 1) {
put = (average.get(0)).get(k);
}
else {
put = (data.get(0)).get(k);
}
}
else {
put = (data.get(0)).get(k);
}
if (average.get(0).contains(put)) {
index = average.get(0).indexOf(put);
int count = dataCounts.get(put);
dataCounts.put(put, count + 1);
for (int i = 1; i < data.size(); i++) {
double old = (average.get(i)).get(index);
(average.get(i)).set(index, old + (((data.get(i)).get(k) - old) / (count + 1)));
double newMean = (average.get(i)).get(index);
double vary = (((count - 1) * (variance.get(i)).get(index)) + ((data.get(i)).get(k) - newMean)
* ((data.get(i)).get(k) - old))
/ count;
(variance.get(i)).set(index, vary);
}
}
else {
dataCounts.put(put, 1);
for (int a = 0; a < average.get(0).size(); a++) {
if (average.get(0).get(a) > put) {
index = a;
break;
}
}
if (index == -1) {
index = average.get(0).size() - 1;
}
average.get(0).add(put);
variance.get(0).add(put);
for (int a = 1; a < average.size(); a++) {
average.get(a).add(data.get(a).get(k));
variance.get(a).add(0.0);
}
if (index != average.get(0).size() - 1) {
for (int a = average.get(0).size() - 2; a >= 0; a--) {
if (average.get(0).get(a) > average.get(0).get(a + 1)) {
for (int b = 0; b < average.size(); b++) {
double temp = average.get(b).get(a);
average.get(b).set(a, average.get(b).get(a + 1));
average.get(b).set(a + 1, temp);
temp = variance.get(b).get(a);
variance.get(b).set(a, variance.get(b).get(a + 1));
variance.get(b).set(a + 1, temp);
}
}
else {
break;
}
}
}
}
}
}
first = false;
}
deviation = new ArrayList<ArrayList<Double>>();
for (int i = 0; i < variance.size(); i++) {
deviation.add(new ArrayList<Double>());
for (int j = 0; j < variance.get(i).size(); j++) {
deviation.get(i).add(variance.get(i).get(j));
}
}
for (int i = 1; i < deviation.size(); i++) {
for (int j = 0; j < deviation.get(i).size(); j++) {
deviation.get(i).set(j, Math.sqrt(deviation.get(i).get(j)));
}
}
averageOrder = null;
}
catch (Exception e) {
JOptionPane.showMessageDialog(Gui.frame, "Unable to output average, variance, and standard deviation!", "Error",
JOptionPane.ERROR_MESSAGE);
}
lock.unlock();
if (output) {
DataParser m = new DataParser(graphSpecies, average);
DataParser d = new DataParser(graphSpecies, deviation);
DataParser v = new DataParser(graphSpecies, variance);
if (directory == null) {
m.outputTSD(outDir + separator + "mean.tsd");
v.outputTSD(outDir + separator + "variance.tsd");
d.outputTSD(outDir + separator + "standard_deviation.tsd");
}
else {
m.outputTSD(outDir + separator + directory + separator + "mean.tsd");
v.outputTSD(outDir + separator + directory + separator + "variance.tsd");
d.outputTSD(outDir + separator + directory + separator + "standard_deviation.tsd");
}
}
if (choice == 0) {
return average;
}
else if (choice == 1) {
return variance;
}
else {
return deviation;
}
}
return null;
}
public void run() {
reb2sac.getRunButton().doClick();
}
public void save() {
if (timeSeries) {
Properties graph = new Properties();
graph.setProperty("title", chart.getTitle().getText());
graph.setProperty("chart.background.paint", "" + ((Color) chart.getBackgroundPaint()).getRGB());
graph.setProperty("plot.background.paint", "" + ((Color) chart.getPlot().getBackgroundPaint()).getRGB());
graph.setProperty("plot.domain.grid.line.paint", "" + ((Color) chart.getXYPlot().getDomainGridlinePaint()).getRGB());
graph.setProperty("plot.range.grid.line.paint", "" + ((Color) chart.getXYPlot().getRangeGridlinePaint()).getRGB());
graph.setProperty("x.axis", chart.getXYPlot().getDomainAxis().getLabel());
graph.setProperty("y.axis", chart.getXYPlot().getRangeAxis().getLabel());
graph.setProperty("x.min", XMin.getText());
graph.setProperty("x.max", XMax.getText());
graph.setProperty("x.scale", XScale.getText());
graph.setProperty("y.min", YMin.getText());
graph.setProperty("y.max", YMax.getText());
graph.setProperty("y.scale", YScale.getText());
graph.setProperty("auto.resize", "" + resize.isSelected());
graph.setProperty("LogX", "" + LogX.isSelected());
graph.setProperty("LogY", "" + LogY.isSelected());
graph.setProperty("visibleLegend", "" + visibleLegend.isSelected());
for (int i = 0; i < graphed.size(); i++) {
graph.setProperty("species.connected." + i, "" + graphed.get(i).getConnected());
graph.setProperty("species.filled." + i, "" + graphed.get(i).getFilled());
graph.setProperty("species.xnumber." + i, "" + graphed.get(i).getXNumber());
graph.setProperty("species.number." + i, "" + graphed.get(i).getNumber());
graph.setProperty("species.run.number." + i, graphed.get(i).getRunNumber());
graph.setProperty("species.name." + i, graphed.get(i).getSpecies());
graph.setProperty("species.id." + i, graphed.get(i).getID());
graph.setProperty("species.visible." + i, "" + graphed.get(i).getVisible());
graph.setProperty("species.paint." + i, graphed.get(i).getShapeAndPaint().getPaintName());
graph.setProperty("species.shape." + i, graphed.get(i).getShapeAndPaint().getShapeName());
graph.setProperty("species.directory." + i, graphed.get(i).getDirectory());
}
try {
FileOutputStream store = new FileOutputStream(new File(outDir + separator + graphName));
graph.store(store, "Graph Data");
store.close();
log.addText("Creating graph file:\n" + outDir + separator + graphName + "\n");
change = false;
}
catch (Exception except) {
JOptionPane.showMessageDialog(Gui.frame, "Unable To Save Graph!", "Error", JOptionPane.ERROR_MESSAGE);
}
}
else {
Properties graph = new Properties();
graph.setProperty("title", chart.getTitle().getText());
graph.setProperty("chart.background.paint", "" + ((Color) chart.getBackgroundPaint()).getRGB());
graph.setProperty("plot.background.paint", "" + ((Color) chart.getPlot().getBackgroundPaint()).getRGB());
graph.setProperty("plot.range.grid.line.paint", "" + ((Color) chart.getCategoryPlot().getRangeGridlinePaint()).getRGB());
graph.setProperty("x.axis", chart.getCategoryPlot().getDomainAxis().getLabel());
graph.setProperty("y.axis", chart.getCategoryPlot().getRangeAxis().getLabel());
graph.setProperty("gradient", "" + (((BarRenderer) chart.getCategoryPlot().getRenderer()).getBarPainter() instanceof GradientBarPainter));
graph.setProperty("shadow", "" + ((BarRenderer) chart.getCategoryPlot().getRenderer()).getShadowsVisible());
graph.setProperty("visibleLegend", "" + visibleLegend.isSelected());
for (int i = 0; i < probGraphed.size(); i++) {
graph.setProperty("species.number." + i, "" + probGraphed.get(i).getNumber());
graph.setProperty("species.name." + i, probGraphed.get(i).getSpecies());
graph.setProperty("species.id." + i, probGraphed.get(i).getID());
graph.setProperty("species.paint." + i, probGraphed.get(i).getPaintName());
graph.setProperty("species.directory." + i, probGraphed.get(i).getDirectory());
}
try {
FileOutputStream store = new FileOutputStream(new File(outDir + separator + graphName));
graph.store(store, "Probability Data");
store.close();
log.addText("Creating graph file:\n" + outDir + separator + graphName + "\n");
change = false;
}
catch (Exception except) {
JOptionPane.showMessageDialog(Gui.frame, "Unable To Save Graph!", "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
public void saveAs() {
if (timeSeries) {
String graphName = JOptionPane.showInputDialog(Gui.frame, "Enter Graph Name:", "Graph Name", JOptionPane.PLAIN_MESSAGE);
if (graphName != null && !graphName.trim().equals("")) {
graphName = graphName.trim();
if (graphName.length() > 3) {
if (!graphName.substring(graphName.length() - 4).equals(".grf")) {
graphName += ".grf";
}
}
else {
graphName += ".grf";
}
File f;
if (topLevel) {
f = new File(outDir + separator + graphName);
}
else {
f = new File(outDir.substring(0, outDir.length() - outDir.split(separator)[outDir.split(separator).length - 1].length())
+ separator + graphName);
}
if (f.exists()) {
Object[] options = { "Overwrite", "Cancel" };
int value = JOptionPane.showOptionDialog(Gui.frame, "File already exists." + "\nDo you want to overwrite?", "Overwrite",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
if (value == JOptionPane.YES_OPTION) {
File del;
if (topLevel) {
del = new File(outDir + separator + graphName);
}
else {
del = new File(
outDir.substring(0, outDir.length() - outDir.split(separator)[outDir.split(separator).length - 1].length())
+ separator + graphName);
}
if (del.isDirectory()) {
biomodelsim.deleteDir(del);
}
else {
del.delete();
}
for (int i = 0; i < biomodelsim.getTab().getTabCount(); i++) {
if (biomodelsim.getTab().getTitleAt(i).equals(graphName)) {
biomodelsim.getTab().remove(i);
}
}
}
else {
return;
}
}
Properties graph = new Properties();
graph.setProperty("title", chart.getTitle().getText());
graph.setProperty("x.axis", chart.getXYPlot().getDomainAxis().getLabel());
graph.setProperty("y.axis", chart.getXYPlot().getRangeAxis().getLabel());
graph.setProperty("x.min", XMin.getText());
graph.setProperty("x.max", XMax.getText());
graph.setProperty("x.scale", XScale.getText());
graph.setProperty("y.min", YMin.getText());
graph.setProperty("y.max", YMax.getText());
graph.setProperty("y.scale", YScale.getText());
graph.setProperty("auto.resize", "" + resize.isSelected());
graph.setProperty("LogX", "" + LogX.isSelected());
graph.setProperty("LogY", "" + LogY.isSelected());
graph.setProperty("visibleLegend", "" + visibleLegend.isSelected());
for (int i = 0; i < graphed.size(); i++) {
graph.setProperty("species.connected." + i, "" + graphed.get(i).getConnected());
graph.setProperty("species.filled." + i, "" + graphed.get(i).getFilled());
graph.setProperty("species.number." + i, "" + graphed.get(i).getNumber());
graph.setProperty("species.run.number." + i, graphed.get(i).getRunNumber());
graph.setProperty("species.name." + i, graphed.get(i).getSpecies());
graph.setProperty("species.id." + i, graphed.get(i).getID());
graph.setProperty("species.visible." + i, "" + graphed.get(i).getVisible());
graph.setProperty("species.paint." + i, graphed.get(i).getShapeAndPaint().getPaintName());
graph.setProperty("species.shape." + i, graphed.get(i).getShapeAndPaint().getShapeName());
if (topLevel) {
graph.setProperty("species.directory." + i, graphed.get(i).getDirectory());
}
else {
if (graphed.get(i).getDirectory().equals("")) {
graph.setProperty("species.directory." + i, outDir.split(separator)[outDir.split(separator).length - 1]);
}
else {
graph.setProperty("species.directory." + i, outDir.split(separator)[outDir.split(separator).length - 1] + "/"
+ graphed.get(i).getDirectory());
}
}
}
try {
FileOutputStream store = new FileOutputStream(f);
graph.store(store, "Graph Data");
store.close();
log.addText("Creating graph file:\n" + f.getAbsolutePath() + "\n");
change = false;
biomodelsim.addToTree(f.getName());
}
catch (Exception except) {
JOptionPane.showMessageDialog(Gui.frame, "Unable To Save Graph!", "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
else {
String graphName = JOptionPane.showInputDialog(Gui.frame, "Enter Probability Graph Name:", "Probability Graph Name",
JOptionPane.PLAIN_MESSAGE);
if (graphName != null && !graphName.trim().equals("")) {
graphName = graphName.trim();
if (graphName.length() > 3) {
if (!graphName.substring(graphName.length() - 4).equals(".prb")) {
graphName += ".prb";
}
}
else {
graphName += ".prb";
}
File f;
if (topLevel) {
f = new File(outDir + separator + graphName);
}
else {
f = new File(outDir.substring(0, outDir.length() - outDir.split(separator)[outDir.split(separator).length - 1].length())
+ separator + graphName);
}
if (f.exists()) {
Object[] options = { "Overwrite", "Cancel" };
int value = JOptionPane.showOptionDialog(Gui.frame, "File already exists." + "\nDo you want to overwrite?", "Overwrite",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
if (value == JOptionPane.YES_OPTION) {
File del;
if (topLevel) {
del = new File(outDir + separator + graphName);
}
else {
del = new File(
outDir.substring(0, outDir.length() - outDir.split(separator)[outDir.split(separator).length - 1].length())
+ separator + graphName);
}
if (del.isDirectory()) {
biomodelsim.deleteDir(del);
}
else {
del.delete();
}
for (int i = 0; i < biomodelsim.getTab().getTabCount(); i++) {
if (biomodelsim.getTab().getTitleAt(i).equals(graphName)) {
biomodelsim.getTab().remove(i);
}
}
}
else {
return;
}
}
Properties graph = new Properties();
graph.setProperty("title", chart.getTitle().getText());
graph.setProperty("x.axis", chart.getCategoryPlot().getDomainAxis().getLabel());
graph.setProperty("y.axis", chart.getCategoryPlot().getRangeAxis().getLabel());
graph.setProperty("gradient", ""
+ (((BarRenderer) chart.getCategoryPlot().getRenderer()).getBarPainter() instanceof GradientBarPainter));
graph.setProperty("shadow", "" + ((BarRenderer) chart.getCategoryPlot().getRenderer()).getShadowsVisible());
graph.setProperty("visibleLegend", "" + visibleLegend.isSelected());
for (int i = 0; i < probGraphed.size(); i++) {
graph.setProperty("species.number." + i, "" + probGraphed.get(i).getNumber());
graph.setProperty("species.name." + i, probGraphed.get(i).getSpecies());
graph.setProperty("species.id." + i, probGraphed.get(i).getID());
graph.setProperty("species.paint." + i, probGraphed.get(i).getPaintName());
if (topLevel) {
graph.setProperty("species.directory." + i, probGraphed.get(i).getDirectory());
}
else {
if (probGraphed.get(i).getDirectory().equals("")) {
graph.setProperty("species.directory." + i, outDir.split(separator)[outDir.split(separator).length - 1]);
}
else {
graph.setProperty("species.directory." + i, outDir.split(separator)[outDir.split(separator).length - 1] + "/"
+ probGraphed.get(i).getDirectory());
}
}
}
try {
FileOutputStream store = new FileOutputStream(f);
graph.store(store, "Probability Graph Data");
store.close();
log.addText("Creating probability graph file:\n" + f.getAbsolutePath() + "\n");
change = false;
biomodelsim.addToTree(f.getName());
}
catch (Exception except) {
JOptionPane.showMessageDialog(Gui.frame, "Unable To Save Probability Graph!", "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
}
private void open(String filename) {
if (timeSeries) {
Properties graph = new Properties();
try {
FileInputStream load = new FileInputStream(new File(filename));
graph.load(load);
load.close();
XMin.setText(graph.getProperty("x.min"));
XMax.setText(graph.getProperty("x.max"));
XScale.setText(graph.getProperty("x.scale"));
YMin.setText(graph.getProperty("y.min"));
YMax.setText(graph.getProperty("y.max"));
YScale.setText(graph.getProperty("y.scale"));
chart.setTitle(graph.getProperty("title"));
if (graph.containsKey("chart.background.paint")) {
chart.setBackgroundPaint(new Color(Integer.parseInt(graph.getProperty("chart.background.paint"))));
}
if (graph.containsKey("plot.background.paint")) {
chart.getPlot().setBackgroundPaint(new Color(Integer.parseInt(graph.getProperty("plot.background.paint"))));
}
if (graph.containsKey("plot.domain.grid.line.paint")) {
chart.getXYPlot().setDomainGridlinePaint(new Color(Integer.parseInt(graph.getProperty("plot.domain.grid.line.paint"))));
}
if (graph.containsKey("plot.range.grid.line.paint")) {
chart.getXYPlot().setRangeGridlinePaint(new Color(Integer.parseInt(graph.getProperty("plot.range.grid.line.paint"))));
}
chart.getXYPlot().getDomainAxis().setLabel(graph.getProperty("x.axis"));
chart.getXYPlot().getRangeAxis().setLabel(graph.getProperty("y.axis"));
if (graph.getProperty("auto.resize").equals("true")) {
resize.setSelected(true);
}
else {
resize.setSelected(false);
}
if (graph.containsKey("LogX") && graph.getProperty("LogX").equals("true")) {
LogX.setSelected(true);
}
else {
LogX.setSelected(false);
}
if (graph.containsKey("LogY") && graph.getProperty("LogY").equals("true")) {
LogY.setSelected(true);
}
else {
LogY.setSelected(false);
}
if (graph.containsKey("visibleLegend") && graph.getProperty("visibleLegend").equals("false")) {
visibleLegend.setSelected(false);
}
else {
visibleLegend.setSelected(true);
}
int next = 0;
while (graph.containsKey("species.name." + next)) {
boolean connected, filled, visible;
if (graph.getProperty("species.connected." + next).equals("true")) {
connected = true;
}
else {
connected = false;
}
if (graph.getProperty("species.filled." + next).equals("true")) {
filled = true;
}
else {
filled = false;
}
if (graph.getProperty("species.visible." + next).equals("true")) {
visible = true;
}
else {
visible = false;
}
int xnumber = 0;
if (graph.containsKey("species.xnumber." + next)) {
xnumber = Integer.parseInt(graph.getProperty("species.xnumber." + next));
}
graphed.add(new GraphSpecies(shapes.get(graph.getProperty("species.shape." + next)), graph.getProperty("species.paint." + next)
.trim(), filled, visible, connected, graph.getProperty("species.run.number." + next), graph.getProperty("species.id."
+ next), graph.getProperty("species.name." + next), xnumber,
Integer.parseInt(graph.getProperty("species.number." + next)), graph.getProperty("species.directory." + next)));
next++;
}
updateXNumber = false;
XVariable.addItem("time");
refresh();
}
catch (IOException except) {
JOptionPane.showMessageDialog(Gui.frame, "Unable To Load Graph!", "Error", JOptionPane.ERROR_MESSAGE);
}
}
else {
Properties graph = new Properties();
try {
FileInputStream load = new FileInputStream(new File(filename));
graph.load(load);
load.close();
chart.setTitle(graph.getProperty("title"));
if (graph.containsKey("chart.background.paint")) {
chart.setBackgroundPaint(new Color(Integer.parseInt(graph.getProperty("chart.background.paint"))));
}
if (graph.containsKey("plot.background.paint")) {
chart.getPlot().setBackgroundPaint(new Color(Integer.parseInt(graph.getProperty("plot.background.paint"))));
}
if (graph.containsKey("plot.range.grid.line.paint")) {
chart.getCategoryPlot().setRangeGridlinePaint(new Color(Integer.parseInt(graph.getProperty("plot.range.grid.line.paint"))));
}
chart.getCategoryPlot().getDomainAxis().setLabel(graph.getProperty("x.axis"));
chart.getCategoryPlot().getRangeAxis().setLabel(graph.getProperty("y.axis"));
if (graph.containsKey("gradient") && graph.getProperty("gradient").equals("true")) {
((BarRenderer) chart.getCategoryPlot().getRenderer()).setBarPainter(new GradientBarPainter());
}
else {
((BarRenderer) chart.getCategoryPlot().getRenderer()).setBarPainter(new StandardBarPainter());
}
if (graph.containsKey("shadow") && graph.getProperty("shadow").equals("false")) {
((BarRenderer) chart.getCategoryPlot().getRenderer()).setShadowVisible(false);
}
else {
((BarRenderer) chart.getCategoryPlot().getRenderer()).setShadowVisible(true);
}
if (graph.containsKey("visibleLegend") && graph.getProperty("visibleLegend").equals("false")) {
visibleLegend.setSelected(false);
}
else {
visibleLegend.setSelected(true);
}
int next = 0;
while (graph.containsKey("species.name." + next)) {
String color = graph.getProperty("species.paint." + next).trim();
Paint paint;
if (color.startsWith("Custom_")) {
paint = new Color(Integer.parseInt(color.replace("Custom_", "")));
}
else {
paint = colors.get(color);
}
probGraphed.add(new GraphProbs(paint, color, graph.getProperty("species.id." + next), graph.getProperty("species.name." + next),
Integer.parseInt(graph.getProperty("species.number." + next)), graph.getProperty("species.directory." + next)));
next++;
}
refreshProb();
}
catch (Exception except) {
JOptionPane.showMessageDialog(Gui.frame, "Unable To Load Graph!", "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
public boolean isTSDGraph() {
return timeSeries;
}
public void refresh() {
lock2.lock();
if (timeSeries) {
if (learnSpecs != null) {
updateSpecies();
}
double minY = 0;
double maxY = 0;
double scaleY = 0;
double minX = 0;
double maxX = 0;
double scaleX = 0;
try {
minY = Double.parseDouble(YMin.getText().trim());
maxY = Double.parseDouble(YMax.getText().trim());
scaleY = Double.parseDouble(YScale.getText().trim());
minX = Double.parseDouble(XMin.getText().trim());
maxX = Double.parseDouble(XMax.getText().trim());
scaleX = Double.parseDouble(XScale.getText().trim());
/*
* NumberFormat num = NumberFormat.getInstance();
* num.setMaximumFractionDigits(4); num.setGroupingUsed(false);
* minY = Double.parseDouble(num.format(minY)); maxY =
* Double.parseDouble(num.format(maxY)); scaleY =
* Double.parseDouble(num.format(scaleY)); minX =
* Double.parseDouble(num.format(minX)); maxX =
* Double.parseDouble(num.format(maxX)); scaleX =
* Double.parseDouble(num.format(scaleX));
*/
}
catch (Exception e1) {
}
ArrayList<XYSeries> graphData = new ArrayList<XYSeries>();
XYLineAndShapeRenderer rend = (XYLineAndShapeRenderer) chart.getXYPlot().getRenderer();
int thisOne = -1;
for (int i = 1; i < graphed.size(); i++) {
GraphSpecies index = graphed.get(i);
int j = i;
while ((j > 0) && (graphed.get(j - 1).getSpecies().compareToIgnoreCase(index.getSpecies()) > 0)) {
graphed.set(j, graphed.get(j - 1));
j = j - 1;
}
graphed.set(j, index);
}
ArrayList<GraphSpecies> unableToGraph = new ArrayList<GraphSpecies>();
HashMap<String, ArrayList<ArrayList<Double>>> allData = new HashMap<String, ArrayList<ArrayList<Double>>>();
for (GraphSpecies g : graphed) {
if (g.getDirectory().equals("")) {
thisOne++;
rend.setSeriesVisible(thisOne, true);
rend.setSeriesLinesVisible(thisOne, g.getConnected());
rend.setSeriesShapesFilled(thisOne, g.getFilled());
rend.setSeriesShapesVisible(thisOne, g.getVisible());
rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint());
rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape());
if (!g.getRunNumber().equals("Average") && !g.getRunNumber().equals("Variance") && !g.getRunNumber().equals("Standard Deviation")
&& !g.getRunNumber().equals("Termination Time") && !g.getRunNumber().equals("Percent Termination")
&& !g.getRunNumber().equals("Constraint Termination")) {
if (new File(outDir + separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
readGraphSpecies(outDir + separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8));
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
}
updateXNumber = false;
XVariable.removeAllItems();
for (int i = 0; i < graphSpecies.size(); i++) {
XVariable.addItem(graphSpecies.get(i));
}
updateXNumber = true;
}
else {
data = readData(outDir + separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8),
g.getRunNumber(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
boolean set = false;
for (int i = 1; i < graphSpecies.size(); i++) {
String compare = g.getID().replace(" (", "~");
if (graphSpecies.get(i).equals(compare.split("~")[0].trim())) {
g.setNumber(i - 1);
set = true;
}
}
if (g.getNumber() + 1 < graphSpecies.size() && set) {
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
}
else {
unableToGraph.add(g);
thisOne--;
}
}
else {
unableToGraph.add(g);
thisOne--;
}
}
else {
boolean ableToGraph = false;
try {
for (String s : new File(outDir).list()) {
if (s.length() > 3 && s.substring(0, 4).equals("run-")) {
ableToGraph = true;
}
}
}
catch (Exception e) {
ableToGraph = false;
}
if (!ableToGraph) {
if (g.getRunNumber().equals("Average")
&& new File(outDir + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
ableToGraph = true;
}
else if (g.getRunNumber().equals("Variance")
&& new File(outDir + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
ableToGraph = true;
}
else if (g.getRunNumber().equals("Standard Deviation")
&& new File(outDir + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
ableToGraph = true;
}
else if (g.getRunNumber().equals("Termination Time")
&& new File(outDir + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
ableToGraph = true;
}
else if (g.getRunNumber().equals("Percent Termination")
&& new File(outDir + separator + "percent-term-time" + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
ableToGraph = true;
}
else if (g.getRunNumber().equals("Constraint Termination")
&& new File(outDir + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
ableToGraph = true;
}
else if (g.getRunNumber().equals("Bifurcation Statistics")
&& new File(outDir + separator + "bifurcation" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
ableToGraph = true;
}
}
if (ableToGraph) {
int nextOne = 1;
// while (!new File(outDir + separator + "run-" +
// nextOne + "."
// + printer_id.substring(0, printer_id.length() -
// 8)).exists()) {
// nextOne++;
// }
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
if (g.getRunNumber().equals("Average")
&& new File(outDir + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8));
}
else if (g.getRunNumber().equals("Variance")
&& new File(outDir + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
readGraphSpecies(outDir + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8));
}
else if (g.getRunNumber().equals("Standard Deviation")
&& new File(outDir + separator + "standard_deviation" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + "standard_deviation" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (g.getRunNumber().equals("Termination Time")
&& new File(outDir + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
readGraphSpecies(outDir + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8));
}
else if (g.getRunNumber().equals("Percent Termination")
&& new File(outDir + separator + "percent-term-time" + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
readGraphSpecies(outDir + separator + "percent-term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (g.getRunNumber().equals("Constraint Termination")
&& new File(outDir + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8));
}
else if (g.getRunNumber().equals("Bifurcation Statistics")
&& new File(outDir + separator + "bifurcation" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + "bifurcation" + "." + printer_id.substring(0, printer_id.length() - 8));
}
else {
while (!new File(outDir + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
nextOne++;
}
readGraphSpecies(outDir + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8));
}
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
}
updateXNumber = false;
XVariable.removeAllItems();
for (int i = 0; i < graphSpecies.size(); i++) {
XVariable.addItem(graphSpecies.get(i));
}
updateXNumber = true;
}
else {
if (g.getRunNumber().equals("Average")
&& new File(outDir + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
data = readData(outDir + separator + "mean." + printer_id.substring(0, printer_id.length() - 8), g.getRunNumber()
.toLowerCase(), null, false);
}
else if (g.getRunNumber().equals("Variance")
&& new File(outDir + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
data = readData(outDir + separator + "variance." + printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
}
else if (g.getRunNumber().equals("Standard Deviation")
&& new File(outDir + separator + "standard_deviation" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
data = readData(outDir + separator + "standard_deviation." + printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
}
else if (g.getRunNumber().equals("Termination Time")
&& new File(outDir + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
data = readData(outDir + separator + "term-time." + printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
}
else if (g.getRunNumber().equals("Percent Termination")
&& new File(outDir + separator + "percent-term-time" + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
data = readData(outDir + separator + "percent-term-time." + printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
}
else if (g.getRunNumber().equals("Constraint Termination")
&& new File(outDir + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
data = readData(outDir + separator + "sim-rep." + printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
}
else if (g.getRunNumber().equals("Bifurcation Statistics")
&& new File(outDir + separator + "bifurcation" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
data = readData(outDir + separator + "bifurcation." + printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
}
else {
while (!new File(outDir + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
nextOne++;
}
data = readData(outDir + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
}
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
boolean set = false;
for (int i = 1; i < graphSpecies.size(); i++) {
String compare = g.getID().replace(" (", "~");
if (graphSpecies.get(i).equals(compare.split("~")[0].trim())) {
g.setNumber(i - 1);
set = true;
}
}
if (g.getNumber() + 1 < graphSpecies.size() && set) {
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
}
else {
unableToGraph.add(g);
thisOne--;
}
}
else {
unableToGraph.add(g);
thisOne--;
}
}
}
else {
thisOne++;
rend.setSeriesVisible(thisOne, true);
rend.setSeriesLinesVisible(thisOne, g.getConnected());
rend.setSeriesShapesFilled(thisOne, g.getFilled());
rend.setSeriesShapesVisible(thisOne, g.getVisible());
rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint());
rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape());
if (!g.getRunNumber().equals("Average") && !g.getRunNumber().equals("Variance") && !g.getRunNumber().equals("Standard Deviation")
&& !g.getRunNumber().equals("Termination Time") && !g.getRunNumber().equals("Percent Termination")
&& !g.getRunNumber().equals("Constraint Termination")) {
if (new File(outDir + separator + g.getDirectory() + separator + g.getRunNumber() + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
readGraphSpecies(outDir + separator + g.getDirectory() + separator + g.getRunNumber() + "."
+ printer_id.substring(0, printer_id.length() - 8));
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
}
updateXNumber = false;
XVariable.removeAllItems();
for (int i = 0; i < graphSpecies.size(); i++) {
XVariable.addItem(graphSpecies.get(i));
}
updateXNumber = true;
}
else {
data = readData(
outDir + separator + g.getDirectory() + separator + g.getRunNumber() + "."
+ printer_id.substring(0, printer_id.length() - 8), g.getRunNumber(), g.getDirectory(), false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
boolean set = false;
for (int i = 1; i < graphSpecies.size(); i++) {
String compare = g.getID().replace(" (", "~");
if (graphSpecies.get(i).equals(compare.split("~")[0].trim())) {
g.setNumber(i - 1);
set = true;
}
}
if (g.getNumber() + 1 < graphSpecies.size() && set) {
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
}
else {
unableToGraph.add(g);
thisOne--;
}
}
else {
unableToGraph.add(g);
thisOne--;
}
}
else {
boolean ableToGraph = false;
try {
for (String s : new File(outDir + separator + g.getDirectory()).list()) {
if (s.length() > 3 && s.substring(0, 4).equals("run-")) {
ableToGraph = true;
}
}
}
catch (Exception e) {
ableToGraph = false;
}
if (!ableToGraph) {
if (g.getRunNumber().equals("Average")
&& new File(outDir + separator + g.getDirectory() + separator + "mean" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
ableToGraph = true;
}
else if (g.getRunNumber().equals("Variance")
&& new File(outDir + separator + g.getDirectory() + separator + "variance" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
ableToGraph = true;
}
else if (g.getRunNumber().equals("Standard Deviation")
&& new File(outDir + separator + g.getDirectory() + separator + "standard_deviation" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
ableToGraph = true;
}
else if (g.getRunNumber().equals("Termination Time")
&& new File(outDir + separator + g.getDirectory() + separator + "term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
ableToGraph = true;
}
else if (g.getRunNumber().equals("Percent Termination")
&& new File(outDir + separator + g.getDirectory() + separator + "percent-term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
ableToGraph = true;
}
else if (g.getRunNumber().equals("Constraint Termination")
&& new File(outDir + separator + g.getDirectory() + separator + "sim-rep" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
ableToGraph = true;
}
else if (g.getRunNumber().equals("Bifurcation Statistics")
&& new File(outDir + separator + g.getDirectory() + separator + "bifurcation" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
ableToGraph = true;
}
}
if (ableToGraph) {
int nextOne = 1;
// while (!new File(outDir + separator +
// g.getDirectory() + separator
// + "run-" + nextOne + "."
// + printer_id.substring(0, printer_id.length() -
// 8)).exists()) {
// nextOne++;
// }
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
if (g.getRunNumber().equals("Average")
&& new File(outDir + separator + g.getDirectory() + separator + "mean" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + g.getDirectory() + separator + "mean" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (g.getRunNumber().equals("Variance")
&& new File(outDir + separator + g.getDirectory() + separator + "variance" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + g.getDirectory() + separator + "variance" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (g.getRunNumber().equals("Standard Deviation")
&& new File(outDir + separator + g.getDirectory() + separator + "standard_deviation" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + g.getDirectory() + separator + "standard_deviation" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (g.getRunNumber().equals("Termination Time")
&& new File(outDir + separator + g.getDirectory() + separator + "term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + g.getDirectory() + separator + "term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (g.getRunNumber().equals("Percent Termination")
&& new File(outDir + separator + g.getDirectory() + separator + "percent-term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + g.getDirectory() + separator + "percent-term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (g.getRunNumber().equals("Constraint Termination")
&& new File(outDir + separator + g.getDirectory() + separator + "sim-rep" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + g.getDirectory() + separator + "sim-rep" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (g.getRunNumber().equals("Bifurcation Statistics")
&& new File(outDir + separator + g.getDirectory() + separator + "bifurcation" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + g.getDirectory() + separator + "bifurcation" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else {
while (!new File(outDir + separator + g.getDirectory() + separator + "run-" + nextOne + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
nextOne++;
}
readGraphSpecies(outDir + separator + g.getDirectory() + separator + "run-" + nextOne + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
}
updateXNumber = false;
XVariable.removeAllItems();
for (int i = 0; i < graphSpecies.size(); i++) {
XVariable.addItem(graphSpecies.get(i));
}
updateXNumber = true;
}
else {
if (g.getRunNumber().equals("Average")
&& new File(outDir + separator + g.getDirectory() + separator + "mean" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
data = readData(
outDir + separator + g.getDirectory() + separator + "mean."
+ printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false);
}
else if (g.getRunNumber().equals("Variance")
&& new File(outDir + separator + g.getDirectory() + separator + "variance" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
data = readData(
outDir + separator + g.getDirectory() + separator + "variance."
+ printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false);
}
else if (g.getRunNumber().equals("Standard Deviation")
&& new File(outDir + separator + g.getDirectory() + separator + "standard_deviation" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
data = readData(
outDir + separator + g.getDirectory() + separator + "standard_deviation."
+ printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false);
}
else if (g.getRunNumber().equals("Termination Time")
&& new File(outDir + separator + g.getDirectory() + separator + "term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
data = readData(
outDir + separator + g.getDirectory() + separator + "term-time."
+ printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false);
}
else if (g.getRunNumber().equals("Percent Termination")
&& new File(outDir + separator + g.getDirectory() + separator + "percent-term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
data = readData(
outDir + separator + g.getDirectory() + separator + "percent-term-time."
+ printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false);
}
else if (g.getRunNumber().equals("Constraint Termination")
&& new File(outDir + separator + g.getDirectory() + separator + "sim-rep" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
data = readData(
outDir + separator + g.getDirectory() + separator + "sim-rep."
+ printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false);
}
else if (g.getRunNumber().equals("Bifurcation Statistics")
&& new File(outDir + separator + g.getDirectory() + separator + "bifurcation" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
data = readData(
outDir + separator + g.getDirectory() + separator + "bifurcation."
+ printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false);
}
else {
while (!new File(outDir + separator + g.getDirectory() + separator + "run-" + nextOne + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
nextOne++;
}
data = readData(
outDir + separator + g.getDirectory() + separator + "run-" + nextOne + "."
+ printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(),
g.getDirectory(), false);
}
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
boolean set = false;
for (int i = 1; i < graphSpecies.size(); i++) {
String compare = g.getID().replace(" (", "~");
if (graphSpecies.get(i).equals(compare.split("~")[0].trim())) {
g.setNumber(i - 1);
set = true;
}
}
if (g.getNumber() + 1 < graphSpecies.size() && set) {
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
}
else {
unableToGraph.add(g);
thisOne--;
}
}
else {
unableToGraph.add(g);
thisOne--;
}
}
}
}
for (GraphSpecies g : unableToGraph) {
graphed.remove(g);
}
XYSeriesCollection dataset = new XYSeriesCollection();
for (int i = 0; i < graphData.size(); i++) {
dataset.addSeries(graphData.get(i));
}
fixGraph(chart.getTitle().getText(), chart.getXYPlot().getDomainAxis().getLabel(), chart.getXYPlot().getRangeAxis().getLabel(), dataset);
chart.getXYPlot().setRenderer(rend);
XYPlot plot = chart.getXYPlot();
if (resize.isSelected()) {
resize(dataset);
}
else {
NumberAxis axis = (NumberAxis) plot.getRangeAxis();
axis.setAutoTickUnitSelection(false);
axis.setRange(minY, maxY);
axis.setTickUnit(new NumberTickUnit(scaleY));
axis = (NumberAxis) plot.getDomainAxis();
axis.setAutoTickUnitSelection(false);
axis.setRange(minX, maxX);
axis.setTickUnit(new NumberTickUnit(scaleX));
}
}
else {
BarRenderer rend = (BarRenderer) chart.getCategoryPlot().getRenderer();
int thisOne = -1;
for (int i = 1; i < probGraphed.size(); i++) {
GraphProbs index = probGraphed.get(i);
int j = i;
while ((j > 0) && (probGraphed.get(j - 1).getSpecies().compareToIgnoreCase(index.getSpecies()) > 0)) {
probGraphed.set(j, probGraphed.get(j - 1));
j = j - 1;
}
probGraphed.set(j, index);
}
ArrayList<GraphProbs> unableToGraph = new ArrayList<GraphProbs>();
DefaultCategoryDataset histDataset = new DefaultCategoryDataset();
for (GraphProbs g : probGraphed) {
if (g.getDirectory().equals("")) {
thisOne++;
rend.setSeriesPaint(thisOne, g.getPaint());
if (new File(outDir + separator + "sim-rep.txt").exists()) {
readProbSpecies(outDir + separator + "sim-rep.txt");
double[] data = readProbs(outDir + separator + "sim-rep.txt");
for (int i = 1; i < graphProbs.size(); i++) {
String index = graphProbs.get(i);
double index2 = data[i];
int j = i;
while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) {
graphProbs.set(j, graphProbs.get(j - 1));
data[j] = data[j - 1];
j = j - 1;
}
graphProbs.set(j, index);
data[j] = index2;
}
if (graphProbs.size() != 0) {
if (graphProbs.contains(g.getID())) {
for (int i = 0; i < graphProbs.size(); i++) {
if (g.getID().equals(graphProbs.get(i))) {
g.setNumber(i);
histDataset.setValue(data[i], g.getSpecies(), "");
}
}
}
else {
unableToGraph.add(g);
thisOne--;
}
}
}
else {
unableToGraph.add(g);
thisOne--;
}
}
else {
thisOne++;
rend.setSeriesPaint(thisOne, g.getPaint());
if (new File(outDir + separator + g.getDirectory() + separator + "sim-rep.txt").exists()) {
readProbSpecies(outDir + separator + g.getDirectory() + separator + "sim-rep.txt");
double[] data = readProbs(outDir + separator + g.getDirectory() + separator + "sim-rep.txt");
for (int i = 1; i < graphProbs.size(); i++) {
String index = graphProbs.get(i);
double index2 = data[i];
int j = i;
while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) {
graphProbs.set(j, graphProbs.get(j - 1));
data[j] = data[j - 1];
j = j - 1;
}
graphProbs.set(j, index);
data[j] = index2;
}
if (graphProbs.size() != 0) {
String compare = g.getID().replace(" (", "~");
if (graphProbs.contains(compare.split("~")[0].trim())) {
for (int i = 0; i < graphProbs.size(); i++) {
if (compare.split("~")[0].trim().equals(graphProbs.get(i))) {
g.setNumber(i);
histDataset.setValue(data[i], g.getSpecies(), "");
}
}
}
else {
unableToGraph.add(g);
thisOne--;
}
}
}
else {
unableToGraph.add(g);
thisOne--;
}
}
}
for (GraphProbs g : unableToGraph) {
probGraphed.remove(g);
}
fixProbGraph(chart.getTitle().getText(), chart.getCategoryPlot().getDomainAxis().getLabel(), chart.getCategoryPlot().getRangeAxis()
.getLabel(), histDataset, rend);
}
lock2.unlock();
}
private class ShapeAndPaint {
private Shape shape;
private Paint paint;
private ShapeAndPaint(Shape s, String p) {
shape = s;
if (p.startsWith("Custom_")) {
paint = new Color(Integer.parseInt(p.replace("Custom_", "")));
}
else {
paint = colors.get(p);
}
}
private Shape getShape() {
return shape;
}
private Paint getPaint() {
return paint;
}
private String getShapeName() {
Object[] set = shapes.keySet().toArray();
for (int i = 0; i < set.length; i++) {
if (shape == shapes.get(set[i])) {
return (String) set[i];
}
}
return "Unknown Shape";
}
private String getPaintName() {
Object[] set = colors.keySet().toArray();
for (int i = 0; i < set.length; i++) {
if (paint == colors.get(set[i])) {
return (String) set[i];
}
}
return "Custom_" + ((Color) paint).getRGB();
}
public void setPaint(String paint) {
if (paint.startsWith("Custom_")) {
this.paint = new Color(Integer.parseInt(paint.replace("Custom_", "")));
}
else {
this.paint = colors.get(paint);
}
}
public void setShape(String shape) {
this.shape = shapes.get(shape);
}
}
private class GraphSpecies {
private ShapeAndPaint sP;
private boolean filled, visible, connected;
private String runNumber, species, directory, id;
private int xnumber, number;
private GraphSpecies(Shape s, String p, boolean filled, boolean visible, boolean connected, String runNumber, String id, String species,
int xnumber, int number, String directory) {
sP = new ShapeAndPaint(s, p);
this.filled = filled;
this.visible = visible;
this.connected = connected;
this.runNumber = runNumber;
this.species = species;
this.xnumber = xnumber;
this.number = number;
this.directory = directory;
this.id = id;
}
private void setDirectory(String directory) {
this.directory = directory;
}
private void setXNumber(int xnumber) {
this.xnumber = xnumber;
}
private void setNumber(int number) {
this.number = number;
}
private void setSpecies(String species) {
this.species = species;
}
private void setPaint(String paint) {
sP.setPaint(paint);
}
private void setShape(String shape) {
sP.setShape(shape);
}
private void setVisible(boolean b) {
visible = b;
}
private void setFilled(boolean b) {
filled = b;
}
private void setConnected(boolean b) {
connected = b;
}
private int getXNumber() {
return xnumber;
}
private int getNumber() {
return number;
}
private String getSpecies() {
return species;
}
private ShapeAndPaint getShapeAndPaint() {
return sP;
}
private boolean getFilled() {
return filled;
}
private boolean getVisible() {
return visible;
}
private boolean getConnected() {
return connected;
}
private String getRunNumber() {
return runNumber;
}
private String getDirectory() {
return directory;
}
private String getID() {
return id;
}
}
public void setDirectory(String newDirectory) {
outDir = newDirectory;
}
public void setGraphName(String graphName) {
this.graphName = graphName;
}
public boolean hasChanged() {
return change;
}
private void probGraph(String label) {
chart = ChartFactory.createBarChart(label, "", "Percent", new DefaultCategoryDataset(), PlotOrientation.VERTICAL, true, true, false);
((BarRenderer) chart.getCategoryPlot().getRenderer()).setBarPainter(new StandardBarPainter());
chart.setBackgroundPaint(new java.awt.Color(238, 238, 238));
chart.getPlot().setBackgroundPaint(java.awt.Color.WHITE);
chart.getCategoryPlot().setRangeGridlinePaint(java.awt.Color.LIGHT_GRAY);
legend = chart.getLegend();
visibleLegend = new JCheckBox("Visible Legend");
visibleLegend.setSelected(true);
ChartPanel graph = new ChartPanel(chart);
graph.setLayout(new GridLayout(1, 1));
JLabel edit = new JLabel("Double click here to create graph");
edit.addMouseListener(this);
Font font = edit.getFont();
font = font.deriveFont(Font.BOLD, 42.0f);
edit.setFont(font);
edit.setHorizontalAlignment(SwingConstants.CENTER);
graph.add(edit);
graph.addMouseListener(this);
change = false;
// creates the buttons for the graph frame
JPanel ButtonHolder = new JPanel();
run = new JButton("Save and Run");
save = new JButton("Save Graph");
saveAs = new JButton("Save As");
export = new JButton("Export");
refresh = new JButton("Refresh");
run.addActionListener(this);
save.addActionListener(this);
saveAs.addActionListener(this);
export.addActionListener(this);
refresh.addActionListener(this);
if (reb2sac != null) {
ButtonHolder.add(run);
}
ButtonHolder.add(save);
ButtonHolder.add(saveAs);
ButtonHolder.add(export);
ButtonHolder.add(refresh);
// puts all the components of the graph gui into a display panel
// JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
// ButtonHolder, null);
// splitPane.setDividerSize(0);
this.removeAll();
this.setLayout(new BorderLayout());
this.add(graph, "Center");
// this.add(splitPane, "South");
}
private void editProbGraph() {
final ArrayList<GraphProbs> old = new ArrayList<GraphProbs>();
for (GraphProbs g : probGraphed) {
old.add(g);
}
final JPanel titlePanel = new JPanel(new BorderLayout());
JLabel titleLabel = new JLabel("Title:");
JLabel xLabel = new JLabel("X-Axis Label:");
JLabel yLabel = new JLabel("Y-Axis Label:");
final JCheckBox gradient = new JCheckBox("Paint In Gradient Style");
gradient.setSelected(!(((BarRenderer) chart.getCategoryPlot().getRenderer()).getBarPainter() instanceof StandardBarPainter));
final JCheckBox shadow = new JCheckBox("Paint Bar Shadows");
shadow.setSelected(((BarRenderer) chart.getCategoryPlot().getRenderer()).getShadowsVisible());
visibleLegend.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (((JCheckBox) e.getSource()).isSelected()) {
if (chart.getLegend() == null) {
chart.addLegend(legend);
}
}
else {
if (chart.getLegend() != null) {
legend = chart.getLegend();
}
chart.removeLegend();
}
}
});
final JTextField title = new JTextField(chart.getTitle().getText(), 5);
final JTextField x = new JTextField(chart.getCategoryPlot().getDomainAxis().getLabel(), 5);
final JTextField y = new JTextField(chart.getCategoryPlot().getRangeAxis().getLabel(), 5);
String simDirString = outDir.split(separator)[outDir.split(separator).length - 1];
simDir = new IconNode(simDirString, simDirString);
simDir.setIconName("");
String[] files = new File(outDir).list();
// for (int i = 1; i < files.length; i++) {
// String index = files[i];
// int j = i;
// while ((j > 0) && files[j - 1].compareToIgnoreCase(index) > 0) {
// files[j] = files[j - 1];
// j = j - 1;
// }
// files[j] = index;
// }
boolean add = false;
final ArrayList<String> directories = new ArrayList<String>();
for (String file : files) {
if (file.length() > 3 && file.substring(file.length() - 4).equals(".txt")) {
if (file.contains("sim-rep")) {
add = true;
}
}
else if (new File(outDir + separator + file).isDirectory()) {
boolean addIt = false;
for (String getFile : new File(outDir + separator + file).list()) {
if (getFile.length() > 3 && getFile.substring(getFile.length() - 4).equals(".txt") && getFile.contains("sim-rep")) {
addIt = true;
}
else if (new File(outDir + separator + file + separator + getFile).isDirectory()) {
for (String getFile2 : new File(outDir + separator + file + separator + getFile).list()) {
if (getFile2.length() > 3 && getFile2.substring(getFile2.length() - 4).equals(".txt") && getFile2.contains("sim-rep")) {
addIt = true;
}
}
}
}
if (addIt) {
directories.add(file);
IconNode d = new IconNode(file, file);
d.setIconName("");
String[] files2 = new File(outDir + separator + file).list();
// for (int i = 1; i < files2.length; i++) {
// String index = files2[i];
// int j = i;
// while ((j > 0) && files2[j -
// 1].compareToIgnoreCase(index) > 0) {
// files2[j] = files2[j - 1];
// j = j - 1;
// }
// files2[j] = index;
// }
boolean add2 = false;
for (String f : files2) {
if (f.equals("sim-rep.txt")) {
add2 = true;
}
else if (new File(outDir + separator + file + separator + f).isDirectory()) {
boolean addIt2 = false;
for (String getFile : new File(outDir + separator + file + separator + f).list()) {
if (getFile.length() > 3 && getFile.substring(getFile.length() - 4).equals(".txt") && getFile.contains("sim-rep")) {
addIt2 = true;
}
}
if (addIt2) {
directories.add(file + separator + f);
IconNode d2 = new IconNode(f, f);
d2.setIconName("");
for (String f2 : new File(outDir + separator + file + separator + f).list()) {
if (f2.equals("sim-rep.txt")) {
IconNode n = new IconNode(f2.substring(0, f2.length() - 4), f2.substring(0, f2.length() - 4));
d2.add(n);
n.setIconName("");
for (GraphProbs g : probGraphed) {
if (g.getDirectory().equals(d.getName() + separator + d2.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d2.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d2.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
}
boolean added = false;
for (int j = 0; j < d.getChildCount(); j++) {
if ((d.getChildAt(j).toString().compareToIgnoreCase(d2.toString()) > 0)
|| new File(outDir + separator + d.toString() + separator + (d.getChildAt(j).toString() + ".txt"))
.isFile()) {
d.insert(d2, j);
added = true;
break;
}
}
if (!added) {
d.add(d2);
}
}
}
}
if (add2) {
IconNode n = new IconNode("sim-rep", "sim-rep");
d.add(n);
n.setIconName("");
for (GraphProbs g : probGraphed) {
if (g.getDirectory().equals(d.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
boolean added = false;
for (int j = 0; j < simDir.getChildCount(); j++) {
if ((simDir.getChildAt(j).toString().compareToIgnoreCase(d.toString()) > 0)
|| new File(outDir + separator + (simDir.getChildAt(j).toString() + ".txt")).isFile()) {
simDir.insert(d, j);
added = true;
break;
}
}
if (!added) {
simDir.add(d);
}
}
}
}
if (add) {
IconNode n = new IconNode("sim-rep", "sim-rep");
simDir.add(n);
n.setIconName("");
for (GraphProbs g : probGraphed) {
if (g.getDirectory().equals("")) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (simDir.getChildCount() == 0) {
JOptionPane.showMessageDialog(Gui.frame, "No data to graph." + "\nPerform some simulations to create some data first.", "No Data",
JOptionPane.PLAIN_MESSAGE);
}
else {
tree = new JTree(simDir);
tree.putClientProperty("JTree.icons", makeIcons());
tree.setCellRenderer(new IconNodeRenderer());
DefaultTreeCellRenderer renderer = (DefaultTreeCellRenderer) tree.getCellRenderer();
renderer.setLeafIcon(MetalIconFactory.getTreeLeafIcon());
renderer.setClosedIcon(MetalIconFactory.getTreeFolderIcon());
renderer.setOpenIcon(MetalIconFactory.getTreeFolderIcon());
final JPanel all = new JPanel(new BorderLayout());
final JScrollPane scroll = new JScrollPane();
tree.addTreeExpansionListener(new TreeExpansionListener() {
public void treeCollapsed(TreeExpansionEvent e) {
JScrollPane scrollpane = new JScrollPane();
scrollpane.getViewport().add(tree);
all.removeAll();
all.add(titlePanel, "North");
all.add(scroll, "Center");
all.add(scrollpane, "West");
all.revalidate();
all.repaint();
}
public void treeExpanded(TreeExpansionEvent e) {
JScrollPane scrollpane = new JScrollPane();
scrollpane.getViewport().add(tree);
all.removeAll();
all.add(titlePanel, "North");
all.add(scroll, "Center");
all.add(scrollpane, "West");
all.revalidate();
all.repaint();
}
});
// for (int i = 0; i < tree.getRowCount(); i++) {
// tree.expandRow(i);
// }
JScrollPane scrollpane = new JScrollPane();
scrollpane.getViewport().add(tree);
scrollpane.setPreferredSize(new Dimension(175, 100));
final JPanel specPanel = new JPanel();
boolean stop = false;
int selectionRow = 1;
for (int i = 1; i < tree.getRowCount(); i++) {
tree.setSelectionRow(i);
if (selected.equals(lastSelected)) {
stop = true;
selectionRow = i;
break;
}
}
tree.addTreeSelectionListener(new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
node = (IconNode) e.getPath().getLastPathComponent();
if (!directories.contains(node.getName())) {
selected = node.getName();
int select;
if (selected.equals("sim-rep")) {
select = 0;
}
else {
select = -1;
}
if (select != -1) {
specPanel.removeAll();
if (node.getParent().getParent() != null
&& directories.contains(((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName())) {
specPanel.add(fixProbChoices(((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName()));
}
else if (directories.contains(((IconNode) node.getParent()).getName())) {
specPanel.add(fixProbChoices(((IconNode) node.getParent()).getName()));
}
else {
specPanel.add(fixProbChoices(""));
}
specPanel.revalidate();
specPanel.repaint();
for (int i = 0; i < series.size(); i++) {
series.get(i).setText(graphProbs.get(i));
series.get(i).setSelectionStart(0);
series.get(i).setSelectionEnd(0);
}
for (int i = 0; i < boxes.size(); i++) {
boxes.get(i).setSelected(false);
}
if (node.getParent().getParent() != null
&& directories.contains(((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName())) {
for (GraphProbs g : probGraphed) {
if (g.getDirectory()
.equals(((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName())) {
boxes.get(g.getNumber()).setSelected(true);
series.get(g.getNumber()).setText(g.getSpecies());
series.get(g.getNumber()).setSelectionStart(0);
series.get(g.getNumber()).setSelectionEnd(0);
colorsButtons.get(g.getNumber()).setBackground((Color) g.getPaint());
colorsButtons.get(g.getNumber()).setForeground((Color) g.getPaint());
colorsCombo.get(g.getNumber()).setSelectedItem(g.getPaintName().split("_")[0]);
}
}
}
else if (directories.contains(((IconNode) node.getParent()).getName())) {
for (GraphProbs g : probGraphed) {
if (g.getDirectory().equals(((IconNode) node.getParent()).getName())) {
boxes.get(g.getNumber()).setSelected(true);
series.get(g.getNumber()).setText(g.getSpecies());
series.get(g.getNumber()).setSelectionStart(0);
series.get(g.getNumber()).setSelectionEnd(0);
colorsButtons.get(g.getNumber()).setBackground((Color) g.getPaint());
colorsButtons.get(g.getNumber()).setForeground((Color) g.getPaint());
colorsCombo.get(g.getNumber()).setSelectedItem(g.getPaintName().split("_")[0]);
}
}
}
else {
for (GraphProbs g : probGraphed) {
if (g.getDirectory().equals("")) {
boxes.get(g.getNumber()).setSelected(true);
series.get(g.getNumber()).setText(g.getSpecies());
series.get(g.getNumber()).setSelectionStart(0);
series.get(g.getNumber()).setSelectionEnd(0);
colorsButtons.get(g.getNumber()).setBackground((Color) g.getPaint());
colorsButtons.get(g.getNumber()).setForeground((Color) g.getPaint());
colorsCombo.get(g.getNumber()).setSelectedItem(g.getPaintName().split("_")[0]);
}
}
}
boolean allChecked = true;
for (int i = 0; i < boxes.size(); i++) {
if (!boxes.get(i).isSelected()) {
allChecked = false;
String s = "";
if (node.getParent().getParent() != null
&& directories.contains(((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName())) {
s = "(" + ((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName() + ")";
}
else if (directories.contains(((IconNode) node.getParent()).getName())) {
s = "(" + ((IconNode) node.getParent()).getName() + ")";
}
String text = series.get(i).getText();
String end = "";
if (!s.equals("")) {
if (text.length() >= s.length()) {
for (int j = 0; j < s.length(); j++) {
end = text.charAt(text.length() - 1 - j) + end;
}
if (!s.equals(end)) {
text += " " + s;
}
}
else {
text += " " + s;
}
}
boxes.get(i).setName(text);
series.get(i).setText(text);
series.get(i).setSelectionStart(0);
series.get(i).setSelectionEnd(0);
colorsCombo.get(i).setSelectedIndex(0);
colorsButtons.get(i).setBackground((Color) colors.get("Black"));
colorsButtons.get(i).setForeground((Color) colors.get("Black"));
}
else {
String s = "";
if (node.getParent().getParent() != null
&& directories.contains(((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName())) {
s = "(" + ((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName() + ")";
}
else if (directories.contains(((IconNode) node.getParent()).getName())) {
s = "(" + ((IconNode) node.getParent()).getName() + ")";
}
String text = graphProbs.get(i);
String end = "";
if (!s.equals("")) {
if (text.length() >= s.length()) {
for (int j = 0; j < s.length(); j++) {
end = text.charAt(text.length() - 1 - j) + end;
}
if (!s.equals(end)) {
text += " " + s;
}
}
else {
text += " " + s;
}
}
boxes.get(i).setName(text);
}
}
if (allChecked) {
use.setSelected(true);
}
else {
use.setSelected(false);
}
}
}
else {
specPanel.removeAll();
specPanel.revalidate();
specPanel.repaint();
}
}
});
if (!stop) {
tree.setSelectionRow(0);
tree.setSelectionRow(1);
}
else {
tree.setSelectionRow(0);
tree.setSelectionRow(selectionRow);
}
scroll.setPreferredSize(new Dimension(1050, 500));
JPanel editPanel = new JPanel(new BorderLayout());
editPanel.add(specPanel, "Center");
scroll.setViewportView(editPanel);
final JButton deselect = new JButton("Deselect All");
deselect.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int size = probGraphed.size();
for (int i = 0; i < size; i++) {
probGraphed.remove();
}
IconNode n = simDir;
while (n != null) {
if (n.isLeaf()) {
n.setIcon(MetalIconFactory.getTreeLeafIcon());
n.setIconName("");
IconNode check = (IconNode) ((DefaultMutableTreeNode) n.getParent()).getChildAfter(n);
if (check == null) {
n = (IconNode) n.getParent();
if (n.getParent() == null) {
n = null;
}
else {
IconNode check2 = (IconNode) ((DefaultMutableTreeNode) n.getParent()).getChildAfter(n);
if (check2 == null) {
n = (IconNode) n.getParent();
if (n.getParent() == null) {
n = null;
}
else {
n = (IconNode) ((DefaultMutableTreeNode) n.getParent()).getChildAfter(n);
}
}
else {
n = check2;
}
}
}
else {
n = check;
}
}
else {
n.setIcon(MetalIconFactory.getTreeFolderIcon());
n.setIconName("");
n = (IconNode) n.getChildAt(0);
}
}
tree.revalidate();
tree.repaint();
if (tree.getSelectionCount() > 0) {
int selectedRow = tree.getSelectionRows()[0];
tree.setSelectionRow(0);
tree.setSelectionRow(selectedRow);
}
}
});
JPanel titlePanel1 = new JPanel(new GridLayout(1, 6));
JPanel titlePanel2 = new JPanel(new GridLayout(1, 6));
titlePanel1.add(titleLabel);
titlePanel1.add(title);
titlePanel1.add(xLabel);
titlePanel1.add(x);
titlePanel1.add(yLabel);
titlePanel1.add(y);
JPanel deselectPanel = new JPanel();
deselectPanel.add(deselect);
titlePanel2.add(deselectPanel);
titlePanel2.add(gradient);
titlePanel2.add(shadow);
titlePanel2.add(visibleLegend);
titlePanel2.add(new JPanel());
titlePanel2.add(new JPanel());
titlePanel.add(titlePanel1, "Center");
titlePanel.add(titlePanel2, "South");
all.add(titlePanel, "North");
all.add(scroll, "Center");
all.add(scrollpane, "West");
Object[] options = { "Ok", "Cancel" };
int value = JOptionPane.showOptionDialog(Gui.frame, all, "Edit Probability Graph", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE,
null, options, options[0]);
if (value == JOptionPane.YES_OPTION) {
change = true;
lastSelected = selected;
selected = "";
BarRenderer rend = (BarRenderer) chart.getCategoryPlot().getRenderer();
if (gradient.isSelected()) {
rend.setBarPainter(new GradientBarPainter());
}
else {
rend.setBarPainter(new StandardBarPainter());
}
if (shadow.isSelected()) {
rend.setShadowVisible(true);
}
else {
rend.setShadowVisible(false);
}
int thisOne = -1;
for (int i = 1; i < probGraphed.size(); i++) {
GraphProbs index = probGraphed.get(i);
int j = i;
while ((j > 0) && (probGraphed.get(j - 1).getSpecies().compareToIgnoreCase(index.getSpecies()) > 0)) {
probGraphed.set(j, probGraphed.get(j - 1));
j = j - 1;
}
probGraphed.set(j, index);
}
ArrayList<GraphProbs> unableToGraph = new ArrayList<GraphProbs>();
DefaultCategoryDataset histDataset = new DefaultCategoryDataset();
for (GraphProbs g : probGraphed) {
if (g.getDirectory().equals("")) {
thisOne++;
rend.setSeriesPaint(thisOne, g.getPaint());
if (new File(outDir + separator + "sim-rep.txt").exists()) {
readProbSpecies(outDir + separator + "sim-rep.txt");
double[] data = readProbs(outDir + separator + "sim-rep.txt");
for (int i = 1; i < graphProbs.size(); i++) {
String index = graphProbs.get(i);
double index2 = data[i];
int j = i;
while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) {
graphProbs.set(j, graphProbs.get(j - 1));
data[j] = data[j - 1];
j = j - 1;
}
graphProbs.set(j, index);
data[j] = index2;
}
if (graphProbs.size() != 0) {
for (int i = 0; i < graphProbs.size(); i++) {
if (g.getID().equals(graphProbs.get(i))) {
histDataset.setValue(data[i], g.getSpecies(), "");
}
}
}
}
else {
unableToGraph.add(g);
thisOne--;
}
}
else {
thisOne++;
rend.setSeriesPaint(thisOne, g.getPaint());
if (new File(outDir + separator + g.getDirectory() + separator + "sim-rep.txt").exists()) {
readProbSpecies(outDir + separator + g.getDirectory() + separator + "sim-rep.txt");
double[] data = readProbs(outDir + separator + g.getDirectory() + separator + "sim-rep.txt");
for (int i = 1; i < graphProbs.size(); i++) {
String index = graphProbs.get(i);
double index2 = data[i];
int j = i;
while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) {
graphProbs.set(j, graphProbs.get(j - 1));
data[j] = data[j - 1];
j = j - 1;
}
graphProbs.set(j, index);
data[j] = index2;
}
if (graphProbs.size() != 0) {
for (int i = 0; i < graphProbs.size(); i++) {
String compare = g.getID().replace(" (", "~");
if (compare.split("~")[0].trim().equals(graphProbs.get(i))) {
histDataset.setValue(data[i], g.getSpecies(), "");
}
}
}
}
else {
unableToGraph.add(g);
thisOne--;
}
}
}
for (GraphProbs g : unableToGraph) {
probGraphed.remove(g);
}
fixProbGraph(title.getText().trim(), x.getText().trim(), y.getText().trim(), histDataset, rend);
}
else {
selected = "";
int size = probGraphed.size();
for (int i = 0; i < size; i++) {
probGraphed.remove();
}
for (GraphProbs g : old) {
probGraphed.add(g);
}
}
}
}
private JPanel fixProbChoices(final String directory) {
if (directory.equals("")) {
readProbSpecies(outDir + separator + "sim-rep.txt");
}
else {
readProbSpecies(outDir + separator + directory + separator + "sim-rep.txt");
}
for (int i = 1; i < graphProbs.size(); i++) {
String index = graphProbs.get(i);
int j = i;
while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) {
graphProbs.set(j, graphProbs.get(j - 1));
j = j - 1;
}
graphProbs.set(j, index);
}
JPanel speciesPanel1 = new JPanel(new GridLayout(graphProbs.size() + 1, 1));
JPanel speciesPanel2 = new JPanel(new GridLayout(graphProbs.size() + 1, 2));
use = new JCheckBox("Use");
JLabel specs = new JLabel("Constraint");
JLabel color = new JLabel("Color");
boxes = new ArrayList<JCheckBox>();
series = new ArrayList<JTextField>();
colorsCombo = new ArrayList<JComboBox>();
colorsButtons = new ArrayList<JButton>();
use.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (use.isSelected()) {
for (JCheckBox box : boxes) {
if (!box.isSelected()) {
box.doClick();
}
}
}
else {
for (JCheckBox box : boxes) {
if (box.isSelected()) {
box.doClick();
}
}
}
}
});
speciesPanel1.add(use);
speciesPanel2.add(specs);
speciesPanel2.add(color);
final HashMap<String, Paint> colory = this.colors;
for (int i = 0; i < graphProbs.size(); i++) {
JCheckBox temp = new JCheckBox();
temp.setActionCommand("" + i);
temp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
if (((JCheckBox) e.getSource()).isSelected()) {
node.setIcon(TextIcons.getIcon("g"));
node.setIconName("" + (char) 10003);
IconNode n = ((IconNode) node.getParent());
while (n != null) {
n.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
n.setIconName("" + (char) 10003);
if (n.getParent() == null) {
n = null;
}
else {
n = ((IconNode) n.getParent());
}
}
tree.revalidate();
tree.repaint();
String s = series.get(i).getText();
((JCheckBox) e.getSource()).setSelected(false);
int[] cols = new int[35];
for (int k = 0; k < boxes.size(); k++) {
if (boxes.get(k).isSelected()) {
if (colorsCombo.get(k).getSelectedItem().equals("Red")) {
cols[0]++;
colorsButtons.get(k).setBackground((Color) colory.get("Red"));
colorsButtons.get(k).setForeground((Color) colory.get("Red"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Blue")) {
cols[1]++;
colorsButtons.get(k).setBackground((Color) colory.get("Blue"));
colorsButtons.get(k).setForeground((Color) colory.get("Blue"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Green")) {
cols[2]++;
colorsButtons.get(k).setBackground((Color) colory.get("Green"));
colorsButtons.get(k).setForeground((Color) colory.get("Green"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Yellow")) {
cols[3]++;
colorsButtons.get(k).setBackground((Color) colory.get("Yellow"));
colorsButtons.get(k).setForeground((Color) colory.get("Yellow"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Magenta")) {
cols[4]++;
colorsButtons.get(k).setBackground((Color) colory.get("Magenta"));
colorsButtons.get(k).setForeground((Color) colory.get("Magenta"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Cyan")) {
cols[5]++;
colorsButtons.get(k).setBackground((Color) colory.get("Cyan"));
colorsButtons.get(k).setForeground((Color) colory.get("Cyan"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Tan")) {
cols[6]++;
colorsButtons.get(k).setBackground((Color) colory.get("Tan"));
colorsButtons.get(k).setForeground((Color) colory.get("Tan"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Gray (Dark)")) {
cols[7]++;
colorsButtons.get(k).setBackground((Color) colory.get("Gray (Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Gray (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Red (Dark)")) {
cols[8]++;
colorsButtons.get(k).setBackground((Color) colory.get("Red (Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Red (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Blue (Dark)")) {
cols[9]++;
colorsButtons.get(k).setBackground((Color) colory.get("Blue (Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Blue (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Green (Dark)")) {
cols[10]++;
colorsButtons.get(k).setBackground((Color) colory.get("Green (Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Green (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Yellow (Dark)")) {
cols[11]++;
colorsButtons.get(k).setBackground((Color) colory.get("Yellow (Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Yellow (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Magenta (Dark)")) {
cols[12]++;
colorsButtons.get(k).setBackground((Color) colory.get("Magenta (Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Magenta (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Cyan (Dark)")) {
cols[13]++;
colorsButtons.get(k).setBackground((Color) colory.get("Cyan (Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Cyan (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Black")) {
cols[14]++;
colorsButtons.get(k).setBackground((Color) colory.get("Black"));
colorsButtons.get(k).setForeground((Color) colory.get("Black"));
}
/*
* else if
* (colorsCombo.get(k).getSelectedItem().
* equals("Red ")) { cols[15]++; } else if
* (colorsCombo
* .get(k).getSelectedItem().equals("Blue ")) {
* cols[16]++; } else if
* (colorsCombo.get(k).getSelectedItem
* ().equals("Green ")) { cols[17]++; } else if
* (colorsCombo.get(k).getSelectedItem().equals(
* "Yellow ")) { cols[18]++; } else if
* (colorsCombo
* .get(k).getSelectedItem().equals("Magenta "))
* { cols[19]++; } else if
* (colorsCombo.get(k).getSelectedItem
* ().equals("Cyan ")) { cols[20]++; }
*/
else if (colorsCombo.get(k).getSelectedItem().equals("Gray")) {
cols[21]++;
colorsButtons.get(k).setBackground((Color) colory.get("Gray"));
colorsButtons.get(k).setForeground((Color) colory.get("Gray"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Red (Extra Dark)")) {
cols[22]++;
colorsButtons.get(k).setBackground((Color) colory.get("Red (Extra Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Red (Extra Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Blue (Extra Dark)")) {
cols[23]++;
colorsButtons.get(k).setBackground((Color) colory.get("Blue (Extra Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Blue (Extra Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Green (Extra Dark)")) {
cols[24]++;
colorsButtons.get(k).setBackground((Color) colory.get("Green (Extra Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Green (Extra Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Yellow (Extra Dark)")) {
cols[25]++;
colorsButtons.get(k).setBackground((Color) colory.get("Yellow (Extra Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Yellow (Extra Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Magenta (Extra Dark)")) {
cols[26]++;
colorsButtons.get(k).setBackground((Color) colory.get("Magenta (Extra Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Magenta (Extra Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Cyan (Extra Dark)")) {
cols[27]++;
colorsButtons.get(k).setBackground((Color) colory.get("Cyan (Extra Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Cyan (Extra Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Red (Light)")) {
cols[28]++;
colorsButtons.get(k).setBackground((Color) colory.get("Red (Light)"));
colorsButtons.get(k).setForeground((Color) colory.get("Red (Light)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Blue (Light)")) {
cols[29]++;
colorsButtons.get(k).setBackground((Color) colory.get("Blue (Light)"));
colorsButtons.get(k).setForeground((Color) colory.get("Blue (Light)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Green (Light)")) {
cols[30]++;
colorsButtons.get(k).setBackground((Color) colory.get("Green (Light)"));
colorsButtons.get(k).setForeground((Color) colory.get("Green (Light)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Yellow (Light)")) {
cols[31]++;
colorsButtons.get(k).setBackground((Color) colory.get("Yellow (Light)"));
colorsButtons.get(k).setForeground((Color) colory.get("Yellow (Light)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Magenta (Light)")) {
cols[32]++;
colorsButtons.get(k).setBackground((Color) colory.get("Magenta (Light)"));
colorsButtons.get(k).setForeground((Color) colory.get("Magenta (Light)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Cyan (Light)")) {
cols[33]++;
colorsButtons.get(k).setBackground((Color) colory.get("Cyan (Light)"));
colorsButtons.get(k).setForeground((Color) colory.get("Cyan (Light)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Gray (Light)")) {
cols[34]++;
colorsButtons.get(k).setBackground((Color) colory.get("Gray (Light)"));
colorsButtons.get(k).setForeground((Color) colory.get("Gray (Light)"));
}
}
}
for (GraphProbs graph : probGraphed) {
if (graph.getPaintName().equals("Red")) {
cols[0]++;
}
else if (graph.getPaintName().equals("Blue")) {
cols[1]++;
}
else if (graph.getPaintName().equals("Green")) {
cols[2]++;
}
else if (graph.getPaintName().equals("Yellow")) {
cols[3]++;
}
else if (graph.getPaintName().equals("Magenta")) {
cols[4]++;
}
else if (graph.getPaintName().equals("Cyan")) {
cols[5]++;
}
else if (graph.getPaintName().equals("Tan")) {
cols[6]++;
}
else if (graph.getPaintName().equals("Gray (Dark)")) {
cols[7]++;
}
else if (graph.getPaintName().equals("Red (Dark)")) {
cols[8]++;
}
else if (graph.getPaintName().equals("Blue (Dark)")) {
cols[9]++;
}
else if (graph.getPaintName().equals("Green (Dark)")) {
cols[10]++;
}
else if (graph.getPaintName().equals("Yellow (Dark)")) {
cols[11]++;
}
else if (graph.getPaintName().equals("Magenta (Dark)")) {
cols[12]++;
}
else if (graph.getPaintName().equals("Cyan (Dark)")) {
cols[13]++;
}
else if (graph.getPaintName().equals("Black")) {
cols[14]++;
}
/*
* else if (graph.getPaintName().equals("Red ")) {
* cols[15]++; } else if
* (graph.getPaintName().equals("Blue ")) {
* cols[16]++; } else if
* (graph.getPaintName().equals("Green ")) {
* cols[17]++; } else if
* (graph.getPaintName().equals("Yellow ")) {
* cols[18]++; } else if
* (graph.getPaintName().equals("Magenta ")) {
* cols[19]++; } else if
* (graph.getPaintName().equals("Cyan ")) {
* cols[20]++; }
*/
else if (graph.getPaintName().equals("Gray")) {
cols[21]++;
}
else if (graph.getPaintName().equals("Red (Extra Dark)")) {
cols[22]++;
}
else if (graph.getPaintName().equals("Blue (Extra Dark)")) {
cols[23]++;
}
else if (graph.getPaintName().equals("Green (Extra Dark)")) {
cols[24]++;
}
else if (graph.getPaintName().equals("Yellow (Extra Dark)")) {
cols[25]++;
}
else if (graph.getPaintName().equals("Magenta (Extra Dark)")) {
cols[26]++;
}
else if (graph.getPaintName().equals("Cyan (Extra Dark)")) {
cols[27]++;
}
else if (graph.getPaintName().equals("Red (Light)")) {
cols[28]++;
}
else if (graph.getPaintName().equals("Blue (Light)")) {
cols[29]++;
}
else if (graph.getPaintName().equals("Green (Light)")) {
cols[30]++;
}
else if (graph.getPaintName().equals("Yellow (Light)")) {
cols[31]++;
}
else if (graph.getPaintName().equals("Magenta (Light)")) {
cols[32]++;
}
else if (graph.getPaintName().equals("Cyan (Light)")) {
cols[33]++;
}
else if (graph.getPaintName().equals("Gray (Light)")) {
cols[34]++;
}
}
((JCheckBox) e.getSource()).setSelected(true);
series.get(i).setText(s);
series.get(i).setSelectionStart(0);
series.get(i).setSelectionEnd(0);
int colorSet = 0;
for (int j = 1; j < cols.length; j++) {
if ((j < 15 || j > 20) && cols[j] < cols[colorSet]) {
colorSet = j;
}
}
DefaultDrawingSupplier draw = new DefaultDrawingSupplier();
Paint paint;
if (colorSet == 34) {
paint = colors.get("Gray (Light)");
}
else {
for (int j = 0; j < colorSet; j++) {
draw.getNextPaint();
}
paint = draw.getNextPaint();
}
Object[] set = colory.keySet().toArray();
for (int j = 0; j < set.length; j++) {
if (paint == colory.get(set[j])) {
colorsCombo.get(i).setSelectedItem(set[j]);
colorsButtons.get(i).setBackground((Color) paint);
colorsButtons.get(i).setForeground((Color) paint);
}
}
boolean allChecked = true;
for (JCheckBox temp : boxes) {
if (!temp.isSelected()) {
allChecked = false;
}
}
if (allChecked) {
use.setSelected(true);
}
String color = (String) colorsCombo.get(i).getSelectedItem();
if (color.equals("Custom")) {
color += "_" + colorsButtons.get(i).getBackground().getRGB();
}
probGraphed.add(new GraphProbs(colorsButtons.get(i).getBackground(), color, boxes.get(i).getName(), series.get(i).getText()
.trim(), i, directory));
}
else {
boolean check = false;
for (JCheckBox b : boxes) {
if (b.isSelected()) {
check = true;
}
}
if (!check) {
node.setIcon(MetalIconFactory.getTreeLeafIcon());
node.setIconName("");
boolean check2 = false;
IconNode parent = ((IconNode) node.getParent());
while (parent != null) {
for (int j = 0; j < parent.getChildCount(); j++) {
if (((IconNode) parent.getChildAt(j)).getIconName().equals("" + (char) 10003)) {
check2 = true;
}
}
if (!check2) {
parent.setIcon(MetalIconFactory.getTreeFolderIcon());
parent.setIconName("");
}
check2 = false;
if (parent.getParent() == null) {
parent = null;
}
else {
parent = ((IconNode) parent.getParent());
}
}
tree.revalidate();
tree.repaint();
}
ArrayList<GraphProbs> remove = new ArrayList<GraphProbs>();
for (GraphProbs g : probGraphed) {
if (g.getNumber() == i && g.getDirectory().equals(directory)) {
remove.add(g);
}
}
for (GraphProbs g : remove) {
probGraphed.remove(g);
}
use.setSelected(false);
colorsCombo.get(i).setSelectedIndex(0);
colorsButtons.get(i).setBackground((Color) colory.get("Black"));
colorsButtons.get(i).setForeground((Color) colory.get("Black"));
}
}
});
boxes.add(temp);
JTextField seriesName = new JTextField(graphProbs.get(i));
seriesName.setName("" + i);
seriesName.addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) {
int i = Integer.parseInt(((JTextField) e.getSource()).getName());
for (GraphProbs g : probGraphed) {
if (g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setSpecies(((JTextField) e.getSource()).getText());
}
}
}
public void keyReleased(KeyEvent e) {
int i = Integer.parseInt(((JTextField) e.getSource()).getName());
for (GraphProbs g : probGraphed) {
if (g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setSpecies(((JTextField) e.getSource()).getText());
}
}
}
public void keyTyped(KeyEvent e) {
int i = Integer.parseInt(((JTextField) e.getSource()).getName());
for (GraphProbs g : probGraphed) {
if (g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setSpecies(((JTextField) e.getSource()).getText());
}
}
}
});
series.add(seriesName);
ArrayList<String> allColors = new ArrayList<String>();
for (String c : this.colors.keySet()) {
allColors.add(c);
}
allColors.add("Custom");
Object[] col = allColors.toArray();
Arrays.sort(col);
JComboBox colBox = new JComboBox(col);
colBox.setActionCommand("" + i);
colBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
if (!((JComboBox) (e.getSource())).getSelectedItem().equals("Custom")) {
colorsButtons.get(i).setBackground((Color) colors.get(((JComboBox) (e.getSource())).getSelectedItem()));
colorsButtons.get(i).setForeground((Color) colors.get(((JComboBox) (e.getSource())).getSelectedItem()));
for (GraphProbs g : probGraphed) {
if (g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setPaintName((String) ((JComboBox) e.getSource()).getSelectedItem());
g.setPaint(colory.get(((JComboBox) e.getSource()).getSelectedItem()));
}
}
}
else {
for (GraphProbs g : probGraphed) {
if (g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setPaintName("Custom_" + colorsButtons.get(i).getBackground().getRGB());
g.setPaint(colorsButtons.get(i).getBackground());
}
}
}
}
});
colorsCombo.add(colBox);
JButton colorButton = new JButton();
colorButton.setPreferredSize(new Dimension(30, 20));
colorButton.setBorder(BorderFactory.createLineBorder(Color.darkGray));
colorButton.setBackground((Color) colory.get("Black"));
colorButton.setForeground((Color) colory.get("Black"));
colorButton.setUI(new MetalButtonUI());
colorButton.setActionCommand("" + i);
colorButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
Color newColor = JColorChooser.showDialog(Gui.frame, "Choose Color", ((JButton) e.getSource()).getBackground());
if (newColor != null) {
((JButton) e.getSource()).setBackground(newColor);
((JButton) e.getSource()).setForeground(newColor);
colorsCombo.get(i).setSelectedItem("Custom");
}
}
});
colorsButtons.add(colorButton);
JPanel colorPanel = new JPanel(new BorderLayout());
colorPanel.add(colorsCombo.get(i), "Center");
colorPanel.add(colorsButtons.get(i), "East");
speciesPanel1.add(boxes.get(i));
speciesPanel2.add(series.get(i));
speciesPanel2.add(colorPanel);
}
JPanel speciesPanel = new JPanel(new BorderLayout());
speciesPanel.add(speciesPanel1, "West");
speciesPanel.add(speciesPanel2, "Center");
return speciesPanel;
}
private void readProbSpecies(String file) {
graphProbs = new ArrayList<String>();
ArrayList<String> data = new ArrayList<String>();
try {
Scanner s = new Scanner(new File(file));
while (s.hasNextLine()) {
String[] ss = s.nextLine().split(" ");
if (ss[0].equals("The") && ss[1].equals("total") && ss[2].equals("termination") && ss[3].equals("count:") && ss[4].equals("0")) {
return;
}
if (data.size() == 0) {
for (String add : ss) {
data.add(add);
}
}
else {
for (int i = 0; i < ss.length; i++) {
data.set(i, data.get(i) + " " + ss[i]);
}
}
}
}
catch (Exception e) {
}
for (String s : data) {
if (!s.split(" ")[0].equals("#total")) {
graphProbs.add(s.split(" ")[0]);
}
}
}
private double[] readProbs(String file) {
ArrayList<String> data = new ArrayList<String>();
try {
Scanner s = new Scanner(new File(file));
while (s.hasNextLine()) {
String[] ss = s.nextLine().split(" ");
if (ss[0].equals("The") && ss[1].equals("total") && ss[2].equals("termination") && ss[3].equals("count:") && ss[4].equals("0")) {
return new double[0];
}
if (data.size() == 0) {
for (String add : ss) {
data.add(add);
}
}
else {
for (int i = 0; i < ss.length; i++) {
data.set(i, data.get(i) + " " + ss[i]);
}
}
}
}
catch (Exception e) {
}
double[] dataSet = new double[data.size()];
double total = 0;
int i = 0;
if (data.get(0).split(" ")[0].equals("#total")) {
total = Double.parseDouble(data.get(0).split(" ")[1]);
i = 1;
}
for (; i < data.size(); i++) {
if (total == 0) {
dataSet[i] = Double.parseDouble(data.get(i).split(" ")[1]);
}
else {
dataSet[i - 1] = 100 * ((Double.parseDouble(data.get(i).split(" ")[1])) / total);
}
}
return dataSet;
}
private void fixProbGraph(String label, String xLabel, String yLabel, DefaultCategoryDataset dataset, BarRenderer rend) {
Paint chartBackground = chart.getBackgroundPaint();
Paint plotBackground = chart.getPlot().getBackgroundPaint();
Paint plotRangeGridLine = chart.getCategoryPlot().getRangeGridlinePaint();
chart = ChartFactory.createBarChart(label, xLabel, yLabel, dataset, PlotOrientation.VERTICAL, true, true, false);
chart.getCategoryPlot().setRenderer(rend);
chart.setBackgroundPaint(chartBackground);
chart.getPlot().setBackgroundPaint(plotBackground);
chart.getCategoryPlot().setRangeGridlinePaint(plotRangeGridLine);
ChartPanel graph = new ChartPanel(chart);
legend = chart.getLegend();
if (visibleLegend.isSelected()) {
if (chart.getLegend() == null) {
chart.addLegend(legend);
}
}
else {
if (chart.getLegend() != null) {
legend = chart.getLegend();
}
chart.removeLegend();
}
if (probGraphed.isEmpty()) {
graph.setLayout(new GridLayout(1, 1));
JLabel edit = new JLabel("Double click here to create graph");
edit.addMouseListener(this);
Font font = edit.getFont();
font = font.deriveFont(Font.BOLD, 42.0f);
edit.setFont(font);
edit.setHorizontalAlignment(SwingConstants.CENTER);
graph.add(edit);
}
graph.addMouseListener(this);
JPanel ButtonHolder = new JPanel();
run = new JButton("Save and Run");
save = new JButton("Save Graph");
saveAs = new JButton("Save As");
export = new JButton("Export");
refresh = new JButton("Refresh");
run.addActionListener(this);
save.addActionListener(this);
saveAs.addActionListener(this);
export.addActionListener(this);
refresh.addActionListener(this);
if (reb2sac != null) {
ButtonHolder.add(run);
}
ButtonHolder.add(save);
ButtonHolder.add(saveAs);
ButtonHolder.add(export);
ButtonHolder.add(refresh);
// JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
// ButtonHolder, null);
// splitPane.setDividerSize(0);
this.removeAll();
this.setLayout(new BorderLayout());
this.add(graph, "Center");
// this.add(splitPane, "South");
this.revalidate();
}
public void refreshProb() {
BarRenderer rend = (BarRenderer) chart.getCategoryPlot().getRenderer();
int thisOne = -1;
for (int i = 1; i < probGraphed.size(); i++) {
GraphProbs index = probGraphed.get(i);
int j = i;
while ((j > 0) && (probGraphed.get(j - 1).getSpecies().compareToIgnoreCase(index.getSpecies()) > 0)) {
probGraphed.set(j, probGraphed.get(j - 1));
j = j - 1;
}
probGraphed.set(j, index);
}
ArrayList<GraphProbs> unableToGraph = new ArrayList<GraphProbs>();
DefaultCategoryDataset histDataset = new DefaultCategoryDataset();
for (GraphProbs g : probGraphed) {
if (g.getDirectory().equals("")) {
thisOne++;
rend.setSeriesPaint(thisOne, g.getPaint());
if (new File(outDir + separator + "sim-rep.txt").exists()) {
readProbSpecies(outDir + separator + "sim-rep.txt");
double[] data = readProbs(outDir + separator + "sim-rep.txt");
for (int i = 1; i < graphProbs.size(); i++) {
String index = graphProbs.get(i);
double index2 = data[i];
int j = i;
while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) {
graphProbs.set(j, graphProbs.get(j - 1));
data[j] = data[j - 1];
j = j - 1;
}
graphProbs.set(j, index);
data[j] = index2;
}
if (graphProbs.size() != 0) {
for (int i = 0; i < graphProbs.size(); i++) {
if (g.getID().equals(graphProbs.get(i))) {
g.setNumber(i);
histDataset.setValue(data[i], g.getSpecies(), "");
}
}
}
}
else {
unableToGraph.add(g);
thisOne--;
}
}
else {
thisOne++;
rend.setSeriesPaint(thisOne, g.getPaint());
if (new File(outDir + separator + g.getDirectory() + separator + "sim-rep.txt").exists()) {
readProbSpecies(outDir + separator + g.getDirectory() + separator + "sim-rep.txt");
double[] data = readProbs(outDir + separator + g.getDirectory() + separator + "sim-rep.txt");
for (int i = 1; i < graphProbs.size(); i++) {
String index = graphProbs.get(i);
double index2 = data[i];
int j = i;
while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) {
graphProbs.set(j, graphProbs.get(j - 1));
data[j] = data[j - 1];
j = j - 1;
}
graphProbs.set(j, index);
data[j] = index2;
}
if (graphProbs.size() != 0) {
for (int i = 0; i < graphProbs.size(); i++) {
String compare = g.getID().replace(" (", "~");
if (compare.split("~")[0].trim().equals(graphProbs.get(i))) {
histDataset.setValue(data[i], g.getSpecies(), "");
}
}
}
}
else {
unableToGraph.add(g);
thisOne--;
}
}
}
for (GraphProbs g : unableToGraph) {
probGraphed.remove(g);
}
fixProbGraph(chart.getTitle().getText(), chart.getCategoryPlot().getDomainAxis().getLabel(), chart.getCategoryPlot().getRangeAxis()
.getLabel(), histDataset, rend);
}
private void updateSpecies() {
String background;
try {
Properties p = new Properties();
String[] split = outDir.split(separator);
FileInputStream load = new FileInputStream(new File(outDir + separator + split[split.length - 1] + ".lrn"));
p.load(load);
load.close();
if (p.containsKey("genenet.file")) {
String[] getProp = p.getProperty("genenet.file").split(separator);
background = outDir.substring(0, outDir.length() - split[split.length - 1].length()) + separator + getProp[getProp.length - 1];
}
else if (p.containsKey("learn.file")) {
String[] getProp = p.getProperty("learn.file").split(separator);
background = outDir.substring(0, outDir.length() - split[split.length - 1].length()) + separator + getProp[getProp.length - 1];
}
else {
background = null;
}
}
catch (Exception e) {
JOptionPane.showMessageDialog(Gui.frame, "Unable to load background file.", "Error", JOptionPane.ERROR_MESSAGE);
background = null;
}
learnSpecs = new ArrayList<String>();
if (background != null) {
if (background.contains(".gcm")) {
BioModel gcm = new BioModel(biomodelsim.getRoot());
gcm.load(background);
learnSpecs = gcm.getSpecies();
}
else if (background.contains(".lpn")) {
LhpnFile lhpn = new LhpnFile(biomodelsim.log);
lhpn.load(background);
/*
HashMap<String, Properties> speciesMap = lhpn.getContinuous();
* for (String s : speciesMap.keySet()) { learnSpecs.add(s); }
*/
// ADDED BY SB.
TSDParser extractVars;
ArrayList<String> datFileVars = new ArrayList<String>();
// ArrayList<String> allVars = new ArrayList<String>();
Boolean varPresent = false;
// Finding the intersection of all the variables present in all
// data files.
for (int i = 1; (new File(outDir + separator + "run-" + i + ".tsd")).exists(); i++) {
extractVars = new TSDParser(outDir + separator + "run-" + i + ".tsd", false);
datFileVars = extractVars.getSpecies();
if (i == 1) {
learnSpecs.addAll(datFileVars);
}
for (String s : learnSpecs) {
varPresent = false;
for (String t : datFileVars) {
if (s.equalsIgnoreCase(t)) {
varPresent = true;
break;
}
}
if (!varPresent) {
learnSpecs.remove(s);
}
}
}
// END ADDED BY SB.
}
else {
SBMLDocument document = Gui.readSBML(background);
Model model = document.getModel();
ListOf ids = model.getListOfSpecies();
for (int i = 0; i < model.getNumSpecies(); i++) {
learnSpecs.add(((Species) ids.get(i)).getId());
}
}
}
for (int i = 0; i < learnSpecs.size(); i++) {
String index = learnSpecs.get(i);
int j = i;
while ((j > 0) && learnSpecs.get(j - 1).compareToIgnoreCase(index) > 0) {
learnSpecs.set(j, learnSpecs.get(j - 1));
j = j - 1;
}
learnSpecs.set(j, index);
}
}
public boolean getWarning() {
return warn;
}
private class GraphProbs {
private Paint paint;
private String species, directory, id, paintName;
private int number;
private GraphProbs(Paint paint, String paintName, String id, String species, int number, String directory) {
this.paint = paint;
this.paintName = paintName;
this.species = species;
this.number = number;
this.directory = directory;
this.id = id;
}
private Paint getPaint() {
return paint;
}
private void setPaint(Paint p) {
paint = p;
}
private String getPaintName() {
return paintName;
}
private void setPaintName(String p) {
paintName = p;
}
private String getSpecies() {
return species;
}
private void setSpecies(String s) {
species = s;
}
private String getDirectory() {
return directory;
}
private String getID() {
return id;
}
private int getNumber() {
return number;
}
private void setNumber(int n) {
number = n;
}
}
private Hashtable makeIcons() {
Hashtable<String, Icon> icons = new Hashtable<String, Icon>();
icons.put("floppyDrive", MetalIconFactory.getTreeFloppyDriveIcon());
icons.put("hardDrive", MetalIconFactory.getTreeHardDriveIcon());
icons.put("computer", MetalIconFactory.getTreeComputerIcon());
icons.put("c", TextIcons.getIcon("c"));
icons.put("java", TextIcons.getIcon("java"));
icons.put("html", TextIcons.getIcon("html"));
return icons;
}
}
class IconNodeRenderer extends DefaultTreeCellRenderer {
/**
*
*/
private static final long serialVersionUID = -940588131120912851L;
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) {
super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
Icon icon = ((IconNode) value).getIcon();
if (icon == null) {
Hashtable icons = (Hashtable) tree.getClientProperty("JTree.icons");
String name = ((IconNode) value).getIconName();
if ((icons != null) && (name != null)) {
icon = (Icon) icons.get(name);
if (icon != null) {
setIcon(icon);
}
}
}
else {
setIcon(icon);
}
return this;
}
}
class IconNode extends DefaultMutableTreeNode {
/**
*
*/
private static final long serialVersionUID = 2887169888272379817L;
protected Icon icon;
protected String iconName;
private String hiddenName;
public IconNode() {
this(null, "");
}
public IconNode(Object userObject, String name) {
this(userObject, true, null, name);
}
public IconNode(Object userObject, boolean allowsChildren, Icon icon, String name) {
super(userObject, allowsChildren);
this.icon = icon;
hiddenName = name;
}
public String getName() {
return hiddenName;
}
public void setName(String name) {
hiddenName = name;
}
public void setIcon(Icon icon) {
this.icon = icon;
}
public Icon getIcon() {
return icon;
}
public String getIconName() {
if (iconName != null) {
return iconName;
}
else {
String str = userObject.toString();
int index = str.lastIndexOf(".");
if (index != -1) {
return str.substring(++index);
}
else {
return null;
}
}
}
public void setIconName(String name) {
iconName = name;
}
}
class TextIcons extends MetalIconFactory.TreeLeafIcon {
/**
*
*/
private static final long serialVersionUID = 1623303213056273064L;
protected String label;
private static Hashtable<String, String> labels;
protected TextIcons() {
}
public void paintIcon(Component c, Graphics g, int x, int y) {
super.paintIcon(c, g, x, y);
if (label != null) {
FontMetrics fm = g.getFontMetrics();
int offsetX = (getIconWidth() - fm.stringWidth(label)) / 2;
int offsetY = (getIconHeight() - fm.getHeight()) / 2 - 2;
g.drawString(label, x + offsetX, y + offsetY + fm.getHeight());
}
}
public static Icon getIcon(String str) {
if (labels == null) {
labels = new Hashtable<String, String>();
setDefaultSet();
}
TextIcons icon = new TextIcons();
icon.label = (String) labels.get(str);
return icon;
}
public static void setLabelSet(String ext, String label) {
if (labels == null) {
labels = new Hashtable<String, String>();
setDefaultSet();
}
labels.put(ext, label);
}
private static void setDefaultSet() {
labels.put("c", "C");
labels.put("java", "J");
labels.put("html", "H");
labels.put("htm", "H");
labels.put("g", "" + (char) 10003);
// and so on
/*
* labels.put("txt" ,"TXT"); labels.put("TXT" ,"TXT"); labels.put("cc"
* ,"C++"); labels.put("C" ,"C++"); labels.put("cpp" ,"C++");
* labels.put("exe" ,"BIN"); labels.put("class" ,"BIN");
* labels.put("gif" ,"GIF"); labels.put("GIF" ,"GIF");
*
* labels.put("", "");
*/
}
}
|
Working on bifurcation code.
|
gui/src/graph/Graph.java
|
Working on bifurcation code.
|
|
Java
|
apache-2.0
|
010a7a90eb80572439701117101c76f6d8bd0d08
| 0
|
jangorecki/h2o-3,mathemage/h2o-3,michalkurka/h2o-3,michalkurka/h2o-3,YzPaul3/h2o-3,mathemage/h2o-3,mathemage/h2o-3,YzPaul3/h2o-3,mathemage/h2o-3,spennihana/h2o-3,spennihana/h2o-3,h2oai/h2o-3,jangorecki/h2o-3,YzPaul3/h2o-3,YzPaul3/h2o-3,michalkurka/h2o-3,michalkurka/h2o-3,mathemage/h2o-3,spennihana/h2o-3,jangorecki/h2o-3,YzPaul3/h2o-3,h2oai/h2o-dev,michalkurka/h2o-3,h2oai/h2o-dev,mathemage/h2o-3,h2oai/h2o-dev,jangorecki/h2o-3,spennihana/h2o-3,h2oai/h2o-dev,h2oai/h2o-3,mathemage/h2o-3,spennihana/h2o-3,h2oai/h2o-3,YzPaul3/h2o-3,h2oai/h2o-dev,h2oai/h2o-3,h2oai/h2o-3,spennihana/h2o-3,h2oai/h2o-3,h2oai/h2o-dev,michalkurka/h2o-3,h2oai/h2o-3,h2oai/h2o-3,jangorecki/h2o-3,h2oai/h2o-dev,michalkurka/h2o-3,jangorecki/h2o-3,spennihana/h2o-3,jangorecki/h2o-3,YzPaul3/h2o-3
|
package hex.glm;
import hex.*;
import hex.deeplearning.DeepLearningModel.DeepLearningParameters.MissingValuesHandling;
import hex.glm.ComputationState.GLMSubsetGinfo;
import hex.glm.GLMModel.*;
import hex.optimization.ADMM.L1Solver;
import hex.optimization.L_BFGS;
import hex.glm.GLMModel.GLMParameters.Family;
import hex.glm.GLMModel.GLMParameters.Link;
import hex.glm.GLMModel.GLMParameters.Solver;
import hex.glm.GLMTask.*;
import hex.gram.Gram;
import hex.gram.Gram.Cholesky;
import hex.gram.Gram.NonSPDMatrixException;
import hex.optimization.ADMM;
import hex.optimization.ADMM.ProximalSolver;
import hex.optimization.L_BFGS.*;
import hex.optimization.OptimizationUtils.*;
import jsr166y.CountedCompleter;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import water.*;
import water.exceptions.H2OModelBuilderIllegalArgumentException;
import water.fvec.*;
import water.parser.BufferedString;
import water.util.*;
import water.util.ArrayUtils;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
/**
* Created by tomasnykodym on 8/27/14.
*
* Generalized linear model implementation.
*/
public class GLM extends ModelBuilder<GLMModel,GLMParameters,GLMOutput> {
static NumberFormat lambdaFormatter = new DecimalFormat(".##E0");
static NumberFormat devFormatter = new DecimalFormat(".##");
public static final int SCORING_INTERVAL_MSEC = 15000; // scoreAndUpdateModel every minute unless socre every iteration is set
public String _generatedWeights = null;
public GLM(boolean startup_once){super(new GLMParameters(),startup_once);}
public GLM(GLMModel.GLMParameters parms) {
super(parms);
init(false);
}
public GLM(GLMModel.GLMParameters parms,Key dest) {
super(parms,dest);
init(false);
}
public boolean isSupervised() {
return true;
}
@Override
public ModelCategory[] can_build() {
return new ModelCategory[]{
ModelCategory.Regression,
ModelCategory.Binomial,
};
}
@Override
protected void checkMemoryFootPrint() {/* see below */ }
protected void checkMemoryFootPrint(DataInfo dinfo) {
if (_parms._solver == Solver.IRLSM && !_parms._lambda_search) {
HeartBeat hb = H2O.SELF._heartbeat;
double p = dinfo.fullN() - dinfo.largestCat();
long mem_usage = (long) (hb._cpus_allowed * (p * p + dinfo.largestCat()) * 8/*doubles*/ * (1 + .5 * Math.log((double) _train.lastVec().nChunks()) / Math.log(2.))); //one gram per core
long max_mem = hb.get_free_mem();
if (mem_usage > max_mem) {
String msg = "Gram matrices (one per thread) won't fit in the driver node's memory ("
+ PrettyPrint.bytes(mem_usage) + " > " + PrettyPrint.bytes(max_mem)
+ ") - try reducing the number of columns and/or the number of categorical factors (or switch to the L-BFGS solver).";
error("_train", msg);
}
}
}
static class TooManyPredictorsException extends RuntimeException {}
DataInfo _dinfo;
private int _lambdaId;
private transient DataInfo _validDinfo;
// time per iteration in ms
private static class ScoringHistory {
private ArrayList<Integer> _scoringIters = new ArrayList<>();
private ArrayList<Long> _scoringTimes = new ArrayList<>();
private ArrayList<Double> _likelihoods = new ArrayList<>();
private ArrayList<Double> _objectives = new ArrayList<>();
public synchronized void addIterationScore(int iter, double likelihood, double obj) {
if (_scoringIters.size() > 0 && _scoringIters.get(_scoringIters.size() - 1) == iter)
return; // do not record twice, happens for the last iteration, need to record scoring history in checkKKTs because of gaussian fam.
_scoringIters.add(iter);
_scoringTimes.add(System.currentTimeMillis());
_likelihoods.add(likelihood);
_objectives.add(obj);
}
public synchronized TwoDimTable to2dTable() {
String[] cnames = new String[]{"timestamp", "duration", "iteration", "negative_log_likelihood", "objective"};
String[] ctypes = new String[]{"string", "string", "int", "double", "double"};
String[] cformats = new String[]{"%s", "%s", "%d", "%.5f", "%.5f"};
TwoDimTable res = new TwoDimTable("Scoring History", "", new String[_scoringIters.size()], cnames, ctypes, cformats, "");
int j = 0;
DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
for (int i = 0; i < _scoringIters.size(); ++i) {
int col = 0;
res.set(i, col++, fmt.print(_scoringTimes.get(i)));
res.set(i, col++, PrettyPrint.msecs(_scoringTimes.get(i) - _scoringTimes.get(0), true));
res.set(i, col++, _scoringIters.get(i));
res.set(i, col++, _likelihoods.get(i));
res.set(i, col++, _objectives.get(i));
}
return res;
}
}
private static class LambdaSearchScoringHistory {
ArrayList<Long> _scoringTimes = new ArrayList<>();
private ArrayList<Double> _lambdas = new ArrayList<>();
private ArrayList<Integer> _lambdaIters = new ArrayList<>();
private ArrayList<Integer> _lambdaPredictors = new ArrayList<>();
private ArrayList<Double> _lambdaDevTrain = new ArrayList<>();
private ArrayList<Double> _lambdaDevTest = new ArrayList<>();
public synchronized void addLambdaScore(int iter, int predictors, double lambda, double devRatioTrain, double devRatioTest) {
_scoringTimes.add(System.currentTimeMillis());
_lambdaIters.add(iter);
_lambdas.add(lambda);
_lambdaPredictors.add(predictors);
_lambdaDevTrain.add(devRatioTrain);
_lambdaDevTest.add(devRatioTest);
}
public synchronized TwoDimTable to2dTable() {
String[] cnames = new String[]{"timestamp", "duration", "iteration", "lambda", "predictors", "Explained Deviance (train)", "Explained Deviance (test)"};
String[] ctypes = new String[]{"string", "string", "int", "string","int", "double","double"};
String[] cformats = new String[]{"%s", "%s", "%d","%s", "%d", "%.3f","%.3f"};
TwoDimTable res = new TwoDimTable("Scoring History", "", new String[_lambdaIters.size()], cnames, ctypes, cformats, "");
int j = 0;
DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
for (int i = 0; i < _lambdaIters.size(); ++i) {
int col = 0;
res.set(i, col++, fmt.print(_scoringTimes.get(i)));
res.set(i, col++, PrettyPrint.msecs(_scoringTimes.get(i) - _scoringTimes.get(0), true));
res.set(i, col++, _lambdaIters.get(i));
res.set(i, col++, lambdaFormatter.format(_lambdas.get(i)));
res.set(i, col++, _lambdaPredictors.get(i));
res.set(i, col++, _lambdaDevTrain.get(i));
if(_lambdaDevTest.size() > i)
res.set(i, col++, _lambdaDevTest.get(i));
}
return res;
}
}
private transient ScoringHistory _sc;
private transient LambdaSearchScoringHistory _lsc;
long _t0 = System.currentTimeMillis();
private transient double _iceptAdjust = 0;
private transient GradientInfo _ginfo;
private double _lmax;
private transient long _nobs;
private transient GLMModel _model;
// special vecs made for irlsm
private static final String _wName = "__glm_irlsm_wvec";
private static final String _zName = "__glm_irlsm_zvec";
private transient Vec _w;
private transient Vec _z;
// and for multinomial irlsm
@Override
public int nclasses() {
if (_parms._family == Family.multinomial)
return _nclass;
if (_parms._family == Family.binomial)
return 2;
return 1;
}
private boolean doingIRLSM() {
if (_parms._family == Family.gaussian && _parms._link == Link.identity)
return false; // no need for IRLSM, standard LSM will do
if (_parms._solver == Solver.IRLSM)
return true;
if (_parms._solver == Solver.AUTO)
return true; // todo
return false;
}
private transient double[] _nullBeta;
private double[] getNullPrediction() {
double [] nb = getNullBeta();
if(_parms._family != Family.multinomial)
return new double[]{_parms.linkInv(nb[nb.length-1])};
double [] res = new double[_nclass];
if(_parms._intercept) {
int N = _dinfo.fullN()+1;
for (int i = 0; i < res.length; ++i)
res[i] = Math.exp(nb[_dinfo.fullN() + i*N]);
}
return res;
}
private double[] getNullBeta() {
if (_nullBeta == null) {
if (_parms._family == Family.multinomial) {
_nullBeta = MemoryManager.malloc8d((_dinfo.fullN() + 1) * nclasses());
int N = _dinfo.fullN() + 1;
for (int i = 0; i < nclasses(); ++i)
_nullBeta[_dinfo.fullN() + i * N] = Math.log(_state._ymu[i]);
} else {
_nullBeta = MemoryManager.malloc8d(_dinfo.fullN() + 1);
if (_parms._intercept)
_nullBeta[_dinfo.fullN()] = new GLMModel.GLMWeightsFun(_parms).link(_state._ymu[0]);
else
_nullBeta[_dinfo.fullN()] = 0;
}
}
return _nullBeta;
}
private transient GLMMetricBuilder _nullValidation;
// static so I can make inner class mr task without sending whole glm over
private static GLMMetricBuilder getNullValidation(final GLM glm) {
return null;
}
protected boolean computePriorClassDistribution(){return _parms._family == Family.multinomial;}
@Override
public void init(boolean expensive) {
super.init(expensive);
hide("_balance_classes", "Not applicable since class balancing is not required for GLM.");
hide("_max_after_balance_size", "Not applicable since class balancing is not required for GLM.");
hide("_class_sampling_factors", "Not applicable since class balancing is not required for GLM.");
_parms.validate(this);
if(_response != null)
switch( _parms._family) {
case binomial:
if( !_response.isBinary() && _nclass != 2)
error("_family", H2O.technote(2, "Binomial requires the response to be a 2-class categorical or a binary column (0/1)"));
break;
case multinomial:
if (_nclass <= 2) error("_family", H2O.technote(2, "Multinomial requires a categorical response with at least 3 levels (for 2 class problem use family=binomial."));
break;
case poisson:
if (_nclass != 1) error("_family", "Poisson requires the response to be numeric.");
if(_response.min() < 0)
error("_family", "Poisson requires response >= 0");
if(!_response.isInt())
warn("_family","Poisson expects non-negative integer response, got floats.");
break;
case gamma:
if (_nclass != 1) error("_distribution", H2O.technote(2, "Gamma requires the response to be numeric."));
if(_response.min() <= 0) error("_family","Gamma requires positive respone");
break;
case tweedie:
if (_nclass != 1) error("_family", H2O.technote(2, "Tweedie requires the response to be numeric."));
break;
case gaussian:
// if (_nclass != 1) error("_family", H2O.technote(2, "Gaussian requires the response to be numeric."));
break;
default:
error("_family","Invalid distribution: " + _parms._distribution);
}
if (expensive) {
if (error_count() > 0) return;
_lsc = new LambdaSearchScoringHistory();
_sc = new ScoringHistory();
if (_parms._alpha == null)
_parms._alpha = new double[]{_parms._solver == Solver.IRLSM || _parms._solver == Solver.COORDINATE_DESCENT_NAIVE ? .5 : 0};
_train.bulkRollups(); // make sure we have all the rollups computed in parallel
_sc = new ScoringHistory();
_t0 = System.currentTimeMillis();
if (_parms._lambda_search || !_parms._intercept || _parms._lambda == null || _parms._lambda[0] > 0)
_parms._use_all_factor_levels = true;
if (_parms._max_active_predictors == -1)
_parms._max_active_predictors = _parms._solver == Solver.IRLSM ? 7000 : 100000000;
if (_parms._link == Link.family_default)
_parms._link = _parms._family.defaultLink;
_dinfo = new DataInfo(_train.clone(), _valid, 1, _parms._use_all_factor_levels || _parms._lambda_search, _parms._standardize ? DataInfo.TransformType.STANDARDIZE : DataInfo.TransformType.NONE, DataInfo.TransformType.NONE, _parms._missing_values_handling == MissingValuesHandling.Skip, false ,_parms._missing_values_handling == MissingValuesHandling.MeanImputation, hasWeightCol(), hasOffsetCol(), hasFoldCol());
checkMemoryFootPrint(_dinfo);
if (_parms._max_iterations == -1) { // fill in default max iterations
int numclasses = _parms._family == Family.multinomial?nclasses():1;
if (_parms._solver == Solver.IRLSM) {
_parms._max_iterations = _parms._lambda_search ? numclasses * 10 * _parms._nlambdas : numclasses * 50;
} else {
_parms._max_iterations = numclasses * Math.max(20, _dinfo.fullN() >> 2);
if (_parms._lambda_search)
_parms._max_iterations = _parms._nlambdas * 100 * numclasses;
}
}
if (_valid != null)
_validDinfo = _dinfo.validDinfo(_valid);
_state = new ComputationState(_job._key, _parms, _dinfo, null, nclasses());
// skipping extra rows? (outside of weights == 0)GLMT
boolean skippingRows = (_parms._missing_values_handling == MissingValuesHandling.Skip && _train.hasNAs());
if (true || hasWeightCol() || _train.hasNAs()) { // need to re-compute means and sd
boolean setWeights = skippingRows && _parms._lambda_search && _parms._alpha[0] > 0;
if (setWeights) {
Vec wc = _weights == null ? _dinfo._adaptedFrame.anyVec().makeCon(1) : _weights.makeCopy();
_dinfo.setWeights(_generatedWeights = "__glm_gen_weights", wc);
}
YMUTask ymt = new YMUTask(_dinfo, _parms._family == Family.multinomial?nclasses():1, !_parms._stdOverride, setWeights, skippingRows,true).doAll(_dinfo._adaptedFrame);
if (ymt._wsum == 0)
throw new IllegalArgumentException("No rows left in the dataset after filtering out rows with missing values. Ignore columns with many NAs or impute your missing values prior to calling glm.");
Log.info(LogMsg("using " + ymt._nobs + " nobs out of " + _dinfo._adaptedFrame.numRows() + " total"));
_nobs = ymt._nobs;
if (_parms._obj_reg == -1)
_parms._obj_reg = 1.0 / ymt._wsum;
_dinfo.updateWeightedSigmaAndMean(ymt._basicStats.sigma(), ymt._basicStats.mean());
_state._ymu = _parms._intercept?ymt._yMu:new double[]{_parms.linkInv(0)};
} else {
_nobs = _train.numRows();
if (_parms._obj_reg == -1)
_parms._obj_reg = 1.0 / _nobs;
if (_parms._family == Family.multinomial) {
_state._ymu = MemoryManager.malloc8d(_nclass);
for (int i = 0; i < _state._ymu.length; ++i)
_state._ymu[i] = _priorClassDist[i];
} else
_state._ymu = new double[]{_parms._intercept?_train.lastVec().mean():_parms.linkInv(0)};
}
BetaConstraint bc = (_parms._beta_constraints != null)?new BetaConstraint(_parms._beta_constraints.get()):new BetaConstraint();
if((bc.hasBounds() || bc.hasProximalPenalty()) && _parms._compute_p_values)
error("_compute_p_values","P-values can not be computed for constrained problems");
_state.setBC(bc);
if(hasOffsetCol() && _parms._intercept) { // fit intercept
GLMGradientSolver gslvr = new GLMGradientSolver(_job._key,_parms, _dinfo.filterExpandedColumns(new int[0]), 0, _state.activeBC());
double [] x = new L_BFGS().solve(gslvr,new double[]{-_offset.mean()}).coefs;
x[0] = _parms.linkInv(x[0]);
_state._ymu = x;
Log.info(LogMsg("fitted intercept = " + x[0]));
}
if (_parms._prior > 0)
_iceptAdjust = -Math.log(_state._ymu[0] * (1 - _parms._prior) / (_parms._prior * (1 - _state._ymu[0])));
ArrayList<Vec> vecs = new ArrayList<>();
if(_weights != null) vecs.add(_weights);
if(_offset != null) vecs.add(_offset);
vecs.add(_response);
_model = new GLMModel(_result, _parms, GLM.this, _state._ymu, _dinfo._adaptedFrame.lastVec().sigma(), _lmax, _nobs);
String[] warns = _model.adaptTestForTrain(_valid, true, true);
for (String s : warns) warn("_validation_frame", s);
if (_parms._lambda_min_ratio == -1)
_parms._lambda_min_ratio = (_nobs >> 4) > _dinfo.fullN() ? 1e-4 : 1e-2;
double [] beta = getNullBeta();
GLMGradientInfo ginfo = new GLMGradientSolver(_job._key,_parms, _dinfo, 0, _state.activeBC()).getGradient(beta);
_state.updateState(beta,ginfo);
if (_parms._lambda == null) { // no lambda given, we will base lambda as a fraction of lambda max
_lmax = lmax(ginfo._gradient);
if (_parms._lambda_search) {
if (_parms._nlambdas == -1)
_parms._nlambdas = 100;
_parms._lambda = new double[_parms._nlambdas];
double dec = Math.pow(_parms._lambda_min_ratio, 1.0/(_parms._nlambdas - 1));
_parms._lambda[0] = _lmax;
double l = _lmax;
for (int i = 1; i < _parms._nlambdas; ++i)
_parms._lambda[i] = (l *= dec);
// todo set the null submodel
} else
_parms._lambda = new double[]{10 * _parms._lambda_min_ratio * _lmax};
}
// clone2 so that I don't change instance which is in the DKV directly
// (clone2 also shallow clones _output)
_model.clone2().delete_and_lock(_job._key);
}
}
protected static final long WORK_TOTAL = 1000000;
@Override protected GLMDriver trainModelImpl() { return new GLMDriver(); }
private final double lmax(double[] grad) {
return Math.max(ArrayUtils.maxValue(grad), -ArrayUtils.minValue(grad)) / Math.max(1e-2, _parms._alpha[0]);
}
private transient ComputationState _state;
/**
* Main loop of the glm algo.
*/
public final class GLMDriver extends Driver implements ProgressMonitor {
private long _workPerIteration;
private void doCleanup() {
try {
_model.unlock(_job);
} catch(Throwable t){
// nada
}
try {
_parms.read_unlock_frames(_job);
} catch (Throwable t) {
// nada
}
Scope.exit(_keys2Keep.values().toArray(new Key[0]));
}
private transient Cholesky _chol;
private transient L1Solver _lslvr;
private double[] solveGram(Gram gram, double [] xy) {
if(!_parms._intercept) {
gram.dropIntercept();
xy = Arrays.copyOf(xy, xy.length - 1);
}
int [] zeros = gram.dropZeroCols();
assert zeros.length == 0:"zero column(s) in gram matrix";
gram.mul(_parms._obj_reg);
ArrayUtils.mult(xy, _parms._obj_reg);
if(_parms._remove_collinear_columns || _parms._compute_p_values) {
ArrayList<Integer> ignoredCols = new ArrayList<>();
Cholesky chol = ((_state._iter == 0)?gram.qrCholesky(ignoredCols):gram.cholesky(null));
if(!ignoredCols.isEmpty() && !_parms._remove_collinear_columns) {
int [] collinear_cols = new int[ignoredCols.size()];
for(int i = 0; i < collinear_cols.length; ++i)
collinear_cols[i] = ignoredCols.get(i);
throw new Gram.CollinearColumnsException("Found collinear columns in the dataset. P-values can not be computed with collinear columns in the dataset. Set remove_collinear_columns flag to true to remove collinear columns automatically. Found collinear columns " + Arrays.toString(ArrayUtils.select(_dinfo.coefNames(),collinear_cols)));
}
if(!chol.isSPD()) throw new NonSPDMatrixException();
_chol = chol;
if(!ignoredCols.isEmpty()) { // got some redundant cols
int [] collinear_cols = new int[ignoredCols.size()];
for(int i = 0; i < collinear_cols.length; ++i)
collinear_cols[i] = ignoredCols.get(i);
String [] collinear_col_names = ArrayUtils.select(_state.activeData().coefNames(),collinear_cols);
// need to drop the cols from everywhere
_model.addWarning("Removed collinear columns " + Arrays.toString(collinear_col_names));
Log.warn("Removed collinear columns " + Arrays.toString(collinear_col_names));
_state.removeCols(collinear_cols);
xy = ArrayUtils.removeIds(xy,collinear_cols);
}
chol.solve(xy);
} else { // todo add switch between COD and ADMM
GramSolver slvr = new GramSolver(gram.clone(), xy.clone(), _parms._intercept, _state.l2pen(),_state.l1pen(), _state.activeBC()._betaGiven, _state.activeBC()._rho, _state.activeBC()._betaLB, _state.activeBC()._betaUB);
_chol = slvr._chol;
if(_state.l1pen() == 0 && !_state.activeBC().hasBounds()) {
slvr.solve(xy);
} else {
xy = MemoryManager.malloc8d(xy.length);
// if(_parms._solver == Solver.IRLSM)
(_lslvr = new ADMM.L1Solver(1e-4, 10000)).solve(slvr, xy, _state.l1pen(), _parms._intercept, _state.activeBC()._betaLB, _state.activeBC()._betaUB);
// else if(_parms._solver == Solver.COORDINATE_DESCENT){
// } else throw new IllegalStateException("solver can only be IRLSM or COD at this point.");
}
}
return _parms._intercept?xy:Arrays.copyOf(xy,xy.length+1);
}
private void fitIRLSM_multinomial(){
assert _dinfo._responses == 3;
double relImprovement = 1;
double obj = _state.objective();
while(_state._iter < _parms._max_iterations && relImprovement > _parms._objective_epsilon) {
for (int c = 0; c < _nclass; ++c) {
if (_state.activeDataMultinomial(c).fullN() == 0) continue;
LineSearchSolver ls = (_state.l1pen() == 0 && !_state.activeBC().hasBounds())
? new MoreThuente(_state.gslvrMultinomial(c), _state.betaMultinomial(c), _state.ginfoMultinomial(c))
: new SimpleBacktrackingLS(_state.gslvrMultinomial(c), _state.betaMultinomial(c), _state.l1pen());
GLMWeightsFun glmw = new GLMWeightsFun(_parms);
double bdiff = _parms._beta_epsilon + 1;
_state._iter++;
long t1 = System.currentTimeMillis();
new GLMMultinomialUpdate(_state.activeData(), _job._key, _state.beta(), c).doAll(_state.activeData()._adaptedFrame);
long t2 = System.currentTimeMillis();
GLMIterationTask t = new GLMTask.GLMIterationTask(_job._key, _state.activeDataMultinomial(c), glmw, ls.getX(), c).doAll(_state.activeDataMultinomial(c)._adaptedFrame);
long t3 = System.currentTimeMillis();
double[] betaCnd = solveGram(t._gram, t._xy);
long t4 = System.currentTimeMillis();
if (!ls.evaluate(ArrayUtils.subtract(betaCnd, ls.getX(), betaCnd))) {
Log.info(LogMsg("Ls failed " + ls));
continue;
}
long t5 = System.currentTimeMillis();
_state.setBetaMultinomial(c, ls.getX(), (GLMSubsetGinfo) ls.ginfo());
bdiff = betaDiff(t._beta, ls.getX());
// update multinomial
if(!_parms._lambda_search)
updateProgress();
Log.info(LogMsg("computed in " + (t2 - t1) + "+" + (t3 - t2) + "+" + (t4 - t3) + "+" + (t5 - t4) + "=" + (t5 - t1) + "ms, step = " + ls.step() + ((_lslvr != null) ? ", l1solver " + _lslvr : "") + " bdiff = " + bdiff));
}
relImprovement = (obj - _state.objective())/obj;
obj = _state.objective();
}
}
private void fitLSM(){
GLMIterationTask t = new GLMTask.GLMIterationTask(_job._key, _state.activeData(), new GLMWeightsFun(_parms), null).doAll(_state.activeData()._adaptedFrame);
_state.updateState(solveGram(t._gram,t._xy), -1);
}
private void fitIRLSM() {
GLMWeightsFun glmw = new GLMWeightsFun(_parms);
double [] betaCnd = _state.beta();
LineSearchSolver ls = null;
boolean firstIter = true;
try {
while (true) {
long t1 = System.currentTimeMillis();
GLMIterationTask t = new GLMTask.GLMIterationTask(_job._key, _state.activeData(), glmw, betaCnd).doAll(_state.activeData()._adaptedFrame);
assert !firstIter || MathUtils.compare(t._likelihood,_state.likelihood(),1e-15,1e-15):LogMsg("likelihoods don't match, " + t._likelihood + " != " + _state.likelihood());
long t2 = System.currentTimeMillis();
if (Double.isNaN(t._likelihood) || _state.objective(t._beta, t._likelihood) > _state.objective() + _parms._objective_epsilon) {
assert !_state._lsNeeded;
_state._lsNeeded = true;
} else {
if (!firstIter && !_state._lsNeeded && !progress(t._beta, t._likelihood))
return;
betaCnd = _parms._solver == Solver.COORDINATE_DESCENT ? COD_solve(t, _state._alpha, _state.lambda()) : solveGram(t._gram, t._xy);
}
firstIter = false;
long t3 = System.currentTimeMillis();
if(_state._lsNeeded) {
if(ls == null)
ls = (_state.l1pen() == 0 && !_state.activeBC().hasBounds())
? new MoreThuente(_state.gslvr(),_state.beta(), _state.ginfo())
: new SimpleBacktrackingLS(_state.gslvr(),_state.beta().clone(), _state.l1pen(), _state.ginfo());
if (!ls.evaluate(ArrayUtils.subtract(betaCnd, ls.getX(), betaCnd))) {
Log.info(LogMsg("Ls failed " + ls));
return;
}
betaCnd = ls.getX();
if(!progress(betaCnd,ls.ginfo()))
return;
long t4 = System.currentTimeMillis();
Log.info(LogMsg("computed in " + (t2 - t1) + "+" + (t3 - t2) + "+" + (t4 - t3) + "=" + (t4 - t1) + "ms, step = " + ls.step() + ((_lslvr != null) ? ", l1solver " + _lslvr : "")));
} else
Log.info(LogMsg("computed in " + (t2 - t1) + "+" + (t3 - t2) + "=" + (t3 - t1) + "ms, step = " + 1 + ((_lslvr != null) ? ", l1solver " + _lslvr : "")));
}
} catch(NonSPDMatrixException e) {
Log.warn(LogMsg("Got Non SPD matrix, stopped."));
}
}
private void fitLBFGS() {
double [] beta = _state.beta();
double lambda = _state.lambda();
final double l1pen = _state.l1pen();
final double l2pen = _state.l2pen();
GLMGradientSolver gslvr = _state.gslvr();
GLMWeightsFun glmw = new GLMWeightsFun(_parms);
if (_parms._family == Family.multinomial) {
beta = MemoryManager.malloc8d((_state.activeData().fullN() + 1) * _nclass);
int P = _state.activeData().fullN() + 1;
for (int i = 0; i < _nclass; ++i)
beta[i * P + P - 1] = glmw.link(_state._ymu[i]);
}
if (beta == null) {
beta = MemoryManager.malloc8d(_state.activeData().fullN() + 1);
if (_parms._intercept)
beta[beta.length - 1] = glmw.link(_state._ymu[0]);
}
L_BFGS lbfgs = new L_BFGS().setObjEps(_parms._objective_epsilon).setGradEps(_parms._gradient_epsilon).setMaxIter(_parms._max_iterations);
assert beta.length == _state.ginfo()._gradient.length;
int P = _dinfo.fullN();
if (l1pen > 0 || _state.activeBC().hasBounds()) {
double[] nullBeta = MemoryManager.malloc8d(beta.length); // compute ginfo at null beta to get estimate for rho
if (_dinfo._intercept) {
if (_parms._family == Family.multinomial) {
for (int c = 0; c < _nclass; c++)
nullBeta[(c + 1) * (P + 1) - 1] = glmw.link(_state._ymu[c]);
} else
nullBeta[nullBeta.length - 1] = glmw.link(_state._ymu[0]);
}
GradientInfo ginfo = gslvr.getGradient(nullBeta);
double[] direction = ArrayUtils.mult(ginfo._gradient.clone(), -1);
double t = 1;
if (l1pen > 0) {
MoreThuente mt = new MoreThuente(gslvr,nullBeta);
mt.evaluate(direction);
t = mt.step();
}
double[] rho = MemoryManager.malloc8d(beta.length);
double r = _state.activeBC().hasBounds()?1:.1;
BetaConstraint bc = _state.activeBC();
// compute rhos
for (int i = 0; i < rho.length - 1; ++i)
rho[i] = r * ADMM.L1Solver.estimateRho(nullBeta[i] + t * direction[i], l1pen, bc._betaLB == null ? Double.NEGATIVE_INFINITY : bc._betaLB[i], bc._betaUB == null ? Double.POSITIVE_INFINITY : bc._betaUB[i]);
for (int ii = P; ii < rho.length; ii += P + 1)
rho[ii] = r * ADMM.L1Solver.estimateRho(nullBeta[ii] + t * direction[ii], 0, bc._betaLB == null ? Double.NEGATIVE_INFINITY : bc._betaLB[ii], bc._betaUB == null ? Double.POSITIVE_INFINITY : bc._betaUB[ii]);
final double[] objvals = new double[2];
objvals[1] = Double.POSITIVE_INFINITY;
double reltol = L1Solver.DEFAULT_RELTOL;
double abstol = L1Solver.DEFAULT_ABSTOL;
double ADMM_gradEps = 1e-3;
ProximalGradientSolver innerSolver = new ProximalGradientSolver(gslvr, beta, rho, _parms._objective_epsilon * 1e-1, _parms._gradient_epsilon, new ProgressMonitor() {
@Override
public boolean progress(double[] betaDiff, GradientInfo ginfo) {return ++_state._iter < _parms._max_iterations;}
});
new ADMM.L1Solver(ADMM_gradEps, 250, reltol, abstol).solve(innerSolver, beta, l1pen, true, _state.activeBC()._betaLB, _state.activeBC()._betaUB);
_state.updateState(beta,gslvr.getGradient(beta));
} else {
Result r = lbfgs.solve(gslvr, beta, _state.ginfo(), new ProgressMonitor() {
@Override
public boolean progress(double[] beta, GradientInfo ginfo) {
if(_state._iter < 4 || ((_state._iter & 3) == 0))
Log.info(LogMsg("LBFGS, gradient norm = " + ArrayUtils.linfnorm(ginfo._gradient,false)));
return GLMDriver.this.progress(beta,ginfo);
}
});
Log.info(LogMsg(r.toString()));
_state.updateState(r.coefs,(GLMGradientInfo)r.ginfo);
}
}
private void fitCOD() {
double [] beta = _state.beta();
int p = _state.activeData().fullN()+ 1;
double wsum,wsumu; // intercept denum
double [] denums;
boolean skipFirstLevel = !_state.activeData()._useAllFactorLevels;
double [] betaold = beta.clone();
double objold = _state.objective();
int iter2=0; // total cd iters
// get reweighted least squares vectors
Vec[] newVecs = _state.activeData()._adaptedFrame.anyVec().makeZeros(3);
Vec w = newVecs[0]; // fixed before each CD loop
Vec z = newVecs[1]; // fixed before each CD loop
Vec zTilda = newVecs[2]; // will be updated at every variable within CD loop
long startTimeTotalNaive = System.currentTimeMillis();
// generate new IRLS iteration
while (iter2++ < 30) {
Frame fr = new Frame(_state.activeData()._adaptedFrame);
fr.add("w", w); // fr has all data
fr.add("z", z);
fr.add("zTilda", zTilda);
GLMGenerateWeightsTask gt = new GLMGenerateWeightsTask(_job._key, _state.activeData(), _parms, beta).doAll(fr);
double objVal = objVal(gt._likelihood, gt._betaw, _state.lambda());
denums = gt.denums;
wsum = gt.wsum;
wsumu = gt.wsumu;
int iter1 = 0;
// coordinate descent loop
while (iter1++ < 100) {
Frame fr2 = new Frame();
fr2.add("w", w);
fr2.add("z", z);
fr2.add("zTilda", zTilda); // original x%*%beta if first iteration
for(int i=0; i < _state.activeData()._cats; i++) {
Frame fr3 = new Frame(fr2);
int level_num = _state.activeData()._catOffsets[i+1]-_state.activeData()._catOffsets[i];
int prev_level_num = 0;
fr3.add("xj", _state.activeData()._adaptedFrame.vec(i));
boolean intercept = (i == 0); // prev var is intercept
if(!intercept) {
prev_level_num = _state.activeData()._catOffsets[i]-_state.activeData()._catOffsets[i-1];
fr3.add("xjm1", _state.activeData()._adaptedFrame.vec(i-1)); // add previous categorical variable
}
int start_old = _state.activeData()._catOffsets[i];
GLMCoordinateDescentTaskSeqNaive stupdate;
if(intercept)
stupdate = new GLMCoordinateDescentTaskSeqNaive(intercept, false, 4 , Arrays.copyOfRange(betaold, start_old, start_old+level_num),
new double [] {beta[p-1]}, _state.activeData()._catLvls[i], null, null, null, null, null, skipFirstLevel).doAll(fr3);
else
stupdate = new GLMCoordinateDescentTaskSeqNaive(intercept, false, 1 , Arrays.copyOfRange(betaold, start_old,start_old+level_num),
Arrays.copyOfRange(beta, _state.activeData()._catOffsets[i-1], _state.activeData()._catOffsets[i]) , _state.activeData()._catLvls[i] ,
_state.activeData()._catLvls[i-1], null, null, null, null, skipFirstLevel ).doAll(fr3);
for(int j=0; j < level_num; ++j)
beta[_state.activeData()._catOffsets[i]+j] = ADMM.shrinkage(stupdate._temp[j] / wsumu, _parms._lambda[_lambdaId] * _parms._alpha[0])
/ (denums[_state.activeData()._catOffsets[i]+j] / wsumu + _parms._lambda[_lambdaId] * (1 - _parms._alpha[0]));
}
int cat_num = 2; // if intercept, or not intercept but not first numeric, then both are numeric .
for (int i = 0; i < _state.activeData()._nums; ++i) {
GLMCoordinateDescentTaskSeqNaive stupdate;
Frame fr3 = new Frame(fr2);
fr3.add("xj", _state.activeData()._adaptedFrame.vec(i+_state.activeData()._cats)); // add current variable col
boolean intercept = (i == 0 && _state.activeData().numStart() == 0); // if true then all numeric case and doing beta_1
double [] meannew=null, meanold=null, varnew=null, varold=null;
if(i > 0 || intercept) {// previous var is a numeric var
cat_num = 3;
if(!intercept)
fr3.add("xjm1", _state.activeData()._adaptedFrame.vec(i - 1 + _state.activeData()._cats)); // add previous one if not doing a beta_1 update, ow just pass it the intercept term
if( _state.activeData()._normMul!=null ) {
varold = new double[]{_state.activeData()._normMul[i]};
meanold = new double[]{_state.activeData()._normSub[i]};
if (i!= 0){
varnew = new double []{ _state.activeData()._normMul[i-1]};
meannew = new double [] { _state.activeData()._normSub[i-1]};
}
}
stupdate = new GLMCoordinateDescentTaskSeqNaive(intercept, false, cat_num , new double [] { betaold[_state.activeData().numStart()+ i]},
new double []{ beta[ (_state.activeData().numStart()+i-1+p)%p ]}, null, null,
varold, meanold, varnew, meannew, skipFirstLevel ).doAll(fr3);
beta[i+_state.activeData().numStart()] = ADMM.shrinkage(stupdate._temp[0] / wsumu, _parms._lambda[_lambdaId] * _parms._alpha[0])
/ (denums[i+_state.activeData().numStart()] / wsumu + _parms._lambda[_lambdaId] * (1 - _parms._alpha[0]));
}
else if (i == 0 && !intercept){ // previous one is the last categorical variable
int prev_level_num = _state.activeData().numStart()-_state.activeData()._catOffsets[_state.activeData()._cats-1];
fr3.add("xjm1", _state.activeData()._adaptedFrame.vec(_state.activeData()._cats-1)); // add previous categorical variable
if( _state.activeData()._normMul!=null){
varold = new double []{ _state.activeData()._normMul[i]};
meanold = new double [] { _state.activeData()._normSub[i]};
}
stupdate = new GLMCoordinateDescentTaskSeqNaive(intercept, false, cat_num , new double [] {betaold[ _state.activeData().numStart()]},
Arrays.copyOfRange(beta,_state.activeData()._catOffsets[_state.activeData()._cats-1],_state.activeData().numStart() ), null, _state.activeData()._catLvls[_state.activeData()._cats-1],
varold, meanold, null, null, skipFirstLevel ).doAll(fr3);
beta[_state.activeData().numStart()] = ADMM.shrinkage(stupdate._temp[0] / wsumu, _parms._lambda[_lambdaId] * _parms._alpha[0])
/ (denums[_state.activeData().numStart()] / wsumu + _parms._lambda[_lambdaId] * (1 - _parms._alpha[0]));
}
}
if(_state.activeData()._nums + _state.activeData()._cats > 0) {
// intercept update: preceded by a categorical or numeric variable
Frame fr3 = new Frame(fr2);
fr3.add("xjm1", _state.activeData()._adaptedFrame.vec(_state.activeData()._cats + _state.activeData()._nums - 1)); // add last variable updated in cycle to the frame
GLMCoordinateDescentTaskSeqNaive iupdate;
if (_state.activeData()._adaptedFrame.vec(_state.activeData()._cats + _state.activeData()._nums - 1).isCategorical()) { // only categorical vars
cat_num = 2;
iupdate = new GLMCoordinateDescentTaskSeqNaive(false, true, cat_num, new double[]{betaold[betaold.length - 1]},
Arrays.copyOfRange(beta, _state.activeData()._catOffsets[_state.activeData()._cats - 1], _state.activeData()._catOffsets[_state.activeData()._cats]),
null, _state.activeData()._catLvls[_state.activeData()._cats - 1], null, null, null, null, skipFirstLevel).doAll(fr3);
} else { // last variable is numeric
cat_num = 3;
double[] meannew = null, varnew = null;
if (_state.activeData()._normMul != null) {
varnew = new double[]{_state.activeData()._normMul[_state.activeData()._normMul.length - 1]};
meannew = new double[]{_state.activeData()._normSub[_state.activeData()._normSub.length - 1]};
}
iupdate = new GLMCoordinateDescentTaskSeqNaive(false, true, cat_num,
new double[]{betaold[betaold.length - 1]}, new double[]{beta[beta.length - 2]}, null, null,
null, null, varnew, meannew, skipFirstLevel).doAll(fr3);
}
if (_parms._intercept)
beta[beta.length - 1] = iupdate._temp[0] / wsum;
}
double maxdiff = ArrayUtils.linfnorm(ArrayUtils.subtract(beta, betaold), false); // false to keep the intercept
System.arraycopy(beta, 0, betaold, 0, beta.length);
if (maxdiff < _parms._beta_epsilon)
break;
}
double percdiff = Math.abs((objold - objVal)/objold);
if (percdiff < _parms._objective_epsilon & iter2 >1 )
break;
objold=objVal;
System.out.println("iter1 = " + iter1);
}
System.out.println("iter2 = " + iter2);
long endTimeTotalNaive = System.currentTimeMillis();
long durationTotalNaive = (endTimeTotalNaive - startTimeTotalNaive)/1000;
System.out.println("Time to run Naive Coordinate Descent " + durationTotalNaive);
_state._iter = iter2;
for (Vec v : newVecs) v.remove();
_state.updateState(beta,objold);
}
private void fitModel() {
Solver solver = (_parms._solver == Solver.AUTO) ? defaultSolver() : _parms._solver;
switch (solver) {
case COORDINATE_DESCENT: // fall through to IRLSM
case IRLSM:
if(_parms._family == Family.multinomial)
fitIRLSM_multinomial();
else if(_parms._family == Family.gaussian && _parms._link == Link.identity)
fitLSM();
else
fitIRLSM();
break;
case L_BFGS:
fitLBFGS();
break;
case COORDINATE_DESCENT_NAIVE:
fitCOD();
break;
default:
throw H2O.unimpl();
}
if(_parms._compute_p_values) { // compute p-values
double se = 1;
boolean seEst = false;
double [] beta = _state.beta();
if(_parms._family != Family.binomial && _parms._family != Family.poisson) {
seEst = true;
ComputeSETsk ct = new ComputeSETsk(null, _state.activeData(), _job._key, beta, _parms).doAll(_state.activeData()._adaptedFrame);
se = ct._sumsqe / (_nobs - 1 - _state.activeData().fullN());
}
double [] zvalues = MemoryManager.malloc8d(_state.activeData().fullN()+1);
double [] gInvDiag = _chol.getInvDiag();
for(int i = 0; i < zvalues.length; ++i)
zvalues[i] = beta[i]/Math.sqrt(_parms._obj_reg*gInvDiag[i]*se);
_model.setZValues(expandVec(zvalues,_state.activeData()._activeCols,_dinfo.fullN()+1,Double.NaN),se, seEst);
}
}
private long _lastScore = System.currentTimeMillis();
private long timeSinceLastScoring(){return System.currentTimeMillis() - _lastScore;}
private transient HashMap<String,Key> _keys2Keep = new HashMap<>();
private void scoreAndUpdateModel(){
// compute full validation on train and test
Log.info(LogMsg("Scoring after " + timeSinceLastScoring() + "ms"));
long t1 = System.currentTimeMillis();
Frame train = DKV.<Frame>getGet(_parms._train);
_model.score(train).delete();
ModelMetrics mtrain = ModelMetrics.getFromDKV(_model, train); // updated by model.scoreAndUpdateModel
_model._output._training_metrics = mtrain;
long t2 = System.currentTimeMillis();
Log.info(LogMsg("Training metrics computed in " + (t2-t1) + "ms"));
Log.info(LogMsg(mtrain.toString()));
_keys2Keep.put("training_metrics",mtrain._key);
if(_valid != null) {
Frame valid = DKV.<Frame>getGet(_parms._valid);
_model.score(valid).delete();
_model._output._validation_metrics = ModelMetrics.getFromDKV(_model, valid); //updated by model.scoreAndUpdateModel
_keys2Keep.put("validation_metrics",_model._output._validation_metrics._key);
}
_model._output._scoring_history = _parms._lambda_search?_lsc.to2dTable():_sc.to2dTable();
_model.update(_job._key);
_model.generateSummary(_parms._train,_state._iter);
_lastScore = System.currentTimeMillis();
long scoringTime = System.currentTimeMillis() - t1;
_scoringInterval = Math.max(_scoringInterval,20*scoringTime); // at most 5% overhead for scoring
}
@Override
public void compute2() {
Scope.enter();
_keys2Keep.put("dest",dest());
_parms.read_lock_frames(_job);
init(true);
if (error_count() > 0) {
throw H2OModelBuilderIllegalArgumentException.makeFromBuilder(GLM.this);
}
double nullDevTrain = Double.NaN;
double nullDevTest = Double.NaN;
if(_parms._lambda_search) {
nullDevTrain = _parms._family == Family.multinomial
?new GLMResDevTaskMultinomial(_job._key,_state._dinfo,getNullBeta(), _nclass).doAll(_state._dinfo._adaptedFrame)._likelihood*2
:new GLMResDevTask(_job._key, _state._dinfo, _parms, getNullBeta()).doAll(_state._dinfo._adaptedFrame)._resDev;
if(_validDinfo != null)
nullDevTest = _parms._family == Family.multinomial
?new GLMResDevTaskMultinomial(_job._key,_validDinfo,getNullBeta(), _nclass).doAll(_validDinfo._adaptedFrame)._likelihood*2
:new GLMResDevTask(_job._key, _validDinfo, _parms, getNullBeta()).doAll(_validDinfo._adaptedFrame)._resDev;
_workPerIteration = WORK_TOTAL/_parms._nlambdas;
} else
_workPerIteration = 1 + (WORK_TOTAL/_parms._max_iterations);
if(_parms._family == Family.multinomial && _parms._solver == Solver.IRLSM) {
double [] nb = getNullBeta();
double maxRow = ArrayUtils.maxValue(nb);
double sumExp = 0;
int P = _dinfo.fullN();
int N = _dinfo.fullN()+1;
for(int i = 1; i < _nclass; ++i)
sumExp += Math.exp(nb[i*N + P] - maxRow);
_dinfo.addResponse(new String[]{"__glm_sumExp", "__glm_maxRow"}, _dinfo._adaptedFrame.anyVec().makeDoubles(2, new double[]{sumExp,maxRow}));
}
double testDevOld = Double.NaN;
double trainDevOld = Double.NaN;
int impcnt = 0;
// lambda search loop
for (int i = 0; i < _parms._lambda.length; ++i) { // lambda search
_model.addSubmodel(_state.beta(),_parms._lambda[i],_state._iter);
_state.setLambda(_parms._lambda[i]);
do {
if(_parms._family == Family.multinomial)
for(int c = 0; c < _nclass; ++c)
Log.info(LogMsg("Class " + c + " got " + _state.activeDataMultinomial(c).fullN() + " active columns out of " + _state._dinfo.fullN() + " total"));
else
Log.info(LogMsg("Got " + _state.activeData().fullN() + " active columns out of " + _state._dinfo.fullN() + " total"));
fitModel();
} while(!_state.checkKKTs());
Log.info(LogMsg("solution has " + ArrayUtils.countNonzeros(_state.beta()) + " nonzeros"));
if(_parms._lambda_search) { // compute train and test dev
double trainDev = _parms._family == Family.multinomial
?new GLMResDevTaskMultinomial(_job._key,_state._dinfo,_state.beta(), _nclass).doAll(_state._dinfo._adaptedFrame)._likelihood*2
:new GLMResDevTask(_job._key, _state._dinfo, _parms, _state.beta()).doAll(_state._dinfo._adaptedFrame)._resDev;
double testDev = -1;
if(_validDinfo != null)
testDev = _parms._family == Family.multinomial
?new GLMResDevTaskMultinomial(_job._key,_validDinfo,_dinfo.denormalizeBeta(_state.beta()), _nclass).doAll(_validDinfo._adaptedFrame)._likelihood*2
:new GLMResDevTask(_job._key, _validDinfo, _parms, _dinfo.denormalizeBeta(_state.beta())).doAll(_validDinfo._adaptedFrame)._resDev;
Log.info(LogMsg("train deviance = " + trainDev + ", test deviance = " + testDev));
_lsc.addLambdaScore(_state._iter,ArrayUtils.countNonzeros(_state.beta()), _state.lambda(),1 - trainDev/nullDevTrain, 1.0 - testDev/nullDevTest);
_model.update(_state.beta(), trainDev, testDev, _state._iter);
if(testDev > testDevOld)
break; // started overfitting
testDevOld = testDev;
if(_parms._score_each_iteration || timeSinceLastScoring() > _scoringInterval)
scoreAndUpdateModel(); // update partial results
_job.update(_workPerIteration,"iter=" + _state._iter + " lmb=" + lambdaFormatter.format(_state.lambda()) + "exp.dev.ratio trn/tst= " + devFormatter.format(1 - trainDev/nullDevTrain) + "/" + devFormatter.format(1.0 - testDev/nullDevTest) + " P=" + ArrayUtils.countNonzeros(_state.beta()));
} else
_model.update(_state.beta(), -1, -1, _state._iter);
}
_model._output.pickBestModel();
scoreAndUpdateModel();
if(_iceptAdjust != 0) { // apply the intercept adjust according to prior probability
assert _parms._intercept;
double [] b = _model._output._global_beta;
b[b.length-1] += _iceptAdjust;
for(Submodel sm:_model._output._submodels)
sm.beta[sm.beta.length-1] += _iceptAdjust;
_model.update(_job._key);
}
doCleanup();
tryComplete();
}
@Override public boolean onExceptionalCompletion(Throwable t, CountedCompleter caller){
_keys2Keep.clear();
doCleanup();
return true;
}
private double betaDiff(double [] b1, double [] b2) {
double res = Math.abs(b1[0] - b2[0]);
for(int i = 0; i < b1.length; ++i) {
double diff = b1[i] - b2[i];
if(diff > res) res = diff;
else if(-diff > res) res = -diff;
}
return res;
}
@Override public boolean progress(double [] beta, GradientInfo ginfo) {
GLMGradientInfo gginfo = (GLMGradientInfo)ginfo;
_state.updateState(beta,gginfo);
if(!_parms._lambda_search)
updateProgress();
return _job.isRunning() && _state._iter++ < _parms._max_iterations && !_state.converged();
}
public boolean progress(double [] beta, double likelihood) {
_state.updateState(beta,likelihood);
if(!_parms._lambda_search)
updateProgress();
return _job.isRunning() && _state._iter++ < _parms._max_iterations && !_state.converged();
}
private transient long _scoringInterval = SCORING_INTERVAL_MSEC;
// update user visible progress
protected void updateProgress(){
assert !_parms._lambda_search;
_sc.addIterationScore(_state._iter, _state.likelihood(), _state.objective());
_job.update(_workPerIteration,_state.toString());
if(_parms._score_each_iteration || timeSinceLastScoring() > _scoringInterval) {
_model.update(_state.expandBeta(_state.beta()), -1, -1, _state._iter);
scoreAndUpdateModel();
}
}
}
private Solver defaultSolver() {
return Solver.IRLSM;
}
private double currentLambda() {
return _parms._lambda[_lambdaId];
}
double objVal(double likelihood, double[] beta, double lambda) {
double alpha = _parms._alpha[0];
double proximalPen = 0;
BetaConstraint bc = _state.activeBC();
if (_state.activeBC()._betaGiven != null && bc._rho != null) {
for (int i = 0; i < bc._betaGiven.length; ++i) {
double diff = beta[i] - bc._betaGiven[i];
proximalPen += diff * diff * bc._rho[i];
}
}
return (likelihood * _parms._obj_reg
+ .5 * proximalPen
+ lambda * (alpha * ArrayUtils.l1norm(beta, _parms._intercept)
+ (1 - alpha) * .5 * ArrayUtils.l2norm2(beta, _parms._intercept)));
}
private String LogMsg(String msg) {return "GLM[dest=" + dest() + ", " + _state + "] " + msg;}
private static final double[] expandVec(double[] beta, final int[] activeCols, int fullN) {
return expandVec(beta, activeCols, fullN, 0);
}
private static final double[] expandVec(double[] beta, final int[] activeCols, int fullN, double filler) {
assert beta != null;
if (activeCols == null) return beta;
double[] res = MemoryManager.malloc8d(fullN);
Arrays.fill(res, filler);
int i = 0;
for (int c : activeCols)
res[c] = beta[i++];
res[res.length - 1] = beta[beta.length - 1];
return res;
}
private static double [] doUpdateCD(double [] grads, double [][] xx, double diff , int variable, int variable_min, int variable_max) {
double[] ary = xx[variable];
for (int i = 0; i < variable_min; i++)
grads[i] += diff * ary[i];
for (int i = variable_max; i < grads.length; i++)
grads[i] += diff * ary[i];
return grads;
}
public double [] COD_solve(GLMIterationTask gt, double alpha, double lambda) {
gt._gram.mul(_parms._obj_reg);
ArrayUtils.mult(gt._xy,_parms._obj_reg);
double wsumInv = 1.0/(gt.wsum*_parms._obj_reg);
double l1pen = lambda * alpha;
double l2pen = lambda*(1-alpha);
double [][] xx = gt._gram.getXX();
double [] grads = gt._xy.clone();
double [] beta = gt._beta.clone();
for(int i = 0; i < grads.length; ++i) {
double ip = 0;
for(int j = 0; j < beta.length; ++j)
ip += beta[j]*xx[i][j];
grads[i] = grads[i] - ip + beta[i]*xx[i][i];
}
double [] diagInv = MemoryManager.malloc8d(xx.length);
for(int i = 0; i < diagInv.length; ++i)
diagInv[i] = 1.0/(xx[i][i] + l2pen);
int iter1 = 0;
int P = gt._xy.length - 1;
DataInfo activeData = _state.activeData();
// CD loop
while (iter1++ < 1000 /*Math.max(P,500)*/) {
double bdiffPos = 0;
double bdiffNeg = 0;
for (int i = 0; i < activeData._cats; ++i) {
for(int j = activeData._catOffsets[i]; j < activeData._catOffsets[i+1]; ++j) { // can do in parallel
double b = ADMM.shrinkage(grads[j], l1pen) * diagInv[j];
double bd = beta[j] - b;
bdiffPos = bd > bdiffPos?bd:bdiffPos;
bdiffNeg = bd < bdiffNeg?bd:bdiffNeg;
doUpdateCD(grads, xx, bd, j, activeData._catOffsets[i], activeData._catOffsets[i + 1]);
beta[j] = b;
}
}
int numStart = activeData.numStart();
for (int i = numStart; i < P; ++i) {
double b = ADMM.shrinkage(grads[i], l1pen) * diagInv[i];
double bd = beta[i] - b;
bdiffPos = bd > bdiffPos?bd:bdiffPos;
bdiffNeg = bd < bdiffNeg?bd:bdiffNeg;
doUpdateCD(grads, xx, bd, i,i,i+1);
beta[i] = b;
}
// intercept
double b = grads[P] * wsumInv;
double bd = beta[P] - b;
doUpdateCD(grads, xx, bd, P,P,P+1);
bdiffPos = bd > bdiffPos?bd:bdiffPos;
bdiffNeg = bd < bdiffNeg?bd:bdiffNeg;
beta[P] = b;
if (-1e-4 < bdiffNeg && bdiffPos < 1e-4)
break;
}
return beta;
}
/**
* Created by tomasnykodym on 3/30/15.
*/
public static final class GramSolver implements ProximalSolver {
private final Gram _gram;
private Cholesky _chol;
private final double[] _xy;
final double _lambda;
double[] _rho;
boolean _addedL2;
double _betaEps;
private static double boundedX(double x, double lb, double ub) {
if (x < lb) x = lb;
if (x > ub) x = ub;
return x;
}
public GramSolver(Gram gram, double[] xy, double lmax, double betaEps, boolean intercept) {
_gram = gram;
_lambda = 0;
_betaEps = betaEps;
_xy = xy;
double[] rhos = MemoryManager.malloc8d(xy.length);
computeCholesky(gram, rhos, lmax * 1e-8);
_addedL2 = rhos[0] != 0;
_rho = _addedL2 ? rhos : null;
}
// solve non-penalized problem
public void solve(double[] result) {
System.arraycopy(_xy, 0, result, 0, _xy.length);
_chol.solve(result);
double gerr = Double.POSITIVE_INFINITY;
if (_addedL2) { // had to add l2-pen to turn the gram to be SPD
double[] oldRes = MemoryManager.arrayCopyOf(result, result.length);
for (int i = 0; i < 1000; ++i) {
solve(oldRes, result);
double[] g = gradient(result);
gerr = Math.max(-ArrayUtils.minValue(g), ArrayUtils.maxValue(g));
if (gerr < 1e-4) return;
System.arraycopy(result, 0, oldRes, 0, result.length);
}
Log.warn("Gram solver did not converge, gerr = " + gerr);
}
}
public GramSolver(Gram gram, double[] xy, boolean intercept, double l2pen, double l1pen, double[] beta_given, double[] proxPen, double[] lb, double[] ub) {
if (ub != null && lb != null)
for (int i = 0; i < ub.length; ++i) {
assert ub[i] >= lb[i] : i + ": ub < lb, ub = " + Arrays.toString(ub) + ", lb = " + Arrays.toString(lb);
}
_lambda = l2pen;
_gram = gram;
// Try to pick optimal rho constant here used in ADMM solver.
//
// Rho defines the strength of proximal-penalty and also the strentg of L1 penalty aplpied in each step.
// Picking good rho constant is tricky and greatly influences the speed of convergence and precision with which we are able to solve the problem.
//
// Intuitively, we want the proximal l2-penalty ~ l1 penalty (l1 pen = lambda/rho, where lambda is the l1 penalty applied to the problem)
// Here we compute the rho for each coordinate by using equation for computing coefficient for single coordinate and then making the two penalties equal.
//
int ii = intercept ? 1 : 0;
int icptCol = xy.length - 1;
double[] rhos = MemoryManager.malloc8d(xy.length);
double min = Double.POSITIVE_INFINITY;
for (int i = 0; i < xy.length - ii; ++i) {
double d = xy[i];
d = d >= 0 ? d : -d;
if (d < min && d != 0) min = d;
}
double ybar = xy[icptCol];
for (int i = 0; i < rhos.length - ii; ++i) {
double y = xy[i];
if (y == 0) y = min;
double xbar = gram.get(icptCol, i);
double x = ((y - ybar * xbar) / ((gram.get(i, i) - xbar * xbar) + l2pen));///gram.get(i,i);
rhos[i] = ADMM.L1Solver.estimateRho(x, l1pen, lb == null ? Double.NEGATIVE_INFINITY : lb[i], ub == null ? Double.POSITIVE_INFINITY : ub[i]);
}
// do the intercept separate as l1pen does not apply to it
if (intercept && (lb != null && !Double.isInfinite(lb[icptCol]) || ub != null && !Double.isInfinite(ub[icptCol]))) {
int icpt = xy.length - 1;
rhos[icpt] = 1;//(xy[icpt] >= 0 ? xy[icpt] : -xy[icpt]);
}
if (l2pen > 0)
gram.addDiag(l2pen);
if (proxPen != null && beta_given != null) {
gram.addDiag(proxPen);
xy = xy.clone();
for (int i = 0; i < xy.length; ++i)
xy[i] += proxPen[i] * beta_given[i];
}
computeCholesky(gram, rhos, 1e-5);
_rho = rhos;
_xy = xy;
}
private void computeCholesky(Gram gram, double[] rhos, double rhoAdd) {
gram.addDiag(rhos);
_chol = gram.cholesky(null, true, null);
if (!_chol.isSPD()) { // make sure rho is big enough
gram.addDiag(ArrayUtils.mult(rhos, -1));
ArrayUtils.mult(rhos, -1);
for (int i = 0; i < rhos.length; ++i)
rhos[i] += rhoAdd;//1e-5;
Log.info("Got NonSPD matrix with original rho, re-computing with rho = " + rhos[0]);
_gram.addDiag(rhos);
_chol = gram.cholesky(null, true, null);
int cnt = 0;
while (!_chol.isSPD() && cnt++ < 5) {
gram.addDiag(ArrayUtils.mult(rhos, -1));
ArrayUtils.mult(rhos, -1);
for (int i = 0; i < rhos.length; ++i)
rhos[i] *= 100;
Log.warn("Still NonSPD matrix, re-computing with rho = " + rhos[0]);
_gram.addDiag(rhos);
_chol = gram.cholesky(null, true, null);
}
if (!_chol.isSPD())
throw new NonSPDMatrixException();
}
gram.addDiag(ArrayUtils.mult(rhos, -1));
ArrayUtils.mult(rhos, -1);
}
@Override
public double[] rho() {
return _rho;
}
@Override
public boolean solve(double[] beta_given, double[] result) {
if (beta_given != null)
for (int i = 0; i < _xy.length; ++i)
result[i] = _xy[i] + _rho[i] * beta_given[i];
else
System.arraycopy(_xy, 0, result, 0, _xy.length);
_chol.solve(result);
return true;
}
@Override
public boolean hasGradient() {
return false;
}
@Override
public double[] gradient(double[] beta) {
double[] grad = _gram.mul(beta);
for (int i = 0; i < _xy.length; ++i)
grad[i] -= _xy[i];
return grad;
}
@Override
public int iter() {
return 0;
}
}
public static class ProximalGradientInfo extends GradientInfo {
final GradientInfo _origGinfo;
public ProximalGradientInfo(GradientInfo origGinfo, double objVal, double[] gradient) {
super(objVal, gradient);
_origGinfo = origGinfo;
}
}
/**
* Simple wrapper around ginfo computation, adding proximal penalty
*/
public static class ProximalGradientSolver implements GradientSolver, ProximalSolver {
final GradientSolver _solver;
double[] _betaGiven;
double[] _beta;
private ProximalGradientInfo _ginfo;
private final ProgressMonitor _pm;
final double[] _rho;
private final double _objEps;
private final double _gradEps;
public ProximalGradientSolver(GradientSolver s, double[] betaStart, double[] rho, double objEps, double gradEps, ProgressMonitor pm) {
super();
_solver = s;
_rho = rho;
_objEps = objEps;
_gradEps = gradEps;
_pm = pm;
_beta = betaStart;
_betaGiven = MemoryManager.malloc8d(betaStart.length);
}
public static double proximal_gradient(double[] grad, double obj, double[] beta, double[] beta_given, double[] rho) {
for (int i = 0; i < beta.length; ++i) {
double diff = (beta[i] - beta_given[i]);
double pen = rho[i] * diff;
if(grad != null)
grad[i] += pen;
obj += .5 * pen * diff;
}
return obj;
}
@Override
public ProximalGradientInfo getGradient(double[] beta) {
GradientInfo ginfo = _solver.getGradient(beta);
double[] gradient = ginfo._gradient.clone();
double obj = proximal_gradient(gradient, ginfo._objVal, beta, _betaGiven, _rho);
return new ProximalGradientInfo(ginfo, obj, gradient);
}
@Override
public GradientInfo getObjective(double[] beta) {
GradientInfo ginfo = _solver.getObjective(beta);
double obj = proximal_gradient(null, ginfo._objVal, beta, _betaGiven, _rho);
return new ProximalGradientInfo(ginfo,obj,null);
}
@Override
public double[] rho() {
return _rho;
}
private int _iter;
@Override
public boolean solve(double[] beta_given, double[] beta) {
if (_ginfo == null || beta != _beta) {
_ginfo = getGradient(beta);
_beta = beta;
}
double[] gradient = _ginfo._gradient;
System.arraycopy(_ginfo._origGinfo._gradient, 0, gradient, 0, gradient.length);
double obj = proximal_gradient(gradient, _ginfo._origGinfo._objVal, beta, beta_given, _rho);
_ginfo = new ProximalGradientInfo(_ginfo._origGinfo, obj, gradient);
System.arraycopy(beta_given, 0, _betaGiven, 0, _betaGiven.length);
L_BFGS.Result r = new L_BFGS().setObjEps(_objEps).setGradEps(_gradEps).solve(this, beta, _ginfo, _pm);
System.arraycopy(r.coefs,0,beta,0,r.coefs.length);
_iter += r.iter;
_ginfo = (ProximalGradientInfo) r.ginfo;
return r.converged;
}
@Override
public boolean hasGradient() {
return true;
}
@Override
public double[] gradient(double[] beta) {
return getGradient(beta)._origGinfo._gradient;
}
@Override
public int iter() {
return _iter;
}
}
public static class GLMGradientInfo extends GradientInfo {
final double _likelihood;
public GLMGradientInfo(double likelihood, double objVal, double[] grad) {
super(objVal, grad);
_likelihood = likelihood;
}
public String toString(){
return "GLM grad info: likelihood = " + _likelihood + ", obj = " + _objVal + ", gradient = " + Arrays.toString(_gradient);
}
}
/**
* Gradient and line search computation for L_BFGS and also L_BFGS solver wrapper (for ADMM)
*/
public static final class GLMGradientSolver implements GradientSolver {
final GLMParameters _parms;
final DataInfo _dinfo;
final BetaConstraint _bc;
final double _l2pen; // l2 penalty
double[][] _betaMultinomial;
final Key _jobKey;
public GLMGradientSolver(Key jobKey, GLMParameters glmp, DataInfo dinfo, double l2pen, BetaConstraint bc) {
_jobKey = jobKey;
_bc = bc;
_parms = glmp;
_dinfo = dinfo;
_l2pen = l2pen;
}
@Override
public GLMGradientInfo getGradient(double[] beta) {
if (_parms._family == Family.multinomial) {
if (_betaMultinomial == null) {
int nclasses = beta.length / (_dinfo.fullN() + 1);
assert beta.length % (_dinfo.fullN() + 1) == 0:"beta len = " + beta.length + ", fullN +1 == " + (_dinfo.fullN()+1);
_betaMultinomial = new double[nclasses][];
for (int i = 0; i < nclasses; ++i)
_betaMultinomial[i] = MemoryManager.malloc8d(_dinfo.fullN() + 1);
}
int off = 0;
for (int i = 0; i < _betaMultinomial.length; ++i) {
System.arraycopy(beta, off, _betaMultinomial[i], 0, _betaMultinomial[i].length);
off += _betaMultinomial[i].length;
}
GLMMultinomialGradientTask gt = new GLMMultinomialGradientTask(_jobKey,_dinfo, _l2pen, _betaMultinomial, _parms._obj_reg, false, null).doAll(_dinfo._adaptedFrame);
double l2pen = 0;
for (double[] b : _betaMultinomial)
l2pen += ArrayUtils.l2norm2(b, _dinfo._intercept);
return new GLMGradientInfo(gt._likelihood, gt._likelihood * _parms._obj_reg + .5 * _l2pen * l2pen, gt._gradient);
} else {
assert beta.length == _dinfo.fullN() + 1;
assert _parms._intercept || (beta[beta.length-1] == 0);
GLMGradientTask gt;
if(_parms._family == Family.binomial && _parms._link == Link.logit)
gt = new GLMBinomialGradientTask(_jobKey,_dinfo,_parms,_l2pen, beta).doAll(_dinfo._adaptedFrame);
else if(_parms._family == Family.gaussian && _parms._link == Link.identity)
gt = new GLMGaussianGradientTask(_jobKey,_dinfo,_parms,_l2pen, beta).doAll(_dinfo._adaptedFrame);
else
gt = new GLMGenericGradientTask(_jobKey, _dinfo, _parms, _l2pen, beta).doAll(_dinfo._adaptedFrame);
double [] gradient = gt._gradient;
double likelihood = gt._likelihood;
if (!_parms._intercept) // no intercept, null the ginfo
gradient[gradient.length - 1] = 0;
double obj = likelihood * _parms._obj_reg + .5 * _l2pen * ArrayUtils.l2norm2(beta, true);
if (_bc != null && _bc._betaGiven != null && _bc._rho != null)
obj = ProximalGradientSolver.proximal_gradient(gradient, obj, beta, _bc._betaGiven, _bc._rho);
return new GLMGradientInfo(likelihood, obj, gradient);
}
}
@Override
public GradientInfo getObjective(double[] beta) {
double l = new GLMResDevTask(_jobKey,_dinfo,_parms,beta).doAll(_dinfo._adaptedFrame)._likelihood;
return new GLMGradientInfo(l,l*_parms._obj_reg + .5*_l2pen*ArrayUtils.l2norm2(beta,true),null);
}
}
protected static double sparseOffset(double[] beta, DataInfo dinfo) {
double etaOffset = 0;
if (dinfo._normMul != null && dinfo._normSub != null && beta != null) {
int ns = dinfo.numStart();
for (int i = 0; i < dinfo._nums; ++i)
etaOffset -= beta[i + ns] * dinfo._normSub[i] * dinfo._normMul[i];
}
return etaOffset;
}
public class BetaConstraint extends Iced {
double[] _betaStart;
double[] _betaGiven;
double[] _rho;
double[] _betaLB;
double[] _betaUB;
public BetaConstraint() {
if (_parms._non_negative) setNonNegative();
}
public void setNonNegative() {
if (_betaLB == null) {
_betaLB = MemoryManager.malloc8d(_dinfo.fullN() + 1);
_betaLB[_dinfo.fullN()] = Double.NEGATIVE_INFINITY;
} else for (int i = 0; i < _betaLB.length - 1; ++i)
_betaLB[i] = Math.max(0, _betaLB[i]);
if (_betaUB == null) {
_betaUB = MemoryManager.malloc8d(_dinfo.fullN() + 1);
Arrays.fill(_betaUB, Double.POSITIVE_INFINITY);
}
}
public BetaConstraint(Frame beta_constraints) {
Vec v = beta_constraints.vec("names");
String[] dom;
int[] map;
if (v.isString()) {
dom = new String[(int) v.length()];
map = new int[dom.length];
BufferedString tmpStr = new BufferedString();
for (int i = 0; i < dom.length; ++i) {
dom[i] = v.atStr(tmpStr, i).toString();
map[i] = i;
}
// check for dups
String[] sortedDom = dom.clone();
Arrays.sort(sortedDom);
for (int i = 1; i < sortedDom.length; ++i)
if (sortedDom[i - 1].equals(sortedDom[i]))
throw new IllegalArgumentException("Illegal beta constraints file, got duplicate constraint for predictor '" + sortedDom[i - 1] + "'!");
} else if (v.isCategorical()) {
dom = v.domain();
map = FrameUtils.asInts(v);
// check for dups
int[] sortedMap = MemoryManager.arrayCopyOf(map, map.length);
Arrays.sort(sortedMap);
for (int i = 1; i < sortedMap.length; ++i)
if (sortedMap[i - 1] == sortedMap[i])
throw new IllegalArgumentException("Illegal beta constraints file, got duplicate constraint for predictor '" + dom[sortedMap[i - 1]] + "'!");
} else
throw new IllegalArgumentException("Illegal beta constraints file, names column expected to contain column names (strings)");
// for now only categoricals allowed here
String[] names = ArrayUtils.append(_dinfo.coefNames(), "Intercept");
if (!Arrays.deepEquals(dom, names)) { // need mapping
HashMap<String, Integer> m = new HashMap<String, Integer>();
for (int i = 0; i < names.length; ++i)
m.put(names[i], i);
int[] newMap = MemoryManager.malloc4(dom.length);
for (int i = 0; i < map.length; ++i) {
if (_removedCols.contains(dom[map[i]])) {
newMap[i] = -1;
continue;
}
Integer I = m.get(dom[map[i]]);
if (I == null) {
throw new IllegalArgumentException("Unrecognized coefficient name in beta-constraint file, unknown name '" + dom[map[i]] + "'");
}
newMap[i] = I;
}
map = newMap;
}
final int numoff = _dinfo.numStart();
String[] valid_col_names = new String[]{"names", "beta_given", "beta_start", "lower_bounds", "upper_bounds", "rho", "mean", "std_dev"};
Arrays.sort(valid_col_names);
for (String s : beta_constraints.names())
if (Arrays.binarySearch(valid_col_names, s) < 0)
error("beta_constraints", "Unknown column name '" + s + "'");
if ((v = beta_constraints.vec("beta_start")) != null) {
_betaStart = MemoryManager.malloc8d(_dinfo.fullN() + (_dinfo._intercept ? 1 : 0));
for (int i = 0; i < (int) v.length(); ++i)
if (map[i] != -1)
_betaStart[map[i]] = v.at(i);
}
if ((v = beta_constraints.vec("beta_given")) != null) {
_betaGiven = MemoryManager.malloc8d(_dinfo.fullN() + (_dinfo._intercept ? 1 : 0));
for (int i = 0; i < (int) v.length(); ++i)
if (map[i] != -1)
_betaGiven[map[i]] = v.at(i);
}
if ((v = beta_constraints.vec("upper_bounds")) != null) {
_betaUB = MemoryManager.malloc8d(_dinfo.fullN() + (_dinfo._intercept ? 1 : 0));
Arrays.fill(_betaUB, Double.POSITIVE_INFINITY);
for (int i = 0; i < (int) v.length(); ++i)
if (map[i] != -1)
_betaUB[map[i]] = v.at(i);
}
if ((v = beta_constraints.vec("lower_bounds")) != null) {
_betaLB = MemoryManager.malloc8d(_dinfo.fullN() + (_dinfo._intercept ? 1 : 0));
Arrays.fill(_betaLB, Double.NEGATIVE_INFINITY);
for (int i = 0; i < (int) v.length(); ++i)
if (map[i] != -1)
_betaLB[map[i]] = v.at(i);
}
if ((v = beta_constraints.vec("rho")) != null) {
_rho = MemoryManager.malloc8d(_dinfo.fullN() + (_dinfo._intercept ? 1 : 0));
for (int i = 0; i < (int) v.length(); ++i)
if (map[i] != -1)
_rho[map[i]] = v.at(i);
}
// mean override (for data standardization)
if ((v = beta_constraints.vec("mean")) != null) {
_parms._stdOverride = true;
for (int i = 0; i < v.length(); ++i) {
if (!v.isNA(i) && map[i] != -1) {
int idx = map == null ? i : map[i];
if (idx > _dinfo.numStart() && idx < _dinfo.fullN()) {
_dinfo._normSub[idx - _dinfo.numStart()] = v.at(i);
} else {
// categorical or Intercept, will be ignored
}
}
}
}
// standard deviation override (for data standardization)
if ((v = beta_constraints.vec("std_dev")) != null) {
_parms._stdOverride = true;
for (int i = 0; i < v.length(); ++i) {
if (!v.isNA(i) && map[i] != -1) {
int idx = map == null ? i : map[i];
if (idx > _dinfo.numStart() && idx < _dinfo.fullN()) {
_dinfo._normMul[idx - _dinfo.numStart()] = 1.0 / v.at(i);
} else {
// categorical or Intercept, will be ignored
}
}
}
}
if (_dinfo._normMul != null) {
double normG = 0, normS = 0, normLB = 0, normUB = 0;
for (int i = numoff; i < _dinfo.fullN(); ++i) {
double s = _dinfo._normSub[i - numoff];
double d = 1.0 / _dinfo._normMul[i - numoff];
if (_betaUB != null && !Double.isInfinite(_betaUB[i])) {
normUB *= s;
_betaUB[i] *= d;
}
if (_betaLB != null && !Double.isInfinite(_betaUB[i])) {
normLB *= s;
_betaLB[i] *= d;
}
if (_betaGiven != null) {
normG += _betaGiven[i] * s;
_betaGiven[i] *= d;
}
if (_betaStart != null) {
normS += _betaStart[i] * s;
_betaStart[i] *= d;
}
}
if (_dinfo._intercept) {
int n = _dinfo.fullN();
if (_betaGiven != null)
_betaGiven[n] += normG;
if (_betaStart != null)
_betaStart[n] += normS;
if (_betaLB != null)
_betaLB[n] += normLB;
if (_betaUB != null)
_betaUB[n] += normUB;
}
}
if (_betaStart == null && _betaGiven != null)
_betaStart = _betaGiven.clone();
if (_betaStart != null) {
if (_betaLB != null || _betaUB != null) {
for (int i = 0; i < _betaStart.length; ++i) {
if (_betaLB != null && _betaLB[i] > _betaStart[i])
_betaStart[i] = _betaLB[i];
if (_betaUB != null && _betaUB[i] < _betaStart[i])
_betaStart[i] = _betaUB[i];
}
}
}
if (_parms._non_negative) setNonNegative();
check();
}
public String toString() {
double[][] ary = new double[_betaGiven.length][3];
for (int i = 0; i < _betaGiven.length; ++i) {
ary[i][0] = _betaGiven[i];
ary[i][1] = _betaLB[i];
ary[i][2] = _betaUB[i];
}
return ArrayUtils.pprint(ary);
}
public boolean hasBounds() {
if (_betaLB != null)
for (double d : _betaLB)
if (!Double.isInfinite(d)) return true;
if (_betaUB != null)
for (double d : _betaUB)
if (!Double.isInfinite(d)) return true;
return false;
}
public boolean hasProximalPenalty() {
return _betaGiven != null && _rho != null && ArrayUtils.countNonzeros(_rho) > 0;
}
public void adjustGradient(double[] beta, double[] grad) {
if (_betaGiven != null && _rho != null) {
for (int i = 0; i < _betaGiven.length; ++i) {
double diff = beta[i] - _betaGiven[i];
grad[i] += _rho[i] * diff;
}
}
}
double proxPen(double[] beta) {
double res = 0;
if (_betaGiven != null && _rho != null) {
for (int i = 0; i < _betaGiven.length; ++i) {
double diff = beta[i] - _betaGiven[i];
res += _rho[i] * diff * diff;
}
res *= .5;
}
return res;
}
public void check() {
if (_betaLB != null && _betaUB != null)
for (int i = 0; i < _betaLB.length; ++i)
if (!(_betaLB[i] <= _betaUB[i]))
throw new IllegalArgumentException("lower bounds myst be <= upper bounds, " + _betaLB[i] + " !<= " + _betaUB[i]);
}
public BetaConstraint filterExpandedColumns(int[] activeCols) {
BetaConstraint res = new BetaConstraint();
if (_betaLB != null)
res._betaLB = ArrayUtils.select(_betaLB, activeCols);
if (_betaUB != null)
res._betaUB = ArrayUtils.select(_betaUB, activeCols);
if (_betaGiven != null)
res._betaGiven = ArrayUtils.select(_betaGiven, activeCols);
if (_rho != null)
res._rho = ArrayUtils.select(_rho, activeCols);
if (_betaStart != null)
res._betaStart = ArrayUtils.select(_betaStart, activeCols);
return res;
}
}
}
|
h2o-algos/src/main/java/hex/glm/GLM.java
|
package hex.glm;
import hex.*;
import hex.deeplearning.DeepLearningModel.DeepLearningParameters.MissingValuesHandling;
import hex.glm.ComputationState.GLMSubsetGinfo;
import hex.glm.GLMModel.*;
import hex.optimization.ADMM.L1Solver;
import hex.optimization.L_BFGS;
import hex.glm.GLMModel.GLMParameters.Family;
import hex.glm.GLMModel.GLMParameters.Link;
import hex.glm.GLMModel.GLMParameters.Solver;
import hex.glm.GLMTask.*;
import hex.gram.Gram;
import hex.gram.Gram.Cholesky;
import hex.gram.Gram.NonSPDMatrixException;
import hex.optimization.ADMM;
import hex.optimization.ADMM.ProximalSolver;
import hex.optimization.L_BFGS.*;
import hex.optimization.OptimizationUtils.*;
import jsr166y.CountedCompleter;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import water.*;
import water.exceptions.H2OModelBuilderIllegalArgumentException;
import water.fvec.*;
import water.parser.BufferedString;
import water.util.*;
import water.util.ArrayUtils;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
/**
* Created by tomasnykodym on 8/27/14.
*
* Generalized linear model implementation.
*/
public class GLM extends ModelBuilder<GLMModel,GLMParameters,GLMOutput> {
static NumberFormat lambdaFormatter = new DecimalFormat(".##E0");
static NumberFormat devFormatter = new DecimalFormat(".##");
public static final int SCORING_INTERVAL_MSEC = 15000; // scoreAndUpdateModel every minute unless socre every iteration is set
public String _generatedWeights = null;
public GLM(boolean startup_once){super(new GLMParameters(),startup_once);}
public GLM(GLMModel.GLMParameters parms) {
super(parms);
init(false);
}
public GLM(GLMModel.GLMParameters parms,Key dest) {
super(parms,dest);
init(false);
}
public boolean isSupervised() {
return true;
}
@Override
public ModelCategory[] can_build() {
return new ModelCategory[]{
ModelCategory.Regression,
ModelCategory.Binomial,
};
}
@Override
protected void checkMemoryFootPrint() {/* see below */ }
protected void checkMemoryFootPrint(DataInfo dinfo) {
if (_parms._solver == Solver.IRLSM && !_parms._lambda_search) {
HeartBeat hb = H2O.SELF._heartbeat;
double p = dinfo.fullN() - dinfo.largestCat();
long mem_usage = (long) (hb._cpus_allowed * (p * p + dinfo.largestCat()) * 8/*doubles*/ * (1 + .5 * Math.log((double) _train.lastVec().nChunks()) / Math.log(2.))); //one gram per core
long max_mem = hb.get_free_mem();
if (mem_usage > max_mem) {
String msg = "Gram matrices (one per thread) won't fit in the driver node's memory ("
+ PrettyPrint.bytes(mem_usage) + " > " + PrettyPrint.bytes(max_mem)
+ ") - try reducing the number of columns and/or the number of categorical factors (or switch to the L-BFGS solver).";
error("_train", msg);
}
}
}
static class TooManyPredictorsException extends RuntimeException {}
DataInfo _dinfo;
private int _lambdaId;
private transient DataInfo _validDinfo;
// time per iteration in ms
private static class ScoringHistory {
private ArrayList<Integer> _scoringIters = new ArrayList<>();
private ArrayList<Long> _scoringTimes = new ArrayList<>();
private ArrayList<Double> _likelihoods = new ArrayList<>();
private ArrayList<Double> _objectives = new ArrayList<>();
public synchronized void addIterationScore(int iter, double likelihood, double obj) {
if (_scoringIters.size() > 0 && _scoringIters.get(_scoringIters.size() - 1) == iter)
return; // do not record twice, happens for the last iteration, need to record scoring history in checkKKTs because of gaussian fam.
_scoringIters.add(iter);
_scoringTimes.add(System.currentTimeMillis());
_likelihoods.add(likelihood);
_objectives.add(obj);
}
public synchronized TwoDimTable to2dTable() {
String[] cnames = new String[]{"timestamp", "duration", "iteration", "negative_log_likelihood", "objective"};
String[] ctypes = new String[]{"string", "string", "int", "double", "double"};
String[] cformats = new String[]{"%s", "%s", "%d", "%.5f", "%.5f"};
TwoDimTable res = new TwoDimTable("Scoring History", "", new String[_scoringIters.size()], cnames, ctypes, cformats, "");
int j = 0;
DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
for (int i = 0; i < _scoringIters.size(); ++i) {
int col = 0;
res.set(i, col++, fmt.print(_scoringTimes.get(i)));
res.set(i, col++, PrettyPrint.msecs(_scoringTimes.get(i) - _scoringTimes.get(0), true));
res.set(i, col++, _scoringIters.get(i));
res.set(i, col++, _likelihoods.get(i));
res.set(i, col++, _objectives.get(i));
}
return res;
}
}
private static class LambdaSearchScoringHistory {
ArrayList<Long> _scoringTimes = new ArrayList<>();
private ArrayList<Double> _lambdas = new ArrayList<>();
private ArrayList<Integer> _lambdaIters = new ArrayList<>();
private ArrayList<Integer> _lambdaPredictors = new ArrayList<>();
private ArrayList<Double> _lambdaDevTrain = new ArrayList<>();
private ArrayList<Double> _lambdaDevTest = new ArrayList<>();
public synchronized void addLambdaScore(int iter, int predictors, double lambda, double devRatioTrain, double devRatioTest) {
_scoringTimes.add(System.currentTimeMillis());
_lambdaIters.add(iter);
_lambdas.add(lambda);
_lambdaPredictors.add(predictors);
_lambdaDevTrain.add(devRatioTrain);
_lambdaDevTest.add(devRatioTest);
}
public synchronized TwoDimTable to2dTable() {
String[] cnames = new String[]{"timestamp", "duration", "iteration", "lambda", "predictors", "Explained Deviance (train)", "Explained Deviance (test)"};
String[] ctypes = new String[]{"string", "string", "int", "string","int", "double","double"};
String[] cformats = new String[]{"%s", "%s", "%d","%s", "%d", "%.3f","%.3f"};
TwoDimTable res = new TwoDimTable("Scoring History", "", new String[_lambdaIters.size()], cnames, ctypes, cformats, "");
int j = 0;
DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
for (int i = 0; i < _lambdaIters.size(); ++i) {
int col = 0;
res.set(i, col++, fmt.print(_scoringTimes.get(i)));
res.set(i, col++, PrettyPrint.msecs(_scoringTimes.get(i) - _scoringTimes.get(0), true));
res.set(i, col++, _lambdaIters.get(i));
res.set(i, col++, lambdaFormatter.format(_lambdas.get(i)));
res.set(i, col++, _lambdaPredictors.get(i));
res.set(i, col++, _lambdaDevTrain.get(i));
if(_lambdaDevTest.size() > i)
res.set(i, col++, _lambdaDevTest.get(i));
}
return res;
}
}
private transient ScoringHistory _sc;
private transient LambdaSearchScoringHistory _lsc;
long _t0 = System.currentTimeMillis();
private transient double _iceptAdjust = 0;
private transient GradientInfo _ginfo;
private double _lmax;
private transient long _nobs;
private transient GLMModel _model;
// special vecs made for irlsm
private static final String _wName = "__glm_irlsm_wvec";
private static final String _zName = "__glm_irlsm_zvec";
private transient Vec _w;
private transient Vec _z;
// and for multinomial irlsm
@Override
public int nclasses() {
if (_parms._family == Family.multinomial)
return _nclass;
if (_parms._family == Family.binomial)
return 2;
return 1;
}
private boolean doingIRLSM() {
if (_parms._family == Family.gaussian && _parms._link == Link.identity)
return false; // no need for IRLSM, standard LSM will do
if (_parms._solver == Solver.IRLSM)
return true;
if (_parms._solver == Solver.AUTO)
return true; // todo
return false;
}
private transient double[] _nullBeta;
private double[] getNullPrediction() {
double [] nb = getNullBeta();
if(_parms._family != Family.multinomial)
return new double[]{_parms.linkInv(nb[nb.length-1])};
double [] res = new double[_nclass];
if(_parms._intercept) {
int N = _dinfo.fullN()+1;
for (int i = 0; i < res.length; ++i)
res[i] = Math.exp(nb[_dinfo.fullN() + i*N]);
}
return res;
}
private double[] getNullBeta() {
if (_nullBeta == null) {
if (_parms._family == Family.multinomial) {
_nullBeta = MemoryManager.malloc8d((_dinfo.fullN() + 1) * nclasses());
int N = _dinfo.fullN() + 1;
for (int i = 0; i < nclasses(); ++i)
_nullBeta[_dinfo.fullN() + i * N] = Math.log(_state._ymu[i]);
} else {
_nullBeta = MemoryManager.malloc8d(_dinfo.fullN() + 1);
if (_parms._intercept)
_nullBeta[_dinfo.fullN()] = new GLMModel.GLMWeightsFun(_parms).link(_state._ymu[0]);
else
_nullBeta[_dinfo.fullN()] = 0;
}
}
return _nullBeta;
}
private transient GLMMetricBuilder _nullValidation;
// static so I can make inner class mr task without sending whole glm over
private static GLMMetricBuilder getNullValidation(final GLM glm) {
return null;
}
protected boolean computePriorClassDistribution(){return _parms._family == Family.multinomial;}
@Override
public void init(boolean expensive) {
super.init(expensive);
hide("_balance_classes", "Not applicable since class balancing is not required for GLM.");
hide("_max_after_balance_size", "Not applicable since class balancing is not required for GLM.");
hide("_class_sampling_factors", "Not applicable since class balancing is not required for GLM.");
_parms.validate(this);
if(_response != null)
switch( _parms._family) {
case binomial:
if( !_response.isBinary() && _nclass != 2)
error("_family", H2O.technote(2, "Binomial requires the response to be a 2-class categorical or a binary column (0/1)"));
break;
case multinomial:
if (_nclass <= 2) error("_family", H2O.technote(2, "Multinomial requires a categorical response with at least 3 levels (for 2 class problem use family=binomial."));
break;
case poisson:
if (_nclass != 1) error("_family", "Poisson requires the response to be numeric.");
if(_response.min() < 0)
error("_family", "Poisson requires response >= 0");
if(!_response.isInt())
warn("_family","Poisson expects non-negative integer response, got floats.");
break;
case gamma:
if (_nclass != 1) error("_distribution", H2O.technote(2, "Gamma requires the response to be numeric."));
if(_response.min() <= 0) error("_family","Gamma requires positive respone");
break;
case tweedie:
if (_nclass != 1) error("_family", H2O.technote(2, "Tweedie requires the response to be numeric."));
break;
case gaussian:
// if (_nclass != 1) error("_family", H2O.technote(2, "Gaussian requires the response to be numeric."));
break;
default:
error("_family","Invalid distribution: " + _parms._distribution);
}
if (expensive) {
if (error_count() > 0) return;
_lsc = new LambdaSearchScoringHistory();
_sc = new ScoringHistory();
if (_parms._alpha == null)
_parms._alpha = new double[]{_parms._solver == Solver.IRLSM || _parms._solver == Solver.COORDINATE_DESCENT_NAIVE ? .5 : 0};
_train.bulkRollups(); // make sure we have all the rollups computed in parallel
_sc = new ScoringHistory();
_t0 = System.currentTimeMillis();
if (_parms._lambda_search || !_parms._intercept || _parms._lambda == null || _parms._lambda[0] > 0)
_parms._use_all_factor_levels = true;
if (_parms._max_active_predictors == -1)
_parms._max_active_predictors = _parms._solver == Solver.IRLSM ? 7000 : 100000000;
if (_parms._link == Link.family_default)
_parms._link = _parms._family.defaultLink;
_dinfo = new DataInfo(_train.clone(), _valid, 1, _parms._use_all_factor_levels || _parms._lambda_search, _parms._standardize ? DataInfo.TransformType.STANDARDIZE : DataInfo.TransformType.NONE, DataInfo.TransformType.NONE, _parms._missing_values_handling == MissingValuesHandling.Skip, false ,_parms._missing_values_handling == MissingValuesHandling.MeanImputation, hasWeightCol(), hasOffsetCol(), hasFoldCol());
checkMemoryFootPrint(_dinfo);
if (_parms._max_iterations == -1) { // fill in default max iterations
int numclasses = _parms._family == Family.multinomial?nclasses():1;
if (_parms._solver == Solver.IRLSM) {
_parms._max_iterations = _parms._lambda_search ? numclasses * 10 * _parms._nlambdas : numclasses * 50;
} else {
_parms._max_iterations = numclasses * Math.max(20, _dinfo.fullN() >> 2);
if (_parms._lambda_search)
_parms._max_iterations = _parms._nlambdas * 100 * numclasses;
}
}
if (_valid != null)
_validDinfo = _dinfo.validDinfo(_valid);
_state = new ComputationState(_job._key, _parms, _dinfo, null, nclasses());
// skipping extra rows? (outside of weights == 0)GLMT
boolean skippingRows = (_parms._missing_values_handling == MissingValuesHandling.Skip && _train.hasNAs());
if (true || hasWeightCol() || _train.hasNAs()) { // need to re-compute means and sd
boolean setWeights = skippingRows && _parms._lambda_search && _parms._alpha[0] > 0;
if (setWeights) {
Vec wc = _weights == null ? _dinfo._adaptedFrame.anyVec().makeCon(1) : _weights.makeCopy();
_dinfo.setWeights(_generatedWeights = "__glm_gen_weights", wc);
}
YMUTask ymt = new YMUTask(_dinfo, _parms._family == Family.multinomial?nclasses():1, !_parms._stdOverride, setWeights, skippingRows,true).doAll(_dinfo._adaptedFrame);
if (ymt._wsum == 0)
throw new IllegalArgumentException("No rows left in the dataset after filtering out rows with missing values. Ignore columns with many NAs or impute your missing values prior to calling glm.");
Log.info(LogMsg("using " + ymt._nobs + " nobs out of " + _dinfo._adaptedFrame.numRows() + " total"));
_nobs = ymt._nobs;
if (_parms._obj_reg == -1)
_parms._obj_reg = 1.0 / ymt._wsum;
_dinfo.updateWeightedSigmaAndMean(ymt._basicStats.sigma(), ymt._basicStats.mean());
_state._ymu = _parms._intercept?ymt._yMu:new double[]{_parms.linkInv(0)};
} else {
_nobs = _train.numRows();
if (_parms._obj_reg == -1)
_parms._obj_reg = 1.0 / _nobs;
if (_parms._family == Family.multinomial) {
_state._ymu = MemoryManager.malloc8d(_nclass);
for (int i = 0; i < _state._ymu.length; ++i)
_state._ymu[i] = _priorClassDist[i];
} else
_state._ymu = new double[]{_parms._intercept?_train.lastVec().mean():_parms.linkInv(0)};
}
BetaConstraint bc = (_parms._beta_constraints != null)?new BetaConstraint(_parms._beta_constraints.get()):new BetaConstraint();
if((bc.hasBounds() || bc.hasProximalPenalty()) && _parms._compute_p_values)
error("_compute_p_values","P-values can not be computed for constrained problems");
_state.setBC(bc);
if(hasOffsetCol() && _parms._intercept) { // fit intercept
GLMGradientSolver gslvr = new GLMGradientSolver(_job._key,_parms, _dinfo.filterExpandedColumns(new int[0]), 0, _state.activeBC());
double [] x = new L_BFGS().solve(gslvr,new double[]{-_offset.mean()}).coefs;
x[0] = _parms.linkInv(x[0]);
_state._ymu = x;
Log.info(LogMsg("fitted intercept = " + x[0]));
}
if (_parms._prior > 0)
_iceptAdjust = -Math.log(_state._ymu[0] * (1 - _parms._prior) / (_parms._prior * (1 - _state._ymu[0])));
ArrayList<Vec> vecs = new ArrayList<>();
if(_weights != null) vecs.add(_weights);
if(_offset != null) vecs.add(_offset);
vecs.add(_response);
_model = new GLMModel(_result, _parms, GLM.this, _state._ymu, _dinfo._adaptedFrame.lastVec().sigma(), _lmax, _nobs);
String[] warns = _model.adaptTestForTrain(_valid, true, true);
for (String s : warns) warn("_validation_frame", s);
if (_parms._lambda_min_ratio == -1)
_parms._lambda_min_ratio = (_nobs >> 4) > _dinfo.fullN() ? 1e-4 : 1e-2;
double [] beta = getNullBeta();
GLMGradientInfo ginfo = new GLMGradientSolver(_job._key,_parms, _dinfo, 0, _state.activeBC()).getGradient(beta);
_state.updateState(beta,ginfo);
if (_parms._lambda == null) { // no lambda given, we will base lambda as a fraction of lambda max
_lmax = lmax(ginfo._gradient);
if (_parms._lambda_search) {
if (_parms._nlambdas == -1)
_parms._nlambdas = 100;
_parms._lambda = new double[_parms._nlambdas];
double dec = Math.pow(_parms._lambda_min_ratio, 1.0/(_parms._nlambdas - 1));
_parms._lambda[0] = _lmax;
double l = _lmax;
for (int i = 1; i < _parms._nlambdas; ++i)
_parms._lambda[i] = (l *= dec);
// todo set the null submodel
} else
_parms._lambda = new double[]{10 * _parms._lambda_min_ratio * _lmax};
}
// clone2 so that I don't change instance which is in the DKV directly
// (clone2 also shallow clones _output)
_model.clone2().delete_and_lock(_job._key);
}
}
protected static final long WORK_TOTAL = 1000000;
@Override protected GLMDriver trainModelImpl() { return new GLMDriver(); }
private final double lmax(double[] grad) {
return Math.max(ArrayUtils.maxValue(grad), -ArrayUtils.minValue(grad)) / Math.max(1e-2, _parms._alpha[0]);
}
private transient ComputationState _state;
/**
* Main loop of the glm algo.
*/
public final class GLMDriver extends Driver implements ProgressMonitor {
private long _workPerIteration;
private void doCleanup() {
try {
_model.unlock(_job);
} catch(Throwable t){
// nada
}
try {
_parms.read_unlock_frames(_job);
} catch (Throwable t) {
// nada
}
Scope.exit(_keys2Keep.values().toArray(new Key[0]));
}
private transient Cholesky _chol;
private transient L1Solver _lslvr;
private double[] solveGram(Gram gram, double [] xy) {
if(!_parms._intercept) {
gram.dropIntercept();
xy = Arrays.copyOf(xy, xy.length - 1);
}
int [] zeros = gram.dropZeroCols();
assert zeros.length == 0:"zero column(s) in gram matrix";
gram.mul(_parms._obj_reg);
ArrayUtils.mult(xy, _parms._obj_reg);
if(_parms._remove_collinear_columns || _parms._compute_p_values) {
ArrayList<Integer> ignoredCols = new ArrayList<>();
Cholesky chol = ((_state._iter == 0)?gram.qrCholesky(ignoredCols):gram.cholesky(null));
if(!ignoredCols.isEmpty() && !_parms._remove_collinear_columns) {
int [] collinear_cols = new int[ignoredCols.size()];
for(int i = 0; i < collinear_cols.length; ++i)
collinear_cols[i] = ignoredCols.get(i);
throw new Gram.CollinearColumnsException("Found collinear columns in the dataset. P-values can not be computed with collinear columns in the dataset. Set remove_collinear_columns flag to true to remove collinear columns automatically. Found collinear columns " + Arrays.toString(ArrayUtils.select(_dinfo.coefNames(),collinear_cols)));
}
if(!chol.isSPD()) throw new NonSPDMatrixException();
_chol = chol;
if(!ignoredCols.isEmpty()) { // got some redundant cols
int [] collinear_cols = new int[ignoredCols.size()];
for(int i = 0; i < collinear_cols.length; ++i)
collinear_cols[i] = ignoredCols.get(i);
String [] collinear_col_names = ArrayUtils.select(_state.activeData().coefNames(),collinear_cols);
// need to drop the cols from everywhere
_model.addWarning("Removed collinear columns " + Arrays.toString(collinear_col_names));
Log.warn("Removed collinear columns " + Arrays.toString(collinear_col_names));
_state.removeCols(collinear_cols);
xy = ArrayUtils.removeIds(xy,collinear_cols);
}
chol.solve(xy);
} else { // todo add switch between COD and ADMM
GramSolver slvr = new GramSolver(gram.clone(), xy.clone(), _parms._intercept, _state.l2pen(),_state.l1pen(), _state.activeBC()._betaGiven, _state.activeBC()._rho, _state.activeBC()._betaLB, _state.activeBC()._betaUB);
_chol = slvr._chol;
if(_state.l1pen() == 0 && !_state.activeBC().hasBounds()) {
slvr.solve(xy);
} else {
xy = MemoryManager.malloc8d(xy.length);
// if(_parms._solver == Solver.IRLSM)
(_lslvr = new ADMM.L1Solver(1e-4, 10000)).solve(slvr, xy, _state.l1pen(), _parms._intercept, _state.activeBC()._betaLB, _state.activeBC()._betaUB);
// else if(_parms._solver == Solver.COORDINATE_DESCENT){
// } else throw new IllegalStateException("solver can only be IRLSM or COD at this point.");
}
}
return _parms._intercept?xy:Arrays.copyOf(xy,xy.length+1);
}
private void fitIRLSM_multinomial(){
assert _dinfo._responses == 3;
double relImprovement = 1;
double obj = _state.objective();
while(_state._iter < _parms._max_iterations && relImprovement > _parms._objective_epsilon) {
for (int c = 0; c < _nclass; ++c) {
if (_state.activeDataMultinomial(c).fullN() == 0) continue;
LineSearchSolver ls = (_state.l1pen() == 0 && !_state.activeBC().hasBounds())
? new MoreThuente(_state.gslvrMultinomial(c), _state.betaMultinomial(c), _state.ginfoMultinomial(c))
: new SimpleBacktrackingLS(_state.gslvrMultinomial(c), _state.betaMultinomial(c), _state.l1pen());
GLMWeightsFun glmw = new GLMWeightsFun(_parms);
double bdiff = _parms._beta_epsilon + 1;
_state._iter++;
long t1 = System.currentTimeMillis();
new GLMMultinomialUpdate(_state.activeData(), _job._key, _state.beta(), c).doAll(_state.activeData()._adaptedFrame);
long t2 = System.currentTimeMillis();
GLMIterationTask t = new GLMTask.GLMIterationTask(_job._key, _state.activeDataMultinomial(c), glmw, ls.getX(), c).doAll(_state.activeDataMultinomial(c)._adaptedFrame);
long t3 = System.currentTimeMillis();
double[] betaCnd = solveGram(t._gram, t._xy);
long t4 = System.currentTimeMillis();
if (!ls.evaluate(ArrayUtils.subtract(betaCnd, ls.getX(), betaCnd))) {
Log.info(LogMsg("Ls failed " + ls));
continue;
}
long t5 = System.currentTimeMillis();
_state.setBetaMultinomial(c, ls.getX(), (GLMSubsetGinfo) ls.ginfo());
bdiff = betaDiff(t._beta, ls.getX());
// update multinomial
if(!_parms._lambda_search)
updateProgress();
Log.info(LogMsg("computed in " + (t2 - t1) + "+" + (t3 - t2) + "+" + (t4 - t3) + "+" + (t5 - t4) + "=" + (t5 - t1) + "ms, step = " + ls.step() + ((_lslvr != null) ? ", l1solver " + _lslvr : "") + " bdiff = " + bdiff));
}
relImprovement = (obj - _state.objective())/obj;
obj = _state.objective();
}
}
private void fitLSM(){
GLMIterationTask t = new GLMTask.GLMIterationTask(_job._key, _state.activeData(), new GLMWeightsFun(_parms), null).doAll(_state.activeData()._adaptedFrame);
_state.updateState(solveGram(t._gram,t._xy), -1);
}
private void fitIRLSM() {
GLMWeightsFun glmw = new GLMWeightsFun(_parms);
double [] betaCnd = _state.beta();
LineSearchSolver ls = null;
boolean firstIter = true;
try {
while (true) {
long t1 = System.currentTimeMillis();
GLMIterationTask t = new GLMTask.GLMIterationTask(_job._key, _state.activeData(), glmw, betaCnd).doAll(_state.activeData()._adaptedFrame);
assert !firstIter || t._likelihood == _state.likelihood():LogMsg("likelihoods don't match, " + t._likelihood + " != " + _state.likelihood());
long t2 = System.currentTimeMillis();
if (Double.isNaN(t._likelihood) || _state.objective(t._beta, t._likelihood) > _state.objective() + _parms._objective_epsilon) {
assert !_state._lsNeeded;
_state._lsNeeded = true;
} else {
if (!firstIter && !_state._lsNeeded && !progress(t._beta, t._likelihood))
return;
betaCnd = _parms._solver == Solver.COORDINATE_DESCENT ? COD_solve(t, _state._alpha, _state.lambda()) : solveGram(t._gram, t._xy);
}
firstIter = false;
long t3 = System.currentTimeMillis();
if(_state._lsNeeded) {
if(ls == null)
ls = (_state.l1pen() == 0 && !_state.activeBC().hasBounds())
? new MoreThuente(_state.gslvr(),_state.beta(), _state.ginfo())
: new SimpleBacktrackingLS(_state.gslvr(),_state.beta().clone(), _state.l1pen(), _state.ginfo());
if (!ls.evaluate(ArrayUtils.subtract(betaCnd, ls.getX(), betaCnd))) {
Log.info(LogMsg("Ls failed " + ls));
return;
}
betaCnd = ls.getX();
if(!progress(betaCnd,ls.ginfo()))
return;
long t4 = System.currentTimeMillis();
Log.info(LogMsg("computed in " + (t2 - t1) + "+" + (t3 - t2) + "+" + (t4 - t3) + "=" + (t4 - t1) + "ms, step = " + ls.step() + ((_lslvr != null) ? ", l1solver " + _lslvr : "")));
} else
Log.info(LogMsg("computed in " + (t2 - t1) + "+" + (t3 - t2) + "=" + (t3 - t1) + "ms, step = " + 1 + ((_lslvr != null) ? ", l1solver " + _lslvr : "")));
}
} catch(NonSPDMatrixException e) {
Log.warn(LogMsg("Got Non SPD matrix, stopped."));
}
}
private void fitLBFGS() {
double [] beta = _state.beta();
double lambda = _state.lambda();
final double l1pen = _state.l1pen();
final double l2pen = _state.l2pen();
GLMGradientSolver gslvr = _state.gslvr();
GLMWeightsFun glmw = new GLMWeightsFun(_parms);
if (_parms._family == Family.multinomial) {
beta = MemoryManager.malloc8d((_state.activeData().fullN() + 1) * _nclass);
int P = _state.activeData().fullN() + 1;
for (int i = 0; i < _nclass; ++i)
beta[i * P + P - 1] = glmw.link(_state._ymu[i]);
}
if (beta == null) {
beta = MemoryManager.malloc8d(_state.activeData().fullN() + 1);
if (_parms._intercept)
beta[beta.length - 1] = glmw.link(_state._ymu[0]);
}
L_BFGS lbfgs = new L_BFGS().setObjEps(_parms._objective_epsilon).setGradEps(_parms._gradient_epsilon).setMaxIter(_parms._max_iterations);
assert beta.length == _state.ginfo()._gradient.length;
int P = _dinfo.fullN();
if (l1pen > 0 || _state.activeBC().hasBounds()) {
double[] nullBeta = MemoryManager.malloc8d(beta.length); // compute ginfo at null beta to get estimate for rho
if (_dinfo._intercept) {
if (_parms._family == Family.multinomial) {
for (int c = 0; c < _nclass; c++)
nullBeta[(c + 1) * (P + 1) - 1] = glmw.link(_state._ymu[c]);
} else
nullBeta[nullBeta.length - 1] = glmw.link(_state._ymu[0]);
}
GradientInfo ginfo = gslvr.getGradient(nullBeta);
double[] direction = ArrayUtils.mult(ginfo._gradient.clone(), -1);
double t = 1;
if (l1pen > 0) {
MoreThuente mt = new MoreThuente(gslvr,nullBeta);
mt.evaluate(direction);
t = mt.step();
}
double[] rho = MemoryManager.malloc8d(beta.length);
double r = _state.activeBC().hasBounds()?1:.1;
BetaConstraint bc = _state.activeBC();
// compute rhos
for (int i = 0; i < rho.length - 1; ++i)
rho[i] = r * ADMM.L1Solver.estimateRho(nullBeta[i] + t * direction[i], l1pen, bc._betaLB == null ? Double.NEGATIVE_INFINITY : bc._betaLB[i], bc._betaUB == null ? Double.POSITIVE_INFINITY : bc._betaUB[i]);
for (int ii = P; ii < rho.length; ii += P + 1)
rho[ii] = r * ADMM.L1Solver.estimateRho(nullBeta[ii] + t * direction[ii], 0, bc._betaLB == null ? Double.NEGATIVE_INFINITY : bc._betaLB[ii], bc._betaUB == null ? Double.POSITIVE_INFINITY : bc._betaUB[ii]);
final double[] objvals = new double[2];
objvals[1] = Double.POSITIVE_INFINITY;
double reltol = L1Solver.DEFAULT_RELTOL;
double abstol = L1Solver.DEFAULT_ABSTOL;
double ADMM_gradEps = 1e-3;
ProximalGradientSolver innerSolver = new ProximalGradientSolver(gslvr, beta, rho, _parms._objective_epsilon * 1e-1, _parms._gradient_epsilon, new ProgressMonitor() {
@Override
public boolean progress(double[] betaDiff, GradientInfo ginfo) {return ++_state._iter < _parms._max_iterations;}
});
new ADMM.L1Solver(ADMM_gradEps, 250, reltol, abstol).solve(innerSolver, beta, l1pen, true, _state.activeBC()._betaLB, _state.activeBC()._betaUB);
_state.updateState(beta,gslvr.getGradient(beta));
} else {
Result r = lbfgs.solve(gslvr, beta, _state.ginfo(), new ProgressMonitor() {
@Override
public boolean progress(double[] beta, GradientInfo ginfo) {
if(_state._iter < 4 || ((_state._iter & 3) == 0))
Log.info(LogMsg("LBFGS, gradient norm = " + ArrayUtils.linfnorm(ginfo._gradient,false)));
return GLMDriver.this.progress(beta,ginfo);
}
});
Log.info(LogMsg(r.toString()));
_state.updateState(r.coefs,(GLMGradientInfo)r.ginfo);
}
}
private void fitCOD() {
double [] beta = _state.beta();
int p = _state.activeData().fullN()+ 1;
double wsum,wsumu; // intercept denum
double [] denums;
boolean skipFirstLevel = !_state.activeData()._useAllFactorLevels;
double [] betaold = beta.clone();
double objold = _state.objective();
int iter2=0; // total cd iters
// get reweighted least squares vectors
Vec[] newVecs = _state.activeData()._adaptedFrame.anyVec().makeZeros(3);
Vec w = newVecs[0]; // fixed before each CD loop
Vec z = newVecs[1]; // fixed before each CD loop
Vec zTilda = newVecs[2]; // will be updated at every variable within CD loop
long startTimeTotalNaive = System.currentTimeMillis();
// generate new IRLS iteration
while (iter2++ < 30) {
Frame fr = new Frame(_state.activeData()._adaptedFrame);
fr.add("w", w); // fr has all data
fr.add("z", z);
fr.add("zTilda", zTilda);
GLMGenerateWeightsTask gt = new GLMGenerateWeightsTask(_job._key, _state.activeData(), _parms, beta).doAll(fr);
double objVal = objVal(gt._likelihood, gt._betaw, _state.lambda());
denums = gt.denums;
wsum = gt.wsum;
wsumu = gt.wsumu;
int iter1 = 0;
// coordinate descent loop
while (iter1++ < 100) {
Frame fr2 = new Frame();
fr2.add("w", w);
fr2.add("z", z);
fr2.add("zTilda", zTilda); // original x%*%beta if first iteration
for(int i=0; i < _state.activeData()._cats; i++) {
Frame fr3 = new Frame(fr2);
int level_num = _state.activeData()._catOffsets[i+1]-_state.activeData()._catOffsets[i];
int prev_level_num = 0;
fr3.add("xj", _state.activeData()._adaptedFrame.vec(i));
boolean intercept = (i == 0); // prev var is intercept
if(!intercept) {
prev_level_num = _state.activeData()._catOffsets[i]-_state.activeData()._catOffsets[i-1];
fr3.add("xjm1", _state.activeData()._adaptedFrame.vec(i-1)); // add previous categorical variable
}
int start_old = _state.activeData()._catOffsets[i];
GLMCoordinateDescentTaskSeqNaive stupdate;
if(intercept)
stupdate = new GLMCoordinateDescentTaskSeqNaive(intercept, false, 4 , Arrays.copyOfRange(betaold, start_old, start_old+level_num),
new double [] {beta[p-1]}, _state.activeData()._catLvls[i], null, null, null, null, null, skipFirstLevel).doAll(fr3);
else
stupdate = new GLMCoordinateDescentTaskSeqNaive(intercept, false, 1 , Arrays.copyOfRange(betaold, start_old,start_old+level_num),
Arrays.copyOfRange(beta, _state.activeData()._catOffsets[i-1], _state.activeData()._catOffsets[i]) , _state.activeData()._catLvls[i] ,
_state.activeData()._catLvls[i-1], null, null, null, null, skipFirstLevel ).doAll(fr3);
for(int j=0; j < level_num; ++j)
beta[_state.activeData()._catOffsets[i]+j] = ADMM.shrinkage(stupdate._temp[j] / wsumu, _parms._lambda[_lambdaId] * _parms._alpha[0])
/ (denums[_state.activeData()._catOffsets[i]+j] / wsumu + _parms._lambda[_lambdaId] * (1 - _parms._alpha[0]));
}
int cat_num = 2; // if intercept, or not intercept but not first numeric, then both are numeric .
for (int i = 0; i < _state.activeData()._nums; ++i) {
GLMCoordinateDescentTaskSeqNaive stupdate;
Frame fr3 = new Frame(fr2);
fr3.add("xj", _state.activeData()._adaptedFrame.vec(i+_state.activeData()._cats)); // add current variable col
boolean intercept = (i == 0 && _state.activeData().numStart() == 0); // if true then all numeric case and doing beta_1
double [] meannew=null, meanold=null, varnew=null, varold=null;
if(i > 0 || intercept) {// previous var is a numeric var
cat_num = 3;
if(!intercept)
fr3.add("xjm1", _state.activeData()._adaptedFrame.vec(i - 1 + _state.activeData()._cats)); // add previous one if not doing a beta_1 update, ow just pass it the intercept term
if( _state.activeData()._normMul!=null ) {
varold = new double[]{_state.activeData()._normMul[i]};
meanold = new double[]{_state.activeData()._normSub[i]};
if (i!= 0){
varnew = new double []{ _state.activeData()._normMul[i-1]};
meannew = new double [] { _state.activeData()._normSub[i-1]};
}
}
stupdate = new GLMCoordinateDescentTaskSeqNaive(intercept, false, cat_num , new double [] { betaold[_state.activeData().numStart()+ i]},
new double []{ beta[ (_state.activeData().numStart()+i-1+p)%p ]}, null, null,
varold, meanold, varnew, meannew, skipFirstLevel ).doAll(fr3);
beta[i+_state.activeData().numStart()] = ADMM.shrinkage(stupdate._temp[0] / wsumu, _parms._lambda[_lambdaId] * _parms._alpha[0])
/ (denums[i+_state.activeData().numStart()] / wsumu + _parms._lambda[_lambdaId] * (1 - _parms._alpha[0]));
}
else if (i == 0 && !intercept){ // previous one is the last categorical variable
int prev_level_num = _state.activeData().numStart()-_state.activeData()._catOffsets[_state.activeData()._cats-1];
fr3.add("xjm1", _state.activeData()._adaptedFrame.vec(_state.activeData()._cats-1)); // add previous categorical variable
if( _state.activeData()._normMul!=null){
varold = new double []{ _state.activeData()._normMul[i]};
meanold = new double [] { _state.activeData()._normSub[i]};
}
stupdate = new GLMCoordinateDescentTaskSeqNaive(intercept, false, cat_num , new double [] {betaold[ _state.activeData().numStart()]},
Arrays.copyOfRange(beta,_state.activeData()._catOffsets[_state.activeData()._cats-1],_state.activeData().numStart() ), null, _state.activeData()._catLvls[_state.activeData()._cats-1],
varold, meanold, null, null, skipFirstLevel ).doAll(fr3);
beta[_state.activeData().numStart()] = ADMM.shrinkage(stupdate._temp[0] / wsumu, _parms._lambda[_lambdaId] * _parms._alpha[0])
/ (denums[_state.activeData().numStart()] / wsumu + _parms._lambda[_lambdaId] * (1 - _parms._alpha[0]));
}
}
if(_state.activeData()._nums + _state.activeData()._cats > 0) {
// intercept update: preceded by a categorical or numeric variable
Frame fr3 = new Frame(fr2);
fr3.add("xjm1", _state.activeData()._adaptedFrame.vec(_state.activeData()._cats + _state.activeData()._nums - 1)); // add last variable updated in cycle to the frame
GLMCoordinateDescentTaskSeqNaive iupdate;
if (_state.activeData()._adaptedFrame.vec(_state.activeData()._cats + _state.activeData()._nums - 1).isCategorical()) { // only categorical vars
cat_num = 2;
iupdate = new GLMCoordinateDescentTaskSeqNaive(false, true, cat_num, new double[]{betaold[betaold.length - 1]},
Arrays.copyOfRange(beta, _state.activeData()._catOffsets[_state.activeData()._cats - 1], _state.activeData()._catOffsets[_state.activeData()._cats]),
null, _state.activeData()._catLvls[_state.activeData()._cats - 1], null, null, null, null, skipFirstLevel).doAll(fr3);
} else { // last variable is numeric
cat_num = 3;
double[] meannew = null, varnew = null;
if (_state.activeData()._normMul != null) {
varnew = new double[]{_state.activeData()._normMul[_state.activeData()._normMul.length - 1]};
meannew = new double[]{_state.activeData()._normSub[_state.activeData()._normSub.length - 1]};
}
iupdate = new GLMCoordinateDescentTaskSeqNaive(false, true, cat_num,
new double[]{betaold[betaold.length - 1]}, new double[]{beta[beta.length - 2]}, null, null,
null, null, varnew, meannew, skipFirstLevel).doAll(fr3);
}
if (_parms._intercept)
beta[beta.length - 1] = iupdate._temp[0] / wsum;
}
double maxdiff = ArrayUtils.linfnorm(ArrayUtils.subtract(beta, betaold), false); // false to keep the intercept
System.arraycopy(beta, 0, betaold, 0, beta.length);
if (maxdiff < _parms._beta_epsilon)
break;
}
double percdiff = Math.abs((objold - objVal)/objold);
if (percdiff < _parms._objective_epsilon & iter2 >1 )
break;
objold=objVal;
System.out.println("iter1 = " + iter1);
}
System.out.println("iter2 = " + iter2);
long endTimeTotalNaive = System.currentTimeMillis();
long durationTotalNaive = (endTimeTotalNaive - startTimeTotalNaive)/1000;
System.out.println("Time to run Naive Coordinate Descent " + durationTotalNaive);
_state._iter = iter2;
for (Vec v : newVecs) v.remove();
_state.updateState(beta,objold);
}
private void fitModel() {
Solver solver = (_parms._solver == Solver.AUTO) ? defaultSolver() : _parms._solver;
switch (solver) {
case COORDINATE_DESCENT: // fall through to IRLSM
case IRLSM:
if(_parms._family == Family.multinomial)
fitIRLSM_multinomial();
else if(_parms._family == Family.gaussian && _parms._link == Link.identity)
fitLSM();
else
fitIRLSM();
break;
case L_BFGS:
fitLBFGS();
break;
case COORDINATE_DESCENT_NAIVE:
fitCOD();
break;
default:
throw H2O.unimpl();
}
if(_parms._compute_p_values) { // compute p-values
double se = 1;
boolean seEst = false;
double [] beta = _state.beta();
if(_parms._family != Family.binomial && _parms._family != Family.poisson) {
seEst = true;
ComputeSETsk ct = new ComputeSETsk(null, _state.activeData(), _job._key, beta, _parms).doAll(_state.activeData()._adaptedFrame);
se = ct._sumsqe / (_nobs - 1 - _state.activeData().fullN());
}
double [] zvalues = MemoryManager.malloc8d(_state.activeData().fullN()+1);
double [] gInvDiag = _chol.getInvDiag();
for(int i = 0; i < zvalues.length; ++i)
zvalues[i] = beta[i]/Math.sqrt(_parms._obj_reg*gInvDiag[i]*se);
_model.setZValues(expandVec(zvalues,_state.activeData()._activeCols,_dinfo.fullN()+1,Double.NaN),se, seEst);
}
}
private long _lastScore = System.currentTimeMillis();
private long timeSinceLastScoring(){return System.currentTimeMillis() - _lastScore;}
private transient HashMap<String,Key> _keys2Keep = new HashMap<>();
private void scoreAndUpdateModel(){
// compute full validation on train and test
Log.info(LogMsg("Scoring after " + timeSinceLastScoring() + "ms"));
long t1 = System.currentTimeMillis();
Frame train = DKV.<Frame>getGet(_parms._train);
_model.score(train).delete();
ModelMetrics mtrain = ModelMetrics.getFromDKV(_model, train); // updated by model.scoreAndUpdateModel
_model._output._training_metrics = mtrain;
long t2 = System.currentTimeMillis();
Log.info(LogMsg("Training metrics computed in " + (t2-t1) + "ms"));
Log.info(LogMsg(mtrain.toString()));
_keys2Keep.put("training_metrics",mtrain._key);
if(_valid != null) {
Frame valid = DKV.<Frame>getGet(_parms._valid);
_model.score(valid).delete();
_model._output._validation_metrics = ModelMetrics.getFromDKV(_model, valid); //updated by model.scoreAndUpdateModel
_keys2Keep.put("validation_metrics",_model._output._validation_metrics._key);
}
_model._output._scoring_history = _parms._lambda_search?_lsc.to2dTable():_sc.to2dTable();
_model.update(_job._key);
_model.generateSummary(_parms._train,_state._iter);
_lastScore = System.currentTimeMillis();
long scoringTime = System.currentTimeMillis() - t1;
_scoringInterval = Math.max(_scoringInterval,20*scoringTime); // at most 5% overhead for scoring
}
@Override
public void compute2() {
Scope.enter();
_keys2Keep.put("dest",dest());
_parms.read_lock_frames(_job);
init(true);
if (error_count() > 0) {
throw H2OModelBuilderIllegalArgumentException.makeFromBuilder(GLM.this);
}
double nullDevTrain = Double.NaN;
double nullDevTest = Double.NaN;
if(_parms._lambda_search) {
nullDevTrain = _parms._family == Family.multinomial
?new GLMResDevTaskMultinomial(_job._key,_state._dinfo,getNullBeta(), _nclass).doAll(_state._dinfo._adaptedFrame)._likelihood*2
:new GLMResDevTask(_job._key, _state._dinfo, _parms, getNullBeta()).doAll(_state._dinfo._adaptedFrame)._resDev;
if(_validDinfo != null)
nullDevTest = _parms._family == Family.multinomial
?new GLMResDevTaskMultinomial(_job._key,_validDinfo,getNullBeta(), _nclass).doAll(_validDinfo._adaptedFrame)._likelihood*2
:new GLMResDevTask(_job._key, _validDinfo, _parms, getNullBeta()).doAll(_validDinfo._adaptedFrame)._resDev;
_workPerIteration = WORK_TOTAL/_parms._nlambdas;
} else
_workPerIteration = 1 + (WORK_TOTAL/_parms._max_iterations);
if(_parms._family == Family.multinomial && _parms._solver == Solver.IRLSM) {
double [] nb = getNullBeta();
double maxRow = ArrayUtils.maxValue(nb);
double sumExp = 0;
int P = _dinfo.fullN();
int N = _dinfo.fullN()+1;
for(int i = 1; i < _nclass; ++i)
sumExp += Math.exp(nb[i*N + P] - maxRow);
_dinfo.addResponse(new String[]{"__glm_sumExp", "__glm_maxRow"}, _dinfo._adaptedFrame.anyVec().makeDoubles(2, new double[]{sumExp,maxRow}));
}
double testDevOld = Double.NaN;
double trainDevOld = Double.NaN;
int impcnt = 0;
// lambda search loop
for (int i = 0; i < _parms._lambda.length; ++i) { // lambda search
_model.addSubmodel(_state.beta(),_parms._lambda[i],_state._iter);
_state.setLambda(_parms._lambda[i]);
do {
if(_parms._family == Family.multinomial)
for(int c = 0; c < _nclass; ++c)
Log.info(LogMsg("Class " + c + " got " + _state.activeDataMultinomial(c).fullN() + " active columns out of " + _state._dinfo.fullN() + " total"));
else
Log.info(LogMsg("Got " + _state.activeData().fullN() + " active columns out of " + _state._dinfo.fullN() + " total"));
fitModel();
} while(!_state.checkKKTs());
Log.info(LogMsg("solution has " + ArrayUtils.countNonzeros(_state.beta()) + " nonzeros"));
if(_parms._lambda_search) { // compute train and test dev
double trainDev = _parms._family == Family.multinomial
?new GLMResDevTaskMultinomial(_job._key,_state._dinfo,_state.beta(), _nclass).doAll(_state._dinfo._adaptedFrame)._likelihood*2
:new GLMResDevTask(_job._key, _state._dinfo, _parms, _state.beta()).doAll(_state._dinfo._adaptedFrame)._resDev;
double testDev = -1;
if(_validDinfo != null)
testDev = _parms._family == Family.multinomial
?new GLMResDevTaskMultinomial(_job._key,_validDinfo,_dinfo.denormalizeBeta(_state.beta()), _nclass).doAll(_validDinfo._adaptedFrame)._likelihood*2
:new GLMResDevTask(_job._key, _validDinfo, _parms, _dinfo.denormalizeBeta(_state.beta())).doAll(_validDinfo._adaptedFrame)._resDev;
Log.info(LogMsg("train deviance = " + trainDev + ", test deviance = " + testDev));
_lsc.addLambdaScore(_state._iter,ArrayUtils.countNonzeros(_state.beta()), _state.lambda(),1 - trainDev/nullDevTrain, 1.0 - testDev/nullDevTest);
_model.update(_state.beta(), trainDev, testDev, _state._iter);
if(testDev > testDevOld)
break; // started overfitting
testDevOld = testDev;
if(_parms._score_each_iteration || timeSinceLastScoring() > _scoringInterval)
scoreAndUpdateModel(); // update partial results
_job.update(_workPerIteration,"iter=" + _state._iter + " lmb=" + lambdaFormatter.format(_state.lambda()) + "exp.dev.ratio trn/tst= " + devFormatter.format(1 - trainDev/nullDevTrain) + "/" + devFormatter.format(1.0 - testDev/nullDevTest) + " P=" + ArrayUtils.countNonzeros(_state.beta()));
} else
_model.update(_state.beta(), -1, -1, _state._iter);
}
_model._output.pickBestModel();
scoreAndUpdateModel();
if(_iceptAdjust != 0) { // apply the intercept adjust according to prior probability
assert _parms._intercept;
double [] b = _model._output._global_beta;
b[b.length-1] += _iceptAdjust;
for(Submodel sm:_model._output._submodels)
sm.beta[sm.beta.length-1] += _iceptAdjust;
_model.update(_job._key);
}
doCleanup();
tryComplete();
}
@Override public boolean onExceptionalCompletion(Throwable t, CountedCompleter caller){
_keys2Keep.clear();
doCleanup();
return true;
}
private double betaDiff(double [] b1, double [] b2) {
double res = Math.abs(b1[0] - b2[0]);
for(int i = 0; i < b1.length; ++i) {
double diff = b1[i] - b2[i];
if(diff > res) res = diff;
else if(-diff > res) res = -diff;
}
return res;
}
@Override public boolean progress(double [] beta, GradientInfo ginfo) {
GLMGradientInfo gginfo = (GLMGradientInfo)ginfo;
_state.updateState(beta,gginfo);
if(!_parms._lambda_search)
updateProgress();
return _job.isRunning() && _state._iter++ < _parms._max_iterations && !_state.converged();
}
public boolean progress(double [] beta, double likelihood) {
_state.updateState(beta,likelihood);
if(!_parms._lambda_search)
updateProgress();
return _job.isRunning() && _state._iter++ < _parms._max_iterations && !_state.converged();
}
private transient long _scoringInterval = SCORING_INTERVAL_MSEC;
// update user visible progress
protected void updateProgress(){
assert !_parms._lambda_search;
_sc.addIterationScore(_state._iter, _state.likelihood(), _state.objective());
_job.update(_workPerIteration,_state.toString());
if(_parms._score_each_iteration || timeSinceLastScoring() > _scoringInterval) {
_model.update(_state.expandBeta(_state.beta()), -1, -1, _state._iter);
scoreAndUpdateModel();
}
}
}
private Solver defaultSolver() {
return Solver.IRLSM;
}
private double currentLambda() {
return _parms._lambda[_lambdaId];
}
double objVal(double likelihood, double[] beta, double lambda) {
double alpha = _parms._alpha[0];
double proximalPen = 0;
BetaConstraint bc = _state.activeBC();
if (_state.activeBC()._betaGiven != null && bc._rho != null) {
for (int i = 0; i < bc._betaGiven.length; ++i) {
double diff = beta[i] - bc._betaGiven[i];
proximalPen += diff * diff * bc._rho[i];
}
}
return (likelihood * _parms._obj_reg
+ .5 * proximalPen
+ lambda * (alpha * ArrayUtils.l1norm(beta, _parms._intercept)
+ (1 - alpha) * .5 * ArrayUtils.l2norm2(beta, _parms._intercept)));
}
private String LogMsg(String msg) {return "GLM[dest=" + dest() + ", " + _state + "] " + msg;}
private static final double[] expandVec(double[] beta, final int[] activeCols, int fullN) {
return expandVec(beta, activeCols, fullN, 0);
}
private static final double[] expandVec(double[] beta, final int[] activeCols, int fullN, double filler) {
assert beta != null;
if (activeCols == null) return beta;
double[] res = MemoryManager.malloc8d(fullN);
Arrays.fill(res, filler);
int i = 0;
for (int c : activeCols)
res[c] = beta[i++];
res[res.length - 1] = beta[beta.length - 1];
return res;
}
private static double [] doUpdateCD(double [] grads, double [][] xx, double diff , int variable, int variable_min, int variable_max) {
double[] ary = xx[variable];
for (int i = 0; i < variable_min; i++)
grads[i] += diff * ary[i];
for (int i = variable_max; i < grads.length; i++)
grads[i] += diff * ary[i];
return grads;
}
public double [] COD_solve(GLMIterationTask gt, double alpha, double lambda) {
gt._gram.mul(_parms._obj_reg);
ArrayUtils.mult(gt._xy,_parms._obj_reg);
double wsumInv = 1.0/(gt.wsum*_parms._obj_reg);
double l1pen = lambda * alpha;
double l2pen = lambda*(1-alpha);
double [][] xx = gt._gram.getXX();
double [] grads = gt._xy.clone();
double [] beta = gt._beta.clone();
for(int i = 0; i < grads.length; ++i) {
double ip = 0;
for(int j = 0; j < beta.length; ++j)
ip += beta[j]*xx[i][j];
grads[i] = grads[i] - ip + beta[i]*xx[i][i];
}
double [] diagInv = MemoryManager.malloc8d(xx.length);
for(int i = 0; i < diagInv.length; ++i)
diagInv[i] = 1.0/(xx[i][i] + l2pen);
int iter1 = 0;
int P = gt._xy.length - 1;
DataInfo activeData = _state.activeData();
// CD loop
while (iter1++ < 1000 /*Math.max(P,500)*/) {
double bdiffPos = 0;
double bdiffNeg = 0;
for (int i = 0; i < activeData._cats; ++i) {
for(int j = activeData._catOffsets[i]; j < activeData._catOffsets[i+1]; ++j) { // can do in parallel
double b = ADMM.shrinkage(grads[j], l1pen) * diagInv[j];
double bd = beta[j] - b;
bdiffPos = bd > bdiffPos?bd:bdiffPos;
bdiffNeg = bd < bdiffNeg?bd:bdiffNeg;
doUpdateCD(grads, xx, bd, j, activeData._catOffsets[i], activeData._catOffsets[i + 1]);
beta[j] = b;
}
}
int numStart = activeData.numStart();
for (int i = numStart; i < P; ++i) {
double b = ADMM.shrinkage(grads[i], l1pen) * diagInv[i];
double bd = beta[i] - b;
bdiffPos = bd > bdiffPos?bd:bdiffPos;
bdiffNeg = bd < bdiffNeg?bd:bdiffNeg;
doUpdateCD(grads, xx, bd, i,i,i+1);
beta[i] = b;
}
// intercept
double b = grads[P] * wsumInv;
double bd = beta[P] - b;
doUpdateCD(grads, xx, bd, P,P,P+1);
bdiffPos = bd > bdiffPos?bd:bdiffPos;
bdiffNeg = bd < bdiffNeg?bd:bdiffNeg;
beta[P] = b;
if (-1e-4 < bdiffNeg && bdiffPos < 1e-4)
break;
}
return beta;
}
/**
* Created by tomasnykodym on 3/30/15.
*/
public static final class GramSolver implements ProximalSolver {
private final Gram _gram;
private Cholesky _chol;
private final double[] _xy;
final double _lambda;
double[] _rho;
boolean _addedL2;
double _betaEps;
private static double boundedX(double x, double lb, double ub) {
if (x < lb) x = lb;
if (x > ub) x = ub;
return x;
}
public GramSolver(Gram gram, double[] xy, double lmax, double betaEps, boolean intercept) {
_gram = gram;
_lambda = 0;
_betaEps = betaEps;
_xy = xy;
double[] rhos = MemoryManager.malloc8d(xy.length);
computeCholesky(gram, rhos, lmax * 1e-8);
_addedL2 = rhos[0] != 0;
_rho = _addedL2 ? rhos : null;
}
// solve non-penalized problem
public void solve(double[] result) {
System.arraycopy(_xy, 0, result, 0, _xy.length);
_chol.solve(result);
double gerr = Double.POSITIVE_INFINITY;
if (_addedL2) { // had to add l2-pen to turn the gram to be SPD
double[] oldRes = MemoryManager.arrayCopyOf(result, result.length);
for (int i = 0; i < 1000; ++i) {
solve(oldRes, result);
double[] g = gradient(result);
gerr = Math.max(-ArrayUtils.minValue(g), ArrayUtils.maxValue(g));
if (gerr < 1e-4) return;
System.arraycopy(result, 0, oldRes, 0, result.length);
}
Log.warn("Gram solver did not converge, gerr = " + gerr);
}
}
public GramSolver(Gram gram, double[] xy, boolean intercept, double l2pen, double l1pen, double[] beta_given, double[] proxPen, double[] lb, double[] ub) {
if (ub != null && lb != null)
for (int i = 0; i < ub.length; ++i) {
assert ub[i] >= lb[i] : i + ": ub < lb, ub = " + Arrays.toString(ub) + ", lb = " + Arrays.toString(lb);
}
_lambda = l2pen;
_gram = gram;
// Try to pick optimal rho constant here used in ADMM solver.
//
// Rho defines the strength of proximal-penalty and also the strentg of L1 penalty aplpied in each step.
// Picking good rho constant is tricky and greatly influences the speed of convergence and precision with which we are able to solve the problem.
//
// Intuitively, we want the proximal l2-penalty ~ l1 penalty (l1 pen = lambda/rho, where lambda is the l1 penalty applied to the problem)
// Here we compute the rho for each coordinate by using equation for computing coefficient for single coordinate and then making the two penalties equal.
//
int ii = intercept ? 1 : 0;
int icptCol = xy.length - 1;
double[] rhos = MemoryManager.malloc8d(xy.length);
double min = Double.POSITIVE_INFINITY;
for (int i = 0; i < xy.length - ii; ++i) {
double d = xy[i];
d = d >= 0 ? d : -d;
if (d < min && d != 0) min = d;
}
double ybar = xy[icptCol];
for (int i = 0; i < rhos.length - ii; ++i) {
double y = xy[i];
if (y == 0) y = min;
double xbar = gram.get(icptCol, i);
double x = ((y - ybar * xbar) / ((gram.get(i, i) - xbar * xbar) + l2pen));///gram.get(i,i);
rhos[i] = ADMM.L1Solver.estimateRho(x, l1pen, lb == null ? Double.NEGATIVE_INFINITY : lb[i], ub == null ? Double.POSITIVE_INFINITY : ub[i]);
}
// do the intercept separate as l1pen does not apply to it
if (intercept && (lb != null && !Double.isInfinite(lb[icptCol]) || ub != null && !Double.isInfinite(ub[icptCol]))) {
int icpt = xy.length - 1;
rhos[icpt] = 1;//(xy[icpt] >= 0 ? xy[icpt] : -xy[icpt]);
}
if (l2pen > 0)
gram.addDiag(l2pen);
if (proxPen != null && beta_given != null) {
gram.addDiag(proxPen);
xy = xy.clone();
for (int i = 0; i < xy.length; ++i)
xy[i] += proxPen[i] * beta_given[i];
}
computeCholesky(gram, rhos, 1e-5);
_rho = rhos;
_xy = xy;
}
private void computeCholesky(Gram gram, double[] rhos, double rhoAdd) {
gram.addDiag(rhos);
_chol = gram.cholesky(null, true, null);
if (!_chol.isSPD()) { // make sure rho is big enough
gram.addDiag(ArrayUtils.mult(rhos, -1));
ArrayUtils.mult(rhos, -1);
for (int i = 0; i < rhos.length; ++i)
rhos[i] += rhoAdd;//1e-5;
Log.info("Got NonSPD matrix with original rho, re-computing with rho = " + rhos[0]);
_gram.addDiag(rhos);
_chol = gram.cholesky(null, true, null);
int cnt = 0;
while (!_chol.isSPD() && cnt++ < 5) {
gram.addDiag(ArrayUtils.mult(rhos, -1));
ArrayUtils.mult(rhos, -1);
for (int i = 0; i < rhos.length; ++i)
rhos[i] *= 100;
Log.warn("Still NonSPD matrix, re-computing with rho = " + rhos[0]);
_gram.addDiag(rhos);
_chol = gram.cholesky(null, true, null);
}
if (!_chol.isSPD())
throw new NonSPDMatrixException();
}
gram.addDiag(ArrayUtils.mult(rhos, -1));
ArrayUtils.mult(rhos, -1);
}
@Override
public double[] rho() {
return _rho;
}
@Override
public boolean solve(double[] beta_given, double[] result) {
if (beta_given != null)
for (int i = 0; i < _xy.length; ++i)
result[i] = _xy[i] + _rho[i] * beta_given[i];
else
System.arraycopy(_xy, 0, result, 0, _xy.length);
_chol.solve(result);
return true;
}
@Override
public boolean hasGradient() {
return false;
}
@Override
public double[] gradient(double[] beta) {
double[] grad = _gram.mul(beta);
for (int i = 0; i < _xy.length; ++i)
grad[i] -= _xy[i];
return grad;
}
@Override
public int iter() {
return 0;
}
}
public static class ProximalGradientInfo extends GradientInfo {
final GradientInfo _origGinfo;
public ProximalGradientInfo(GradientInfo origGinfo, double objVal, double[] gradient) {
super(objVal, gradient);
_origGinfo = origGinfo;
}
}
/**
* Simple wrapper around ginfo computation, adding proximal penalty
*/
public static class ProximalGradientSolver implements GradientSolver, ProximalSolver {
final GradientSolver _solver;
double[] _betaGiven;
double[] _beta;
private ProximalGradientInfo _ginfo;
private final ProgressMonitor _pm;
final double[] _rho;
private final double _objEps;
private final double _gradEps;
public ProximalGradientSolver(GradientSolver s, double[] betaStart, double[] rho, double objEps, double gradEps, ProgressMonitor pm) {
super();
_solver = s;
_rho = rho;
_objEps = objEps;
_gradEps = gradEps;
_pm = pm;
_beta = betaStart;
_betaGiven = MemoryManager.malloc8d(betaStart.length);
}
public static double proximal_gradient(double[] grad, double obj, double[] beta, double[] beta_given, double[] rho) {
for (int i = 0; i < beta.length; ++i) {
double diff = (beta[i] - beta_given[i]);
double pen = rho[i] * diff;
if(grad != null)
grad[i] += pen;
obj += .5 * pen * diff;
}
return obj;
}
@Override
public ProximalGradientInfo getGradient(double[] beta) {
GradientInfo ginfo = _solver.getGradient(beta);
double[] gradient = ginfo._gradient.clone();
double obj = proximal_gradient(gradient, ginfo._objVal, beta, _betaGiven, _rho);
return new ProximalGradientInfo(ginfo, obj, gradient);
}
@Override
public GradientInfo getObjective(double[] beta) {
GradientInfo ginfo = _solver.getObjective(beta);
double obj = proximal_gradient(null, ginfo._objVal, beta, _betaGiven, _rho);
return new ProximalGradientInfo(ginfo,obj,null);
}
@Override
public double[] rho() {
return _rho;
}
private int _iter;
@Override
public boolean solve(double[] beta_given, double[] beta) {
if (_ginfo == null || beta != _beta) {
_ginfo = getGradient(beta);
_beta = beta;
}
double[] gradient = _ginfo._gradient;
System.arraycopy(_ginfo._origGinfo._gradient, 0, gradient, 0, gradient.length);
double obj = proximal_gradient(gradient, _ginfo._origGinfo._objVal, beta, beta_given, _rho);
_ginfo = new ProximalGradientInfo(_ginfo._origGinfo, obj, gradient);
System.arraycopy(beta_given, 0, _betaGiven, 0, _betaGiven.length);
L_BFGS.Result r = new L_BFGS().setObjEps(_objEps).setGradEps(_gradEps).solve(this, beta, _ginfo, _pm);
System.arraycopy(r.coefs,0,beta,0,r.coefs.length);
_iter += r.iter;
_ginfo = (ProximalGradientInfo) r.ginfo;
return r.converged;
}
@Override
public boolean hasGradient() {
return true;
}
@Override
public double[] gradient(double[] beta) {
return getGradient(beta)._origGinfo._gradient;
}
@Override
public int iter() {
return _iter;
}
}
public static class GLMGradientInfo extends GradientInfo {
final double _likelihood;
public GLMGradientInfo(double likelihood, double objVal, double[] grad) {
super(objVal, grad);
_likelihood = likelihood;
}
public String toString(){
return "GLM grad info: likelihood = " + _likelihood + ", obj = " + _objVal + ", gradient = " + Arrays.toString(_gradient);
}
}
/**
* Gradient and line search computation for L_BFGS and also L_BFGS solver wrapper (for ADMM)
*/
public static final class GLMGradientSolver implements GradientSolver {
final GLMParameters _parms;
final DataInfo _dinfo;
final BetaConstraint _bc;
final double _l2pen; // l2 penalty
double[][] _betaMultinomial;
final Key _jobKey;
public GLMGradientSolver(Key jobKey, GLMParameters glmp, DataInfo dinfo, double l2pen, BetaConstraint bc) {
_jobKey = jobKey;
_bc = bc;
_parms = glmp;
_dinfo = dinfo;
_l2pen = l2pen;
}
@Override
public GLMGradientInfo getGradient(double[] beta) {
if (_parms._family == Family.multinomial) {
if (_betaMultinomial == null) {
int nclasses = beta.length / (_dinfo.fullN() + 1);
assert beta.length % (_dinfo.fullN() + 1) == 0:"beta len = " + beta.length + ", fullN +1 == " + (_dinfo.fullN()+1);
_betaMultinomial = new double[nclasses][];
for (int i = 0; i < nclasses; ++i)
_betaMultinomial[i] = MemoryManager.malloc8d(_dinfo.fullN() + 1);
}
int off = 0;
for (int i = 0; i < _betaMultinomial.length; ++i) {
System.arraycopy(beta, off, _betaMultinomial[i], 0, _betaMultinomial[i].length);
off += _betaMultinomial[i].length;
}
GLMMultinomialGradientTask gt = new GLMMultinomialGradientTask(_jobKey,_dinfo, _l2pen, _betaMultinomial, _parms._obj_reg, false, null).doAll(_dinfo._adaptedFrame);
double l2pen = 0;
for (double[] b : _betaMultinomial)
l2pen += ArrayUtils.l2norm2(b, _dinfo._intercept);
return new GLMGradientInfo(gt._likelihood, gt._likelihood * _parms._obj_reg + .5 * _l2pen * l2pen, gt._gradient);
} else {
assert beta.length == _dinfo.fullN() + 1;
assert _parms._intercept || (beta[beta.length-1] == 0);
GLMGradientTask gt;
if(_parms._family == Family.binomial && _parms._link == Link.logit)
gt = new GLMBinomialGradientTask(_jobKey,_dinfo,_parms,_l2pen, beta).doAll(_dinfo._adaptedFrame);
else if(_parms._family == Family.gaussian && _parms._link == Link.identity)
gt = new GLMGaussianGradientTask(_jobKey,_dinfo,_parms,_l2pen, beta).doAll(_dinfo._adaptedFrame);
else
gt = new GLMGenericGradientTask(_jobKey, _dinfo, _parms, _l2pen, beta).doAll(_dinfo._adaptedFrame);
double [] gradient = gt._gradient;
double likelihood = gt._likelihood;
if (!_parms._intercept) // no intercept, null the ginfo
gradient[gradient.length - 1] = 0;
double obj = likelihood * _parms._obj_reg + .5 * _l2pen * ArrayUtils.l2norm2(beta, true);
if (_bc != null && _bc._betaGiven != null && _bc._rho != null)
obj = ProximalGradientSolver.proximal_gradient(gradient, obj, beta, _bc._betaGiven, _bc._rho);
return new GLMGradientInfo(likelihood, obj, gradient);
}
}
@Override
public GradientInfo getObjective(double[] beta) {
double l = new GLMResDevTask(_jobKey,_dinfo,_parms,beta).doAll(_dinfo._adaptedFrame)._likelihood;
return new GLMGradientInfo(l,l*_parms._obj_reg + .5*_l2pen*ArrayUtils.l2norm2(beta,true),null);
}
}
protected static double sparseOffset(double[] beta, DataInfo dinfo) {
double etaOffset = 0;
if (dinfo._normMul != null && dinfo._normSub != null && beta != null) {
int ns = dinfo.numStart();
for (int i = 0; i < dinfo._nums; ++i)
etaOffset -= beta[i + ns] * dinfo._normSub[i] * dinfo._normMul[i];
}
return etaOffset;
}
public class BetaConstraint extends Iced {
double[] _betaStart;
double[] _betaGiven;
double[] _rho;
double[] _betaLB;
double[] _betaUB;
public BetaConstraint() {
if (_parms._non_negative) setNonNegative();
}
public void setNonNegative() {
if (_betaLB == null) {
_betaLB = MemoryManager.malloc8d(_dinfo.fullN() + 1);
_betaLB[_dinfo.fullN()] = Double.NEGATIVE_INFINITY;
} else for (int i = 0; i < _betaLB.length - 1; ++i)
_betaLB[i] = Math.max(0, _betaLB[i]);
if (_betaUB == null) {
_betaUB = MemoryManager.malloc8d(_dinfo.fullN() + 1);
Arrays.fill(_betaUB, Double.POSITIVE_INFINITY);
}
}
public BetaConstraint(Frame beta_constraints) {
Vec v = beta_constraints.vec("names");
String[] dom;
int[] map;
if (v.isString()) {
dom = new String[(int) v.length()];
map = new int[dom.length];
BufferedString tmpStr = new BufferedString();
for (int i = 0; i < dom.length; ++i) {
dom[i] = v.atStr(tmpStr, i).toString();
map[i] = i;
}
// check for dups
String[] sortedDom = dom.clone();
Arrays.sort(sortedDom);
for (int i = 1; i < sortedDom.length; ++i)
if (sortedDom[i - 1].equals(sortedDom[i]))
throw new IllegalArgumentException("Illegal beta constraints file, got duplicate constraint for predictor '" + sortedDom[i - 1] + "'!");
} else if (v.isCategorical()) {
dom = v.domain();
map = FrameUtils.asInts(v);
// check for dups
int[] sortedMap = MemoryManager.arrayCopyOf(map, map.length);
Arrays.sort(sortedMap);
for (int i = 1; i < sortedMap.length; ++i)
if (sortedMap[i - 1] == sortedMap[i])
throw new IllegalArgumentException("Illegal beta constraints file, got duplicate constraint for predictor '" + dom[sortedMap[i - 1]] + "'!");
} else
throw new IllegalArgumentException("Illegal beta constraints file, names column expected to contain column names (strings)");
// for now only categoricals allowed here
String[] names = ArrayUtils.append(_dinfo.coefNames(), "Intercept");
if (!Arrays.deepEquals(dom, names)) { // need mapping
HashMap<String, Integer> m = new HashMap<String, Integer>();
for (int i = 0; i < names.length; ++i)
m.put(names[i], i);
int[] newMap = MemoryManager.malloc4(dom.length);
for (int i = 0; i < map.length; ++i) {
if (_removedCols.contains(dom[map[i]])) {
newMap[i] = -1;
continue;
}
Integer I = m.get(dom[map[i]]);
if (I == null) {
throw new IllegalArgumentException("Unrecognized coefficient name in beta-constraint file, unknown name '" + dom[map[i]] + "'");
}
newMap[i] = I;
}
map = newMap;
}
final int numoff = _dinfo.numStart();
String[] valid_col_names = new String[]{"names", "beta_given", "beta_start", "lower_bounds", "upper_bounds", "rho", "mean", "std_dev"};
Arrays.sort(valid_col_names);
for (String s : beta_constraints.names())
if (Arrays.binarySearch(valid_col_names, s) < 0)
error("beta_constraints", "Unknown column name '" + s + "'");
if ((v = beta_constraints.vec("beta_start")) != null) {
_betaStart = MemoryManager.malloc8d(_dinfo.fullN() + (_dinfo._intercept ? 1 : 0));
for (int i = 0; i < (int) v.length(); ++i)
if (map[i] != -1)
_betaStart[map[i]] = v.at(i);
}
if ((v = beta_constraints.vec("beta_given")) != null) {
_betaGiven = MemoryManager.malloc8d(_dinfo.fullN() + (_dinfo._intercept ? 1 : 0));
for (int i = 0; i < (int) v.length(); ++i)
if (map[i] != -1)
_betaGiven[map[i]] = v.at(i);
}
if ((v = beta_constraints.vec("upper_bounds")) != null) {
_betaUB = MemoryManager.malloc8d(_dinfo.fullN() + (_dinfo._intercept ? 1 : 0));
Arrays.fill(_betaUB, Double.POSITIVE_INFINITY);
for (int i = 0; i < (int) v.length(); ++i)
if (map[i] != -1)
_betaUB[map[i]] = v.at(i);
}
if ((v = beta_constraints.vec("lower_bounds")) != null) {
_betaLB = MemoryManager.malloc8d(_dinfo.fullN() + (_dinfo._intercept ? 1 : 0));
Arrays.fill(_betaLB, Double.NEGATIVE_INFINITY);
for (int i = 0; i < (int) v.length(); ++i)
if (map[i] != -1)
_betaLB[map[i]] = v.at(i);
}
if ((v = beta_constraints.vec("rho")) != null) {
_rho = MemoryManager.malloc8d(_dinfo.fullN() + (_dinfo._intercept ? 1 : 0));
for (int i = 0; i < (int) v.length(); ++i)
if (map[i] != -1)
_rho[map[i]] = v.at(i);
}
// mean override (for data standardization)
if ((v = beta_constraints.vec("mean")) != null) {
_parms._stdOverride = true;
for (int i = 0; i < v.length(); ++i) {
if (!v.isNA(i) && map[i] != -1) {
int idx = map == null ? i : map[i];
if (idx > _dinfo.numStart() && idx < _dinfo.fullN()) {
_dinfo._normSub[idx - _dinfo.numStart()] = v.at(i);
} else {
// categorical or Intercept, will be ignored
}
}
}
}
// standard deviation override (for data standardization)
if ((v = beta_constraints.vec("std_dev")) != null) {
_parms._stdOverride = true;
for (int i = 0; i < v.length(); ++i) {
if (!v.isNA(i) && map[i] != -1) {
int idx = map == null ? i : map[i];
if (idx > _dinfo.numStart() && idx < _dinfo.fullN()) {
_dinfo._normMul[idx - _dinfo.numStart()] = 1.0 / v.at(i);
} else {
// categorical or Intercept, will be ignored
}
}
}
}
if (_dinfo._normMul != null) {
double normG = 0, normS = 0, normLB = 0, normUB = 0;
for (int i = numoff; i < _dinfo.fullN(); ++i) {
double s = _dinfo._normSub[i - numoff];
double d = 1.0 / _dinfo._normMul[i - numoff];
if (_betaUB != null && !Double.isInfinite(_betaUB[i])) {
normUB *= s;
_betaUB[i] *= d;
}
if (_betaLB != null && !Double.isInfinite(_betaUB[i])) {
normLB *= s;
_betaLB[i] *= d;
}
if (_betaGiven != null) {
normG += _betaGiven[i] * s;
_betaGiven[i] *= d;
}
if (_betaStart != null) {
normS += _betaStart[i] * s;
_betaStart[i] *= d;
}
}
if (_dinfo._intercept) {
int n = _dinfo.fullN();
if (_betaGiven != null)
_betaGiven[n] += normG;
if (_betaStart != null)
_betaStart[n] += normS;
if (_betaLB != null)
_betaLB[n] += normLB;
if (_betaUB != null)
_betaUB[n] += normUB;
}
}
if (_betaStart == null && _betaGiven != null)
_betaStart = _betaGiven.clone();
if (_betaStart != null) {
if (_betaLB != null || _betaUB != null) {
for (int i = 0; i < _betaStart.length; ++i) {
if (_betaLB != null && _betaLB[i] > _betaStart[i])
_betaStart[i] = _betaLB[i];
if (_betaUB != null && _betaUB[i] < _betaStart[i])
_betaStart[i] = _betaUB[i];
}
}
}
if (_parms._non_negative) setNonNegative();
check();
}
public String toString() {
double[][] ary = new double[_betaGiven.length][3];
for (int i = 0; i < _betaGiven.length; ++i) {
ary[i][0] = _betaGiven[i];
ary[i][1] = _betaLB[i];
ary[i][2] = _betaUB[i];
}
return ArrayUtils.pprint(ary);
}
public boolean hasBounds() {
if (_betaLB != null)
for (double d : _betaLB)
if (!Double.isInfinite(d)) return true;
if (_betaUB != null)
for (double d : _betaUB)
if (!Double.isInfinite(d)) return true;
return false;
}
public boolean hasProximalPenalty() {
return _betaGiven != null && _rho != null && ArrayUtils.countNonzeros(_rho) > 0;
}
public void adjustGradient(double[] beta, double[] grad) {
if (_betaGiven != null && _rho != null) {
for (int i = 0; i < _betaGiven.length; ++i) {
double diff = beta[i] - _betaGiven[i];
grad[i] += _rho[i] * diff;
}
}
}
double proxPen(double[] beta) {
double res = 0;
if (_betaGiven != null && _rho != null) {
for (int i = 0; i < _betaGiven.length; ++i) {
double diff = beta[i] - _betaGiven[i];
res += _rho[i] * diff * diff;
}
res *= .5;
}
return res;
}
public void check() {
if (_betaLB != null && _betaUB != null)
for (int i = 0; i < _betaLB.length; ++i)
if (!(_betaLB[i] <= _betaUB[i]))
throw new IllegalArgumentException("lower bounds myst be <= upper bounds, " + _betaLB[i] + " !<= " + _betaUB[i]);
}
public BetaConstraint filterExpandedColumns(int[] activeCols) {
BetaConstraint res = new BetaConstraint();
if (_betaLB != null)
res._betaLB = ArrayUtils.select(_betaLB, activeCols);
if (_betaUB != null)
res._betaUB = ArrayUtils.select(_betaUB, activeCols);
if (_betaGiven != null)
res._betaGiven = ArrayUtils.select(_betaGiven, activeCols);
if (_rho != null)
res._rho = ArrayUtils.select(_rho, activeCols);
if (_betaStart != null)
res._betaStart = ArrayUtils.select(_betaStart, activeCols);
return res;
}
}
}
|
Relaxed likelihood comparison in glm, can not expect exactly same float number because of switching between sparse / dense (numerically not the same due to the way standardization is applied), need epsilon tolerance.
|
h2o-algos/src/main/java/hex/glm/GLM.java
|
Relaxed likelihood comparison in glm, can not expect exactly same float number because of switching between sparse / dense (numerically not the same due to the way standardization is applied), need epsilon tolerance.
|
|
Java
|
apache-2.0
|
a157763459202ef51716e48a0790fcda0ced47b0
| 0
|
couchbase/couchbase-lite-java-core
|
/**
* Copyright (c) 2016 Couchbase, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.couchbase.lite.store;
import com.couchbase.lite.BlobKey;
import com.couchbase.lite.ChangesOptions;
import com.couchbase.lite.CouchbaseLiteException;
import com.couchbase.lite.DocumentChange;
import com.couchbase.lite.Manager;
import com.couchbase.lite.Misc;
import com.couchbase.lite.Query;
import com.couchbase.lite.QueryOptions;
import com.couchbase.lite.QueryRow;
import com.couchbase.lite.ReplicationFilter;
import com.couchbase.lite.Revision;
import com.couchbase.lite.RevisionList;
import com.couchbase.lite.Status;
import com.couchbase.lite.TransactionalTask;
import com.couchbase.lite.View;
import com.couchbase.lite.internal.InterfaceAudience;
import com.couchbase.lite.internal.RevisionInternal;
import com.couchbase.lite.internal.database.ContentValues;
import com.couchbase.lite.storage.Cursor;
import com.couchbase.lite.storage.SQLException;
import com.couchbase.lite.storage.SQLiteStorageEngine;
import com.couchbase.lite.storage.SQLiteStorageEngineFactory;
import com.couchbase.lite.support.RevisionUtils;
import com.couchbase.lite.support.action.Action;
import com.couchbase.lite.support.action.ActionBlock;
import com.couchbase.lite.support.action.ActionException;
import com.couchbase.lite.support.security.SymmetricKey;
import com.couchbase.lite.util.Log;
import com.couchbase.lite.util.SQLiteUtils;
import com.couchbase.lite.util.TextUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
public class SQLiteStore implements Store, EncryptableStore {
public String TAG = Log.TAG_DATABASE;
public static String kDBFilename = "db.sqlite3";
// Default value for maxRevTreeDepth, the max rev depth to preserve in a prune operation
private static final int DEFAULT_MAX_REVS = Integer.MAX_VALUE;
// Empty JSON string: "{}"
private static final byte[] EMPTY_JSON_OBJECT_CHARS = new byte[]{(byte) 0x007B, (byte) 0x007D};
// First-time initialization:
// (Note: Declaring revs.sequence as AUTOINCREMENT means the values will always be
// monotonically increasing, never reused. See <http://www.sqlite.org/autoinc.html>)
public static final String SCHEMA = "" +
// docs
"CREATE TABLE docs ( " +
" doc_id INTEGER PRIMARY KEY, " +
" docid TEXT UNIQUE NOT NULL); " +
" CREATE INDEX docs_docid ON docs(docid); " +
// revs
" CREATE TABLE revs ( " +
" sequence INTEGER PRIMARY KEY AUTOINCREMENT, " +
" doc_id INTEGER NOT NULL REFERENCES docs(doc_id) ON DELETE CASCADE, " +
" revid TEXT NOT NULL COLLATE REVID, " +
" parent INTEGER REFERENCES revs(sequence) ON DELETE SET NULL, " +
" current BOOLEAN, " +
" deleted BOOLEAN DEFAULT 0, " +
" json BLOB, " +
" no_attachments BOOLEAN, " +
" UNIQUE (doc_id, revid)); " +
" CREATE INDEX revs_parent ON revs(parent); " +
" CREATE INDEX revs_by_docid_revid ON revs(doc_id, revid desc, current, deleted); " +
" CREATE INDEX revs_current ON revs(doc_id, current desc, deleted, revid desc); " +
// localdocs
" CREATE TABLE localdocs ( " +
" docid TEXT UNIQUE NOT NULL, " +
" revid TEXT NOT NULL COLLATE REVID, " +
" json BLOB); " +
" CREATE INDEX localdocs_by_docid ON localdocs(docid); " +
// views
" CREATE TABLE views ( " +
" view_id INTEGER PRIMARY KEY, " +
" name TEXT UNIQUE NOT NULL," +
" version TEXT, " +
" lastsequence INTEGER DEFAULT 0," +
" total_docs INTEGER DEFAULT -1); " +
" CREATE INDEX views_by_name ON views(name); " +
// info
" CREATE TABLE info (" +
" key TEXT PRIMARY KEY," +
" value TEXT);" +
// version
" PRAGMA user_version = 17"; // at the end, update user_version
//OPT: Would be nice to use partial indexes but that requires SQLite 3.8 and makes the
// db file only readable by SQLite 3.8+, i.e. the file would not be portable to iOS 8
// which only has SQLite 3.7 :(
// On the revs_parent _index we could add "WHERE parent not null".
// transactionLevel is per thread
static class TransactionLevel extends ThreadLocal<Integer> {
@Override
protected Integer initialValue() {
return 0;
}
}
private String directory;
private String path;
private Manager manager;
private SQLiteStorageEngine storageEngine;
private TransactionLevel transactionLevel;
private StoreDelegate delegate;
private int maxRevTreeDepth;
private boolean autoCompact;
private SymmetricKey encryptionKey;
private final Object compactLock = new Object(); // lock for compact() method
///////////////////////////////////////////////////////////////////////////
// Constructor
///////////////////////////////////////////////////////////////////////////
public SQLiteStore(String directory, Manager manager, StoreDelegate delegate)
throws CouchbaseLiteException {
assert (new File(directory).isAbsolute()); // path must be absolute
this.directory = directory;
File dir = new File(directory);
if (!dir.exists() || !dir.isDirectory()) {
throw new IllegalArgumentException("directory '" + directory + "' does not exist or not directory");
}
this.path = new File(directory, kDBFilename).getPath();
this.manager = manager;
this.storageEngine = null;
this.transactionLevel = new TransactionLevel();
this.delegate = delegate;
this.maxRevTreeDepth = DEFAULT_MAX_REVS;
}
///////////////////////////////////////////////////////////////////////////
// Implementation of Storage
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
// INITIALIZATION AND CONFIGURATION:
///////////////////////////////////////////////////////////////////////////
@Override
public boolean databaseExists(String directory) {
return new File(directory, kDBFilename).exists();
}
@Override
public synchronized void open() throws CouchbaseLiteException {
// Try to open the storage engine and stop if we fail:
if (storageEngine == null)
storageEngine = createStorageEngine();
if (storageEngine.isOpen())
return;
boolean isOpenSuccess = false;
try {
// Open database:
storageEngine.open(path, encryptionKey);
isOpenSuccess = true;
} catch (SQLException e) {
String message = "Unable to create a storage engine";
Log.e(TAG, message, e);
int statusCode;
if (e.getCode() == SQLException.SQLITE_ENCRYPTION_UNAUTHORIZED)
statusCode = Status.UNAUTHORIZED;
else if (e.getCode() == SQLException.SQLITE_ENCRYPTION_NOTAVAILABLE)
statusCode = Status.NOT_IMPLEMENTED;
else
statusCode = Status.DB_ERROR;
throw new CouchbaseLiteException(message, e, statusCode);
} finally {
if (!isOpenSuccess) {
// As an exception will be thrown, no return false is needed here:
close();
}
}
// Stuff we need to initialize every time the sqliteDb opens:
try {
initialize("PRAGMA foreign_keys = ON;");
} catch (SQLException e) {
String message = "Cannot set enforcement of foreign key constraints";
Log.e(TAG, message, e);
throw new CouchbaseLiteException(message, e, Status.DB_ERROR);
}
// Check the user_version number we last stored in the sqliteDb:
int dbVersion = storageEngine.getVersion();
// Incompatible version changes increment the hundreds' place:
if (dbVersion >= 200) {
close();
String message = "Database version " + dbVersion +
" is newer than I know how to work with";
Log.e(TAG, message);
throw new CouchbaseLiteException(message, Status.NOT_ACCEPTABLE);
}
// Enable Write-Ahead Log (WAL)
// write-ahead log is enabled through SQLiteDatabase API
// https://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#enableWriteAheadLogging()
// BEGIN TRANSACTION
boolean isSuccessful = false;
if (!beginTransaction()) {
close();
String message = "Cannot begin transaction";
Log.e(TAG, message);
throw new CouchbaseLiteException(message, Status.DB_ERROR);
}
try {
boolean isNew = (dbVersion == 0);
if (dbVersion < 17) {
// First-time initialization:
// (Note: Declaring revs.sequence as AUTOINCREMENT means the values will always be
// monotonically increasing, never reused. See <http://www.sqlite.org/autoinc.html>)
if (!isNew) {
String message = "Database version " + dbVersion +
" is older than I know how to work with";
Log.e(TAG, message);
throw new CouchbaseLiteException(message, Status.NOT_ACCEPTABLE);
}
try {
initialize(SCHEMA);
} catch (SQLException e) {
String message = "Cannot initialize database schema";
Log.e(TAG, message, e);
throw new CouchbaseLiteException(message, e, Status.DB_ERROR);
}
dbVersion = 17;
}
if (dbVersion < 21) {
// Version 18:
String upgradeSql = "ALTER TABLE revs ADD COLUMN doc_type TEXT; " +
"PRAGMA user_version = 21";
try {
initialize(upgradeSql);
} catch (SQLException e) {
String message = "Cannot update revs table";
Log.e(TAG, message, e);
throw new CouchbaseLiteException(message, e, Status.DB_ERROR);
}
dbVersion = 21;
}
if (dbVersion < 101) {
String upgradeSql = "PRAGMA user_version = 101";
try {
initialize(upgradeSql);
} catch (SQLException e) {
String message = "Cannot update user_version to " + dbVersion;
Log.e(TAG, message, e);
throw new CouchbaseLiteException(message, e, Status.DB_ERROR);
}
dbVersion = 101;
}
if (dbVersion < 102) {
String upgradeSql = "ALTER TABLE docs ADD COLUMN expiry_timestamp INTEGER; "
+ "CREATE INDEX IF NOT EXISTS docs_expiry ON docs(expiry_timestamp) "
+ "WHERE expiry_timestamp not null; PRAGMA user_version = 102";
try {
initialize(upgradeSql);
} catch (SQLException e) {
String message = "Cannot update user_version to " + dbVersion;
Log.e(TAG, message, e);
throw new CouchbaseLiteException(message, e, Status.DB_ERROR);
}
dbVersion = 102;
}
if (isNew)
setInfo("pruned", "true"); // See -compact: for explanation
if (!isNew)
optimizeSQLIndexes(); // runs ANALYZE query
// successfully updated storageEngine schema:
isSuccessful = true;
} finally {
// END TRANSACTION WITH COMMIT OR ROLLBACK
endTransaction(isSuccessful);
// if failed, close storageEngine before return:
if (!isSuccessful) {
close();
}
}
}
@Override
public void close() {
if (storageEngine != null && storageEngine.isOpen())
storageEngine.close();
storageEngine = null;
}
private SQLiteStorageEngine createStorageEngine() throws CouchbaseLiteException {
SQLiteStorageEngineFactory factory =
manager.getContext().getSQLiteStorageEngineFactory();
SQLiteStorageEngine engine = factory.createStorageEngine();
if (engine == null) {
String message = "Unable to create a storage engine, fatal error";
Log.e(TAG, message);
throw new CouchbaseLiteException(message, Status.INTERNAL_SERVER_ERROR);
}
return engine;
}
@Override
public void setDelegate(StoreDelegate delegate) {
this.delegate = delegate;
}
@Override
public StoreDelegate getDelegate() {
return delegate;
}
/**
* Set the maximum depth of a document's revision tree (or, max length of its revision history.)
* Revisions older than this limit will be deleted during a -compact: operation.
* Smaller values save space, at the expense of making document conflicts somewhat more likely.
*/
@Override
public void setMaxRevTreeDepth(int maxRevTreeDepth) {
this.maxRevTreeDepth = maxRevTreeDepth;
}
/**
* Get the maximum depth of a document's revision tree (or, max length of its revision history.)
* Revisions older than this limit will be deleted during a -compact: operation.
* Smaller values save space, at the expense of making document conflicts somewhat more likely.
*/
@Override
public int getMaxRevTreeDepth() {
return maxRevTreeDepth;
}
@Override
public void setAutoCompact(boolean value) {
autoCompact = value;
}
@Override
public boolean getAutoCompact() {
return autoCompact;
}
///////////////////////////////////////////////////////////////////////////
// Database Encryption
///////////////////////////////////////////////////////////////////////////
private void decrypt(SymmetricKey encryptionKey) throws CouchbaseLiteException {
if (encryptionKey != null) {
if (!storageEngine.supportEncryption()) {
Log.w(TAG, "SQLiteStore: encryption not available (app not built with SQLCipher)");
throw new CouchbaseLiteException("Encryption not available",
Status.NOT_IMPLEMENTED);
} else {
try {
storageEngine.execSQL("PRAGMA key = \"x'" + encryptionKey.getHexData() + "'\"");
} catch (SQLException e) {
Log.w(TAG, "SQLiteStore: 'pragma key' failed", e);
throw e;
}
}
}
// Verify that encryption key is correct (or db is unencrypted, if no key given)
Cursor cursor = null;
try {
cursor = storageEngine.rawQuery("SELECT count(*) FROM sqlite_master", null);
if (cursor == null || !cursor.moveToNext()) {
// Backup error:
Log.w(TAG, "SQLiteStore: database is unreadable, unknown error");
throw new CouchbaseLiteException("Cannot decrypt or access the database",
Status.DB_ERROR);
}
} catch (Exception e) {
Log.w(TAG, "SQLiteStore: database is unreadable", e);
if (e.getMessage() != null &&
e.getMessage().contains("file is encrypted or is not a database (code 26)")) {
throw new CouchbaseLiteException("Cannot decrypt or access the database",
Status.UNAUTHORIZED);
} else {
throw new CouchbaseLiteException(e, Status.DB_ERROR);
}
} finally {
if (cursor != null) {
cursor.close();
}
}
}
///////////////////////////////////////////////////////////////////////////
// ENCRYPTABLE STORE
///////////////////////////////////////////////////////////////////////////
@Override
public void setEncryptionKey(SymmetricKey key) {
encryptionKey = key;
}
@Override
public SymmetricKey getEncryptionKey() {
return encryptionKey;
}
@Override
public Action actionToChangeEncryptionKey(final SymmetricKey newKey) {
if (!storageEngine.supportEncryption())
return null;
Action action = new Action();
final AtomicBoolean dbWasClosed = new AtomicBoolean(false);
// Make a path for a tempoary database file:
final File tempDbFile = new File(manager.getDirectory(), Misc.CreateUUID());
action.add(null, new ActionBlock() {
@Override
public void execute() throws ActionException {
if (tempDbFile.exists()) {
if (!tempDbFile.delete()) {
throw new ActionException("Cannot delete the temp database file " +
tempDbFile.getAbsolutePath());
}
}
}
}, null);
// Create & attach the temporary database encrypted with the new key:
action.add(
// Perform:
new ActionBlock() {
@Override
public void execute() throws ActionException {
String keyStr = newKey != null ? newKey.getHexData() : "";
String sql = "ATTACH DATABASE ? AS rekeyed_db KEY \"x'" + keyStr + "'\"";
String[] args = {tempDbFile.getAbsolutePath()};
try {
storageEngine.execSQL(sql, args);
} catch (Exception e) {
throw new ActionException(e);
}
}
},
// Backout or cleanup:
new ActionBlock() {
@Override
public void execute() throws ActionException {
if (dbWasClosed.get())
return;
try {
storageEngine.execSQL("DETACH DATABASE rekeyed_db");
} catch (Exception e) {
throw new ActionException(e);
}
}
});
// Export the current database's contents to the new one:
action.add(new ActionBlock() {
@Override
public void execute() throws ActionException {
try {
storageEngine.execSQL("SELECT sqlcipher_export('rekeyed_db')");
storageEngine.execSQL("PRAGMA rekeyed_db.user_version = " +
storageEngine.getVersion());
} catch (Exception e) {
throw new ActionException(e);
}
}
}, null, null);
// Close the database (and re-open it on cleanup):
action.add(
// Perform:
new ActionBlock() {
@Override
public void execute() throws ActionException {
storageEngine.close();
dbWasClosed.set(true);
}
},
// Backout:
new ActionBlock() {
@Override
public void execute() throws ActionException {
try {
open();
} catch (CouchbaseLiteException e) {
throw new ActionException("Cannot open the SQLiteStore", e);
}
}
},
// Cleanup:
new ActionBlock() {
@Override
public void execute() throws ActionException {
setEncryptionKey(newKey);
try {
open();
} catch (CouchbaseLiteException e) {
throw new ActionException("Cannot open the SQLiteStore", e);
}
}
}
);
// Overwrite the old db file with the new one:
action.add(Action.moveAndReplaceFile(tempDbFile.getAbsolutePath(), path,
manager.getContext().getTempDir().getAbsolutePath()));
return action;
}
@Override
public byte[] derivePBKDF2SHA256Key(String password, byte[] salt, int rounds)
throws CouchbaseLiteException {
if (storageEngine == null)
storageEngine = createStorageEngine();
if (!storageEngine.supportEncryption()) {
Log.w(TAG, "SQLiteStore: encryption not available (app not built with SQLCipher)");
throw new CouchbaseLiteException("Encryption not available",
Status.NOT_IMPLEMENTED);
}
byte[] result = storageEngine.derivePBKDF2SHA256Key(password, salt, rounds);
if (result == null)
throw new CouchbaseLiteException("Cannot derive key for the password",
Status.BAD_REQUEST);
return result;
}
///////////////////////////////////////////////////////////////////////////
// DATABASE ATTRIBUTES & OPERATIONS:
///////////////////////////////////////////////////////////////////////////
@Override
public long setInfo(String key, String info) {
ContentValues args = new ContentValues();
args.put("key", key);
args.put("value", info);
if (storageEngine.insertWithOnConflict("info", null, args,
SQLiteStorageEngine.CONFLICT_REPLACE) == -1)
return Status.DB_ERROR;
else
return Status.OK;
}
@Override
public String getInfo(String key) {
String result = null;
Cursor cursor = null;
try {
String[] args = {key};
cursor = storageEngine.rawQuery("SELECT value FROM info WHERE key=?", args);
if (cursor.moveToNext()) {
result = cursor.getString(0);
}
} catch (SQLException e) {
Log.e(TAG, "Error querying " + key, e);
} finally {
if (cursor != null) {
cursor.close();
}
}
return result;
}
@Override
public int getDocumentCount() {
String sql = "SELECT COUNT(DISTINCT doc_id) FROM revs WHERE current=1 AND deleted=0";
Cursor cursor = null;
int result = 0;
try {
cursor = storageEngine.rawQuery(sql, null);
if (cursor.moveToNext()) {
result = cursor.getInt(0);
}
} catch (SQLException e) {
Log.e(TAG, "Error getting document count", e);
} finally {
if (cursor != null) {
cursor.close();
}
}
return result;
}
/**
* The latest sequence number used. Every new revision is assigned a new sequence number,
* so this property increases monotonically as changes are made to the storageEngine. It can be
* used to check whether the storageEngine has changed between two points in time.
*/
public long getLastSequence() {
String sql = "SELECT MAX(sequence) FROM revs";
Cursor cursor = null;
long result = 0;
try {
cursor = storageEngine.rawQuery(sql, null);
if (cursor.moveToNext()) {
result = cursor.getLong(0);
}
} catch (SQLException e) {
Log.e(TAG, "Error getting last sequence", e);
} finally {
if (cursor != null) {
cursor.close();
}
}
return result;
}
/**
* Is a transaction active?
*/
@Override
public boolean inTransaction() {
return transactionLevel.get() > 0;
}
@Override
public void compact() throws CouchbaseLiteException {
Log.v(TAG, "Begin database compaction...");
synchronized (compactLock) {
boolean shouldCommit = false;
beginTransaction();
try {
if (getInfo("pruned") == null) {
// Bulk pruning is no longer needed, because revisions are pruned incrementally as new
// ones are added. But databases from before this feature was added (1.3) may have documents
// that need pruning. So we'll do a one-time bulk prune, then set a flag indicating that
// it isn't needed anymore.
pruneRevsToMaxDepth(maxRevTreeDepth);
setInfo("pruned", "true");
}
// Remove the JSON of non-current revisions, which is most of the space.
try {
Log.v(TAG, "Deleting JSON of old revisions...");
ContentValues args = new ContentValues();
args.put("json", (String) null);
args.put("doc_type", (String) null);
args.put("no_attachments", 1);
int changes = storageEngine.update("revs", args, "current=0", null);
Log.v(TAG, "... deleted %d revisions", changes);
} catch (SQLException e) {
Log.e(TAG, "Error compacting", e);
throw new CouchbaseLiteException(Status.INTERNAL_SERVER_ERROR);
}
shouldCommit = true;
} finally {
endTransaction(shouldCommit);
}
// https://www.sqlite.org/pragma.html#pragma_wal_checkpoint
Log.v(TAG, "Flushing SQLite WAL...");
try {
storageEngine.execSQL("PRAGMA wal_checkpoint(RESTART)");
} catch (SQLException e) {
Log.e(TAG, "Error PRAGMA wal_checkpoint(RESTART)", e);
throw new CouchbaseLiteException(Status.INTERNAL_SERVER_ERROR);
}
Log.v(TAG, "Vacuuming SQLite database...");
try {
storageEngine.execSQL("VACUUM");
} catch (SQLException e) {
Log.e(TAG, "Error vacuuming sqliteDb", e);
throw new CouchbaseLiteException(Status.INTERNAL_SERVER_ERROR);
}
}
Log.v(TAG, "...Finished database compaction.");
}
@Override
public boolean runInTransaction(TransactionalTask transactionalTask) {
boolean shouldCommit = true;
beginTransaction();
try {
shouldCommit = transactionalTask.run();
} catch (Exception e) {
shouldCommit = false;
Log.e(TAG, e.toString(), e);
throw new RuntimeException(e);
} finally {
endTransaction(shouldCommit);
}
return shouldCommit;
}
boolean runInOuterTransaction(TransactionalTask transactionalTask) {
if (!inTransaction())
return runInTransaction(transactionalTask);
return transactionalTask.run();
}
///////////////////////////////////////////////////////////////////////////
// DOCUMENTS:
///////////////////////////////////////////////////////////////////////////
@Override
public RevisionInternal getDocument(String docID, String revID, boolean withBody) {
long docNumericID = getDocNumericID(docID);
if (docNumericID < 0) {
return null;
}
RevisionInternal result = null;
String sql;
Cursor cursor = null;
try {
cursor = null;
String cols = "revid, deleted, sequence";
if (withBody) {
cols += ", json";
}
if (revID != null) {
sql = "SELECT " + cols + " FROM revs WHERE revs.doc_id=? AND revid=? AND json notnull LIMIT 1";
String[] args = {Long.toString(docNumericID), revID};
cursor = storageEngine.rawQuery(sql, args);
} else {
sql = "SELECT " + cols + " FROM revs WHERE revs.doc_id=? and current=1 and deleted=0 ORDER BY revid DESC LIMIT 1";
String[] args = {Long.toString(docNumericID)};
cursor = storageEngine.rawQuery(sql, args);
}
if (cursor.moveToNext()) {
if (revID == null) {
revID = cursor.getString(0);
}
boolean deleted = (cursor.getInt(1) > 0);
result = new RevisionInternal(docID, revID, deleted);
result.setSequence(cursor.getLong(2));
if (withBody) {
byte[] json = cursor.getBlob(3);
result.setJSON(json);
}
} else {
// revID != null?Status.NOT_FOUND:Status.DELTED
}
} catch (SQLException e) {
Log.e(TAG, "Error getting document with id and rev", e);
} finally {
if (cursor != null) {
cursor.close();
}
}
return result;
}
@Override
public RevisionInternal loadRevisionBody(RevisionInternal rev)
throws CouchbaseLiteException {
if (rev.getBody() != null && rev.getSequence() != 0) // no-op
return rev;
assert (rev.getDocID() != null && rev.getRevID() != null);
// SQLite read operation
long docNumericID = getDocNumericID(rev.getDocID());
if (docNumericID <= 0)
throw new CouchbaseLiteException(Status.NOT_FOUND);
Cursor cursor = null;
Status result = new Status(Status.NOT_FOUND);
try {
String sql = "SELECT sequence, json FROM revs WHERE doc_id=? AND revid=? LIMIT 1";
String[] args = {String.valueOf(docNumericID), rev.getRevID()};
cursor = storageEngine.rawQuery(sql, args);
if (cursor.moveToNext()) {
byte[] json = cursor.getBlob(1);
if (json != null) {
result.setCode(Status.OK);
rev.setSequence(cursor.getLong(0));
rev.setJSON(json);
}
}
} catch (SQLException e) {
Log.e(TAG, "Error loading revision body", e);
throw new CouchbaseLiteException(Status.INTERNAL_SERVER_ERROR);
} finally {
if (cursor != null) {
cursor.close();
}
}
if (result.getCode() == Status.NOT_FOUND) {
throw new CouchbaseLiteException(result);
}
return rev;
}
@Override
public RevisionInternal getParentRevision(RevisionInternal rev) {
// First get the parent's sequence:
long seq = rev.getSequence();
if (seq > 0) {
seq = SQLiteUtils.longForQuery(storageEngine,
"SELECT parent FROM revs WHERE sequence=?",
new String[]{Long.toString(seq)});
} else {
long docNumericID = getDocNumericID(rev.getDocID());
if (docNumericID <= 0) {
return null;
}
String[] args = new String[]{Long.toString(docNumericID), rev.getRevID()};
seq = SQLiteUtils.longForQuery(storageEngine,
"SELECT parent FROM revs WHERE doc_id=? and revid=?", args);
}
if (seq == 0) {
return null;
}
// Now get its revID and deletion status:
RevisionInternal result = null;
String[] args = {Long.toString(seq)};
String queryString = "SELECT revid, deleted FROM revs WHERE sequence=?";
Cursor cursor = null;
try {
cursor = storageEngine.rawQuery(queryString, args);
if (cursor.moveToNext()) {
String revId = cursor.getString(0);
boolean deleted = (cursor.getInt(1) > 0);
result = new RevisionInternal(rev.getDocID(), revId, deleted/*, this*/);
result.setSequence(seq);
}
} finally {
cursor.close();
}
return result;
}
/**
* Returns an array of TDRevs in reverse chronological order, starting with the given revision.
*/
@Override
public List<RevisionInternal> getRevisionHistory(RevisionInternal rev) {
String docId = rev.getDocID();
String revId = rev.getRevID();
assert ((docId != null) && (revId != null));
// SQlite read operation
long docNumericId = getDocNumericID(docId);
if (docNumericId < 0) {
return null;
} else if (docNumericId == 0) {
return new ArrayList<RevisionInternal>();
}
String sql = "SELECT sequence, parent, revid, deleted, json isnull FROM revs " +
"WHERE doc_id=? ORDER BY sequence DESC";
String[] args = {Long.toString(docNumericId)};
Cursor cursor = null;
List<RevisionInternal> result;
try {
cursor = storageEngine.rawQuery(sql, args);
cursor.moveToNext();
long lastSequence = 0;
result = new ArrayList<RevisionInternal>();
while (!cursor.isAfterLast()) {
long sequence = cursor.getLong(0);
boolean matches = false;
if (lastSequence == 0) {
matches = revId.equals(cursor.getString(2));
} else {
matches = (sequence == lastSequence);
}
if (matches) {
revId = cursor.getString(2);
boolean deleted = (cursor.getInt(3) > 0);
boolean missing = (cursor.getInt(4) > 0);
RevisionInternal aRev = new RevisionInternal(docId, revId, deleted);
aRev.setMissing(missing);
aRev.setSequence(cursor.getLong(0));
result.add(aRev);
lastSequence = cursor.getLong(1);
if (lastSequence == 0) {
break;
}
}
cursor.moveToNext();
}
} catch (SQLException e) {
Log.e(TAG, "Error getting revision history", e);
return null;
} finally {
if (cursor != null) {
cursor.close();
}
}
return result;
}
private RevisionList getAllRevisions(String docId, long docNumericID, boolean onlyCurrent) {
String sql = null;
if (onlyCurrent)
sql = "SELECT sequence, revid, deleted FROM revs " +
"WHERE doc_id=? AND current ORDER BY sequence DESC";
else
sql = "SELECT sequence, revid, deleted FROM revs " +
"WHERE doc_id=? ORDER BY sequence DESC";
String[] args = {Long.toString(docNumericID)};
Cursor cursor = storageEngine.rawQuery(sql, args);
RevisionList result = null;
try {
cursor.moveToNext();
result = new RevisionList();
while (!cursor.isAfterLast()) {
RevisionInternal rev = new RevisionInternal(docId,
cursor.getString(1),
(cursor.getInt(2) > 0));
rev.setSequence(cursor.getLong(0));
result.add(rev);
cursor.moveToNext();
}
} catch (SQLException e) {
return null;
} finally {
if (cursor != null)
cursor.close();
}
return result;
}
@Override
public List<String> getPossibleAncestorRevisionIDs(RevisionInternal rev,
int limit,
AtomicBoolean onlyAttachments) {
int generation = rev.getGeneration();
if (generation <= 1)
return null;
long docNumericID = getDocNumericID(rev.getDocID());
if (docNumericID <= 0)
return null;
List<String> revIDs = new ArrayList<String>();
int sqlLimit = limit > 0 ? (int) limit : -1; // SQL uses -1, not 0, to denote 'no limit'
StringBuilder sql = new StringBuilder("SELECT revid, sequence FROM revs WHERE doc_id=? and revid < ?");
sql.append(" and deleted=0 and json not null");
sql.append(" and no_attachments=0");
sql.append(" ORDER BY sequence DESC LIMIT ?");
String[] args = {Long.toString(docNumericID), generation + "-", Integer.toString(sqlLimit)};
Cursor cursor = null;
try {
cursor = storageEngine.rawQuery(sql.toString(), args);
cursor.moveToNext();
while (!cursor.isAfterLast()) {
if (onlyAttachments != null && revIDs.size() == 0)
onlyAttachments.set(sequenceHasAttachments(cursor.getLong(1)));
revIDs.add(cursor.getString(0));
cursor.moveToNext();
}
} catch (SQLException e) {
Log.e(TAG, "Error getting all revisions of document", e);
} finally {
if (cursor != null) {
cursor.close();
}
}
return revIDs;
}
/**
* Returns the most recent member of revIDs that appears in rev's ancestry.
*/
@Override
public String findCommonAncestorOf(RevisionInternal rev, List<String> revIDs) {
if (revIDs == null || revIDs.size() == 0)
return null;
long docNumericID = getDocNumericID(rev.getDocID());
if (docNumericID <= 0)
return null;
String quotedRevIds = TextUtils.joinQuoted(revIDs);
String sql = String.format(Locale.ENGLISH, "SELECT revid FROM revs " +
"WHERE doc_id=? and revid in (%s) and revid <= ? " +
"ORDER BY revid DESC LIMIT 1", quotedRevIds);
String[] args = {Long.toString(docNumericID), rev.getRevID()};
return SQLiteUtils.stringForQuery(storageEngine, sql, args);
}
@Override
public int findMissingRevisions(RevisionList touchRevs) throws SQLException {
int numRevisionsRemoved = 0;
if (touchRevs.size() == 0) {
return numRevisionsRemoved;
}
String quotedDocIds = TextUtils.joinQuoted(touchRevs.getAllDocIds());
String quotedRevIds = TextUtils.joinQuoted(touchRevs.getAllRevIds());
String sql = "SELECT docid, revid FROM revs, docs " +
"WHERE docid IN (" +
quotedDocIds +
") AND revid in (" +
quotedRevIds + ')' +
" AND revs.doc_id == docs.doc_id";
Cursor cursor = null;
try {
cursor = storageEngine.rawQuery(sql, null);
cursor.moveToNext();
while (!cursor.isAfterLast()) {
RevisionInternal rev = touchRevs.revWithDocIdAndRevId(cursor.getString(0),
cursor.getString(1));
if (rev != null) {
touchRevs.remove(rev);
numRevisionsRemoved += 1;
}
cursor.moveToNext();
}
} finally {
if (cursor != null) {
cursor.close();
}
}
return numRevisionsRemoved;
}
/**
* - (NSSet*) findAllAttachmentKeys: (NSError**)outError
*/
@Override
public Set<BlobKey> findAllAttachmentKeys() throws CouchbaseLiteException {
Set<BlobKey> allKeys = new HashSet<BlobKey>();
String sql = "SELECT json FROM revs WHERE no_attachments != 1";
Cursor cursor = null;
try {
cursor = storageEngine.rawQuery(sql, null);
cursor.moveToNext();
while (!cursor.isAfterLast()) {
byte[] json = cursor.getBlob(0);
if (json != null && json.length > 0) {
try {
Map<String, Object> docProperties = Manager.getObjectMapper().readValue(json, Map.class);
if (docProperties.containsKey("_attachments")) {
Map<String, Object> attachments = (Map<String, Object>) docProperties.get("_attachments");
Iterator<String> itr = attachments.keySet().iterator();
while (itr.hasNext()) {
String name = itr.next();
Map<String, Object> attachment = (Map<String, Object>) attachments.get(name);
String digest = (String) attachment.get("digest");
BlobKey key = new BlobKey(digest);
allKeys.add(key);
}
}
} catch (IOException e) {
Log.e(TAG, e.toString(), e);
}
}
cursor.moveToNext();
}
} finally {
if (cursor != null) {
cursor.close();
}
}
return allKeys;
}
/**
* - (CBLQueryIteratorBlock) getAllDocs: (CBLQueryOptions*)options
* status: (CBLStatus*)outStatus
*/
@Override
public Map<String, Object> getAllDocs(QueryOptions options) throws CouchbaseLiteException {
Map<String, Object> result = new HashMap<String, Object>();
List<QueryRow> rows = new ArrayList<QueryRow>();
if (options == null) {
options = new QueryOptions();
}
boolean includeDeletedDocs = (options.getAllDocsMode() == Query.AllDocsMode.INCLUDE_DELETED);
long updateSeq = 0;
if (options.isUpdateSeq()) {
updateSeq = getLastSequence(); // TODO: needs to be atomic with the following SELECT
}
// Generate the SELECT statement, based on the options:
StringBuilder sql = new StringBuilder("SELECT revs.doc_id, docid, revid, sequence");
if (options.isIncludeDocs()) {
sql.append(", json, no_attachments");
}
if (includeDeletedDocs) {
sql.append(", deleted");
}
sql.append(" FROM revs, docs WHERE");
if (options.getKeys() != null) {
if (options.getKeys().size() == 0) {
return result;
}
String commaSeperatedIds = TextUtils.joinQuotedObjects(options.getKeys());
sql.append(String.format(Locale.ENGLISH, " revs.doc_id IN (SELECT doc_id FROM docs WHERE docid IN (%s)) AND",
commaSeperatedIds));
}
sql.append(" docs.doc_id = revs.doc_id AND current=1");
if (!includeDeletedDocs) {
sql.append(" AND deleted=0");
}
List<String> args = new ArrayList<String>();
Object minKey = options.getStartKey();
Object maxKey = options.getEndKey();
boolean inclusiveMin = true;
boolean inclusiveMax = options.isInclusiveEnd();
if (options.isDescending()) {
minKey = maxKey;
maxKey = options.getStartKey();
inclusiveMin = inclusiveMax;
inclusiveMax = true;
}
if (minKey != null) {
assert (minKey instanceof String);
sql.append((inclusiveMin ? " AND docid >= ?" : " AND docid > ?"));
args.add((String) minKey);
}
if (maxKey != null) {
assert (maxKey instanceof String);
maxKey = View.keyForPrefixMatch(maxKey, options.getPrefixMatchLevel());
sql.append((inclusiveMax ? " AND docid <= ?" : " AND docid < ?"));
args.add((String) maxKey);
}
sql.append(
String.format(Locale.ENGLISH,
" ORDER BY docid %s, %s revid DESC LIMIT ? OFFSET ?",
(options.isDescending() ? "DESC" : "ASC"),
(includeDeletedDocs ? "deleted ASC," : "")
)
);
args.add(Integer.toString(options.getLimit()));
args.add(Integer.toString(options.getSkip()));
// Now run the database query:
Cursor cursor = null;
Map<String, QueryRow> docs = new HashMap<String, QueryRow>();
try {
// Get row values now, before the code below advances 'cursor':
cursor = storageEngine.rawQuery(sql.toString(), args.toArray(new String[args.size()]));
boolean keepGoing = cursor.moveToNext(); // Go to first result row
while (keepGoing) {
long docNumericID = cursor.getLong(0);
String docID = cursor.getString(1);
String revID = cursor.getString(2);
long sequence = cursor.getLong(3);
boolean deleted = includeDeletedDocs && cursor.getInt(getDeletedColumnIndex(options)) > 0;
RevisionInternal docRevision = null;
if (options.isIncludeDocs()) {
//docRevision = revision(docID, revID, deleted, sequence, cursor.getBlob(4));
byte[] json = cursor.getBlob(4);
Map<String, Object> properties = documentPropertiesFromJSON(json, docID, revID,
false, sequence);
docRevision = revision(
docID, // docID
revID, // revID
false, // deleted
sequence, // sequence
properties// properties
);
}
// Iterate over following rows with the same doc_id -- these are conflicts.
// Skip them, but collect their revIDs if the 'conflicts' option is set:
List<String> conflicts = new ArrayList<String>();
while (((keepGoing = cursor.moveToNext()) == true) && cursor.getLong(0) == docNumericID) {
if (options.getAllDocsMode() == Query.AllDocsMode.SHOW_CONFLICTS ||
options.getAllDocsMode() == Query.AllDocsMode.ONLY_CONFLICTS) {
if (conflicts.isEmpty()) {
conflicts.add(revID);
}
conflicts.add(cursor.getString(2));
}
}
if (options.getAllDocsMode() == Query.AllDocsMode.ONLY_CONFLICTS && conflicts.isEmpty())
continue;
Map<String, Object> value = new HashMap<String, Object>();
value.put("rev", revID);
value.put("_conflicts", conflicts);
if (includeDeletedDocs) {
value.put("deleted", (deleted ? true : null));
}
QueryRow change = new QueryRow(docID,
sequence,
docID,
value,
docRevision);
if (options.getKeys() != null)
docs.put(docID, change);
// TODO: In the future, we need to implement CBLRowPassesFilter() in CBLView+Querying.m
else if (options.getPostFilter() == null || options.getPostFilter().apply(change))
rows.add(change);
}
// If given doc IDs, sort the output into that order, and add entries for missing docs:
if (options.getKeys() != null) {
for (Object docIdObject : options.getKeys()) {
if (docIdObject instanceof String) {
String docID = (String) docIdObject;
QueryRow change = docs.get(docID);
if (change == null) {
Map<String, Object> value = new HashMap<String, Object>();
long docNumericID = getDocNumericID(docID);
if (docNumericID > 0) {
boolean deleted;
AtomicBoolean outIsDeleted = new AtomicBoolean(false);
String revID = winningRevIDOfDocNumericID(docNumericID, outIsDeleted, null);
if (revID != null) {
value.put("rev", revID);
value.put("deleted", true);
}
}
change = new QueryRow((value != null ? docID : null), 0, docID, value, null);
}
// TODO add options.filter
rows.add(change);
}
}
}
} catch (SQLException e) {
Log.e(TAG, "Error getting all docs", e);
throw new CouchbaseLiteException("Error getting all docs", e, new Status(Status.INTERNAL_SERVER_ERROR));
} finally {
if (cursor != null) {
cursor.close();
}
}
result.put("rows", rows);
result.put("total_rows", rows.size());
result.put("offset", options.getSkip());
if (updateSeq != 0) {
result.put("update_seq", updateSeq);
}
return result;
}
@Override
public RevisionList changesSince(long lastSequence,
ChangesOptions options,
ReplicationFilter filter,
Map<String, Object> filterParams) {
// http://wiki.apache.org/couchdb/HTTP_database_API#Changes
if (options == null) {
options = new ChangesOptions();
}
RevisionList changes = new RevisionList();
boolean includeDocs = options.isIncludeDocs() || (filter != null);
String additionalSelectColumns = "";
if (includeDocs) {
additionalSelectColumns = ", json";
}
String sql = "SELECT sequence, revs.doc_id, docid, revid, deleted" + additionalSelectColumns
+ " FROM revs, docs "
+ "WHERE sequence > ? AND current=1 "
+ "AND revs.doc_id = docs.doc_id "
+ "ORDER BY revs.doc_id, revid DESC";
String[] args = {Long.toString(lastSequence)};
Cursor cursor = storageEngine.rawQuery(sql, args);
cursor.moveToNext();
long lastDocId = 0;
try {
while (!cursor.isAfterLast()) {
if (!options.isIncludeConflicts()) {
// Only count the first rev for a given doc (the rest will be losing conflicts):
long docNumericId = cursor.getLong(1);
if (docNumericId == lastDocId) {
cursor.moveToNext();
continue;
}
lastDocId = docNumericId;
}
RevisionInternal rev = new RevisionInternal(
cursor.getString(2), cursor.getString(3), (cursor.getInt(4) > 0));
rev.setSequence(cursor.getLong(0));
if (includeDocs)
rev.setJSON(cursor.getBlob(5));
changes.add(rev);
cursor.moveToNext();
}
} catch (SQLException e) {
Log.e(TAG, "Error looking for changes", e);
} finally {
if (cursor != null) {
cursor.close();
}
}
// Note: To minimize holding SQLite connection, executing filter out-of SQLite query.
if (filter != null) {
// to avoid to create another list, filter from end to front.
for (int i = changes.size() - 1; i >= 0; i--) {
if (!delegate.runFilter(filter, filterParams, changes.get(i)))
changes.remove(i);
}
}
if (options.isSortBySequence()) {
changes.sortBySequence();
}
changes.limit(options.getLimit());
return changes;
}
///////////////////////////////////////////////////////////////////////////
// INSERTION / DELETION:
///////////////////////////////////////////////////////////////////////////
/**
* Creates a new revision of a document.
* On success, before returning the new CBL_Revision, the implementation will also call the
* delegate's -databaseStorageChanged: method to give it more details about the change.
*
* @param docID The document ID, or nil if an ID should be generated at random.
* @param prevRevID The parent revision ID, or nil if creating a new document.
* @param properties The new revision's properties. (Metadata other than "_attachments" ignored.)
* @param deleting YES if this revision is a deletion.
* @param allowConflict YES if this operation is allowed to create a conflict; otherwise a 409,
* status will be returned if the parent revision is not a leaf.
* @param validationBlock If non-nil, this block will be called before the revision is added.
* It's given the parent revision, with its properties if available, and can reject
* the operation by returning an error status.
* @param outStatus On return a status will be stored here. Note that on success, the
* status should be 201 for a created revision but 200 for a deletion.
* @return The new revision, with its revID and sequence filled in, or nil on error.
*/
@Override
@InterfaceAudience.Private
public RevisionInternal add(
String docID,
String prevRevID,
Map<String, Object> properties,
boolean deleting,
boolean allowConflict,
StorageValidation validationBlock,
Status outStatus)
throws CouchbaseLiteException {
byte[] json;
if (properties != null && properties.size() > 0) {
json = RevisionUtils.asCanonicalJSON(properties);
if (json == null)
throw new CouchbaseLiteException(Status.BAD_JSON);
} else {
json = "{}".getBytes();
}
RevisionInternal newRev = null;
String winningRevID = null;
boolean inConflict = false;
beginTransaction();
// try - finally for beginTransaction() and endTransaction()
try {
//// PART I: In which are performed lookups and validations prior to the insert...
// Get the doc's numeric ID (doc_id) and its current winning revision:
AtomicBoolean isNewDoc = new AtomicBoolean(prevRevID == null);
long docNumericID = -1;
if (docID != null) {
docNumericID = createOrGetDocNumericID(docID, isNewDoc);
if (docNumericID <= 0)
// TODO: error
throw new CouchbaseLiteException(Status.UNKNOWN);
} else {
docNumericID = 0;
isNewDoc.set(true);
}
AtomicBoolean oldWinnerWasDeletion = new AtomicBoolean(false);
AtomicBoolean wasConflicted = new AtomicBoolean(false);
String oldWinningRevID = null;
if (!isNewDoc.get()) {
// Look up which rev is the winner, before this insertion
//OPT: This rev ID could be cached in the 'docs' row
oldWinningRevID = winningRevIDOfDocNumericID(docNumericID, oldWinnerWasDeletion, wasConflicted);
}
long parentSequence = 0;
if (prevRevID != null) {
// Replacing: make sure given prevRevID is current & find its sequence number:
if (isNewDoc.get())
throw new CouchbaseLiteException(Status.NOT_FOUND);
parentSequence = getSequenceOfDocument(docNumericID, prevRevID, !allowConflict);
if (parentSequence <= 0) { // -1 if not found
// Not found: either a 404 or a 409, depending on whether there is any current revision
if (!allowConflict && existsDocument(docID, null)) {
throw new CouchbaseLiteException(Status.CONFLICT);
} else {
throw new CouchbaseLiteException(Status.NOT_FOUND);
}
}
} else {
// Inserting first revision.
if (deleting && docID != null) {
// Didn't specify a revision to delete: 404 or a 409, depending
if (existsDocument(docID, null))
throw new CouchbaseLiteException(Status.CONFLICT);
else
throw new CouchbaseLiteException(Status.NOT_FOUND);
}
if (docID != null) {
// Inserting first revision, with docID given (PUT):
// Doc ID exists; check whether current winning revision is deleted:
if (oldWinnerWasDeletion.get() == true) {
prevRevID = oldWinningRevID;
parentSequence = getSequenceOfDocument(docNumericID, prevRevID, false);
} else if (oldWinningRevID != null) {
// The current winning revision is not deleted, so this is a conflict
throw new CouchbaseLiteException(Status.CONFLICT);
}
} else {
// Inserting first revision, with no docID given (POST): generate a unique docID:
docID = Misc.CreateUUID();
docNumericID = createOrGetDocNumericID(docID, isNewDoc);
if (docNumericID <= 0)
return null;
}
}
// There may be a conflict if (a) the document was already in conflict, or
// (b) a conflict is created by adding a non-deletion child of a non-winning rev.
inConflict = wasConflicted.get() ||
(!deleting &&
prevRevID != null &&
oldWinningRevID != null &&
!prevRevID.equals(oldWinningRevID));
//// PART II: In which we prepare for insertion...
// Bump the revID and update the JSON:
String newRevId = delegate.generateRevID(json, deleting, prevRevID);
if (newRevId == null)
throw new CouchbaseLiteException(Status.BAD_ID); // invalid previous revID (no numeric prefix)
assert (docID != null);
newRev = new RevisionInternal(docID, newRevId, deleting);
if (properties != null) {
properties.put("_id", docID);
properties.put("_rev", newRevId);
newRev.setProperties(properties);
}
// Validate:
if (validationBlock != null) {
// Fetch the previous revision and validate the new one against it:
RevisionInternal prevRev = null;
if (prevRevID != null)
prevRev = new RevisionInternal(docID, prevRevID, false);
Status status = validationBlock.validate(newRev, prevRev, prevRevID);
if (status.isError()) {
outStatus.setCode(status.getCode());
throw new CouchbaseLiteException(status);
}
}
// Don't store a SQL null in the 'json' column -- I reserve it to mean that the revision data
// is missing due to compaction or replication.
// Instead, store an empty zero-length blob.
if (json == null)
json = new byte[0];
//// PART III: In which the actual insertion finally takes place:
boolean hasAttachments = properties == null ? false :
properties.get("_attachments") != null;
String docType = null;
if (properties != null && properties.containsKey("type") && properties.get("type") instanceof String)
docType = (String) properties.get("type");
long sequence = 0;
try {
sequence = insertRevision(newRev,
docNumericID,
parentSequence,
true,
hasAttachments,
json,
docType);
} catch (SQLException ex) {
// The insert failed. If it was due to a constraint violation, that means a revision
// already exists with identical contents and the same parent rev. We can ignore this
// insert call, then.
if (ex.getCode() != SQLException.SQLITE_CONSTRAINT) {
Log.e(TAG, "Error inserting revision: ", ex);
throw new CouchbaseLiteException(Status.INTERNAL_SERVER_ERROR);
}
Log.w(TAG, "Duplicate rev insertion: " + docID + " / " + newRevId);
newRev.setBody(null);
// The pre-existing revision may have a nulled-out parent link since its original
// parent may have been pruned earlier. Fix that link:
if (parentSequence != 0) {
try {
ContentValues args = new ContentValues();
args.put("parent", parentSequence);
storageEngine.update("revs", args, "doc_id=? and revid=?",
new String[]{String.valueOf(docNumericID), newRevId});
} catch (SQLException e) {
throw new CouchbaseLiteException(e, Status.INTERNAL_SERVER_ERROR);
}
}
// Keep going, to make the parent rev non-current, before returning...
}
// Make replaced rev non-current:
if (parentSequence > 0) {
try {
ContentValues args = new ContentValues();
args.put("current", 0);
args.put("doc_type", (String) null);
storageEngine.update("revs", args, "sequence=?", new String[]{String.valueOf(parentSequence)});
} catch (SQLException e) {
Log.e(TAG, "Error setting parent rev non-current", e);
storageEngine.delete("revs", "sequence=?", new String[]{String.valueOf(sequence)});
throw new CouchbaseLiteException(e, Status.INTERNAL_SERVER_ERROR);
}
}
if (sequence <= 0) {
// duplicate rev; see above
outStatus.setCode(Status.OK);
if (newRev.getSequence() != 0)
delegate.databaseStorageChanged(new DocumentChange(newRev, winningRevID, inConflict, null));
return newRev;
}
// Delete the deepest revs in the tree to enforce the maxRevTreeDepth:
int minGenToKeep = newRev.getGeneration() - maxRevTreeDepth + 1;
if (minGenToKeep > 1) {
int pruned = pruneDocument(docID, docNumericID, minGenToKeep);
if (pruned > 0)
Log.v(TAG, "Pruned %d old revisions of doc '%s'", pruned, docID);
}
// Figure out what the new winning rev ID is:
winningRevID = winner(docNumericID, oldWinningRevID, oldWinnerWasDeletion.get(), newRev);
// Success!
if (deleting) {
outStatus.setCode(Status.OK);
} else {
outStatus.setCode(Status.CREATED);
}
} finally {
endTransaction(outStatus.isSuccessful());
}
//// EPILOGUE: A change notification is sent...
if (newRev.getSequence() != 0)
delegate.databaseStorageChanged(new DocumentChange(newRev, winningRevID, inConflict, null));
return newRev;
}
/**
* Inserts an already-existing revision replicated from a remote sqliteDb.
* <p/>
* It must already have a revision ID. This may create a conflict! The revision's history must be given; ancestor revision IDs that don't already exist locally will create phantom revisions with no content.
*
* @exclude in CBLDatabase+Insertion.m
* - (CBLStatus) forceInsert: (CBL_Revision*)inRev
* revisionHistory: (NSArray*)history // in *reverse* order, starting with rev's revID
* source: (NSURL*)source
*/
@Override
@InterfaceAudience.Private
public void forceInsert(RevisionInternal inRev,
List<String> history,
StorageValidation validationBlock,
URL source)
throws CouchbaseLiteException {
Status status = new Status(Status.UNKNOWN);
RevisionInternal rev = inRev.copy();
rev.setSequence(0);
String docID = rev.getDocID();
String winningRevID = null;
AtomicBoolean inConflict = new AtomicBoolean(false);
boolean success = false;
beginTransaction();
try {
// First look up the document's row-id and all locally-known revisions of it:
Map<String, RevisionInternal> localRevs = null;
String oldWinningRevID = null;
AtomicBoolean oldWinnerWasDeletion = new AtomicBoolean(false);
AtomicBoolean isNewDoc = new AtomicBoolean(history.size() == 1);
long docNumericID = createOrGetDocNumericID(docID, isNewDoc);
if (docNumericID <= 0)
throw new CouchbaseLiteException(Status.INTERNAL_SERVER_ERROR);
if (!isNewDoc.get()) {
RevisionList localRevsList = getAllRevisions(docID, docNumericID, false);
if (localRevsList == null)
throw new CouchbaseLiteException(Status.INTERNAL_SERVER_ERROR);
localRevs = new HashMap<String, RevisionInternal>();
for (RevisionInternal r : localRevsList)
localRevs.put(r.getRevID(), r);
// Look up which rev is the winner, before this insertion
oldWinningRevID = winningRevIDOfDocNumericID(
docNumericID,
oldWinnerWasDeletion,
inConflict);
}
// Validate against the latest common ancestor:
if (validationBlock != null) {
RevisionInternal oldRev = null;
for (int i = 1; i < history.size(); i++) {
oldRev = (localRevs != null) ? localRevs.get(history.get(i)) : null;
if (oldRev != null) {
break;
}
}
String parentRevId = (history.size() > 1) ? history.get(1) : null;
Status tmpStatus = validationBlock.validate(rev, oldRev, parentRevId);
if (tmpStatus.isError()) {
throw new CouchbaseLiteException(tmpStatus);
}
}
// Walk through the remote history in chronological order, matching each revision ID to
// a local revision. When the list diverges, start creating blank local revisions to
// fill in the local history:
long sequence = 0;
long localParentSequence = 0;
for (int i = history.size() - 1; i >= 0; --i) {
String revID = history.get(i);
RevisionInternal localRev = (localRevs != null) ? localRevs.get(revID) : null;
if (localRev != null) {
// This revision is known locally. Remember its sequence as the parent of
// the next one:
sequence = localRev.getSequence();
assert (sequence > 0);
localParentSequence = sequence;
} else {
// This revision isn't known, so add it:
RevisionInternal newRev = null;
byte[] json = null;
String docType = null;
boolean current = false;
if (i == 0) {
// Hey, this is the leaf revision we're inserting:
newRev = rev;
json = RevisionUtils.asCanonicalJSON(inRev);
if (json == null)
throw new CouchbaseLiteException(Status.BAD_JSON);
Object obj = rev.getObject("type");
if (obj != null && obj instanceof String)
docType = (String) obj;
current = true;
} else {
// It's an intermediate parent, so insert a stub:
newRev = new RevisionInternal(docID, revID, false);
}
// Insert it:
sequence = insertRevision(
newRev,
docNumericID,
sequence,
current,
(newRev.getAttachments() != null && newRev.getAttachments().size() > 0),
json,
docType);
if (sequence <= 0)
throw new CouchbaseLiteException(Status.INTERNAL_SERVER_ERROR);
}
}
if (localParentSequence == sequence) {
success = true; // No-op: No new revisions were inserted.
status.setCode(Status.OK);
}
// Mark the latest local rev as no longer current:
else if (localParentSequence > 0) {
ContentValues args = new ContentValues();
args.put("current", 0);
args.put("doc_type", (String) null);
String[] whereArgs = {Long.toString(localParentSequence)};
int numRowsChanged = 0;
try {
numRowsChanged = storageEngine.update("revs", args, "sequence=? AND current!=0", whereArgs);
if (numRowsChanged == 0)
inConflict.set(true); // local parent wasn't a leaf, ergo we just created a branch
} catch (SQLException e) {
throw new CouchbaseLiteException(Status.INTERNAL_SERVER_ERROR);
}
}
// Delete the deepest revs in the tree to enforce the maxRevTreeDepth:
int gen = inRev.getGeneration();
String oldestRevID = null;
if (history.size() > 0)
oldestRevID = history.get(history.size() - 1);
int oldGen = Revision.generationFromRevID(oldestRevID);
if (gen > maxRevTreeDepth) {
int minGen = oldGen;
int maxGen = gen;
if (localRevs != null) {
for (RevisionInternal r : localRevs.values()) {
int generation = r.getGeneration();
minGen = Math.min(minGen, generation);
maxGen = Math.max(maxGen, generation);
}
}
int minGenToKeep = maxGen - maxRevTreeDepth + 1;
if (minGen < minGenToKeep) {
int pruned = pruneDocument(docID, docNumericID, minGenToKeep);
if (pruned > 0)
Log.v(TAG, "Pruned %d old revisions of doc '%s'", pruned, docID);
}
}
if (!success) {
// Figure out what the new winning rev ID is:
winningRevID = winner(docNumericID, oldWinningRevID, oldWinnerWasDeletion.get(), rev);
success = true;
status.setCode(Status.CREATED);
}
} catch (SQLException e) {
Log.e(TAG, "Error inserting revisions", e);
throw new CouchbaseLiteException(Status.INTERNAL_SERVER_ERROR);
} finally {
endTransaction(success);
}
// Notify and return:
if (status.getCode() == Status.CREATED)
delegate.databaseStorageChanged(new DocumentChange(rev, winningRevID, inConflict.get(), source));
else if (status.isError())
throw new CouchbaseLiteException(status);
}
/**
* Purges specific revisions, which deletes them completely from the local storageEngine _without_ adding a "tombstone" revision. It's as though they were never there.
* This operation is described here: http://wiki.apache.org/couchdb/Purge_Documents
*
* @param docsToRevs A dictionary mapping document IDs to arrays of revision IDs.
* @resultOn success will point to an NSDictionary with the same form as docsToRev, containing the doc/revision IDs that were actually removed.
*/
@Override
@InterfaceAudience.Private
public Map<String, Object> purgeRevisions(final Map<String, List<String>> docsToRevs) {
final Map<String, Object> result = new HashMap<String, Object>();
runInTransaction(new TransactionalTask() {
@Override
public boolean run() {
for (String docID : docsToRevs.keySet()) {
long docNumericID = getDocNumericID(docID);
if (docNumericID == -1) {
continue; // no such document, skip it
}
List<String> revsPurged = new ArrayList<String>();
List<String> revIDs = (List<String>) docsToRevs.get(docID);
if (revIDs == null) {
return false;
} else if (revIDs.size() == 0) {
revsPurged = new ArrayList<String>();
} else if (revIDs.contains("*")) {
// Delete all revisions if magic "*" revision ID is given:
try {
String[] args = {Long.toString(docNumericID)};
storageEngine.execSQL("DELETE FROM revs WHERE doc_id=?", args);
} catch (SQLException e) {
Log.e(TAG, "Error deleting revisions", e);
return false;
}
revsPurged = new ArrayList<String>();
revsPurged.add("*");
} else {
// Iterate over all the revisions of the doc, in reverse sequence order.
// Keep track of all the sequences to delete, i.e. the given revs and ancestors,
// but not any non-given leaf revs or their ancestors.
Cursor cursor = null;
try {
String[] args = {Long.toString(docNumericID)};
String queryString = "SELECT revid, sequence, parent FROM revs WHERE doc_id=? ORDER BY sequence DESC";
cursor = storageEngine.rawQuery(queryString, args);
if (!cursor.moveToNext()) {
Log.w(TAG, "No results for query: %s", queryString);
return false;
}
Set<Long> seqsToPurge = new HashSet<Long>();
Set<Long> seqsToKeep = new HashSet<Long>();
Set<String> revsToPurge = new HashSet<String>();
while (!cursor.isAfterLast()) {
String revID = cursor.getString(0);
long sequence = cursor.getLong(1);
long parent = cursor.getLong(2);
if (seqsToPurge.contains(sequence) || revIDs.contains(revID) && !seqsToKeep.contains(sequence)) {
// Purge it and maybe its parent:
seqsToPurge.add(sequence);
revsToPurge.add(revID);
if (parent > 0) {
seqsToPurge.add(parent);
}
} else {
// Keep it and its parent:
seqsToPurge.remove(sequence);
revsToPurge.remove(revID);
seqsToKeep.add(parent);
}
cursor.moveToNext();
}
seqsToPurge.removeAll(seqsToKeep);
Log.i(TAG, "Purging doc '%s' revs (%s)", docID, revIDs);
// Now delete the sequences to be purged.
if (!purgeSequences(seqsToPurge))
return false;
revsPurged.addAll(revsToPurge);
} catch (SQLException e) {
Log.e(TAG, "Error getting revisions", e);
return false;
} finally {
if (cursor != null) {
cursor.close();
}
}
}
result.put(docID, revsPurged);
}
return true;
}
});
return result;
}
private boolean purgeSequences(Set<Long> seqsToPurge) {
if (seqsToPurge.size() == 0)
return true;
String seqsString = TextUtils.join(",", seqsToPurge);
Log.v(TAG, " purging %d sequences: %s", seqsToPurge.size(), seqsString);
String sql = String.format(Locale.ENGLISH, "DELETE FROM revs WHERE sequence in (%s)", seqsString);
try {
storageEngine.execSQL(sql);
} catch (SQLException e) {
Log.e(TAG, "Error deleting revisions via: " + sql, e);
return false;
}
return true;
}
///////////////////////////////////////////////////////////////////////////
// EXPIRATION:
///////////////////////////////////////////////////////////////////////////
/**
* @return Java Time
*/
@Override
public long expirationOfDocument(String docID) {
return SQLiteUtils.longForQuery(storageEngine,
"SELECT expiry_timestamp FROM docs WHERE docid=?",
new String[]{docID}) * 1000L;
}
@Override
public boolean setExpirationOfDocument(long unixTime, String docID) {
try {
ContentValues values = new ContentValues();
values.put("expiry_timestamp", unixTime);
String[] whereArgs = {docID};
int rowsUpdated = storageEngine.update("docs", values, "docid=?", whereArgs);
return rowsUpdated > 0 ? true : false;
} catch (SQLException e) {
Log.w(TAG, "Failed to update expiry_timestamp for docID=%s", e, docID);
return false;
}
}
/**
* @return Java Time
*/
@Override
public long nextDocumentExpiry() {
return SQLiteUtils.longForQuery(storageEngine,
"SELECT MIN(expiry_timestamp) FROM docs WHERE expiry_timestamp not null and expiry_timestamp != 0",
null) * 1000L;
}
@Override
public int purgeExpiredDocuments() {
final AtomicInteger nPurged = new AtomicInteger(0);
runInOuterTransaction(new TransactionalTask() {
@Override
public boolean run() {
if (storageEngine == null)
return false;
long nowUnixTime = System.currentTimeMillis() / 1000L;
invalidateDocNumericIDs();
String[] args = {String.valueOf(nowUnixTime)};
// First capture the docIDs to be purged, so we can notify about them:
List<String> purgedIDs = new ArrayList<String>();
String queryString = "SELECT docid FROM docs WHERE expiry_timestamp <= ? and expiry_timestamp != 0";
Cursor cursor = storageEngine.rawQuery(queryString, args);
try {
cursor.moveToNext();
while (!cursor.isAfterLast()) {
purgedIDs.add(cursor.getString(0));
cursor.moveToNext();
}
} finally {
cursor.close();
}
// Now delete the docs:
try {
int count = storageEngine.delete("docs", "expiry_timestamp <= ? and expiry_timestamp != 0", args);
Log.v(TAG, "purged doc count: %d/%d", count, purgedIDs.size());
} catch (SQLException e) {
Log.w(TAG, "Failed to delete from docs expiry_timestamp <= %d", e, nowUnixTime);
return false;
}
// Finally notify:
for (String docID : purgedIDs)
notifyPurgedDocument(docID);
nPurged.set(purgedIDs.size());
return true;
}
});
return nPurged.get();
}
private void notifyPurgedDocument(String docID) {
delegate.databaseStorageChanged(new DocumentChange(docID));
}
///////////////////////////////////////////////////////////////////////////
// VIEWS:
///////////////////////////////////////////////////////////////////////////
/**
* Instantiates storage for a view.
*
* @param name The name of the view
* @param create If YES, the view should be created; otherwise it must already exist
* @return Storage for the view, or nil if create=NO and it doesn't exist.
*/
public ViewStore getViewStorage(String name, boolean create) throws CouchbaseLiteException {
return new SQLiteViewStore(this, name, create);
}
@Override
public List<String> getAllViewNames() {
Cursor cursor = null;
List<String> result = null;
try {
cursor = storageEngine.rawQuery("SELECT name FROM views", null);
cursor.moveToNext();
result = new ArrayList<String>();
while (!cursor.isAfterLast()) {
//result.add(delegate.getView(cursor.getString(0)));
result.add(cursor.getString(0));
cursor.moveToNext();
}
} catch (Exception e) {
Log.e(TAG, "Error getting all views", e);
} finally {
if (cursor != null) {
cursor.close();
}
}
return result;
}
///////////////////////////////////////////////////////////////////////////
// LOCAL DOCS:
///////////////////////////////////////////////////////////////////////////
@Override
public RevisionInternal getLocalDocument(String docID, String revID) {
// docID already should contain "_local/" prefix
RevisionInternal result = null;
Cursor cursor = null;
try {
String[] args = {docID};
cursor = storageEngine.rawQuery("SELECT revid, json FROM localdocs WHERE docid=?", args);
if (cursor.moveToNext()) {
String gotRevID = cursor.getString(0);
if (revID != null && (!revID.equals(gotRevID))) {
return null;
}
byte[] json = cursor.getBlob(1);
Map<String, Object> properties = null;
try {
properties = Manager.getObjectMapper().readValue(json, Map.class);
properties.put("_id", docID);
properties.put("_rev", gotRevID);
result = new RevisionInternal(docID, gotRevID, false);
result.setProperties(properties);
} catch (Exception e) {
Log.w(TAG, "Error parsing local doc JSON", e);
return null;
}
}
return result;
} catch (SQLException e) {
Log.e(TAG, "Error getting local document", e);
return null;
} finally {
if (cursor != null) {
cursor.close();
}
}
}
@Override
public RevisionInternal putLocalRevision(RevisionInternal revision, String prevRevID, boolean obeyMVCC)
throws CouchbaseLiteException {
String docID = revision.getDocID();
if (!docID.startsWith("_local/")) {
throw new CouchbaseLiteException(Status.BAD_REQUEST);
}
if (!obeyMVCC) {
return putLocalRevisionNoMVCC(revision);
} else if (!revision.isDeleted()) {
// PUT:
byte[] json = RevisionUtils.asCanonicalJSON(revision);
String newRevID;
if (prevRevID != null) {
int generation = RevisionInternal.generationFromRevID(prevRevID);
if (generation == 0) {
throw new CouchbaseLiteException(Status.BAD_REQUEST);
}
newRevID = Integer.toString(++generation) + "-local";
ContentValues values = new ContentValues();
values.put("revid", newRevID);
values.put("json", json);
String[] whereArgs = {docID, prevRevID};
try {
int rowsUpdated = storageEngine.update("localdocs", values, "docid=? AND revid=?", whereArgs);
if (rowsUpdated == 0) {
throw new CouchbaseLiteException(Status.CONFLICT);
}
} catch (SQLException e) {
throw new CouchbaseLiteException(e, Status.INTERNAL_SERVER_ERROR);
}
} else {
newRevID = "1-local";
ContentValues values = new ContentValues();
values.put("docid", docID);
values.put("revid", newRevID);
values.put("json", json);
try {
storageEngine.insertWithOnConflict("localdocs", null, values, SQLiteStorageEngine.CONFLICT_IGNORE);
} catch (SQLException e) {
throw new CouchbaseLiteException(e, Status.INTERNAL_SERVER_ERROR);
}
}
return revision.copyWithDocID(docID, newRevID);
} else {
// DELETE:
deleteLocalDocument(docID, prevRevID);
return revision;
}
}
/**
* - (CBL_Revision*) putLocalRevisionNoMVCC: (CBL_Revision*)revision
* status: (CBLStatus*)outStatus
*/
protected RevisionInternal putLocalRevisionNoMVCC(final RevisionInternal revision)
throws CouchbaseLiteException {
RevisionInternal result = null;
boolean commit = false;
beginTransaction();
try {
RevisionInternal prevRev = getLocalDocument(revision.getDocID(), null);
result = putLocalRevision(revision, prevRev == null ? null : prevRev.getRevID(), true);
commit = true;
} finally {
endTransaction(commit);
}
return result;
}
@Override
public RevisionList getAllRevisions(String docID, boolean onlyCurrent) {
long docNumericId = getDocNumericID(docID);
if (docNumericId < 0) {
return null;
} else if (docNumericId == 0) {
return new RevisionList();
} else {
return getAllRevisions(docID, docNumericId, onlyCurrent);
}
}
///////////////////////////////////////////////////////////////////////////
// Internal (PROTECTED & PRIVATE) METHODS
///////////////////////////////////////////////////////////////////////////
protected SQLiteStorageEngine getStorageEngine() {
return storageEngine;
}
private boolean existsDocument(String docID, String revID) {
return getDocument(docID, revID, false) != null;
}
private void deleteLocalDocument(String docID, String revID) throws CouchbaseLiteException {
if (docID == null) {
throw new CouchbaseLiteException(Status.BAD_REQUEST);
}
if (revID == null) {
// Didn't specify a revision to delete: 404 or a 409, depending
if (getLocalDocument(docID, null) != null) {
throw new CouchbaseLiteException(Status.CONFLICT);
} else {
throw new CouchbaseLiteException(Status.NOT_FOUND);
}
}
String[] whereArgs = {docID, revID};
try {
int rowsDeleted = storageEngine.delete("localdocs", "docid=? AND revid=?", whereArgs);
if (rowsDeleted == 0) {
if (getLocalDocument(docID, null) != null) {
throw new CouchbaseLiteException(Status.CONFLICT);
} else {
throw new CouchbaseLiteException(Status.NOT_FOUND);
}
}
} catch (SQLException e) {
throw new CouchbaseLiteException(e, Status.INTERNAL_SERVER_ERROR);
}
}
/**
* Returns the rev ID of the 'winning' revision of this document, and whether it's deleted.
* <p/>
* in CBLDatabase+Internal.m
* - (NSString*) winningRevIDOfDocNumericID: (SInt64)docNumericID
* isDeleted: (BOOL*)outIsDeleted
* isConflict: (BOOL*)outIsConflict // optional
* status: (CBLStatus*)outStatus
*/
protected String winningRevIDOfDocNumericID(long docNumericId,
AtomicBoolean outIsDeleted,
AtomicBoolean outIsConflict) // optional
throws CouchbaseLiteException {
assert (docNumericId > 0);
Cursor cursor = null;
String sql = "SELECT revid, deleted FROM revs" +
" WHERE doc_id=? and current=1" +
" ORDER BY deleted asc, revid desc LIMIT ?";
long limit = (outIsConflict != null && outIsConflict.get()) ? 2 : 1;
String[] args = {Long.toString(docNumericId), Long.toString(limit)};
String revID = null;
try {
cursor = storageEngine.rawQuery(sql, args);
if (cursor.moveToNext()) {
revID = cursor.getString(0);
outIsDeleted.set(cursor.getInt(1) > 0);
// The document is in conflict if there are two+ result rows that are not deletions.
if (outIsConflict != null) {
outIsConflict.set(!outIsDeleted.get() && cursor.moveToNext() && !(cursor.getInt(1) > 0));
}
} else {
outIsDeleted.set(false);
if (outIsConflict != null) {
outIsConflict.set(false);
}
}
} catch (SQLException e) {
Log.e(TAG, "Error", e);
throw new CouchbaseLiteException("Error", e, new Status(Status.INTERNAL_SERVER_ERROR));
} finally {
if (cursor != null) {
cursor.close();
}
}
return revID;
}
/**
* https://github.com/couchbase/couchbase-lite-ios/issues/615
*/
protected void optimizeSQLIndexes() {
Log.v(Log.TAG_DATABASE, "calls optimizeSQLIndexes()");
final long currentSequence = getLastSequence();
if (currentSequence > 0) {
final long lastOptimized = getLastOptimized();
if (lastOptimized <= currentSequence / 10) {
runInTransaction(new TransactionalTask() {
@Override
public boolean run() {
Log.i(Log.TAG_DATABASE, "%s: Optimizing SQL indexes (curSeq=%d, last run at %d)",
this, currentSequence, lastOptimized);
storageEngine.execSQL("ANALYZE");
storageEngine.execSQL("ANALYZE sqlite_master");
setInfo("last_optimized", String.valueOf(currentSequence));
return true;
}
});
}
}
}
/**
* Begins a storageEngine transaction. Transactions can nest.
* Every beginTransaction() must be balanced by a later endTransaction()
* <p/>
* Notes: 1. SQLiteDatabase.beginTransaction() supported nested transaction. But, in case
* nested transaction rollbacked, it also rollbacks outer transaction too.
* This is not ideal behavior for CBL
* 2. SAVEPOINT...RELEASE supports nested transaction. But Android API 14 and 15,
* it throws Exception. I assume it is Android bug. As CBL need to support from API 10
* . So it does not work for CBL.
* 3. Using Transaction for outer/1st level of transaction and inner/2nd level of transaction
* works with CBL requirement.
* 4. CBL Android and Java uses Thread, So it is better to use SQLiteDatabase.beginTransaction()
* for outer/1st level transaction. if we use BEGIN...COMMIT and SAVEPOINT...RELEASE,
* we need to implement wrapper of BEGIN...COMMIT and SAVEPOINT...RELEASE to be
* Thread-safe.
*/
protected boolean beginTransaction() {
int tLevel = transactionLevel.get();
try {
// Outer (level 0) transaction. Use SQLiteDatabase.beginTransaction()
if (tLevel == 0) {
storageEngine.beginTransaction();
}
// Inner (level 1 or higher) transaction. Use SQLite's SAVEPOINT
else {
storageEngine.execSQL("SAVEPOINT cbl_" + Integer.toString(tLevel));
}
Log.v(Log.TAG_DATABASE, "%s Begin transaction (level %d)", Thread.currentThread().getName(), tLevel);
transactionLevel.set(++tLevel);
} catch (SQLException e) {
Log.e(Log.TAG_DATABASE, Thread.currentThread().getName() + " Error calling beginTransaction()", e);
return false;
}
return true;
}
/**
* Commits or aborts (rolls back) a transaction.
*
* @param commit If true, commits; if false, aborts and rolls back, undoing all changes made
* since the matching -beginTransaction call, *including* any committed nested
* transactions.
* @exclude
*/
protected boolean endTransaction(boolean commit) {
int tLevel = transactionLevel.get();
assert (tLevel > 0);
transactionLevel.set(--tLevel);
// Outer (level 0) transaction. Use SQLiteDatabase.setTransactionSuccessful() and SQLiteDatabase.endTransaction()
if (tLevel == 0) {
if (commit) {
Log.v(Log.TAG_DATABASE, "%s Committing transaction (level %d)", Thread.currentThread().getName(), tLevel);
storageEngine.setTransactionSuccessful();
storageEngine.endTransaction();
} else {
Log.v(Log.TAG_DATABASE, "%s CANCEL transaction (level %d)", Thread.currentThread().getName(), tLevel);
try {
storageEngine.endTransaction();
} catch (SQLException e) {
Log.e(Log.TAG_DATABASE, Thread.currentThread().getName() + " Error calling endTransaction()", e);
return false;
}
}
}
// Inner (level 1 or higher) transaction: Use SQLite's ROLLBACK and RELEASE
else {
if (commit) {
Log.v(Log.TAG_DATABASE, "%s Committing transaction (level %d)", Thread.currentThread().getName(), tLevel);
} else {
Log.v(Log.TAG_DATABASE, "%s CANCEL transaction (level %d)", Thread.currentThread().getName(), tLevel);
try {
storageEngine.execSQL(";ROLLBACK TO cbl_" + Integer.toString(tLevel));
} catch (SQLException e) {
Log.e(Log.TAG_DATABASE, Thread.currentThread().getName() + " Error calling endTransaction()", e);
return false;
}
}
try {
storageEngine.execSQL("RELEASE cbl_" + Integer.toString(tLevel));
} catch (SQLException e) {
Log.e(Log.TAG_DATABASE, Thread.currentThread().getName() + " Error calling endTransaction()", e);
return false;
}
}
if (delegate != null)
delegate.storageExitedTransaction(commit);
return true;
}
protected Map<String, Object> documentPropertiesFromJSON(byte[] json, String docID,
String revID, boolean deleted,
long sequence) {
RevisionInternal rev = new RevisionInternal(docID, revID, deleted);
rev.setSequence(sequence);
rev.setMissing(json == null);
Map<String, Object> docProperties = null;
if (json == null || json.length == 0 || (json.length == 2 && java.util.Arrays.equals(json, EMPTY_JSON_OBJECT_CHARS))) {
docProperties = new HashMap<String, Object>();
} else {
try {
docProperties = Manager.getObjectMapper().readValue(json, Map.class);
} catch (IOException e) {
Log.e(TAG, String.format(Locale.ENGLISH, "Unparseable JSON for doc=%s, rev=%s: %s", docID, revID, new String(json)), e);
docProperties = new HashMap<String, Object>();
}
}
docProperties.put("_id", docID);
docProperties.put("_rev", revID);
if (deleted)
docProperties.put("_deleted", true);
return docProperties;
}
/**
* Prune revisions to the given max depth. Eg, remove revisions older than that max depth,
* which will reduce storage requirements.
* <p/>
* TODO: This implementation is a bit simplistic. It won't do quite the right thing in
* histories with branches, if one branch stops much earlier than another. The shorter branch
* will be deleted entirely except for its leaf revision. A more accurate pruning
* would require an expensive full tree traversal. Hopefully this way is good enough.
*/
protected int pruneRevsToMaxDepth(int maxDepth) throws CouchbaseLiteException {
if (maxDepth == 0)
maxDepth = getMaxRevTreeDepth();
Log.v(TAG, "Pruning revisions to max depth %d...", maxDepth);
// First find which docs need pruning, and by how much:
Map<Long, Integer> toPrune = new HashMap<Long, Integer>();
Cursor cursor = null;
try {
String[] args = {};
cursor = storageEngine.rawQuery(
"SELECT doc_id, MIN(revid), MAX(revid) FROM revs GROUP BY doc_id", args);
while (cursor.moveToNext()) {
long docNumericID = cursor.getLong(0);
String minGenRevId = cursor.getString(1);
String maxGenRevId = cursor.getString(2);
int minGen = Revision.generationFromRevID(minGenRevId);
int maxGen = Revision.generationFromRevID(maxGenRevId);
if ((maxGen - minGen + 1) > maxDepth) {
toPrune.put(docNumericID, (maxGen - maxDepth));
}
}
} catch (Exception e) {
throw new CouchbaseLiteException(e, Status.INTERNAL_SERVER_ERROR);
} finally {
if (cursor != null)
cursor.close();
}
if (toPrune.size() == 0)
return 0;
// Now prune:
int outPruned = 0;
boolean shouldCommit = false;
try {
beginTransaction();
for (Long docNumericID : toPrune.keySet())
outPruned += pruneDocument("?", docNumericID, toPrune.get(docNumericID).intValue() + 1);
shouldCommit = true;
} catch (Throwable e) {
throw new CouchbaseLiteException(e, Status.INTERNAL_SERVER_ERROR);
} finally {
endTransaction(shouldCommit);
}
return outPruned;
}
// Returns the number of revisions pruned.
protected int pruneDocument(String docID, long docNumericID, int minGenToKeep) {
// First find the leaves:
Set<Long> leaves = new HashSet<Long>();
Cursor cursor = null;
try {
cursor = storageEngine.rawQuery(
"SELECT sequence FROM revs WHERE doc_id=? AND current",
new String[]{Long.toString(docNumericID)});
while (cursor.moveToNext())
leaves.add(cursor.getLong(0));
} catch (SQLException e) {
Log.e(TAG, "Error querying sequence from revs docNumericID=%d", e, docNumericID);
return -1;
} finally {
if (cursor != null)
cursor.close();
}
if (leaves.size() <= 1) {
// There are no branches, so just delete everything below minGenToKeep:
String minIDToKeep = String.format(Locale.ENGLISH, "%d-", minGenToKeep);
String[] deleteArgs = {Long.toString(docNumericID), minIDToKeep};
int pruned = storageEngine.delete("revs", "doc_id=? AND revid < ? AND current=0", deleteArgs);
Log.v(TAG, " pruned %d revs with gen<%d from %s", pruned, minGenToKeep, docID);
return pruned;
} else {
// Doc has branches. Keep the ancestors of all the leaves, down to _maxRevTreeDepth.
// First fetch the skeleton of the rev tree:
Map<Long, Long> revs = new HashMap<Long, Long>();
Cursor cursor2 = null;
try {
cursor2 = storageEngine.rawQuery(
"SELECT sequence, parent FROM revs WHERE doc_id=?",
new String[]{Long.toString(docNumericID)});
while (cursor2.moveToNext()) {
long seq = cursor2.getLong(0);
long parent = cursor2.getLong(1);
revs.put(seq, parent);
}
} catch (SQLException e) {
Log.e(TAG, "Error querying sequence and parent from revs docNumericID=%d", e, docNumericID);
return -1;
} finally {
if (cursor2 != null)
cursor2.close();
}
// Now remove each leaf and its ancestors from `revs`:
Log.v(TAG, " pruning %s, scanning %d revs in tree...", docID, revs.size());
for (Long leaf : leaves) {
Long seq = leaf;
for (int i = 0; i < maxRevTreeDepth; i++) {
Long parent = revs.get(seq);
revs.remove(seq);
if (parent == null || parent.longValue() == 0)
break;
seq = parent;
}
}
// The remaining keys in `revs` are sequences to purge:
if (!purgeSequences(revs.keySet())) {
Log.w(TAG, "SQLite error: pruning conflicted doc %d", docNumericID);
return -1;
}
return revs.size();
}
}
protected void runStatements(String statements) throws SQLException {
for (String statement : statements.split(";")) {
try {
storageEngine.execSQL(statement);
} catch (SQLException e) {
Log.e(TAG, "Failed to execSQL: " + statement, e);
throw e;
}
}
}
private void initialize(String statements) throws SQLException {
try {
runStatements(statements);
} catch (SQLException e) {
close();
throw e;
}
}
private long getLastOptimized() {
String info = getInfo("last_optimized");
if (info != null) {
return Long.parseLong(info);
}
return 0;
}
private boolean sequenceHasAttachments(long sequence) {
String args[] = {Long.toString(sequence)};
return SQLiteUtils.booleanForQuery(storageEngine, "SELECT no_attachments=0 FROM revs WHERE sequence=?", args);
}
protected long getDocNumericID(String docID) {
return SQLiteUtils.longForQuery(storageEngine,
"SELECT doc_id FROM docs WHERE docid=?",
new String[]{docID});
}
// Registers a docID and returns its numeric row ID in the 'docs' table.
// On input, *ioIsNew should be YES if the docID is probably not known, NO if it's probably known.
// On return, *ioIsNew will be YES iff the docID is newly-created (was not known before.)
// Return value is the positive row ID of this doc, or <= 0 on error.
private long createOrGetDocNumericID(String docID, AtomicBoolean isNew) {
// TODO: cache
long row = isNew.get() ? createDocNumericID(docID, isNew) : getDocNumericID(docID);
if (row < 0)
return row;
if (row == 0) {
isNew.set(!isNew.get());
row = isNew.get() ? createDocNumericID(docID, isNew) : getDocNumericID(docID);
}
// TODO: cache: https://github.com/couchbase/couchbase-lite-java-core/issues/1265
return row;
}
private void invalidateDocNumericID(String docID){
// TODO: cache: https://github.com/couchbase/couchbase-lite-java-core/issues/1265
}
private void invalidateDocNumericIDs(){
// TODO: cache: https://github.com/couchbase/couchbase-lite-java-core/issues/1265
}
//private long getOrInsertDocNumericID(String docID) {
private long createDocNumericID(String docID, AtomicBoolean isNew) {
long docNumericId = getDocNumericID(docID);
if (docNumericId == 0) {
docNumericId = insertDocumentID(docID);
isNew.set(true);
} else {
isNew.set(false);
}
return docNumericId;
}
private long insertDocumentID(String docID) {
long rowId = -1;
try {
ContentValues args = new ContentValues();
args.put("docid", docID);
rowId = storageEngine.insert("docs", null, args);
} catch (Exception e) {
Log.e(TAG, "Error inserting document id", e);
}
return rowId;
}
// Raw row insertion. Returns new sequence, or 0 on error
private long insertRevision(RevisionInternal rev,
long docNumericID,
long parentSequence,
boolean current,
boolean hasAttachments,
byte[] json,
String docType)
throws SQLException {
ContentValues args = new ContentValues();
args.put("doc_id", docNumericID);
args.put("revid", rev.getRevID());
if (parentSequence != 0)
args.put("parent", parentSequence);
args.put("current", current);
args.put("deleted", rev.isDeleted());
args.put("no_attachments", !hasAttachments);
args.put("json", json);
args.put("doc_type", docType);
long rowId = storageEngine.insertOrThrow("revs", null, args);
rev.setSequence(rowId);
return rowId;
}
private long getSequenceOfDocument(long docNumericID, String revID, boolean onlyCurrent) {
String sql = String.format(Locale.ENGLISH,
"SELECT sequence FROM revs WHERE doc_id=? AND revid=? %s LIMIT 1",
(onlyCurrent ? "AND current=1" : ""));
String[] args = {Long.toString(docNumericID), revID};
return SQLiteUtils.longForQuery(storageEngine, sql, args);
}
/**
* Hack because cursor interface does not support cursor.getColumnIndex("deleted") yet.
*/
private static int getDeletedColumnIndex(QueryOptions options) {
if (options.isIncludeDocs()) {
return 6; // + json and no_attachments
} else {
return 4; // revs.doc_id, docid, revid, sequence
}
}
/**
* Loads revision given its sequence. Assumes the given docID is valid.
*/
protected RevisionInternal getDocument(String docID, long sequence) {
// Now get its revID and deletion status:
RevisionInternal rev = null;
String[] args = {Long.toString(sequence)};
String queryString = "SELECT revid, deleted, json FROM revs WHERE sequence=?";
Cursor cursor = null;
try {
cursor = storageEngine.rawQuery(queryString, args);
if (cursor.moveToNext()) {
String revID = cursor.getString(0);
boolean deleted = (cursor.getInt(1) > 0);
byte[] json = cursor.getBlob(2);
rev = new RevisionInternal(docID, revID, deleted);
rev.setSequence(sequence);
rev.setJSON(json);
}
} finally {
cursor.close();
}
return rev;
}
protected static RevisionInternal revision(String docID, String revID,
boolean deleted, long sequence, byte[] json) {
RevisionInternal rev = new RevisionInternal(docID, revID, deleted);
rev.setSequence(sequence);
if (json != null)
rev.setJSON(json);
return rev;
}
protected static RevisionInternal revision(String docID, String revID,
boolean deleted, long sequence,
Map<String, Object> properties) {
RevisionInternal rev = new RevisionInternal(docID, revID, deleted);
rev.setSequence(sequence);
if (properties != null)
rev.setProperties(properties);
return rev;
}
private String winner(long docNumericID,
String oldWinningRevID,
boolean oldWinnerWasDeletion,
RevisionInternal newRev)
throws CouchbaseLiteException {
String newRevID = newRev.getRevID();
if (oldWinningRevID == null) {
return newRevID;
}
if (!newRev.isDeleted()) {
if (oldWinnerWasDeletion || RevisionInternal.CBLCompareRevIDs(newRevID, oldWinningRevID) > 0)
return newRevID; // this is now the winning live revision
} else if (oldWinnerWasDeletion) {
if (RevisionInternal.CBLCompareRevIDs(newRevID, oldWinningRevID) > 0)
return newRevID; // doc still deleted, but this beats previous deletion rev
} else {
// Doc was alive. How does this deletion affect the winning rev ID?
AtomicBoolean outIsDeleted = new AtomicBoolean(false);
String winningRevID = winningRevIDOfDocNumericID(docNumericID, outIsDeleted, null);
if (!winningRevID.equals(oldWinningRevID))
return winningRevID;
}
return null; // no change
}
}
|
src/main/java/com/couchbase/lite/store/SQLiteStore.java
|
/**
* Copyright (c) 2016 Couchbase, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.couchbase.lite.store;
import com.couchbase.lite.BlobKey;
import com.couchbase.lite.ChangesOptions;
import com.couchbase.lite.CouchbaseLiteException;
import com.couchbase.lite.DocumentChange;
import com.couchbase.lite.Manager;
import com.couchbase.lite.Misc;
import com.couchbase.lite.Query;
import com.couchbase.lite.QueryOptions;
import com.couchbase.lite.QueryRow;
import com.couchbase.lite.ReplicationFilter;
import com.couchbase.lite.Revision;
import com.couchbase.lite.RevisionList;
import com.couchbase.lite.Status;
import com.couchbase.lite.TransactionalTask;
import com.couchbase.lite.View;
import com.couchbase.lite.internal.InterfaceAudience;
import com.couchbase.lite.internal.RevisionInternal;
import com.couchbase.lite.internal.database.ContentValues;
import com.couchbase.lite.storage.Cursor;
import com.couchbase.lite.storage.SQLException;
import com.couchbase.lite.storage.SQLiteStorageEngine;
import com.couchbase.lite.storage.SQLiteStorageEngineFactory;
import com.couchbase.lite.support.RevisionUtils;
import com.couchbase.lite.support.action.Action;
import com.couchbase.lite.support.action.ActionBlock;
import com.couchbase.lite.support.action.ActionException;
import com.couchbase.lite.support.security.SymmetricKey;
import com.couchbase.lite.util.Log;
import com.couchbase.lite.util.SQLiteUtils;
import com.couchbase.lite.util.TextUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
public class SQLiteStore implements Store, EncryptableStore {
public String TAG = Log.TAG_DATABASE;
public static String kDBFilename = "db.sqlite3";
// Default value for maxRevTreeDepth, the max rev depth to preserve in a prune operation
private static final int DEFAULT_MAX_REVS = Integer.MAX_VALUE;
// Empty JSON string: "{}"
private static final byte[] EMPTY_JSON_OBJECT_CHARS = new byte[]{(byte) 0x007B, (byte) 0x007D};
// First-time initialization:
// (Note: Declaring revs.sequence as AUTOINCREMENT means the values will always be
// monotonically increasing, never reused. See <http://www.sqlite.org/autoinc.html>)
public static final String SCHEMA = "" +
// docs
"CREATE TABLE docs ( " +
" doc_id INTEGER PRIMARY KEY, " +
" docid TEXT UNIQUE NOT NULL); " +
" CREATE INDEX docs_docid ON docs(docid); " +
// revs
" CREATE TABLE revs ( " +
" sequence INTEGER PRIMARY KEY AUTOINCREMENT, " +
" doc_id INTEGER NOT NULL REFERENCES docs(doc_id) ON DELETE CASCADE, " +
" revid TEXT NOT NULL COLLATE REVID, " +
" parent INTEGER REFERENCES revs(sequence) ON DELETE SET NULL, " +
" current BOOLEAN, " +
" deleted BOOLEAN DEFAULT 0, " +
" json BLOB, " +
" no_attachments BOOLEAN, " +
" UNIQUE (doc_id, revid)); " +
" CREATE INDEX revs_parent ON revs(parent); " +
" CREATE INDEX revs_by_docid_revid ON revs(doc_id, revid desc, current, deleted); " +
" CREATE INDEX revs_current ON revs(doc_id, current desc, deleted, revid desc); " +
// localdocs
" CREATE TABLE localdocs ( " +
" docid TEXT UNIQUE NOT NULL, " +
" revid TEXT NOT NULL COLLATE REVID, " +
" json BLOB); " +
" CREATE INDEX localdocs_by_docid ON localdocs(docid); " +
// views
" CREATE TABLE views ( " +
" view_id INTEGER PRIMARY KEY, " +
" name TEXT UNIQUE NOT NULL," +
" version TEXT, " +
" lastsequence INTEGER DEFAULT 0," +
" total_docs INTEGER DEFAULT -1); " +
" CREATE INDEX views_by_name ON views(name); " +
// info
" CREATE TABLE info (" +
" key TEXT PRIMARY KEY," +
" value TEXT);" +
// version
" PRAGMA user_version = 17"; // at the end, update user_version
//OPT: Would be nice to use partial indexes but that requires SQLite 3.8 and makes the
// db file only readable by SQLite 3.8+, i.e. the file would not be portable to iOS 8
// which only has SQLite 3.7 :(
// On the revs_parent _index we could add "WHERE parent not null".
// transactionLevel is per thread
static class TransactionLevel extends ThreadLocal<Integer> {
@Override
protected Integer initialValue() {
return 0;
}
}
private String directory;
private String path;
private Manager manager;
private SQLiteStorageEngine storageEngine;
private TransactionLevel transactionLevel;
private StoreDelegate delegate;
private int maxRevTreeDepth;
private boolean autoCompact;
private SymmetricKey encryptionKey;
private final Object compactLock = new Object(); // lock for compact() method
///////////////////////////////////////////////////////////////////////////
// Constructor
///////////////////////////////////////////////////////////////////////////
public SQLiteStore(String directory, Manager manager, StoreDelegate delegate)
throws CouchbaseLiteException {
assert (new File(directory).isAbsolute()); // path must be absolute
this.directory = directory;
File dir = new File(directory);
if (!dir.exists() || !dir.isDirectory()) {
throw new IllegalArgumentException("directory '" + directory + "' does not exist or not directory");
}
this.path = new File(directory, kDBFilename).getPath();
this.manager = manager;
this.storageEngine = null;
this.transactionLevel = new TransactionLevel();
this.delegate = delegate;
this.maxRevTreeDepth = DEFAULT_MAX_REVS;
}
///////////////////////////////////////////////////////////////////////////
// Implementation of Storage
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
// INITIALIZATION AND CONFIGURATION:
///////////////////////////////////////////////////////////////////////////
@Override
public boolean databaseExists(String directory) {
return new File(directory, kDBFilename).exists();
}
@Override
public synchronized void open() throws CouchbaseLiteException {
// Try to open the storage engine and stop if we fail:
if (storageEngine == null)
storageEngine = createStorageEngine();
if (storageEngine.isOpen())
return;
boolean isOpenSuccess = false;
try {
// Open database:
storageEngine.open(path, encryptionKey);
isOpenSuccess = true;
} catch (SQLException e) {
String message = "Unable to create a storage engine";
Log.e(TAG, message, e);
int statusCode;
if (e.getCode() == SQLException.SQLITE_ENCRYPTION_UNAUTHORIZED)
statusCode = Status.UNAUTHORIZED;
else if (e.getCode() == SQLException.SQLITE_ENCRYPTION_NOTAVAILABLE)
statusCode = Status.NOT_IMPLEMENTED;
else
statusCode = Status.DB_ERROR;
throw new CouchbaseLiteException(message, e, statusCode);
} finally {
if (!isOpenSuccess) {
// As an exception will be thrown, no return false is needed here:
close();
}
}
// Stuff we need to initialize every time the sqliteDb opens:
try {
initialize("PRAGMA foreign_keys = ON;");
} catch (SQLException e) {
String message = "Cannot set enforcement of foreign key constraints";
Log.e(TAG, message, e);
throw new CouchbaseLiteException(message, e, Status.DB_ERROR);
}
// Check the user_version number we last stored in the sqliteDb:
int dbVersion = storageEngine.getVersion();
// Incompatible version changes increment the hundreds' place:
if (dbVersion >= 200) {
close();
String message = "Database version " + dbVersion +
" is newer than I know how to work with";
Log.e(TAG, message);
throw new CouchbaseLiteException(message, Status.NOT_ACCEPTABLE);
}
// Enable Write-Ahead Log (WAL)
// write-ahead log is enabled through SQLiteDatabase API
// https://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#enableWriteAheadLogging()
// BEGIN TRANSACTION
boolean isSuccessful = false;
if (!beginTransaction()) {
close();
String message = "Cannot begin transaction";
Log.e(TAG, message);
throw new CouchbaseLiteException(message, Status.DB_ERROR);
}
try {
boolean isNew = (dbVersion == 0);
if (dbVersion < 17) {
// First-time initialization:
// (Note: Declaring revs.sequence as AUTOINCREMENT means the values will always be
// monotonically increasing, never reused. See <http://www.sqlite.org/autoinc.html>)
if (!isNew) {
String message = "Database version " + dbVersion +
" is older than I know how to work with";
Log.e(TAG, message);
throw new CouchbaseLiteException(message, Status.NOT_ACCEPTABLE);
}
try {
initialize(SCHEMA);
} catch (SQLException e) {
String message = "Cannot initialize database schema";
Log.e(TAG, message, e);
throw new CouchbaseLiteException(message, e, Status.DB_ERROR);
}
dbVersion = 17;
}
if (dbVersion < 21) {
// Version 18:
String upgradeSql = "ALTER TABLE revs ADD COLUMN doc_type TEXT; " +
"PRAGMA user_version = 21";
try {
initialize(upgradeSql);
} catch (SQLException e) {
String message = "Cannot update revs table";
Log.e(TAG, message, e);
throw new CouchbaseLiteException(message, e, Status.DB_ERROR);
}
dbVersion = 21;
}
if (dbVersion < 101) {
String upgradeSql = "PRAGMA user_version = 101";
try {
initialize(upgradeSql);
} catch (SQLException e) {
String message = "Cannot update user_version to " + dbVersion;
Log.e(TAG, message, e);
throw new CouchbaseLiteException(message, e, Status.DB_ERROR);
}
dbVersion = 101;
}
if (dbVersion < 102) {
String upgradeSql = "ALTER TABLE docs ADD COLUMN expiry_timestamp INTEGER; "
+ "CREATE INDEX IF NOT EXISTS docs_expiry ON docs(expiry_timestamp) "
+ "WHERE expiry_timestamp not null; PRAGMA user_version = 102";
try {
initialize(upgradeSql);
} catch (SQLException e) {
String message = "Cannot update user_version to " + dbVersion;
Log.e(TAG, message, e);
throw new CouchbaseLiteException(message, e, Status.DB_ERROR);
}
dbVersion = 102;
}
if (isNew)
setInfo("pruned", "true"); // See -compact: for explanation
if (!isNew)
optimizeSQLIndexes(); // runs ANALYZE query
// successfully updated storageEngine schema:
isSuccessful = true;
} finally {
// END TRANSACTION WITH COMMIT OR ROLLBACK
endTransaction(isSuccessful);
// if failed, close storageEngine before return:
if (!isSuccessful) {
close();
}
}
}
@Override
public void close() {
if (storageEngine != null && storageEngine.isOpen())
storageEngine.close();
storageEngine = null;
}
private SQLiteStorageEngine createStorageEngine() throws CouchbaseLiteException {
SQLiteStorageEngineFactory factory =
manager.getContext().getSQLiteStorageEngineFactory();
SQLiteStorageEngine engine = factory.createStorageEngine();
if (engine == null) {
String message = "Unable to create a storage engine, fatal error";
Log.e(TAG, message);
throw new CouchbaseLiteException(message, Status.INTERNAL_SERVER_ERROR);
}
return engine;
}
@Override
public void setDelegate(StoreDelegate delegate) {
this.delegate = delegate;
}
@Override
public StoreDelegate getDelegate() {
return delegate;
}
/**
* Set the maximum depth of a document's revision tree (or, max length of its revision history.)
* Revisions older than this limit will be deleted during a -compact: operation.
* Smaller values save space, at the expense of making document conflicts somewhat more likely.
*/
@Override
public void setMaxRevTreeDepth(int maxRevTreeDepth) {
this.maxRevTreeDepth = maxRevTreeDepth;
}
/**
* Get the maximum depth of a document's revision tree (or, max length of its revision history.)
* Revisions older than this limit will be deleted during a -compact: operation.
* Smaller values save space, at the expense of making document conflicts somewhat more likely.
*/
@Override
public int getMaxRevTreeDepth() {
return maxRevTreeDepth;
}
@Override
public void setAutoCompact(boolean value) {
autoCompact = value;
}
@Override
public boolean getAutoCompact() {
return autoCompact;
}
///////////////////////////////////////////////////////////////////////////
// Database Encryption
///////////////////////////////////////////////////////////////////////////
private void decrypt(SymmetricKey encryptionKey) throws CouchbaseLiteException {
if (encryptionKey != null) {
if (!storageEngine.supportEncryption()) {
Log.w(TAG, "SQLiteStore: encryption not available (app not built with SQLCipher)");
throw new CouchbaseLiteException("Encryption not available",
Status.NOT_IMPLEMENTED);
} else {
try {
storageEngine.execSQL("PRAGMA key = \"x'" + encryptionKey.getHexData() + "'\"");
} catch (SQLException e) {
Log.w(TAG, "SQLiteStore: 'pragma key' failed", e);
throw e;
}
}
}
// Verify that encryption key is correct (or db is unencrypted, if no key given)
Cursor cursor = null;
try {
cursor = storageEngine.rawQuery("SELECT count(*) FROM sqlite_master", null);
if (cursor == null || !cursor.moveToNext()) {
// Backup error:
Log.w(TAG, "SQLiteStore: database is unreadable, unknown error");
throw new CouchbaseLiteException("Cannot decrypt or access the database",
Status.DB_ERROR);
}
} catch (Exception e) {
Log.w(TAG, "SQLiteStore: database is unreadable", e);
if (e.getMessage() != null &&
e.getMessage().contains("file is encrypted or is not a database (code 26)")) {
throw new CouchbaseLiteException("Cannot decrypt or access the database",
Status.UNAUTHORIZED);
} else {
throw new CouchbaseLiteException(e, Status.DB_ERROR);
}
} finally {
if (cursor != null) {
cursor.close();
}
}
}
///////////////////////////////////////////////////////////////////////////
// ENCRYPTABLE STORE
///////////////////////////////////////////////////////////////////////////
@Override
public void setEncryptionKey(SymmetricKey key) {
encryptionKey = key;
}
@Override
public SymmetricKey getEncryptionKey() {
return encryptionKey;
}
@Override
public Action actionToChangeEncryptionKey(final SymmetricKey newKey) {
if (!storageEngine.supportEncryption())
return null;
Action action = new Action();
final AtomicBoolean dbWasClosed = new AtomicBoolean(false);
// Make a path for a tempoary database file:
final File tempDbFile = new File(manager.getDirectory(), Misc.CreateUUID());
action.add(null, new ActionBlock() {
@Override
public void execute() throws ActionException {
if (tempDbFile.exists()) {
if (!tempDbFile.delete()) {
throw new ActionException("Cannot delete the temp database file " +
tempDbFile.getAbsolutePath());
}
}
}
}, null);
// Create & attach the temporary database encrypted with the new key:
action.add(
// Perform:
new ActionBlock() {
@Override
public void execute() throws ActionException {
String keyStr = newKey != null ? newKey.getHexData() : "";
String sql = "ATTACH DATABASE ? AS rekeyed_db KEY \"x'" + keyStr + "'\"";
String[] args = {tempDbFile.getAbsolutePath()};
try {
storageEngine.execSQL(sql, args);
} catch (Exception e) {
throw new ActionException(e);
}
}
},
// Backout or cleanup:
new ActionBlock() {
@Override
public void execute() throws ActionException {
if (dbWasClosed.get())
return;
try {
storageEngine.execSQL("DETACH DATABASE rekeyed_db");
} catch (Exception e) {
throw new ActionException(e);
}
}
});
// Export the current database's contents to the new one:
action.add(new ActionBlock() {
@Override
public void execute() throws ActionException {
try {
storageEngine.execSQL("SELECT sqlcipher_export('rekeyed_db')");
storageEngine.execSQL("PRAGMA rekeyed_db.user_version = " +
storageEngine.getVersion());
} catch (Exception e) {
throw new ActionException(e);
}
}
}, null, null);
// Close the database (and re-open it on cleanup):
action.add(
// Perform:
new ActionBlock() {
@Override
public void execute() throws ActionException {
storageEngine.close();
dbWasClosed.set(true);
}
},
// Backout:
new ActionBlock() {
@Override
public void execute() throws ActionException {
try {
open();
} catch (CouchbaseLiteException e) {
throw new ActionException("Cannot open the SQLiteStore", e);
}
}
},
// Cleanup:
new ActionBlock() {
@Override
public void execute() throws ActionException {
setEncryptionKey(newKey);
try {
open();
} catch (CouchbaseLiteException e) {
throw new ActionException("Cannot open the SQLiteStore", e);
}
}
}
);
// Overwrite the old db file with the new one:
action.add(Action.moveAndReplaceFile(tempDbFile.getAbsolutePath(), path,
manager.getContext().getTempDir().getAbsolutePath()));
return action;
}
@Override
public byte[] derivePBKDF2SHA256Key(String password, byte[] salt, int rounds)
throws CouchbaseLiteException {
if (storageEngine == null)
storageEngine = createStorageEngine();
if (!storageEngine.supportEncryption()) {
Log.w(TAG, "SQLiteStore: encryption not available (app not built with SQLCipher)");
throw new CouchbaseLiteException("Encryption not available",
Status.NOT_IMPLEMENTED);
}
byte[] result = storageEngine.derivePBKDF2SHA256Key(password, salt, rounds);
if (result == null)
throw new CouchbaseLiteException("Cannot derive key for the password",
Status.BAD_REQUEST);
return result;
}
///////////////////////////////////////////////////////////////////////////
// DATABASE ATTRIBUTES & OPERATIONS:
///////////////////////////////////////////////////////////////////////////
@Override
public long setInfo(String key, String info) {
ContentValues args = new ContentValues();
args.put("key", key);
args.put("value", info);
if (storageEngine.insertWithOnConflict("info", null, args,
SQLiteStorageEngine.CONFLICT_REPLACE) == -1)
return Status.DB_ERROR;
else
return Status.OK;
}
@Override
public String getInfo(String key) {
String result = null;
Cursor cursor = null;
try {
String[] args = {key};
cursor = storageEngine.rawQuery("SELECT value FROM info WHERE key=?", args);
if (cursor.moveToNext()) {
result = cursor.getString(0);
}
} catch (SQLException e) {
Log.e(TAG, "Error querying " + key, e);
} finally {
if (cursor != null) {
cursor.close();
}
}
return result;
}
@Override
public int getDocumentCount() {
String sql = "SELECT COUNT(DISTINCT doc_id) FROM revs WHERE current=1 AND deleted=0";
Cursor cursor = null;
int result = 0;
try {
cursor = storageEngine.rawQuery(sql, null);
if (cursor.moveToNext()) {
result = cursor.getInt(0);
}
} catch (SQLException e) {
Log.e(TAG, "Error getting document count", e);
} finally {
if (cursor != null) {
cursor.close();
}
}
return result;
}
/**
* The latest sequence number used. Every new revision is assigned a new sequence number,
* so this property increases monotonically as changes are made to the storageEngine. It can be
* used to check whether the storageEngine has changed between two points in time.
*/
public long getLastSequence() {
String sql = "SELECT MAX(sequence) FROM revs";
Cursor cursor = null;
long result = 0;
try {
cursor = storageEngine.rawQuery(sql, null);
if (cursor.moveToNext()) {
result = cursor.getLong(0);
}
} catch (SQLException e) {
Log.e(TAG, "Error getting last sequence", e);
} finally {
if (cursor != null) {
cursor.close();
}
}
return result;
}
/**
* Is a transaction active?
*/
@Override
public boolean inTransaction() {
return transactionLevel.get() > 0;
}
@Override
public void compact() throws CouchbaseLiteException {
Log.v(TAG, "Begin database compaction...");
synchronized (compactLock) {
boolean shouldCommit = false;
beginTransaction();
try {
if (getInfo("pruned") == null) {
// Bulk pruning is no longer needed, because revisions are pruned incrementally as new
// ones are added. But databases from before this feature was added (1.3) may have documents
// that need pruning. So we'll do a one-time bulk prune, then set a flag indicating that
// it isn't needed anymore.
pruneRevsToMaxDepth(maxRevTreeDepth);
setInfo("pruned", "true");
}
// Remove the JSON of non-current revisions, which is most of the space.
try {
Log.v(TAG, "Deleting JSON of old revisions...");
ContentValues args = new ContentValues();
args.put("json", (String) null);
args.put("doc_type", (String) null);
args.put("no_attachments", 1);
int changes = storageEngine.update("revs", args, "current=0", null);
Log.v(TAG, "... deleted %d revisions", changes);
} catch (SQLException e) {
Log.e(TAG, "Error compacting", e);
throw new CouchbaseLiteException(Status.INTERNAL_SERVER_ERROR);
}
shouldCommit = true;
} finally {
endTransaction(shouldCommit);
}
// https://www.sqlite.org/pragma.html#pragma_wal_checkpoint
Log.v(TAG, "Flushing SQLite WAL...");
try {
storageEngine.execSQL("PRAGMA wal_checkpoint(RESTART)");
} catch (SQLException e) {
Log.e(TAG, "Error PRAGMA wal_checkpoint(RESTART)", e);
throw new CouchbaseLiteException(Status.INTERNAL_SERVER_ERROR);
}
Log.v(TAG, "Vacuuming SQLite database...");
try {
storageEngine.execSQL("VACUUM");
} catch (SQLException e) {
Log.e(TAG, "Error vacuuming sqliteDb", e);
throw new CouchbaseLiteException(Status.INTERNAL_SERVER_ERROR);
}
}
Log.v(TAG, "...Finished database compaction.");
}
@Override
public boolean runInTransaction(TransactionalTask transactionalTask) {
boolean shouldCommit = true;
beginTransaction();
try {
shouldCommit = transactionalTask.run();
} catch (Exception e) {
shouldCommit = false;
Log.e(TAG, e.toString(), e);
throw new RuntimeException(e);
} finally {
endTransaction(shouldCommit);
}
return shouldCommit;
}
boolean runInOuterTransaction(TransactionalTask transactionalTask) {
if (!inTransaction())
return runInTransaction(transactionalTask);
return transactionalTask.run();
}
///////////////////////////////////////////////////////////////////////////
// DOCUMENTS:
///////////////////////////////////////////////////////////////////////////
@Override
public RevisionInternal getDocument(String docID, String revID, boolean withBody) {
long docNumericID = getDocNumericID(docID);
if (docNumericID < 0) {
return null;
}
RevisionInternal result = null;
String sql;
Cursor cursor = null;
try {
cursor = null;
String cols = "revid, deleted, sequence";
if (withBody) {
cols += ", json";
}
if (revID != null) {
sql = "SELECT " + cols + " FROM revs WHERE revs.doc_id=? AND revid=? AND json notnull LIMIT 1";
String[] args = {Long.toString(docNumericID), revID};
cursor = storageEngine.rawQuery(sql, args);
} else {
sql = "SELECT " + cols + " FROM revs WHERE revs.doc_id=? and current=1 and deleted=0 ORDER BY revid DESC LIMIT 1";
String[] args = {Long.toString(docNumericID)};
cursor = storageEngine.rawQuery(sql, args);
}
if (cursor.moveToNext()) {
if (revID == null) {
revID = cursor.getString(0);
}
boolean deleted = (cursor.getInt(1) > 0);
result = new RevisionInternal(docID, revID, deleted);
result.setSequence(cursor.getLong(2));
if (withBody) {
byte[] json = cursor.getBlob(3);
result.setJSON(json);
}
} else {
// revID != null?Status.NOT_FOUND:Status.DELTED
}
} catch (SQLException e) {
Log.e(TAG, "Error getting document with id and rev", e);
} finally {
if (cursor != null) {
cursor.close();
}
}
return result;
}
@Override
public RevisionInternal loadRevisionBody(RevisionInternal rev)
throws CouchbaseLiteException {
if (rev.getBody() != null && rev.getSequence() != 0) // no-op
return rev;
assert (rev.getDocID() != null && rev.getRevID() != null);
// SQLite read operation
long docNumericID = getDocNumericID(rev.getDocID());
if (docNumericID <= 0)
throw new CouchbaseLiteException(Status.NOT_FOUND);
Cursor cursor = null;
Status result = new Status(Status.NOT_FOUND);
try {
String sql = "SELECT sequence, json FROM revs WHERE doc_id=? AND revid=? LIMIT 1";
String[] args = {String.valueOf(docNumericID), rev.getRevID()};
cursor = storageEngine.rawQuery(sql, args);
if (cursor.moveToNext()) {
byte[] json = cursor.getBlob(1);
if (json != null) {
result.setCode(Status.OK);
rev.setSequence(cursor.getLong(0));
rev.setJSON(json);
}
}
} catch (SQLException e) {
Log.e(TAG, "Error loading revision body", e);
throw new CouchbaseLiteException(Status.INTERNAL_SERVER_ERROR);
} finally {
if (cursor != null) {
cursor.close();
}
}
if (result.getCode() == Status.NOT_FOUND) {
throw new CouchbaseLiteException(result);
}
return rev;
}
@Override
public RevisionInternal getParentRevision(RevisionInternal rev) {
// First get the parent's sequence:
long seq = rev.getSequence();
if (seq > 0) {
seq = SQLiteUtils.longForQuery(storageEngine,
"SELECT parent FROM revs WHERE sequence=?",
new String[]{Long.toString(seq)});
} else {
long docNumericID = getDocNumericID(rev.getDocID());
if (docNumericID <= 0) {
return null;
}
String[] args = new String[]{Long.toString(docNumericID), rev.getRevID()};
seq = SQLiteUtils.longForQuery(storageEngine,
"SELECT parent FROM revs WHERE doc_id=? and revid=?", args);
}
if (seq == 0) {
return null;
}
// Now get its revID and deletion status:
RevisionInternal result = null;
String[] args = {Long.toString(seq)};
String queryString = "SELECT revid, deleted FROM revs WHERE sequence=?";
Cursor cursor = null;
try {
cursor = storageEngine.rawQuery(queryString, args);
if (cursor.moveToNext()) {
String revId = cursor.getString(0);
boolean deleted = (cursor.getInt(1) > 0);
result = new RevisionInternal(rev.getDocID(), revId, deleted/*, this*/);
result.setSequence(seq);
}
} finally {
cursor.close();
}
return result;
}
/**
* Returns an array of TDRevs in reverse chronological order, starting with the given revision.
*/
@Override
public List<RevisionInternal> getRevisionHistory(RevisionInternal rev) {
String docId = rev.getDocID();
String revId = rev.getRevID();
assert ((docId != null) && (revId != null));
// SQlite read operation
long docNumericId = getDocNumericID(docId);
if (docNumericId < 0) {
return null;
} else if (docNumericId == 0) {
return new ArrayList<RevisionInternal>();
}
String sql = "SELECT sequence, parent, revid, deleted, json isnull FROM revs " +
"WHERE doc_id=? ORDER BY sequence DESC";
String[] args = {Long.toString(docNumericId)};
Cursor cursor = null;
List<RevisionInternal> result;
try {
cursor = storageEngine.rawQuery(sql, args);
cursor.moveToNext();
long lastSequence = 0;
result = new ArrayList<RevisionInternal>();
while (!cursor.isAfterLast()) {
long sequence = cursor.getLong(0);
boolean matches = false;
if (lastSequence == 0) {
matches = revId.equals(cursor.getString(2));
} else {
matches = (sequence == lastSequence);
}
if (matches) {
revId = cursor.getString(2);
boolean deleted = (cursor.getInt(3) > 0);
boolean missing = (cursor.getInt(4) > 0);
RevisionInternal aRev = new RevisionInternal(docId, revId, deleted);
aRev.setMissing(missing);
aRev.setSequence(cursor.getLong(0));
result.add(aRev);
lastSequence = cursor.getLong(1);
if (lastSequence == 0) {
break;
}
}
cursor.moveToNext();
}
} catch (SQLException e) {
Log.e(TAG, "Error getting revision history", e);
return null;
} finally {
if (cursor != null) {
cursor.close();
}
}
return result;
}
private RevisionList getAllRevisions(String docId, long docNumericID, boolean onlyCurrent) {
String sql = null;
if (onlyCurrent)
sql = "SELECT sequence, revid, deleted FROM revs " +
"WHERE doc_id=? AND current ORDER BY sequence DESC";
else
sql = "SELECT sequence, revid, deleted FROM revs " +
"WHERE doc_id=? ORDER BY sequence DESC";
String[] args = {Long.toString(docNumericID)};
Cursor cursor = storageEngine.rawQuery(sql, args);
RevisionList result = null;
try {
cursor.moveToNext();
result = new RevisionList();
while (!cursor.isAfterLast()) {
RevisionInternal rev = new RevisionInternal(docId,
cursor.getString(1),
(cursor.getInt(2) > 0));
rev.setSequence(cursor.getLong(0));
result.add(rev);
cursor.moveToNext();
}
} catch (SQLException e) {
return null;
} finally {
if (cursor != null)
cursor.close();
}
return result;
}
@Override
public List<String> getPossibleAncestorRevisionIDs(RevisionInternal rev,
int limit,
AtomicBoolean onlyAttachments) {
int generation = rev.getGeneration();
if (generation <= 1)
return null;
long docNumericID = getDocNumericID(rev.getDocID());
if (docNumericID <= 0)
return null;
List<String> revIDs = new ArrayList<String>();
int sqlLimit = limit > 0 ? (int) limit : -1; // SQL uses -1, not 0, to denote 'no limit'
StringBuilder sql = new StringBuilder("SELECT revid, sequence FROM revs WHERE doc_id=? and revid < ?");
sql.append(" and deleted=0 and json not null");
sql.append(" and no_attachments=0");
sql.append(" ORDER BY sequence DESC LIMIT ?");
String[] args = {Long.toString(docNumericID), generation + "-", Integer.toString(sqlLimit)};
Cursor cursor = null;
try {
cursor = storageEngine.rawQuery(sql.toString(), args);
cursor.moveToNext();
while (!cursor.isAfterLast()) {
if (onlyAttachments != null && revIDs.size() == 0)
onlyAttachments.set(sequenceHasAttachments(cursor.getLong(1)));
revIDs.add(cursor.getString(0));
cursor.moveToNext();
}
} catch (SQLException e) {
Log.e(TAG, "Error getting all revisions of document", e);
} finally {
if (cursor != null) {
cursor.close();
}
}
return revIDs;
}
/**
* Returns the most recent member of revIDs that appears in rev's ancestry.
*/
@Override
public String findCommonAncestorOf(RevisionInternal rev, List<String> revIDs) {
if (revIDs == null || revIDs.size() == 0)
return null;
long docNumericID = getDocNumericID(rev.getDocID());
if (docNumericID <= 0)
return null;
String quotedRevIds = TextUtils.joinQuoted(revIDs);
String sql = String.format(Locale.ENGLISH, "SELECT revid FROM revs " +
"WHERE doc_id=? and revid in (%s) and revid <= ? " +
"ORDER BY revid DESC LIMIT 1", quotedRevIds);
String[] args = {Long.toString(docNumericID), rev.getRevID()};
return SQLiteUtils.stringForQuery(storageEngine, sql, args);
}
@Override
public int findMissingRevisions(RevisionList touchRevs) throws SQLException {
int numRevisionsRemoved = 0;
if (touchRevs.size() == 0) {
return numRevisionsRemoved;
}
String quotedDocIds = TextUtils.joinQuoted(touchRevs.getAllDocIds());
String quotedRevIds = TextUtils.joinQuoted(touchRevs.getAllRevIds());
String sql = "SELECT docid, revid FROM revs, docs " +
"WHERE docid IN (" +
quotedDocIds +
") AND revid in (" +
quotedRevIds + ')' +
" AND revs.doc_id == docs.doc_id";
Cursor cursor = null;
try {
cursor = storageEngine.rawQuery(sql, null);
cursor.moveToNext();
while (!cursor.isAfterLast()) {
RevisionInternal rev = touchRevs.revWithDocIdAndRevId(cursor.getString(0),
cursor.getString(1));
if (rev != null) {
touchRevs.remove(rev);
numRevisionsRemoved += 1;
}
cursor.moveToNext();
}
} finally {
if (cursor != null) {
cursor.close();
}
}
return numRevisionsRemoved;
}
/**
* - (NSSet*) findAllAttachmentKeys: (NSError**)outError
*/
@Override
public Set<BlobKey> findAllAttachmentKeys() throws CouchbaseLiteException {
Set<BlobKey> allKeys = new HashSet<BlobKey>();
String sql = "SELECT json FROM revs WHERE no_attachments != 1";
Cursor cursor = null;
try {
cursor = storageEngine.rawQuery(sql, null);
cursor.moveToNext();
while (!cursor.isAfterLast()) {
byte[] json = cursor.getBlob(0);
if (json != null && json.length > 0) {
try {
Map<String, Object> docProperties = Manager.getObjectMapper().readValue(json, Map.class);
if (docProperties.containsKey("_attachments")) {
Map<String, Object> attachments = (Map<String, Object>) docProperties.get("_attachments");
Iterator<String> itr = attachments.keySet().iterator();
while (itr.hasNext()) {
String name = itr.next();
Map<String, Object> attachment = (Map<String, Object>) attachments.get(name);
String digest = (String) attachment.get("digest");
BlobKey key = new BlobKey(digest);
allKeys.add(key);
}
}
} catch (IOException e) {
Log.e(TAG, e.toString(), e);
}
}
cursor.moveToNext();
}
} finally {
if (cursor != null) {
cursor.close();
}
}
return allKeys;
}
/**
* - (CBLQueryIteratorBlock) getAllDocs: (CBLQueryOptions*)options
* status: (CBLStatus*)outStatus
*/
@Override
public Map<String, Object> getAllDocs(QueryOptions options) throws CouchbaseLiteException {
Map<String, Object> result = new HashMap<String, Object>();
List<QueryRow> rows = new ArrayList<QueryRow>();
if (options == null) {
options = new QueryOptions();
}
boolean includeDeletedDocs = (options.getAllDocsMode() == Query.AllDocsMode.INCLUDE_DELETED);
long updateSeq = 0;
if (options.isUpdateSeq()) {
updateSeq = getLastSequence(); // TODO: needs to be atomic with the following SELECT
}
// Generate the SELECT statement, based on the options:
StringBuilder sql = new StringBuilder("SELECT revs.doc_id, docid, revid, sequence");
if (options.isIncludeDocs()) {
sql.append(", json, no_attachments");
}
if (includeDeletedDocs) {
sql.append(", deleted");
}
sql.append(" FROM revs, docs WHERE");
if (options.getKeys() != null) {
if (options.getKeys().size() == 0) {
return result;
}
String commaSeperatedIds = TextUtils.joinQuotedObjects(options.getKeys());
sql.append(String.format(Locale.ENGLISH, " revs.doc_id IN (SELECT doc_id FROM docs WHERE docid IN (%s)) AND",
commaSeperatedIds));
}
sql.append(" docs.doc_id = revs.doc_id AND current=1");
if (!includeDeletedDocs) {
sql.append(" AND deleted=0");
}
List<String> args = new ArrayList<String>();
Object minKey = options.getStartKey();
Object maxKey = options.getEndKey();
boolean inclusiveMin = true;
boolean inclusiveMax = options.isInclusiveEnd();
if (options.isDescending()) {
minKey = maxKey;
maxKey = options.getStartKey();
inclusiveMin = inclusiveMax;
inclusiveMax = true;
}
if (minKey != null) {
assert (minKey instanceof String);
sql.append((inclusiveMin ? " AND docid >= ?" : " AND docid > ?"));
args.add((String) minKey);
}
if (maxKey != null) {
assert (maxKey instanceof String);
maxKey = View.keyForPrefixMatch(maxKey, options.getPrefixMatchLevel());
sql.append((inclusiveMax ? " AND docid <= ?" : " AND docid < ?"));
args.add((String) maxKey);
}
sql.append(
String.format(Locale.ENGLISH,
" ORDER BY docid %s, %s revid DESC LIMIT ? OFFSET ?",
(options.isDescending() ? "DESC" : "ASC"),
(includeDeletedDocs ? "deleted ASC," : "")
)
);
args.add(Integer.toString(options.getLimit()));
args.add(Integer.toString(options.getSkip()));
// Now run the database query:
Cursor cursor = null;
Map<String, QueryRow> docs = new HashMap<String, QueryRow>();
try {
// Get row values now, before the code below advances 'cursor':
cursor = storageEngine.rawQuery(sql.toString(), args.toArray(new String[args.size()]));
boolean keepGoing = cursor.moveToNext(); // Go to first result row
while (keepGoing) {
long docNumericID = cursor.getLong(0);
String docID = cursor.getString(1);
String revID = cursor.getString(2);
long sequence = cursor.getLong(3);
boolean deleted = includeDeletedDocs && cursor.getInt(getDeletedColumnIndex(options)) > 0;
RevisionInternal docRevision = null;
if (options.isIncludeDocs()) {
//docRevision = revision(docID, revID, deleted, sequence, cursor.getBlob(4));
byte[] json = cursor.getBlob(4);
Map<String, Object> properties = documentPropertiesFromJSON(json, docID, revID,
false, sequence);
docRevision = revision(
docID, // docID
revID, // revID
false, // deleted
sequence, // sequence
properties// properties
);
}
// Iterate over following rows with the same doc_id -- these are conflicts.
// Skip them, but collect their revIDs if the 'conflicts' option is set:
List<String> conflicts = new ArrayList<String>();
while (((keepGoing = cursor.moveToNext()) == true) && cursor.getLong(0) == docNumericID) {
if (options.getAllDocsMode() == Query.AllDocsMode.SHOW_CONFLICTS ||
options.getAllDocsMode() == Query.AllDocsMode.ONLY_CONFLICTS) {
if (conflicts.isEmpty()) {
conflicts.add(revID);
}
conflicts.add(cursor.getString(2));
}
}
if (options.getAllDocsMode() == Query.AllDocsMode.ONLY_CONFLICTS && conflicts.isEmpty())
continue;
Map<String, Object> value = new HashMap<String, Object>();
value.put("rev", revID);
value.put("_conflicts", conflicts);
if (includeDeletedDocs) {
value.put("deleted", (deleted ? true : null));
}
QueryRow change = new QueryRow(docID,
sequence,
docID,
value,
docRevision);
if (options.getKeys() != null)
docs.put(docID, change);
// TODO: In the future, we need to implement CBLRowPassesFilter() in CBLView+Querying.m
else if (options.getPostFilter() == null || options.getPostFilter().apply(change))
rows.add(change);
}
// If given doc IDs, sort the output into that order, and add entries for missing docs:
if (options.getKeys() != null) {
for (Object docIdObject : options.getKeys()) {
if (docIdObject instanceof String) {
String docID = (String) docIdObject;
QueryRow change = docs.get(docID);
if (change == null) {
Map<String, Object> value = new HashMap<String, Object>();
long docNumericID = getDocNumericID(docID);
if (docNumericID > 0) {
boolean deleted;
AtomicBoolean outIsDeleted = new AtomicBoolean(false);
String revID = winningRevIDOfDocNumericID(docNumericID, outIsDeleted, null);
if (revID != null) {
value.put("rev", revID);
value.put("deleted", true);
}
}
change = new QueryRow((value != null ? docID : null), 0, docID, value, null);
}
// TODO add options.filter
rows.add(change);
}
}
}
} catch (SQLException e) {
Log.e(TAG, "Error getting all docs", e);
throw new CouchbaseLiteException("Error getting all docs", e, new Status(Status.INTERNAL_SERVER_ERROR));
} finally {
if (cursor != null) {
cursor.close();
}
}
result.put("rows", rows);
result.put("total_rows", rows.size());
result.put("offset", options.getSkip());
if (updateSeq != 0) {
result.put("update_seq", updateSeq);
}
return result;
}
@Override
public RevisionList changesSince(long lastSequence,
ChangesOptions options,
ReplicationFilter filter,
Map<String, Object> filterParams) {
// http://wiki.apache.org/couchdb/HTTP_database_API#Changes
if (options == null) {
options = new ChangesOptions();
}
RevisionList changes = new RevisionList();
boolean includeDocs = options.isIncludeDocs() || (filter != null);
String additionalSelectColumns = "";
if (includeDocs) {
additionalSelectColumns = ", json";
}
String sql = "SELECT sequence, revs.doc_id, docid, revid, deleted" + additionalSelectColumns
+ " FROM revs, docs "
+ "WHERE sequence > ? AND current=1 "
+ "AND revs.doc_id = docs.doc_id "
+ "ORDER BY revs.doc_id, revid DESC";
String[] args = {Long.toString(lastSequence)};
Cursor cursor = storageEngine.rawQuery(sql, args);
cursor.moveToNext();
long lastDocId = 0;
try {
while (!cursor.isAfterLast()) {
if (!options.isIncludeConflicts()) {
// Only count the first rev for a given doc (the rest will be losing conflicts):
long docNumericId = cursor.getLong(1);
if (docNumericId == lastDocId) {
cursor.moveToNext();
continue;
}
lastDocId = docNumericId;
}
RevisionInternal rev = new RevisionInternal(
cursor.getString(2), cursor.getString(3), (cursor.getInt(4) > 0));
rev.setSequence(cursor.getLong(0));
if (includeDocs)
rev.setJSON(cursor.getBlob(5));
changes.add(rev);
cursor.moveToNext();
}
} catch (SQLException e) {
Log.e(TAG, "Error looking for changes", e);
} finally {
if (cursor != null) {
cursor.close();
}
}
// Note: To minimize holding SQLite connection, executing filter out-of SQLite query.
if (filter != null) {
// to avoid to create another list, filter from end to front.
for (int i = changes.size() - 1; i >= 0; i--) {
if (!delegate.runFilter(filter, filterParams, changes.get(i)))
changes.remove(i);
}
}
if (options.isSortBySequence()) {
changes.sortBySequence();
}
changes.limit(options.getLimit());
return changes;
}
///////////////////////////////////////////////////////////////////////////
// INSERTION / DELETION:
///////////////////////////////////////////////////////////////////////////
/**
* Creates a new revision of a document.
* On success, before returning the new CBL_Revision, the implementation will also call the
* delegate's -databaseStorageChanged: method to give it more details about the change.
*
* @param docID The document ID, or nil if an ID should be generated at random.
* @param prevRevID The parent revision ID, or nil if creating a new document.
* @param properties The new revision's properties. (Metadata other than "_attachments" ignored.)
* @param deleting YES if this revision is a deletion.
* @param allowConflict YES if this operation is allowed to create a conflict; otherwise a 409,
* status will be returned if the parent revision is not a leaf.
* @param validationBlock If non-nil, this block will be called before the revision is added.
* It's given the parent revision, with its properties if available, and can reject
* the operation by returning an error status.
* @param outStatus On return a status will be stored here. Note that on success, the
* status should be 201 for a created revision but 200 for a deletion.
* @return The new revision, with its revID and sequence filled in, or nil on error.
*/
@Override
@InterfaceAudience.Private
public RevisionInternal add(
String docID,
String prevRevID,
Map<String, Object> properties,
boolean deleting,
boolean allowConflict,
StorageValidation validationBlock,
Status outStatus)
throws CouchbaseLiteException {
byte[] json;
if (properties != null && properties.size() > 0) {
json = RevisionUtils.asCanonicalJSON(properties);
if (json == null)
throw new CouchbaseLiteException(Status.BAD_JSON);
} else {
json = "{}".getBytes();
}
RevisionInternal newRev = null;
String winningRevID = null;
boolean inConflict = false;
beginTransaction();
// try - finally for beginTransaction() and endTransaction()
try {
//// PART I: In which are performed lookups and validations prior to the insert...
// Get the doc's numeric ID (doc_id) and its current winning revision:
AtomicBoolean isNewDoc = new AtomicBoolean(prevRevID == null);
long docNumericID = -1;
if (docID != null) {
docNumericID = createOrGetDocNumericID(docID, isNewDoc);
if (docNumericID <= 0)
// TODO: error
throw new CouchbaseLiteException(Status.UNKNOWN);
} else {
docNumericID = 0;
isNewDoc.set(true);
}
AtomicBoolean oldWinnerWasDeletion = new AtomicBoolean(false);
AtomicBoolean wasConflicted = new AtomicBoolean(false);
String oldWinningRevID = null;
if (!isNewDoc.get()) {
// Look up which rev is the winner, before this insertion
//OPT: This rev ID could be cached in the 'docs' row
oldWinningRevID = winningRevIDOfDocNumericID(docNumericID, oldWinnerWasDeletion, wasConflicted);
}
long parentSequence = 0;
if (prevRevID != null) {
// Replacing: make sure given prevRevID is current & find its sequence number:
if (isNewDoc.get())
throw new CouchbaseLiteException(Status.NOT_FOUND);
parentSequence = getSequenceOfDocument(docNumericID, prevRevID, !allowConflict);
if (parentSequence <= 0) { // -1 if not found
// Not found: either a 404 or a 409, depending on whether there is any current revision
if (!allowConflict && existsDocument(docID, null)) {
throw new CouchbaseLiteException(Status.CONFLICT);
} else {
throw new CouchbaseLiteException(Status.NOT_FOUND);
}
}
} else {
// Inserting first revision.
if (deleting && docID != null) {
// Didn't specify a revision to delete: 404 or a 409, depending
if (existsDocument(docID, null))
throw new CouchbaseLiteException(Status.CONFLICT);
else
throw new CouchbaseLiteException(Status.NOT_FOUND);
}
if (docID != null) {
// Inserting first revision, with docID given (PUT):
// Doc ID exists; check whether current winning revision is deleted:
if (oldWinnerWasDeletion.get() == true) {
prevRevID = oldWinningRevID;
parentSequence = getSequenceOfDocument(docNumericID, prevRevID, false);
} else if (oldWinningRevID != null) {
// The current winning revision is not deleted, so this is a conflict
throw new CouchbaseLiteException(Status.CONFLICT);
}
} else {
// Inserting first revision, with no docID given (POST): generate a unique docID:
docID = Misc.CreateUUID();
docNumericID = createOrGetDocNumericID(docID, isNewDoc);
if (docNumericID <= 0)
return null;
}
}
// There may be a conflict if (a) the document was already in conflict, or
// (b) a conflict is created by adding a non-deletion child of a non-winning rev.
inConflict = wasConflicted.get() ||
(!deleting &&
prevRevID != null &&
oldWinningRevID != null &&
!prevRevID.equals(oldWinningRevID));
//// PART II: In which we prepare for insertion...
// Bump the revID and update the JSON:
String newRevId = delegate.generateRevID(json, deleting, prevRevID);
if (newRevId == null)
throw new CouchbaseLiteException(Status.BAD_ID); // invalid previous revID (no numeric prefix)
assert (docID != null);
newRev = new RevisionInternal(docID, newRevId, deleting);
if (properties != null) {
properties.put("_id", docID);
properties.put("_rev", newRevId);
newRev.setProperties(properties);
}
// Validate:
if (validationBlock != null) {
// Fetch the previous revision and validate the new one against it:
RevisionInternal prevRev = null;
if (prevRevID != null)
prevRev = new RevisionInternal(docID, prevRevID, false);
Status status = validationBlock.validate(newRev, prevRev, prevRevID);
if (status.isError()) {
outStatus.setCode(status.getCode());
throw new CouchbaseLiteException(status);
}
}
// Don't store a SQL null in the 'json' column -- I reserve it to mean that the revision data
// is missing due to compaction or replication.
// Instead, store an empty zero-length blob.
if (json == null)
json = new byte[0];
//// PART III: In which the actual insertion finally takes place:
boolean hasAttachments = properties == null ? false :
properties.get("_attachments") != null;
String docType = null;
if (properties != null && properties.containsKey("type") && properties.get("type") instanceof String)
docType = (String) properties.get("type");
long sequence = 0;
try {
sequence = insertRevision(newRev,
docNumericID,
parentSequence,
true,
hasAttachments,
json,
docType);
} catch (SQLException ex) {
// The insert failed. If it was due to a constraint violation, that means a revision
// already exists with identical contents and the same parent rev. We can ignore this
// insert call, then.
if (ex.getCode() != SQLException.SQLITE_CONSTRAINT) {
Log.e(TAG, "Error inserting revision: ", ex);
throw new CouchbaseLiteException(Status.INTERNAL_SERVER_ERROR);
}
Log.w(TAG, "Duplicate rev insertion: " + docID + " / " + newRevId);
newRev.setBody(null);
// The pre-existing revision may have a nulled-out parent link since its original
// parent may have been pruned earlier. Fix that link:
if (parentSequence != 0) {
try {
ContentValues args = new ContentValues();
args.put("parent", parentSequence);
storageEngine.update("revs", args, "doc_id=? and revid=?",
new String[]{String.valueOf(docNumericID), newRevId});
} catch (SQLException e) {
throw new CouchbaseLiteException(e, Status.INTERNAL_SERVER_ERROR);
}
}
// Keep going, to make the parent rev non-current, before returning...
}
// Make replaced rev non-current:
if (parentSequence > 0) {
try {
ContentValues args = new ContentValues();
args.put("current", 0);
args.put("doc_type", (String) null);
storageEngine.update("revs", args, "sequence=?", new String[]{String.valueOf(parentSequence)});
} catch (SQLException e) {
Log.e(TAG, "Error setting parent rev non-current", e);
storageEngine.delete("revs", "sequence=?", new String[]{String.valueOf(sequence)});
throw new CouchbaseLiteException(e, Status.INTERNAL_SERVER_ERROR);
}
}
if (sequence <= 0) {
// duplicate rev; see above
outStatus.setCode(Status.OK);
if (newRev.getSequence() != 0)
delegate.databaseStorageChanged(new DocumentChange(newRev, winningRevID, inConflict, null));
return newRev;
}
// Delete the deepest revs in the tree to enforce the maxRevTreeDepth:
int minGenToKeep = newRev.getGeneration() - maxRevTreeDepth + 1;
if (minGenToKeep > 1) {
int pruned = pruneDocument(docID, docNumericID, minGenToKeep);
if (pruned > 0)
Log.v(TAG, "Pruned %d old revisions of doc '%s'", pruned, docID);
}
// Figure out what the new winning rev ID is:
winningRevID = winner(docNumericID, oldWinningRevID, oldWinnerWasDeletion.get(), newRev);
// Success!
if (deleting) {
outStatus.setCode(Status.OK);
} else {
outStatus.setCode(Status.CREATED);
}
} finally {
endTransaction(outStatus.isSuccessful());
}
//// EPILOGUE: A change notification is sent...
if (newRev.getSequence() != 0)
delegate.databaseStorageChanged(new DocumentChange(newRev, winningRevID, inConflict, null));
return newRev;
}
/**
* Inserts an already-existing revision replicated from a remote sqliteDb.
* <p/>
* It must already have a revision ID. This may create a conflict! The revision's history must be given; ancestor revision IDs that don't already exist locally will create phantom revisions with no content.
*
* @exclude in CBLDatabase+Insertion.m
* - (CBLStatus) forceInsert: (CBL_Revision*)inRev
* revisionHistory: (NSArray*)history // in *reverse* order, starting with rev's revID
* source: (NSURL*)source
*/
@Override
@InterfaceAudience.Private
public void forceInsert(RevisionInternal inRev,
List<String> history,
StorageValidation validationBlock,
URL source)
throws CouchbaseLiteException {
Status status = new Status(Status.UNKNOWN);
RevisionInternal rev = inRev.copy();
rev.setSequence(0);
String docID = rev.getDocID();
String winningRevID = null;
AtomicBoolean inConflict = new AtomicBoolean(false);
boolean success = false;
beginTransaction();
try {
// First look up the document's row-id and all locally-known revisions of it:
Map<String, RevisionInternal> localRevs = null;
String oldWinningRevID = null;
AtomicBoolean oldWinnerWasDeletion = new AtomicBoolean(false);
AtomicBoolean isNewDoc = new AtomicBoolean(history.size() == 1);
long docNumericID = createOrGetDocNumericID(docID, isNewDoc);
if (docNumericID <= 0)
throw new CouchbaseLiteException(Status.INTERNAL_SERVER_ERROR);
if (!isNewDoc.get()) {
RevisionList localRevsList = getAllRevisions(docID, docNumericID, false);
if (localRevsList == null)
throw new CouchbaseLiteException(Status.INTERNAL_SERVER_ERROR);
localRevs = new HashMap<String, RevisionInternal>();
for (RevisionInternal r : localRevsList)
localRevs.put(r.getRevID(), r);
// Look up which rev is the winner, before this insertion
oldWinningRevID = winningRevIDOfDocNumericID(
docNumericID,
oldWinnerWasDeletion,
inConflict);
}
// Validate against the latest common ancestor:
if (validationBlock != null) {
RevisionInternal oldRev = null;
for (int i = 1; i < history.size(); i++) {
oldRev = (localRevs != null) ? localRevs.get(history.get(i)) : null;
if (oldRev != null) {
break;
}
}
String parentRevId = (history.size() > 1) ? history.get(1) : null;
Status tmpStatus = validationBlock.validate(rev, oldRev, parentRevId);
if (tmpStatus.isError()) {
throw new CouchbaseLiteException(tmpStatus);
}
}
// Walk through the remote history in chronological order, matching each revision ID to
// a local revision. When the list diverges, start creating blank local revisions to
// fill in the local history:
long sequence = 0;
long localParentSequence = 0;
for (int i = history.size() - 1; i >= 0; --i) {
String revID = history.get(i);
RevisionInternal localRev = (localRevs != null) ? localRevs.get(revID) : null;
if (localRev != null) {
// This revision is known locally. Remember its sequence as the parent of
// the next one:
sequence = localRev.getSequence();
assert (sequence > 0);
localParentSequence = sequence;
} else {
// This revision isn't known, so add it:
RevisionInternal newRev = null;
byte[] json = null;
String docType = null;
boolean current = false;
if (i == 0) {
// Hey, this is the leaf revision we're inserting:
newRev = rev;
json = RevisionUtils.asCanonicalJSON(inRev);
if (json == null)
throw new CouchbaseLiteException(Status.BAD_JSON);
Object obj = rev.getObject("type");
if (obj != null && obj instanceof String)
docType = (String) obj;
current = true;
} else {
// It's an intermediate parent, so insert a stub:
newRev = new RevisionInternal(docID, revID, false);
}
// Insert it:
sequence = insertRevision(
newRev,
docNumericID,
sequence,
current,
(newRev.getAttachments() != null && newRev.getAttachments().size() > 0),
json,
docType);
if (sequence <= 0)
throw new CouchbaseLiteException(Status.INTERNAL_SERVER_ERROR);
}
}
if (localParentSequence == sequence) {
success = true; // No-op: No new revisions were inserted.
status.setCode(Status.OK);
}
// Mark the latest local rev as no longer current:
else if (localParentSequence > 0) {
ContentValues args = new ContentValues();
args.put("current", 0);
args.put("doc_type", (String) null);
String[] whereArgs = {Long.toString(localParentSequence)};
int numRowsChanged = 0;
try {
numRowsChanged = storageEngine.update("revs", args, "sequence=? AND current!=0", whereArgs);
if (numRowsChanged == 0)
inConflict.set(true); // local parent wasn't a leaf, ergo we just created a branch
} catch (SQLException e) {
throw new CouchbaseLiteException(Status.INTERNAL_SERVER_ERROR);
}
}
// Delete the deepest revs in the tree to enforce the maxRevTreeDepth:
int gen = inRev.getGeneration();
if (localRevs != null && gen > maxRevTreeDepth) {
int minGen = gen;
int maxGen = gen;
for (RevisionInternal r : localRevs.values()) {
int generation = r.getGeneration();
minGen = Math.min(minGen, generation);
maxGen = Math.max(maxGen, generation);
}
int minGenToKeep = maxGen - maxRevTreeDepth + 1;
if (minGen < minGenToKeep) {
int pruned = pruneDocument(docID, docNumericID, minGenToKeep);
if (pruned > 0)
Log.v(TAG, "Pruned %d old revisions of doc '%s'", pruned, docID);
}
}
if (!success) {
// Figure out what the new winning rev ID is:
winningRevID = winner(docNumericID, oldWinningRevID, oldWinnerWasDeletion.get(), rev);
success = true;
status.setCode(Status.CREATED);
}
} catch (SQLException e) {
Log.e(TAG, "Error inserting revisions", e);
throw new CouchbaseLiteException(Status.INTERNAL_SERVER_ERROR);
} finally {
endTransaction(success);
}
// Notify and return:
if (status.getCode() == Status.CREATED)
delegate.databaseStorageChanged(new DocumentChange(rev, winningRevID, inConflict.get(), source));
else if (status.isError())
throw new CouchbaseLiteException(status);
}
/**
* Purges specific revisions, which deletes them completely from the local storageEngine _without_ adding a "tombstone" revision. It's as though they were never there.
* This operation is described here: http://wiki.apache.org/couchdb/Purge_Documents
*
* @param docsToRevs A dictionary mapping document IDs to arrays of revision IDs.
* @resultOn success will point to an NSDictionary with the same form as docsToRev, containing the doc/revision IDs that were actually removed.
*/
@Override
@InterfaceAudience.Private
public Map<String, Object> purgeRevisions(final Map<String, List<String>> docsToRevs) {
final Map<String, Object> result = new HashMap<String, Object>();
runInTransaction(new TransactionalTask() {
@Override
public boolean run() {
for (String docID : docsToRevs.keySet()) {
long docNumericID = getDocNumericID(docID);
if (docNumericID == -1) {
continue; // no such document, skip it
}
List<String> revsPurged = new ArrayList<String>();
List<String> revIDs = (List<String>) docsToRevs.get(docID);
if (revIDs == null) {
return false;
} else if (revIDs.size() == 0) {
revsPurged = new ArrayList<String>();
} else if (revIDs.contains("*")) {
// Delete all revisions if magic "*" revision ID is given:
try {
String[] args = {Long.toString(docNumericID)};
storageEngine.execSQL("DELETE FROM revs WHERE doc_id=?", args);
} catch (SQLException e) {
Log.e(TAG, "Error deleting revisions", e);
return false;
}
revsPurged = new ArrayList<String>();
revsPurged.add("*");
} else {
// Iterate over all the revisions of the doc, in reverse sequence order.
// Keep track of all the sequences to delete, i.e. the given revs and ancestors,
// but not any non-given leaf revs or their ancestors.
Cursor cursor = null;
try {
String[] args = {Long.toString(docNumericID)};
String queryString = "SELECT revid, sequence, parent FROM revs WHERE doc_id=? ORDER BY sequence DESC";
cursor = storageEngine.rawQuery(queryString, args);
if (!cursor.moveToNext()) {
Log.w(TAG, "No results for query: %s", queryString);
return false;
}
Set<Long> seqsToPurge = new HashSet<Long>();
Set<Long> seqsToKeep = new HashSet<Long>();
Set<String> revsToPurge = new HashSet<String>();
while (!cursor.isAfterLast()) {
String revID = cursor.getString(0);
long sequence = cursor.getLong(1);
long parent = cursor.getLong(2);
if (seqsToPurge.contains(sequence) || revIDs.contains(revID) && !seqsToKeep.contains(sequence)) {
// Purge it and maybe its parent:
seqsToPurge.add(sequence);
revsToPurge.add(revID);
if (parent > 0) {
seqsToPurge.add(parent);
}
} else {
// Keep it and its parent:
seqsToPurge.remove(sequence);
revsToPurge.remove(revID);
seqsToKeep.add(parent);
}
cursor.moveToNext();
}
seqsToPurge.removeAll(seqsToKeep);
Log.i(TAG, "Purging doc '%s' revs (%s)", docID, revIDs);
// Now delete the sequences to be purged.
if (!purgeSequences(seqsToPurge))
return false;
revsPurged.addAll(revsToPurge);
} catch (SQLException e) {
Log.e(TAG, "Error getting revisions", e);
return false;
} finally {
if (cursor != null) {
cursor.close();
}
}
}
result.put(docID, revsPurged);
}
return true;
}
});
return result;
}
private boolean purgeSequences(Set<Long> seqsToPurge) {
if (seqsToPurge.size() == 0)
return true;
String seqsString = TextUtils.join(",", seqsToPurge);
Log.v(TAG, " purging %d sequences: %s", seqsToPurge.size(), seqsString);
String sql = String.format(Locale.ENGLISH, "DELETE FROM revs WHERE sequence in (%s)", seqsString);
try {
storageEngine.execSQL(sql);
} catch (SQLException e) {
Log.e(TAG, "Error deleting revisions via: " + sql, e);
return false;
}
return true;
}
///////////////////////////////////////////////////////////////////////////
// EXPIRATION:
///////////////////////////////////////////////////////////////////////////
/**
* @return Java Time
*/
@Override
public long expirationOfDocument(String docID) {
return SQLiteUtils.longForQuery(storageEngine,
"SELECT expiry_timestamp FROM docs WHERE docid=?",
new String[]{docID}) * 1000L;
}
@Override
public boolean setExpirationOfDocument(long unixTime, String docID) {
try {
ContentValues values = new ContentValues();
values.put("expiry_timestamp", unixTime);
String[] whereArgs = {docID};
int rowsUpdated = storageEngine.update("docs", values, "docid=?", whereArgs);
return rowsUpdated > 0 ? true : false;
} catch (SQLException e) {
Log.w(TAG, "Failed to update expiry_timestamp for docID=%s", e, docID);
return false;
}
}
/**
* @return Java Time
*/
@Override
public long nextDocumentExpiry() {
return SQLiteUtils.longForQuery(storageEngine,
"SELECT MIN(expiry_timestamp) FROM docs WHERE expiry_timestamp not null and expiry_timestamp != 0",
null) * 1000L;
}
@Override
public int purgeExpiredDocuments() {
final AtomicInteger nPurged = new AtomicInteger(0);
runInOuterTransaction(new TransactionalTask() {
@Override
public boolean run() {
if (storageEngine == null)
return false;
long nowUnixTime = System.currentTimeMillis() / 1000L;
invalidateDocNumericIDs();
String[] args = {String.valueOf(nowUnixTime)};
// First capture the docIDs to be purged, so we can notify about them:
List<String> purgedIDs = new ArrayList<String>();
String queryString = "SELECT docid FROM docs WHERE expiry_timestamp <= ? and expiry_timestamp != 0";
Cursor cursor = storageEngine.rawQuery(queryString, args);
try {
cursor.moveToNext();
while (!cursor.isAfterLast()) {
purgedIDs.add(cursor.getString(0));
cursor.moveToNext();
}
} finally {
cursor.close();
}
// Now delete the docs:
try {
int count = storageEngine.delete("docs", "expiry_timestamp <= ? and expiry_timestamp != 0", args);
Log.v(TAG, "purged doc count: %d/%d", count, purgedIDs.size());
} catch (SQLException e) {
Log.w(TAG, "Failed to delete from docs expiry_timestamp <= %d", e, nowUnixTime);
return false;
}
// Finally notify:
for (String docID : purgedIDs)
notifyPurgedDocument(docID);
nPurged.set(purgedIDs.size());
return true;
}
});
return nPurged.get();
}
private void notifyPurgedDocument(String docID) {
delegate.databaseStorageChanged(new DocumentChange(docID));
}
///////////////////////////////////////////////////////////////////////////
// VIEWS:
///////////////////////////////////////////////////////////////////////////
/**
* Instantiates storage for a view.
*
* @param name The name of the view
* @param create If YES, the view should be created; otherwise it must already exist
* @return Storage for the view, or nil if create=NO and it doesn't exist.
*/
public ViewStore getViewStorage(String name, boolean create) throws CouchbaseLiteException {
return new SQLiteViewStore(this, name, create);
}
@Override
public List<String> getAllViewNames() {
Cursor cursor = null;
List<String> result = null;
try {
cursor = storageEngine.rawQuery("SELECT name FROM views", null);
cursor.moveToNext();
result = new ArrayList<String>();
while (!cursor.isAfterLast()) {
//result.add(delegate.getView(cursor.getString(0)));
result.add(cursor.getString(0));
cursor.moveToNext();
}
} catch (Exception e) {
Log.e(TAG, "Error getting all views", e);
} finally {
if (cursor != null) {
cursor.close();
}
}
return result;
}
///////////////////////////////////////////////////////////////////////////
// LOCAL DOCS:
///////////////////////////////////////////////////////////////////////////
@Override
public RevisionInternal getLocalDocument(String docID, String revID) {
// docID already should contain "_local/" prefix
RevisionInternal result = null;
Cursor cursor = null;
try {
String[] args = {docID};
cursor = storageEngine.rawQuery("SELECT revid, json FROM localdocs WHERE docid=?", args);
if (cursor.moveToNext()) {
String gotRevID = cursor.getString(0);
if (revID != null && (!revID.equals(gotRevID))) {
return null;
}
byte[] json = cursor.getBlob(1);
Map<String, Object> properties = null;
try {
properties = Manager.getObjectMapper().readValue(json, Map.class);
properties.put("_id", docID);
properties.put("_rev", gotRevID);
result = new RevisionInternal(docID, gotRevID, false);
result.setProperties(properties);
} catch (Exception e) {
Log.w(TAG, "Error parsing local doc JSON", e);
return null;
}
}
return result;
} catch (SQLException e) {
Log.e(TAG, "Error getting local document", e);
return null;
} finally {
if (cursor != null) {
cursor.close();
}
}
}
@Override
public RevisionInternal putLocalRevision(RevisionInternal revision, String prevRevID, boolean obeyMVCC)
throws CouchbaseLiteException {
String docID = revision.getDocID();
if (!docID.startsWith("_local/")) {
throw new CouchbaseLiteException(Status.BAD_REQUEST);
}
if (!obeyMVCC) {
return putLocalRevisionNoMVCC(revision);
} else if (!revision.isDeleted()) {
// PUT:
byte[] json = RevisionUtils.asCanonicalJSON(revision);
String newRevID;
if (prevRevID != null) {
int generation = RevisionInternal.generationFromRevID(prevRevID);
if (generation == 0) {
throw new CouchbaseLiteException(Status.BAD_REQUEST);
}
newRevID = Integer.toString(++generation) + "-local";
ContentValues values = new ContentValues();
values.put("revid", newRevID);
values.put("json", json);
String[] whereArgs = {docID, prevRevID};
try {
int rowsUpdated = storageEngine.update("localdocs", values, "docid=? AND revid=?", whereArgs);
if (rowsUpdated == 0) {
throw new CouchbaseLiteException(Status.CONFLICT);
}
} catch (SQLException e) {
throw new CouchbaseLiteException(e, Status.INTERNAL_SERVER_ERROR);
}
} else {
newRevID = "1-local";
ContentValues values = new ContentValues();
values.put("docid", docID);
values.put("revid", newRevID);
values.put("json", json);
try {
storageEngine.insertWithOnConflict("localdocs", null, values, SQLiteStorageEngine.CONFLICT_IGNORE);
} catch (SQLException e) {
throw new CouchbaseLiteException(e, Status.INTERNAL_SERVER_ERROR);
}
}
return revision.copyWithDocID(docID, newRevID);
} else {
// DELETE:
deleteLocalDocument(docID, prevRevID);
return revision;
}
}
/**
* - (CBL_Revision*) putLocalRevisionNoMVCC: (CBL_Revision*)revision
* status: (CBLStatus*)outStatus
*/
protected RevisionInternal putLocalRevisionNoMVCC(final RevisionInternal revision)
throws CouchbaseLiteException {
RevisionInternal result = null;
boolean commit = false;
beginTransaction();
try {
RevisionInternal prevRev = getLocalDocument(revision.getDocID(), null);
result = putLocalRevision(revision, prevRev == null ? null : prevRev.getRevID(), true);
commit = true;
} finally {
endTransaction(commit);
}
return result;
}
@Override
public RevisionList getAllRevisions(String docID, boolean onlyCurrent) {
long docNumericId = getDocNumericID(docID);
if (docNumericId < 0) {
return null;
} else if (docNumericId == 0) {
return new RevisionList();
} else {
return getAllRevisions(docID, docNumericId, onlyCurrent);
}
}
///////////////////////////////////////////////////////////////////////////
// Internal (PROTECTED & PRIVATE) METHODS
///////////////////////////////////////////////////////////////////////////
protected SQLiteStorageEngine getStorageEngine() {
return storageEngine;
}
private boolean existsDocument(String docID, String revID) {
return getDocument(docID, revID, false) != null;
}
private void deleteLocalDocument(String docID, String revID) throws CouchbaseLiteException {
if (docID == null) {
throw new CouchbaseLiteException(Status.BAD_REQUEST);
}
if (revID == null) {
// Didn't specify a revision to delete: 404 or a 409, depending
if (getLocalDocument(docID, null) != null) {
throw new CouchbaseLiteException(Status.CONFLICT);
} else {
throw new CouchbaseLiteException(Status.NOT_FOUND);
}
}
String[] whereArgs = {docID, revID};
try {
int rowsDeleted = storageEngine.delete("localdocs", "docid=? AND revid=?", whereArgs);
if (rowsDeleted == 0) {
if (getLocalDocument(docID, null) != null) {
throw new CouchbaseLiteException(Status.CONFLICT);
} else {
throw new CouchbaseLiteException(Status.NOT_FOUND);
}
}
} catch (SQLException e) {
throw new CouchbaseLiteException(e, Status.INTERNAL_SERVER_ERROR);
}
}
/**
* Returns the rev ID of the 'winning' revision of this document, and whether it's deleted.
* <p/>
* in CBLDatabase+Internal.m
* - (NSString*) winningRevIDOfDocNumericID: (SInt64)docNumericID
* isDeleted: (BOOL*)outIsDeleted
* isConflict: (BOOL*)outIsConflict // optional
* status: (CBLStatus*)outStatus
*/
protected String winningRevIDOfDocNumericID(long docNumericId,
AtomicBoolean outIsDeleted,
AtomicBoolean outIsConflict) // optional
throws CouchbaseLiteException {
assert (docNumericId > 0);
Cursor cursor = null;
String sql = "SELECT revid, deleted FROM revs" +
" WHERE doc_id=? and current=1" +
" ORDER BY deleted asc, revid desc LIMIT ?";
long limit = (outIsConflict != null && outIsConflict.get()) ? 2 : 1;
String[] args = {Long.toString(docNumericId), Long.toString(limit)};
String revID = null;
try {
cursor = storageEngine.rawQuery(sql, args);
if (cursor.moveToNext()) {
revID = cursor.getString(0);
outIsDeleted.set(cursor.getInt(1) > 0);
// The document is in conflict if there are two+ result rows that are not deletions.
if (outIsConflict != null) {
outIsConflict.set(!outIsDeleted.get() && cursor.moveToNext() && !(cursor.getInt(1) > 0));
}
} else {
outIsDeleted.set(false);
if (outIsConflict != null) {
outIsConflict.set(false);
}
}
} catch (SQLException e) {
Log.e(TAG, "Error", e);
throw new CouchbaseLiteException("Error", e, new Status(Status.INTERNAL_SERVER_ERROR));
} finally {
if (cursor != null) {
cursor.close();
}
}
return revID;
}
/**
* https://github.com/couchbase/couchbase-lite-ios/issues/615
*/
protected void optimizeSQLIndexes() {
Log.v(Log.TAG_DATABASE, "calls optimizeSQLIndexes()");
final long currentSequence = getLastSequence();
if (currentSequence > 0) {
final long lastOptimized = getLastOptimized();
if (lastOptimized <= currentSequence / 10) {
runInTransaction(new TransactionalTask() {
@Override
public boolean run() {
Log.i(Log.TAG_DATABASE, "%s: Optimizing SQL indexes (curSeq=%d, last run at %d)",
this, currentSequence, lastOptimized);
storageEngine.execSQL("ANALYZE");
storageEngine.execSQL("ANALYZE sqlite_master");
setInfo("last_optimized", String.valueOf(currentSequence));
return true;
}
});
}
}
}
/**
* Begins a storageEngine transaction. Transactions can nest.
* Every beginTransaction() must be balanced by a later endTransaction()
* <p/>
* Notes: 1. SQLiteDatabase.beginTransaction() supported nested transaction. But, in case
* nested transaction rollbacked, it also rollbacks outer transaction too.
* This is not ideal behavior for CBL
* 2. SAVEPOINT...RELEASE supports nested transaction. But Android API 14 and 15,
* it throws Exception. I assume it is Android bug. As CBL need to support from API 10
* . So it does not work for CBL.
* 3. Using Transaction for outer/1st level of transaction and inner/2nd level of transaction
* works with CBL requirement.
* 4. CBL Android and Java uses Thread, So it is better to use SQLiteDatabase.beginTransaction()
* for outer/1st level transaction. if we use BEGIN...COMMIT and SAVEPOINT...RELEASE,
* we need to implement wrapper of BEGIN...COMMIT and SAVEPOINT...RELEASE to be
* Thread-safe.
*/
protected boolean beginTransaction() {
int tLevel = transactionLevel.get();
try {
// Outer (level 0) transaction. Use SQLiteDatabase.beginTransaction()
if (tLevel == 0) {
storageEngine.beginTransaction();
}
// Inner (level 1 or higher) transaction. Use SQLite's SAVEPOINT
else {
storageEngine.execSQL("SAVEPOINT cbl_" + Integer.toString(tLevel));
}
Log.v(Log.TAG_DATABASE, "%s Begin transaction (level %d)", Thread.currentThread().getName(), tLevel);
transactionLevel.set(++tLevel);
} catch (SQLException e) {
Log.e(Log.TAG_DATABASE, Thread.currentThread().getName() + " Error calling beginTransaction()", e);
return false;
}
return true;
}
/**
* Commits or aborts (rolls back) a transaction.
*
* @param commit If true, commits; if false, aborts and rolls back, undoing all changes made
* since the matching -beginTransaction call, *including* any committed nested
* transactions.
* @exclude
*/
protected boolean endTransaction(boolean commit) {
int tLevel = transactionLevel.get();
assert (tLevel > 0);
transactionLevel.set(--tLevel);
// Outer (level 0) transaction. Use SQLiteDatabase.setTransactionSuccessful() and SQLiteDatabase.endTransaction()
if (tLevel == 0) {
if (commit) {
Log.v(Log.TAG_DATABASE, "%s Committing transaction (level %d)", Thread.currentThread().getName(), tLevel);
storageEngine.setTransactionSuccessful();
storageEngine.endTransaction();
} else {
Log.v(Log.TAG_DATABASE, "%s CANCEL transaction (level %d)", Thread.currentThread().getName(), tLevel);
try {
storageEngine.endTransaction();
} catch (SQLException e) {
Log.e(Log.TAG_DATABASE, Thread.currentThread().getName() + " Error calling endTransaction()", e);
return false;
}
}
}
// Inner (level 1 or higher) transaction: Use SQLite's ROLLBACK and RELEASE
else {
if (commit) {
Log.v(Log.TAG_DATABASE, "%s Committing transaction (level %d)", Thread.currentThread().getName(), tLevel);
} else {
Log.v(Log.TAG_DATABASE, "%s CANCEL transaction (level %d)", Thread.currentThread().getName(), tLevel);
try {
storageEngine.execSQL(";ROLLBACK TO cbl_" + Integer.toString(tLevel));
} catch (SQLException e) {
Log.e(Log.TAG_DATABASE, Thread.currentThread().getName() + " Error calling endTransaction()", e);
return false;
}
}
try {
storageEngine.execSQL("RELEASE cbl_" + Integer.toString(tLevel));
} catch (SQLException e) {
Log.e(Log.TAG_DATABASE, Thread.currentThread().getName() + " Error calling endTransaction()", e);
return false;
}
}
if (delegate != null)
delegate.storageExitedTransaction(commit);
return true;
}
protected Map<String, Object> documentPropertiesFromJSON(byte[] json, String docID,
String revID, boolean deleted,
long sequence) {
RevisionInternal rev = new RevisionInternal(docID, revID, deleted);
rev.setSequence(sequence);
rev.setMissing(json == null);
Map<String, Object> docProperties = null;
if (json == null || json.length == 0 || (json.length == 2 && java.util.Arrays.equals(json, EMPTY_JSON_OBJECT_CHARS))) {
docProperties = new HashMap<String, Object>();
} else {
try {
docProperties = Manager.getObjectMapper().readValue(json, Map.class);
} catch (IOException e) {
Log.e(TAG, String.format(Locale.ENGLISH, "Unparseable JSON for doc=%s, rev=%s: %s", docID, revID, new String(json)), e);
docProperties = new HashMap<String, Object>();
}
}
docProperties.put("_id", docID);
docProperties.put("_rev", revID);
if (deleted)
docProperties.put("_deleted", true);
return docProperties;
}
/**
* Prune revisions to the given max depth. Eg, remove revisions older than that max depth,
* which will reduce storage requirements.
* <p/>
* TODO: This implementation is a bit simplistic. It won't do quite the right thing in
* histories with branches, if one branch stops much earlier than another. The shorter branch
* will be deleted entirely except for its leaf revision. A more accurate pruning
* would require an expensive full tree traversal. Hopefully this way is good enough.
*/
protected int pruneRevsToMaxDepth(int maxDepth) throws CouchbaseLiteException {
if (maxDepth == 0)
maxDepth = getMaxRevTreeDepth();
Log.v(TAG, "Pruning revisions to max depth %d...", maxDepth);
// First find which docs need pruning, and by how much:
Map<Long, Integer> toPrune = new HashMap<Long, Integer>();
Cursor cursor = null;
try {
String[] args = {};
cursor = storageEngine.rawQuery(
"SELECT doc_id, MIN(revid), MAX(revid) FROM revs GROUP BY doc_id", args);
while (cursor.moveToNext()) {
long docNumericID = cursor.getLong(0);
String minGenRevId = cursor.getString(1);
String maxGenRevId = cursor.getString(2);
int minGen = Revision.generationFromRevID(minGenRevId);
int maxGen = Revision.generationFromRevID(maxGenRevId);
if ((maxGen - minGen + 1) > maxDepth) {
toPrune.put(docNumericID, (maxGen - maxDepth));
}
}
} catch (Exception e) {
throw new CouchbaseLiteException(e, Status.INTERNAL_SERVER_ERROR);
} finally {
if (cursor != null)
cursor.close();
}
if (toPrune.size() == 0)
return 0;
// Now prune:
int outPruned = 0;
boolean shouldCommit = false;
try {
beginTransaction();
for (Long docNumericID : toPrune.keySet())
outPruned += pruneDocument("?", docNumericID, toPrune.get(docNumericID).intValue() + 1);
shouldCommit = true;
} catch (Throwable e) {
throw new CouchbaseLiteException(e, Status.INTERNAL_SERVER_ERROR);
} finally {
endTransaction(shouldCommit);
}
return outPruned;
}
// Returns the number of revisions pruned.
protected int pruneDocument(String docID, long docNumericID, int minGenToKeep) {
// First find the leaves:
Set<Long> leaves = new HashSet<Long>();
Cursor cursor = null;
try {
cursor = storageEngine.rawQuery(
"SELECT sequence FROM revs WHERE doc_id=? AND current",
new String[]{Long.toString(docNumericID)});
while (cursor.moveToNext())
leaves.add(cursor.getLong(0));
} catch (SQLException e) {
Log.e(TAG, "Error querying sequence from revs docNumericID=%d", e, docNumericID);
return -1;
} finally {
if (cursor != null)
cursor.close();
}
if (leaves.size() <= 1) {
// There are no branches, so just delete everything below minGenToKeep:
String minIDToKeep = String.format(Locale.ENGLISH, "%d-", minGenToKeep);
String[] deleteArgs = {Long.toString(docNumericID), minIDToKeep};
int pruned = storageEngine.delete("revs", "doc_id=? AND revid < ? AND current=0", deleteArgs);
Log.v(TAG, " pruned %d revs with gen<%d from %s", pruned, minGenToKeep, docID);
return pruned;
} else {
// Doc has branches. Keep the ancestors of all the leaves, down to _maxRevTreeDepth.
// First fetch the skeleton of the rev tree:
Map<Long, Long> revs = new HashMap<Long, Long>();
Cursor cursor2 = null;
try {
cursor2 = storageEngine.rawQuery(
"SELECT sequence, parent FROM revs WHERE doc_id=?",
new String[]{Long.toString(docNumericID)});
while (cursor2.moveToNext()) {
long seq = cursor2.getLong(0);
long parent = cursor2.getLong(1);
revs.put(seq, parent);
}
} catch (SQLException e) {
Log.e(TAG, "Error querying sequence and parent from revs docNumericID=%d", e, docNumericID);
return -1;
} finally {
if (cursor2 != null)
cursor2.close();
}
// Now remove each leaf and its ancestors from `revs`:
Log.v(TAG, " pruning %s, scanning %d revs in tree...", docID, revs.size());
for (Long leaf : leaves) {
Long seq = leaf;
for (int i = 0; i < maxRevTreeDepth; i++) {
Long parent = revs.get(seq);
revs.remove(seq);
if (parent == null || parent.longValue() == 0)
break;
seq = parent;
}
}
// The remaining keys in `revs` are sequences to purge:
if (!purgeSequences(revs.keySet())) {
Log.w(TAG, "SQLite error: pruning conflicted doc %d", docNumericID);
return -1;
}
return revs.size();
}
}
protected void runStatements(String statements) throws SQLException {
for (String statement : statements.split(";")) {
try {
storageEngine.execSQL(statement);
} catch (SQLException e) {
Log.e(TAG, "Failed to execSQL: " + statement, e);
throw e;
}
}
}
private void initialize(String statements) throws SQLException {
try {
runStatements(statements);
} catch (SQLException e) {
close();
throw e;
}
}
private long getLastOptimized() {
String info = getInfo("last_optimized");
if (info != null) {
return Long.parseLong(info);
}
return 0;
}
private boolean sequenceHasAttachments(long sequence) {
String args[] = {Long.toString(sequence)};
return SQLiteUtils.booleanForQuery(storageEngine, "SELECT no_attachments=0 FROM revs WHERE sequence=?", args);
}
protected long getDocNumericID(String docID) {
return SQLiteUtils.longForQuery(storageEngine,
"SELECT doc_id FROM docs WHERE docid=?",
new String[]{docID});
}
// Registers a docID and returns its numeric row ID in the 'docs' table.
// On input, *ioIsNew should be YES if the docID is probably not known, NO if it's probably known.
// On return, *ioIsNew will be YES iff the docID is newly-created (was not known before.)
// Return value is the positive row ID of this doc, or <= 0 on error.
private long createOrGetDocNumericID(String docID, AtomicBoolean isNew) {
// TODO: cache
long row = isNew.get() ? createDocNumericID(docID, isNew) : getDocNumericID(docID);
if (row < 0)
return row;
if (row == 0) {
isNew.set(!isNew.get());
row = isNew.get() ? createDocNumericID(docID, isNew) : getDocNumericID(docID);
}
// TODO: cache: https://github.com/couchbase/couchbase-lite-java-core/issues/1265
return row;
}
private void invalidateDocNumericID(String docID){
// TODO: cache: https://github.com/couchbase/couchbase-lite-java-core/issues/1265
}
private void invalidateDocNumericIDs(){
// TODO: cache: https://github.com/couchbase/couchbase-lite-java-core/issues/1265
}
//private long getOrInsertDocNumericID(String docID) {
private long createDocNumericID(String docID, AtomicBoolean isNew) {
long docNumericId = getDocNumericID(docID);
if (docNumericId == 0) {
docNumericId = insertDocumentID(docID);
isNew.set(true);
} else {
isNew.set(false);
}
return docNumericId;
}
private long insertDocumentID(String docID) {
long rowId = -1;
try {
ContentValues args = new ContentValues();
args.put("docid", docID);
rowId = storageEngine.insert("docs", null, args);
} catch (Exception e) {
Log.e(TAG, "Error inserting document id", e);
}
return rowId;
}
// Raw row insertion. Returns new sequence, or 0 on error
private long insertRevision(RevisionInternal rev,
long docNumericID,
long parentSequence,
boolean current,
boolean hasAttachments,
byte[] json,
String docType)
throws SQLException {
ContentValues args = new ContentValues();
args.put("doc_id", docNumericID);
args.put("revid", rev.getRevID());
if (parentSequence != 0)
args.put("parent", parentSequence);
args.put("current", current);
args.put("deleted", rev.isDeleted());
args.put("no_attachments", !hasAttachments);
args.put("json", json);
args.put("doc_type", docType);
long rowId = storageEngine.insertOrThrow("revs", null, args);
rev.setSequence(rowId);
return rowId;
}
private long getSequenceOfDocument(long docNumericID, String revID, boolean onlyCurrent) {
String sql = String.format(Locale.ENGLISH,
"SELECT sequence FROM revs WHERE doc_id=? AND revid=? %s LIMIT 1",
(onlyCurrent ? "AND current=1" : ""));
String[] args = {Long.toString(docNumericID), revID};
return SQLiteUtils.longForQuery(storageEngine, sql, args);
}
/**
* Hack because cursor interface does not support cursor.getColumnIndex("deleted") yet.
*/
private static int getDeletedColumnIndex(QueryOptions options) {
if (options.isIncludeDocs()) {
return 6; // + json and no_attachments
} else {
return 4; // revs.doc_id, docid, revid, sequence
}
}
/**
* Loads revision given its sequence. Assumes the given docID is valid.
*/
protected RevisionInternal getDocument(String docID, long sequence) {
// Now get its revID and deletion status:
RevisionInternal rev = null;
String[] args = {Long.toString(sequence)};
String queryString = "SELECT revid, deleted, json FROM revs WHERE sequence=?";
Cursor cursor = null;
try {
cursor = storageEngine.rawQuery(queryString, args);
if (cursor.moveToNext()) {
String revID = cursor.getString(0);
boolean deleted = (cursor.getInt(1) > 0);
byte[] json = cursor.getBlob(2);
rev = new RevisionInternal(docID, revID, deleted);
rev.setSequence(sequence);
rev.setJSON(json);
}
} finally {
cursor.close();
}
return rev;
}
protected static RevisionInternal revision(String docID, String revID,
boolean deleted, long sequence, byte[] json) {
RevisionInternal rev = new RevisionInternal(docID, revID, deleted);
rev.setSequence(sequence);
if (json != null)
rev.setJSON(json);
return rev;
}
protected static RevisionInternal revision(String docID, String revID,
boolean deleted, long sequence,
Map<String, Object> properties) {
RevisionInternal rev = new RevisionInternal(docID, revID, deleted);
rev.setSequence(sequence);
if (properties != null)
rev.setProperties(properties);
return rev;
}
private String winner(long docNumericID,
String oldWinningRevID,
boolean oldWinnerWasDeletion,
RevisionInternal newRev)
throws CouchbaseLiteException {
String newRevID = newRev.getRevID();
if (oldWinningRevID == null) {
return newRevID;
}
if (!newRev.isDeleted()) {
if (oldWinnerWasDeletion || RevisionInternal.CBLCompareRevIDs(newRevID, oldWinningRevID) > 0)
return newRevID; // this is now the winning live revision
} else if (oldWinnerWasDeletion) {
if (RevisionInternal.CBLCompareRevIDs(newRevID, oldWinningRevID) > 0)
return newRevID; // doc still deleted, but this beats previous deletion rev
} else {
// Doc was alive. How does this deletion affect the winning rev ID?
AtomicBoolean outIsDeleted = new AtomicBoolean(false);
String winningRevID = winningRevIDOfDocNumericID(docNumericID, outIsDeleted, null);
if (!winningRevID.equals(oldWinningRevID))
return winningRevID;
}
return null; // no change
}
}
|
Fixed #1319 - Auto-pruning failing on pull replication
current logic can not handle in case pull with batch.
|
src/main/java/com/couchbase/lite/store/SQLiteStore.java
|
Fixed #1319 - Auto-pruning failing on pull replication
|
|
Java
|
apache-2.0
|
15998662170117967270d5ae79eaaf4be5269ab4
| 0
|
leadwire-apm/leadwire-javaagent,kieker-monitoring/kieker,kieker-monitoring/kieker,kieker-monitoring/kieker,HaStr/kieker,HaStr/kieker,HaStr/kieker,HaStr/kieker,leadwire-apm/leadwire-javaagent,HaStr/kieker,kieker-monitoring/kieker,kieker-monitoring/kieker
|
/***************************************************************************
* Copyright 2012 Kieker Project (http://kieker-monitoring.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
***************************************************************************/
package kieker.monitoring.core.controller;
/**
* @author Jan Waller
*/
public interface IStateController {
/**
* Permanently terminates monitoring.
*
* @see #isMonitoringTerminated()
* @return true if now terminated; false if already terminated
*/
public abstract boolean terminateMonitoring();
/**
* Returns whether monitoring is permanently terminated.
*
* @see #terminateMonitoring()
* @return true if monitoring is permanently terminated, false if monitoring is enabled or disabled.
*/
public abstract boolean isMonitoringTerminated();
/**
* Enables monitoring.
*
* @return true if monitoring is enabled, false otherwise
*/
public abstract boolean enableMonitoring();
/**
* Disables monitoring.
*
* If monitoring is disabled, the MonitoringController simply pauses.
* Furthermore, probes should stop collecting new data and monitoring
* writers stop should stop writing existing data.
*
* @return true if monitoring is disabled, false otherwise
*/
public abstract boolean disableMonitoring();
/**
* Returns whether monitoring is enabled or disabled/terminated.
*
* @see #disableMonitoring()
* @see #enableMonitoring()
*
* @return true of monitoring is enabled, false if monitoring is disabled or terminated.
*/
public abstract boolean isMonitoringEnabled();
/**
* Returns the name of this controller.
*
* @return String
*/
public abstract String getName();
/**
* The hostname will be part of the monitoring data and allows to distinguish
* observations in cases where the software system is deployed on more
* than one host.
*
* When you want to distinguish multiple Virtual Machines on one host, you
* have to set the hostname manually in the Configuration.
*/
public abstract String getHostname();
/**
* Increments the experiment ID by 1 and returns the new value.
*
* @return experimentID
*/
public abstract int incExperimentId();
/**
* Sets the experiment ID to the given value.
*
* @param newExperimentID
*/
public abstract void setExperimentId(final int newExperimentID);
/**
* Returns the experiment ID.
*
* @return experimentID
*/
public abstract int getExperimentId();
/**
* Is the debug mode enabled?
*
* <p>
* Debug mode is for internal use only and changes a few internal id generation mechanisms to enable easier debugging. Additionally, it is possible to enable
* debug logging in the settings of the used logger.
* </p>
*
* @return debug mode
*/
public abstract boolean isDebug();
}
|
src/monitoring/kieker/monitoring/core/controller/IStateController.java
|
/***************************************************************************
* Copyright 2012 Kieker Project (http://kieker-monitoring.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
***************************************************************************/
package kieker.monitoring.core.controller;
/**
* @author Jan Waller
*/
public interface IStateController {
/**
* Permanently terminates monitoring.
*
* @see #isMonitoringTerminated()
* @return true if now terminated; false if already terminated
*/
public abstract boolean terminateMonitoring();
/**
* Returns whether monitoring is permanently terminated.
*
* @see #terminateMonitoring()
* @return true if monitoring is permanently terminated, false if monitoring is enabled or disabled.
*/
public abstract boolean isMonitoringTerminated();
/**
* Enables monitoring.
*
* @return true if monitoring is enabled, false otherwise
*/
public abstract boolean enableMonitoring();
/**
* Disables monitoring.
*
* If monitoring is disabled, the MonitoringController simply pauses.
* Furthermore, probes should stop collecting new data and monitoring
* writers stop should stop writing existing data.
*
* @return true if monitoring is disabled, false otherwise
*/
public abstract boolean disableMonitoring();
/**
* Returns whether monitoring is enabled or disabled/terminated.
*
* @see #disableMonitoring()
* @see #enableMonitoring()
*
* @return true of monitoring is enabled, false if monitoring is disabled or terminated.
*/
public abstract boolean isMonitoringEnabled();
/**
* Returns the name of this controller.
*
* @return String
*/
public abstract String getName();
/**
* The hostname will be part of the monitoring data and allows to distinguish
* observations in cases where the software system is deployed on more
* than one host.
*
* When you want to distinguish multiple Virtual Machines on one host, you
* have to set the hostname manually in the Configuration.
*/
public abstract String getHostname();
/**
* Increments the experiment ID by 1 and returns the new value.
*
* @return experimentID
*/
public abstract int incExperimentId();
/**
* Sets the experiment ID to the given value.
*
* @param newExperimentID
*/
public abstract void setExperimentId(final int newExperimentID);
/**
* Returns the experiment ID.
*
* @return experimentID
*/
public abstract int getExperimentId();
/**
* Is the debug mode enabled?
*
* @return debug mode
*/
public abstract boolean isDebug();
}
|
#706 improve documentation
|
src/monitoring/kieker/monitoring/core/controller/IStateController.java
|
#706 improve documentation
|
|
Java
|
apache-2.0
|
5b44b0c9edb16e79c581a121806547f8346e2128
| 0
|
zrccxyb62/hadoop,zrccxyb62/hadoop,zrccxyb62/hadoop,zrccxyb62/hadoop,zrccxyb62/hadoop,zrccxyb62/hadoop,zrccxyb62/hadoop
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.yarn.server.resourcemanager;
import java.nio.ByteBuffer;
import java.util.concurrent.ConcurrentMap;
import org.apache.hadoop.classification.InterfaceAudience.Private;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.classification.InterfaceStability.Unstable;
import org.apache.hadoop.ha.HAServiceProtocol;
import org.apache.hadoop.ha.HAServiceProtocol.HAServiceState;
import org.apache.hadoop.yarn.LocalConfigurationProvider;
import org.apache.hadoop.yarn.api.records.ApplicationId;
import org.apache.hadoop.yarn.api.records.NodeId;
import org.apache.hadoop.yarn.conf.ConfigurationProvider;
import org.apache.hadoop.yarn.event.Dispatcher;
import org.apache.hadoop.yarn.server.resourcemanager.ahs.RMApplicationHistoryWriter;
import org.apache.hadoop.yarn.server.resourcemanager.metrics.SystemMetricsPublisher;
import org.apache.hadoop.yarn.server.resourcemanager.nodelabels.RMNodeLabelsManager;
import org.apache.hadoop.yarn.server.resourcemanager.nodelabels.RMDelegatedNodeLabelsUpdater;
import org.apache.hadoop.yarn.server.resourcemanager.placement.PlacementManager;
import org.apache.hadoop.yarn.server.resourcemanager.recovery.RMStateStore;
import org.apache.hadoop.yarn.server.resourcemanager.reservation.ReservationSystem;
import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMApp;
import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.AMLivelinessMonitor;
import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.ContainerAllocationExpirer;
import org.apache.hadoop.yarn.server.resourcemanager.rmnode.RMNode;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.ResourceScheduler;
import org.apache.hadoop.yarn.server.resourcemanager.security.AMRMTokenSecretManager;
import org.apache.hadoop.yarn.server.resourcemanager.security.ClientToAMTokenSecretManagerInRM;
import org.apache.hadoop.yarn.server.resourcemanager.security.DelegationTokenRenewer;
import org.apache.hadoop.yarn.server.resourcemanager.security.NMTokenSecretManagerInRM;
import org.apache.hadoop.yarn.server.resourcemanager.security.RMContainerTokenSecretManager;
import org.apache.hadoop.yarn.server.resourcemanager.security.RMDelegationTokenSecretManager;
import org.apache.hadoop.yarn.util.Clock;
import com.google.common.annotations.VisibleForTesting;
public class RMContextImpl implements RMContext {
private Dispatcher rmDispatcher;
private boolean isHAEnabled;
private HAServiceState haServiceState =
HAServiceProtocol.HAServiceState.INITIALIZING;
private AdminService adminService;
private ConfigurationProvider configurationProvider;
private RMActiveServiceContext activeServiceContext;
private Configuration yarnConfiguration;
private RMApplicationHistoryWriter rmApplicationHistoryWriter;
private SystemMetricsPublisher systemMetricsPublisher;
private final Object haServiceStateLock = new Object();
/**
* Default constructor. To be used in conjunction with setter methods for
* individual fields.
*/
public RMContextImpl() {
}
@VisibleForTesting
// helper constructor for tests
public RMContextImpl(Dispatcher rmDispatcher,
ContainerAllocationExpirer containerAllocationExpirer,
AMLivelinessMonitor amLivelinessMonitor,
AMLivelinessMonitor amFinishingMonitor,
DelegationTokenRenewer delegationTokenRenewer,
AMRMTokenSecretManager appTokenSecretManager,
RMContainerTokenSecretManager containerTokenSecretManager,
NMTokenSecretManagerInRM nmTokenSecretManager,
ClientToAMTokenSecretManagerInRM clientToAMTokenSecretManager,
ResourceScheduler scheduler) {
this();
this.setDispatcher(rmDispatcher);
setActiveServiceContext(new RMActiveServiceContext(rmDispatcher,
containerAllocationExpirer, amLivelinessMonitor, amFinishingMonitor,
delegationTokenRenewer, appTokenSecretManager,
containerTokenSecretManager, nmTokenSecretManager,
clientToAMTokenSecretManager,
scheduler));
ConfigurationProvider provider = new LocalConfigurationProvider();
setConfigurationProvider(provider);
}
@VisibleForTesting
// helper constructor for tests
public RMContextImpl(Dispatcher rmDispatcher,
ContainerAllocationExpirer containerAllocationExpirer,
AMLivelinessMonitor amLivelinessMonitor,
AMLivelinessMonitor amFinishingMonitor,
DelegationTokenRenewer delegationTokenRenewer,
AMRMTokenSecretManager appTokenSecretManager,
RMContainerTokenSecretManager containerTokenSecretManager,
NMTokenSecretManagerInRM nmTokenSecretManager,
ClientToAMTokenSecretManagerInRM clientToAMTokenSecretManager) {
this(
rmDispatcher,
containerAllocationExpirer,
amLivelinessMonitor,
amFinishingMonitor,
delegationTokenRenewer,
appTokenSecretManager,
containerTokenSecretManager,
nmTokenSecretManager,
clientToAMTokenSecretManager, null);
}
@Override
public Dispatcher getDispatcher() {
return this.rmDispatcher;
}
@Override
public RMStateStore getStateStore() {
return activeServiceContext.getStateStore();
}
@Override
public ConcurrentMap<ApplicationId, RMApp> getRMApps() {
return activeServiceContext.getRMApps();
}
@Override
public ConcurrentMap<NodeId, RMNode> getRMNodes() {
return activeServiceContext.getRMNodes();
}
@Override
public ConcurrentMap<NodeId, RMNode> getInactiveRMNodes() {
return activeServiceContext.getInactiveRMNodes();
}
@Override
public ContainerAllocationExpirer getContainerAllocationExpirer() {
return activeServiceContext.getContainerAllocationExpirer();
}
@Override
public AMLivelinessMonitor getAMLivelinessMonitor() {
return activeServiceContext.getAMLivelinessMonitor();
}
@Override
public AMLivelinessMonitor getAMFinishingMonitor() {
return activeServiceContext.getAMFinishingMonitor();
}
@Override
public DelegationTokenRenewer getDelegationTokenRenewer() {
return activeServiceContext.getDelegationTokenRenewer();
}
@Override
public AMRMTokenSecretManager getAMRMTokenSecretManager() {
return activeServiceContext.getAMRMTokenSecretManager();
}
@Override
public RMContainerTokenSecretManager getContainerTokenSecretManager() {
return activeServiceContext.getContainerTokenSecretManager();
}
@Override
public NMTokenSecretManagerInRM getNMTokenSecretManager() {
return activeServiceContext.getNMTokenSecretManager();
}
@Override
public ResourceScheduler getScheduler() {
return activeServiceContext.getScheduler();
}
@Override
public ReservationSystem getReservationSystem() {
return activeServiceContext.getReservationSystem();
}
@Override
public NodesListManager getNodesListManager() {
return activeServiceContext.getNodesListManager();
}
@Override
public ClientToAMTokenSecretManagerInRM getClientToAMTokenSecretManager() {
return activeServiceContext.getClientToAMTokenSecretManager();
}
@Override
public AdminService getRMAdminService() {
return this.adminService;
}
@VisibleForTesting
public void setStateStore(RMStateStore store) {
activeServiceContext.setStateStore(store);
}
@Override
public ClientRMService getClientRMService() {
return activeServiceContext.getClientRMService();
}
@Override
public ApplicationMasterService getApplicationMasterService() {
return activeServiceContext.getApplicationMasterService();
}
@Override
public ResourceTrackerService getResourceTrackerService() {
return activeServiceContext.getResourceTrackerService();
}
void setHAEnabled(boolean isHAEnabled) {
this.isHAEnabled = isHAEnabled;
}
void setHAServiceState(HAServiceState serviceState) {
synchronized (haServiceStateLock) {
this.haServiceState = serviceState;
}
}
void setDispatcher(Dispatcher dispatcher) {
this.rmDispatcher = dispatcher;
}
void setRMAdminService(AdminService adminService) {
this.adminService = adminService;
}
@Override
public void setClientRMService(ClientRMService clientRMService) {
activeServiceContext.setClientRMService(clientRMService);
}
@Override
public RMDelegationTokenSecretManager getRMDelegationTokenSecretManager() {
return activeServiceContext.getRMDelegationTokenSecretManager();
}
@Override
public void setRMDelegationTokenSecretManager(
RMDelegationTokenSecretManager delegationTokenSecretManager) {
activeServiceContext
.setRMDelegationTokenSecretManager(delegationTokenSecretManager);
}
void setContainerAllocationExpirer(
ContainerAllocationExpirer containerAllocationExpirer) {
activeServiceContext
.setContainerAllocationExpirer(containerAllocationExpirer);
}
void setAMLivelinessMonitor(AMLivelinessMonitor amLivelinessMonitor) {
activeServiceContext.setAMLivelinessMonitor(amLivelinessMonitor);
}
void setAMFinishingMonitor(AMLivelinessMonitor amFinishingMonitor) {
activeServiceContext.setAMFinishingMonitor(amFinishingMonitor);
}
void setContainerTokenSecretManager(
RMContainerTokenSecretManager containerTokenSecretManager) {
activeServiceContext
.setContainerTokenSecretManager(containerTokenSecretManager);
}
void setNMTokenSecretManager(NMTokenSecretManagerInRM nmTokenSecretManager) {
activeServiceContext.setNMTokenSecretManager(nmTokenSecretManager);
}
@VisibleForTesting
public void setScheduler(ResourceScheduler scheduler) {
activeServiceContext.setScheduler(scheduler);
}
void setReservationSystem(ReservationSystem reservationSystem) {
activeServiceContext.setReservationSystem(reservationSystem);
}
void setDelegationTokenRenewer(DelegationTokenRenewer delegationTokenRenewer) {
activeServiceContext.setDelegationTokenRenewer(delegationTokenRenewer);
}
void setClientToAMTokenSecretManager(
ClientToAMTokenSecretManagerInRM clientToAMTokenSecretManager) {
activeServiceContext
.setClientToAMTokenSecretManager(clientToAMTokenSecretManager);
}
void setAMRMTokenSecretManager(AMRMTokenSecretManager amRMTokenSecretManager) {
activeServiceContext.setAMRMTokenSecretManager(amRMTokenSecretManager);
}
void setNodesListManager(NodesListManager nodesListManager) {
activeServiceContext.setNodesListManager(nodesListManager);
}
void setApplicationMasterService(
ApplicationMasterService applicationMasterService) {
activeServiceContext.setApplicationMasterService(applicationMasterService);
}
void setResourceTrackerService(ResourceTrackerService resourceTrackerService) {
activeServiceContext.setResourceTrackerService(resourceTrackerService);
}
@Override
public boolean isHAEnabled() {
return isHAEnabled;
}
@Override
public HAServiceState getHAServiceState() {
synchronized (haServiceStateLock) {
return haServiceState;
}
}
public void setWorkPreservingRecoveryEnabled(boolean enabled) {
activeServiceContext.setWorkPreservingRecoveryEnabled(enabled);
}
@Override
public boolean isWorkPreservingRecoveryEnabled() {
return activeServiceContext.isWorkPreservingRecoveryEnabled();
}
@Override
public RMApplicationHistoryWriter getRMApplicationHistoryWriter() {
return this.rmApplicationHistoryWriter;
}
@Override
public void setSystemMetricsPublisher(
SystemMetricsPublisher systemMetricsPublisher) {
this.systemMetricsPublisher = systemMetricsPublisher;
}
@Override
public SystemMetricsPublisher getSystemMetricsPublisher() {
return this.systemMetricsPublisher;
}
@Override
public void setRMApplicationHistoryWriter(
RMApplicationHistoryWriter rmApplicationHistoryWriter) {
this.rmApplicationHistoryWriter = rmApplicationHistoryWriter;
}
@Override
public ConfigurationProvider getConfigurationProvider() {
return this.configurationProvider;
}
public void setConfigurationProvider(
ConfigurationProvider configurationProvider) {
this.configurationProvider = configurationProvider;
}
@Override
public long getEpoch() {
return activeServiceContext.getEpoch();
}
void setEpoch(long epoch) {
activeServiceContext.setEpoch(epoch);
}
@Override
public RMNodeLabelsManager getNodeLabelManager() {
return activeServiceContext.getNodeLabelManager();
}
@Override
public void setNodeLabelManager(RMNodeLabelsManager mgr) {
activeServiceContext.setNodeLabelManager(mgr);
}
@Override
public RMDelegatedNodeLabelsUpdater getRMDelegatedNodeLabelsUpdater() {
return activeServiceContext.getRMDelegatedNodeLabelsUpdater();
}
@Override
public void setRMDelegatedNodeLabelsUpdater(
RMDelegatedNodeLabelsUpdater delegatedNodeLabelsUpdater) {
activeServiceContext.setRMDelegatedNodeLabelsUpdater(
delegatedNodeLabelsUpdater);
}
public void setSchedulerRecoveryStartAndWaitTime(long waitTime) {
activeServiceContext.setSchedulerRecoveryStartAndWaitTime(waitTime);
}
public boolean isSchedulerReadyForAllocatingContainers() {
return activeServiceContext.isSchedulerReadyForAllocatingContainers();
}
@Private
@VisibleForTesting
public void setSystemClock(Clock clock) {
activeServiceContext.setSystemClock(clock);
}
public ConcurrentMap<ApplicationId, ByteBuffer> getSystemCredentialsForApps() {
return activeServiceContext.getSystemCredentialsForApps();
}
@Private
@Unstable
public RMActiveServiceContext getActiveServiceContext() {
return activeServiceContext;
}
@Private
@Unstable
void setActiveServiceContext(RMActiveServiceContext activeServiceContext) {
this.activeServiceContext = activeServiceContext;
}
@Override
public Configuration getYarnConfiguration() {
return this.yarnConfiguration;
}
public void setYarnConfiguration(Configuration yarnConfiguration) {
this.yarnConfiguration=yarnConfiguration;
}
@Override
public PlacementManager getQueuePlacementManager() {
return this.activeServiceContext.getQueuePlacementManager();
}
@Override
public void setQueuePlacementManager(PlacementManager placementMgr) {
this.activeServiceContext.setQueuePlacementManager(placementMgr);
}
}
|
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/RMContextImpl.java
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.yarn.server.resourcemanager;
import java.nio.ByteBuffer;
import java.util.concurrent.ConcurrentMap;
import org.apache.hadoop.classification.InterfaceAudience.Private;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.classification.InterfaceStability.Unstable;
import org.apache.hadoop.ha.HAServiceProtocol;
import org.apache.hadoop.ha.HAServiceProtocol.HAServiceState;
import org.apache.hadoop.yarn.LocalConfigurationProvider;
import org.apache.hadoop.yarn.api.records.ApplicationId;
import org.apache.hadoop.yarn.api.records.NodeId;
import org.apache.hadoop.yarn.conf.ConfigurationProvider;
import org.apache.hadoop.yarn.event.Dispatcher;
import org.apache.hadoop.yarn.server.resourcemanager.ahs.RMApplicationHistoryWriter;
import org.apache.hadoop.yarn.server.resourcemanager.metrics.SystemMetricsPublisher;
import org.apache.hadoop.yarn.server.resourcemanager.nodelabels.RMNodeLabelsManager;
import org.apache.hadoop.yarn.server.resourcemanager.nodelabels.RMDelegatedNodeLabelsUpdater;
import org.apache.hadoop.yarn.server.resourcemanager.placement.PlacementManager;
import org.apache.hadoop.yarn.server.resourcemanager.recovery.RMStateStore;
import org.apache.hadoop.yarn.server.resourcemanager.reservation.ReservationSystem;
import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMApp;
import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.AMLivelinessMonitor;
import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.ContainerAllocationExpirer;
import org.apache.hadoop.yarn.server.resourcemanager.rmnode.RMNode;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.ResourceScheduler;
import org.apache.hadoop.yarn.server.resourcemanager.security.AMRMTokenSecretManager;
import org.apache.hadoop.yarn.server.resourcemanager.security.ClientToAMTokenSecretManagerInRM;
import org.apache.hadoop.yarn.server.resourcemanager.security.DelegationTokenRenewer;
import org.apache.hadoop.yarn.server.resourcemanager.security.NMTokenSecretManagerInRM;
import org.apache.hadoop.yarn.server.resourcemanager.security.RMContainerTokenSecretManager;
import org.apache.hadoop.yarn.server.resourcemanager.security.RMDelegationTokenSecretManager;
import org.apache.hadoop.yarn.util.Clock;
import com.google.common.annotations.VisibleForTesting;
public class RMContextImpl implements RMContext {
private Dispatcher rmDispatcher;
private boolean isHAEnabled;
private HAServiceState haServiceState =
HAServiceProtocol.HAServiceState.INITIALIZING;
private AdminService adminService;
private ConfigurationProvider configurationProvider;
private RMActiveServiceContext activeServiceContext;
private Configuration yarnConfiguration;
private RMApplicationHistoryWriter rmApplicationHistoryWriter;
private SystemMetricsPublisher systemMetricsPublisher;
/**
* Default constructor. To be used in conjunction with setter methods for
* individual fields.
*/
public RMContextImpl() {
}
@VisibleForTesting
// helper constructor for tests
public RMContextImpl(Dispatcher rmDispatcher,
ContainerAllocationExpirer containerAllocationExpirer,
AMLivelinessMonitor amLivelinessMonitor,
AMLivelinessMonitor amFinishingMonitor,
DelegationTokenRenewer delegationTokenRenewer,
AMRMTokenSecretManager appTokenSecretManager,
RMContainerTokenSecretManager containerTokenSecretManager,
NMTokenSecretManagerInRM nmTokenSecretManager,
ClientToAMTokenSecretManagerInRM clientToAMTokenSecretManager,
ResourceScheduler scheduler) {
this();
this.setDispatcher(rmDispatcher);
setActiveServiceContext(new RMActiveServiceContext(rmDispatcher,
containerAllocationExpirer, amLivelinessMonitor, amFinishingMonitor,
delegationTokenRenewer, appTokenSecretManager,
containerTokenSecretManager, nmTokenSecretManager,
clientToAMTokenSecretManager,
scheduler));
ConfigurationProvider provider = new LocalConfigurationProvider();
setConfigurationProvider(provider);
}
@VisibleForTesting
// helper constructor for tests
public RMContextImpl(Dispatcher rmDispatcher,
ContainerAllocationExpirer containerAllocationExpirer,
AMLivelinessMonitor amLivelinessMonitor,
AMLivelinessMonitor amFinishingMonitor,
DelegationTokenRenewer delegationTokenRenewer,
AMRMTokenSecretManager appTokenSecretManager,
RMContainerTokenSecretManager containerTokenSecretManager,
NMTokenSecretManagerInRM nmTokenSecretManager,
ClientToAMTokenSecretManagerInRM clientToAMTokenSecretManager) {
this(
rmDispatcher,
containerAllocationExpirer,
amLivelinessMonitor,
amFinishingMonitor,
delegationTokenRenewer,
appTokenSecretManager,
containerTokenSecretManager,
nmTokenSecretManager,
clientToAMTokenSecretManager, null);
}
@Override
public Dispatcher getDispatcher() {
return this.rmDispatcher;
}
@Override
public RMStateStore getStateStore() {
return activeServiceContext.getStateStore();
}
@Override
public ConcurrentMap<ApplicationId, RMApp> getRMApps() {
return activeServiceContext.getRMApps();
}
@Override
public ConcurrentMap<NodeId, RMNode> getRMNodes() {
return activeServiceContext.getRMNodes();
}
@Override
public ConcurrentMap<NodeId, RMNode> getInactiveRMNodes() {
return activeServiceContext.getInactiveRMNodes();
}
@Override
public ContainerAllocationExpirer getContainerAllocationExpirer() {
return activeServiceContext.getContainerAllocationExpirer();
}
@Override
public AMLivelinessMonitor getAMLivelinessMonitor() {
return activeServiceContext.getAMLivelinessMonitor();
}
@Override
public AMLivelinessMonitor getAMFinishingMonitor() {
return activeServiceContext.getAMFinishingMonitor();
}
@Override
public DelegationTokenRenewer getDelegationTokenRenewer() {
return activeServiceContext.getDelegationTokenRenewer();
}
@Override
public AMRMTokenSecretManager getAMRMTokenSecretManager() {
return activeServiceContext.getAMRMTokenSecretManager();
}
@Override
public RMContainerTokenSecretManager getContainerTokenSecretManager() {
return activeServiceContext.getContainerTokenSecretManager();
}
@Override
public NMTokenSecretManagerInRM getNMTokenSecretManager() {
return activeServiceContext.getNMTokenSecretManager();
}
@Override
public ResourceScheduler getScheduler() {
return activeServiceContext.getScheduler();
}
@Override
public ReservationSystem getReservationSystem() {
return activeServiceContext.getReservationSystem();
}
@Override
public NodesListManager getNodesListManager() {
return activeServiceContext.getNodesListManager();
}
@Override
public ClientToAMTokenSecretManagerInRM getClientToAMTokenSecretManager() {
return activeServiceContext.getClientToAMTokenSecretManager();
}
@Override
public AdminService getRMAdminService() {
return this.adminService;
}
@VisibleForTesting
public void setStateStore(RMStateStore store) {
activeServiceContext.setStateStore(store);
}
@Override
public ClientRMService getClientRMService() {
return activeServiceContext.getClientRMService();
}
@Override
public ApplicationMasterService getApplicationMasterService() {
return activeServiceContext.getApplicationMasterService();
}
@Override
public ResourceTrackerService getResourceTrackerService() {
return activeServiceContext.getResourceTrackerService();
}
void setHAEnabled(boolean isHAEnabled) {
this.isHAEnabled = isHAEnabled;
}
void setHAServiceState(HAServiceState haServiceState) {
synchronized (haServiceState) {
this.haServiceState = haServiceState;
}
}
void setDispatcher(Dispatcher dispatcher) {
this.rmDispatcher = dispatcher;
}
void setRMAdminService(AdminService adminService) {
this.adminService = adminService;
}
@Override
public void setClientRMService(ClientRMService clientRMService) {
activeServiceContext.setClientRMService(clientRMService);
}
@Override
public RMDelegationTokenSecretManager getRMDelegationTokenSecretManager() {
return activeServiceContext.getRMDelegationTokenSecretManager();
}
@Override
public void setRMDelegationTokenSecretManager(
RMDelegationTokenSecretManager delegationTokenSecretManager) {
activeServiceContext
.setRMDelegationTokenSecretManager(delegationTokenSecretManager);
}
void setContainerAllocationExpirer(
ContainerAllocationExpirer containerAllocationExpirer) {
activeServiceContext
.setContainerAllocationExpirer(containerAllocationExpirer);
}
void setAMLivelinessMonitor(AMLivelinessMonitor amLivelinessMonitor) {
activeServiceContext.setAMLivelinessMonitor(amLivelinessMonitor);
}
void setAMFinishingMonitor(AMLivelinessMonitor amFinishingMonitor) {
activeServiceContext.setAMFinishingMonitor(amFinishingMonitor);
}
void setContainerTokenSecretManager(
RMContainerTokenSecretManager containerTokenSecretManager) {
activeServiceContext
.setContainerTokenSecretManager(containerTokenSecretManager);
}
void setNMTokenSecretManager(NMTokenSecretManagerInRM nmTokenSecretManager) {
activeServiceContext.setNMTokenSecretManager(nmTokenSecretManager);
}
@VisibleForTesting
public void setScheduler(ResourceScheduler scheduler) {
activeServiceContext.setScheduler(scheduler);
}
void setReservationSystem(ReservationSystem reservationSystem) {
activeServiceContext.setReservationSystem(reservationSystem);
}
void setDelegationTokenRenewer(DelegationTokenRenewer delegationTokenRenewer) {
activeServiceContext.setDelegationTokenRenewer(delegationTokenRenewer);
}
void setClientToAMTokenSecretManager(
ClientToAMTokenSecretManagerInRM clientToAMTokenSecretManager) {
activeServiceContext
.setClientToAMTokenSecretManager(clientToAMTokenSecretManager);
}
void setAMRMTokenSecretManager(AMRMTokenSecretManager amRMTokenSecretManager) {
activeServiceContext.setAMRMTokenSecretManager(amRMTokenSecretManager);
}
void setNodesListManager(NodesListManager nodesListManager) {
activeServiceContext.setNodesListManager(nodesListManager);
}
void setApplicationMasterService(
ApplicationMasterService applicationMasterService) {
activeServiceContext.setApplicationMasterService(applicationMasterService);
}
void setResourceTrackerService(ResourceTrackerService resourceTrackerService) {
activeServiceContext.setResourceTrackerService(resourceTrackerService);
}
@Override
public boolean isHAEnabled() {
return isHAEnabled;
}
@Override
public HAServiceState getHAServiceState() {
synchronized (haServiceState) {
return haServiceState;
}
}
public void setWorkPreservingRecoveryEnabled(boolean enabled) {
activeServiceContext.setWorkPreservingRecoveryEnabled(enabled);
}
@Override
public boolean isWorkPreservingRecoveryEnabled() {
return activeServiceContext.isWorkPreservingRecoveryEnabled();
}
@Override
public RMApplicationHistoryWriter getRMApplicationHistoryWriter() {
return this.rmApplicationHistoryWriter;
}
@Override
public void setSystemMetricsPublisher(
SystemMetricsPublisher systemMetricsPublisher) {
this.systemMetricsPublisher = systemMetricsPublisher;
}
@Override
public SystemMetricsPublisher getSystemMetricsPublisher() {
return this.systemMetricsPublisher;
}
@Override
public void setRMApplicationHistoryWriter(
RMApplicationHistoryWriter rmApplicationHistoryWriter) {
this.rmApplicationHistoryWriter = rmApplicationHistoryWriter;
}
@Override
public ConfigurationProvider getConfigurationProvider() {
return this.configurationProvider;
}
public void setConfigurationProvider(
ConfigurationProvider configurationProvider) {
this.configurationProvider = configurationProvider;
}
@Override
public long getEpoch() {
return activeServiceContext.getEpoch();
}
void setEpoch(long epoch) {
activeServiceContext.setEpoch(epoch);
}
@Override
public RMNodeLabelsManager getNodeLabelManager() {
return activeServiceContext.getNodeLabelManager();
}
@Override
public void setNodeLabelManager(RMNodeLabelsManager mgr) {
activeServiceContext.setNodeLabelManager(mgr);
}
@Override
public RMDelegatedNodeLabelsUpdater getRMDelegatedNodeLabelsUpdater() {
return activeServiceContext.getRMDelegatedNodeLabelsUpdater();
}
@Override
public void setRMDelegatedNodeLabelsUpdater(
RMDelegatedNodeLabelsUpdater delegatedNodeLabelsUpdater) {
activeServiceContext.setRMDelegatedNodeLabelsUpdater(
delegatedNodeLabelsUpdater);
}
public void setSchedulerRecoveryStartAndWaitTime(long waitTime) {
activeServiceContext.setSchedulerRecoveryStartAndWaitTime(waitTime);
}
public boolean isSchedulerReadyForAllocatingContainers() {
return activeServiceContext.isSchedulerReadyForAllocatingContainers();
}
@Private
@VisibleForTesting
public void setSystemClock(Clock clock) {
activeServiceContext.setSystemClock(clock);
}
public ConcurrentMap<ApplicationId, ByteBuffer> getSystemCredentialsForApps() {
return activeServiceContext.getSystemCredentialsForApps();
}
@Private
@Unstable
public RMActiveServiceContext getActiveServiceContext() {
return activeServiceContext;
}
@Private
@Unstable
void setActiveServiceContext(RMActiveServiceContext activeServiceContext) {
this.activeServiceContext = activeServiceContext;
}
@Override
public Configuration getYarnConfiguration() {
return this.yarnConfiguration;
}
public void setYarnConfiguration(Configuration yarnConfiguration) {
this.yarnConfiguration=yarnConfiguration;
}
@Override
public PlacementManager getQueuePlacementManager() {
return this.activeServiceContext.getQueuePlacementManager();
}
@Override
public void setQueuePlacementManager(PlacementManager placementMgr) {
this.activeServiceContext.setQueuePlacementManager(placementMgr);
}
}
|
YARN-5921. Incorrect synchronization in RMContextImpl#setHAServiceState/getHAServiceState. Contributed by Varun Saxena
(cherry picked from commit f3b8ff54ab08545d7093bf8861b44ec9912e8dc3)
|
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/RMContextImpl.java
|
YARN-5921. Incorrect synchronization in RMContextImpl#setHAServiceState/getHAServiceState. Contributed by Varun Saxena
|
|
Java
|
apache-2.0
|
53be20f0c96e97ad9b491c21646fa23a0c05451e
| 0
|
petteyg/intellij-community,orekyuu/intellij-community,muntasirsyed/intellij-community,vvv1559/intellij-community,ivan-fedorov/intellij-community,holmes/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,wreckJ/intellij-community,clumsy/intellij-community,ryano144/intellij-community,vvv1559/intellij-community,da1z/intellij-community,fnouama/intellij-community,gnuhub/intellij-community,FHannes/intellij-community,fnouama/intellij-community,suncycheng/intellij-community,ryano144/intellij-community,allotria/intellij-community,fitermay/intellij-community,salguarnieri/intellij-community,vvv1559/intellij-community,alphafoobar/intellij-community,orekyuu/intellij-community,ernestp/consulo,asedunov/intellij-community,blademainer/intellij-community,fnouama/intellij-community,semonte/intellij-community,joewalnes/idea-community,michaelgallacher/intellij-community,salguarnieri/intellij-community,supersven/intellij-community,retomerz/intellij-community,joewalnes/idea-community,xfournet/intellij-community,consulo/consulo,akosyakov/intellij-community,allotria/intellij-community,blademainer/intellij-community,akosyakov/intellij-community,suncycheng/intellij-community,retomerz/intellij-community,mglukhikh/intellij-community,signed/intellij-community,retomerz/intellij-community,petteyg/intellij-community,robovm/robovm-studio,ibinti/intellij-community,jexp/idea2,semonte/intellij-community,jagguli/intellij-community,ol-loginov/intellij-community,suncycheng/intellij-community,MER-GROUP/intellij-community,allotria/intellij-community,allotria/intellij-community,consulo/consulo,gnuhub/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,allotria/intellij-community,Distrotech/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,retomerz/intellij-community,clumsy/intellij-community,allotria/intellij-community,samthor/intellij-community,ol-loginov/intellij-community,Lekanich/intellij-community,ThiagoGarciaAlves/intellij-community,MER-GROUP/intellij-community,amith01994/intellij-community,retomerz/intellij-community,SerCeMan/intellij-community,MichaelNedzelsky/intellij-community,FHannes/intellij-community,ibinti/intellij-community,amith01994/intellij-community,allotria/intellij-community,Distrotech/intellij-community,fitermay/intellij-community,tmpgit/intellij-community,ol-loginov/intellij-community,semonte/intellij-community,allotria/intellij-community,ahb0327/intellij-community,ahb0327/intellij-community,holmes/intellij-community,samthor/intellij-community,akosyakov/intellij-community,mglukhikh/intellij-community,TangHao1987/intellij-community,kdwink/intellij-community,petteyg/intellij-community,jexp/idea2,ol-loginov/intellij-community,vladmm/intellij-community,samthor/intellij-community,samthor/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,alphafoobar/intellij-community,diorcety/intellij-community,michaelgallacher/intellij-community,mglukhikh/intellij-community,muntasirsyed/intellij-community,slisson/intellij-community,asedunov/intellij-community,signed/intellij-community,adedayo/intellij-community,slisson/intellij-community,supersven/intellij-community,fengbaicanhe/intellij-community,amith01994/intellij-community,SerCeMan/intellij-community,michaelgallacher/intellij-community,ftomassetti/intellij-community,kdwink/intellij-community,fnouama/intellij-community,suncycheng/intellij-community,slisson/intellij-community,da1z/intellij-community,MER-GROUP/intellij-community,xfournet/intellij-community,Lekanich/intellij-community,robovm/robovm-studio,hurricup/intellij-community,apixandru/intellij-community,SerCeMan/intellij-community,ryano144/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,adedayo/intellij-community,pwoodworth/intellij-community,caot/intellij-community,MichaelNedzelsky/intellij-community,apixandru/intellij-community,tmpgit/intellij-community,dslomov/intellij-community,jagguli/intellij-community,lucafavatella/intellij-community,fengbaicanhe/intellij-community,Lekanich/intellij-community,Distrotech/intellij-community,nicolargo/intellij-community,Distrotech/intellij-community,ibinti/intellij-community,FHannes/intellij-community,ibinti/intellij-community,izonder/intellij-community,FHannes/intellij-community,lucafavatella/intellij-community,ivan-fedorov/intellij-community,ol-loginov/intellij-community,ftomassetti/intellij-community,pwoodworth/intellij-community,fitermay/intellij-community,xfournet/intellij-community,semonte/intellij-community,ahb0327/intellij-community,da1z/intellij-community,xfournet/intellij-community,lucafavatella/intellij-community,robovm/robovm-studio,dslomov/intellij-community,vladmm/intellij-community,MER-GROUP/intellij-community,ftomassetti/intellij-community,fitermay/intellij-community,caot/intellij-community,nicolargo/intellij-community,muntasirsyed/intellij-community,MichaelNedzelsky/intellij-community,salguarnieri/intellij-community,gnuhub/intellij-community,hurricup/intellij-community,allotria/intellij-community,ahb0327/intellij-community,fengbaicanhe/intellij-community,vladmm/intellij-community,salguarnieri/intellij-community,signed/intellij-community,caot/intellij-community,joewalnes/idea-community,lucafavatella/intellij-community,SerCeMan/intellij-community,allotria/intellij-community,retomerz/intellij-community,dslomov/intellij-community,adedayo/intellij-community,vladmm/intellij-community,nicolargo/intellij-community,apixandru/intellij-community,amith01994/intellij-community,supersven/intellij-community,adedayo/intellij-community,petteyg/intellij-community,FHannes/intellij-community,orekyuu/intellij-community,jexp/idea2,kool79/intellij-community,signed/intellij-community,MER-GROUP/intellij-community,ryano144/intellij-community,alphafoobar/intellij-community,amith01994/intellij-community,slisson/intellij-community,muntasirsyed/intellij-community,ivan-fedorov/intellij-community,vladmm/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,jagguli/intellij-community,kool79/intellij-community,FHannes/intellij-community,robovm/robovm-studio,Distrotech/intellij-community,tmpgit/intellij-community,adedayo/intellij-community,Distrotech/intellij-community,caot/intellij-community,wreckJ/intellij-community,ol-loginov/intellij-community,ol-loginov/intellij-community,ryano144/intellij-community,salguarnieri/intellij-community,ftomassetti/intellij-community,TangHao1987/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,tmpgit/intellij-community,youdonghai/intellij-community,fengbaicanhe/intellij-community,lucafavatella/intellij-community,akosyakov/intellij-community,tmpgit/intellij-community,caot/intellij-community,ivan-fedorov/intellij-community,lucafavatella/intellij-community,orekyuu/intellij-community,wreckJ/intellij-community,ThiagoGarciaAlves/intellij-community,hurricup/intellij-community,signed/intellij-community,amith01994/intellij-community,ivan-fedorov/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,da1z/intellij-community,vladmm/intellij-community,idea4bsd/idea4bsd,nicolargo/intellij-community,hurricup/intellij-community,holmes/intellij-community,da1z/intellij-community,signed/intellij-community,fengbaicanhe/intellij-community,ibinti/intellij-community,ernestp/consulo,asedunov/intellij-community,youdonghai/intellij-community,ol-loginov/intellij-community,samthor/intellij-community,da1z/intellij-community,ryano144/intellij-community,vvv1559/intellij-community,fengbaicanhe/intellij-community,MichaelNedzelsky/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,pwoodworth/intellij-community,robovm/robovm-studio,kool79/intellij-community,vvv1559/intellij-community,michaelgallacher/intellij-community,alphafoobar/intellij-community,asedunov/intellij-community,ernestp/consulo,diorcety/intellij-community,kool79/intellij-community,ivan-fedorov/intellij-community,suncycheng/intellij-community,nicolargo/intellij-community,orekyuu/intellij-community,mglukhikh/intellij-community,orekyuu/intellij-community,ibinti/intellij-community,jagguli/intellij-community,vvv1559/intellij-community,clumsy/intellij-community,kool79/intellij-community,izonder/intellij-community,samthor/intellij-community,vvv1559/intellij-community,slisson/intellij-community,apixandru/intellij-community,fitermay/intellij-community,retomerz/intellij-community,kool79/intellij-community,fengbaicanhe/intellij-community,gnuhub/intellij-community,salguarnieri/intellij-community,michaelgallacher/intellij-community,lucafavatella/intellij-community,blademainer/intellij-community,signed/intellij-community,dslomov/intellij-community,kdwink/intellij-community,youdonghai/intellij-community,semonte/intellij-community,ahb0327/intellij-community,xfournet/intellij-community,petteyg/intellij-community,clumsy/intellij-community,semonte/intellij-community,supersven/intellij-community,dslomov/intellij-community,semonte/intellij-community,fitermay/intellij-community,hurricup/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,signed/intellij-community,joewalnes/idea-community,jagguli/intellij-community,jexp/idea2,ibinti/intellij-community,pwoodworth/intellij-community,SerCeMan/intellij-community,consulo/consulo,pwoodworth/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,kool79/intellij-community,ftomassetti/intellij-community,da1z/intellij-community,supersven/intellij-community,nicolargo/intellij-community,supersven/intellij-community,akosyakov/intellij-community,clumsy/intellij-community,Lekanich/intellij-community,Distrotech/intellij-community,SerCeMan/intellij-community,TangHao1987/intellij-community,orekyuu/intellij-community,semonte/intellij-community,xfournet/intellij-community,izonder/intellij-community,MER-GROUP/intellij-community,ryano144/intellij-community,vladmm/intellij-community,mglukhikh/intellij-community,alphafoobar/intellij-community,youdonghai/intellij-community,ahb0327/intellij-community,tmpgit/intellij-community,amith01994/intellij-community,ol-loginov/intellij-community,kdwink/intellij-community,fnouama/intellij-community,diorcety/intellij-community,jagguli/intellij-community,wreckJ/intellij-community,izonder/intellij-community,da1z/intellij-community,slisson/intellij-community,wreckJ/intellij-community,holmes/intellij-community,diorcety/intellij-community,fnouama/intellij-community,fitermay/intellij-community,lucafavatella/intellij-community,ibinti/intellij-community,michaelgallacher/intellij-community,lucafavatella/intellij-community,asedunov/intellij-community,fengbaicanhe/intellij-community,SerCeMan/intellij-community,salguarnieri/intellij-community,MER-GROUP/intellij-community,amith01994/intellij-community,muntasirsyed/intellij-community,orekyuu/intellij-community,ftomassetti/intellij-community,blademainer/intellij-community,nicolargo/intellij-community,fengbaicanhe/intellij-community,salguarnieri/intellij-community,gnuhub/intellij-community,retomerz/intellij-community,ThiagoGarciaAlves/intellij-community,kdwink/intellij-community,FHannes/intellij-community,tmpgit/intellij-community,MichaelNedzelsky/intellij-community,jagguli/intellij-community,joewalnes/idea-community,samthor/intellij-community,petteyg/intellij-community,ahb0327/intellij-community,mglukhikh/intellij-community,kdwink/intellij-community,asedunov/intellij-community,orekyuu/intellij-community,blademainer/intellij-community,Lekanich/intellij-community,jexp/idea2,xfournet/intellij-community,MichaelNedzelsky/intellij-community,vladmm/intellij-community,blademainer/intellij-community,amith01994/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,MER-GROUP/intellij-community,fengbaicanhe/intellij-community,joewalnes/idea-community,kdwink/intellij-community,ernestp/consulo,ivan-fedorov/intellij-community,idea4bsd/idea4bsd,muntasirsyed/intellij-community,ol-loginov/intellij-community,fitermay/intellij-community,pwoodworth/intellij-community,ryano144/intellij-community,Lekanich/intellij-community,alphafoobar/intellij-community,diorcety/intellij-community,muntasirsyed/intellij-community,da1z/intellij-community,ivan-fedorov/intellij-community,gnuhub/intellij-community,FHannes/intellij-community,TangHao1987/intellij-community,Distrotech/intellij-community,nicolargo/intellij-community,apixandru/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,TangHao1987/intellij-community,alphafoobar/intellij-community,gnuhub/intellij-community,consulo/consulo,kdwink/intellij-community,samthor/intellij-community,izonder/intellij-community,ryano144/intellij-community,ftomassetti/intellij-community,xfournet/intellij-community,akosyakov/intellij-community,gnuhub/intellij-community,apixandru/intellij-community,apixandru/intellij-community,wreckJ/intellij-community,jexp/idea2,adedayo/intellij-community,adedayo/intellij-community,pwoodworth/intellij-community,FHannes/intellij-community,consulo/consulo,ivan-fedorov/intellij-community,suncycheng/intellij-community,nicolargo/intellij-community,salguarnieri/intellij-community,xfournet/intellij-community,samthor/intellij-community,FHannes/intellij-community,michaelgallacher/intellij-community,jexp/idea2,muntasirsyed/intellij-community,salguarnieri/intellij-community,SerCeMan/intellij-community,hurricup/intellij-community,apixandru/intellij-community,fitermay/intellij-community,izonder/intellij-community,youdonghai/intellij-community,TangHao1987/intellij-community,ftomassetti/intellij-community,Lekanich/intellij-community,ThiagoGarciaAlves/intellij-community,dslomov/intellij-community,kool79/intellij-community,muntasirsyed/intellij-community,fengbaicanhe/intellij-community,robovm/robovm-studio,Distrotech/intellij-community,diorcety/intellij-community,alphafoobar/intellij-community,joewalnes/idea-community,allotria/intellij-community,supersven/intellij-community,hurricup/intellij-community,dslomov/intellij-community,MichaelNedzelsky/intellij-community,idea4bsd/idea4bsd,Lekanich/intellij-community,fitermay/intellij-community,supersven/intellij-community,ahb0327/intellij-community,holmes/intellij-community,holmes/intellij-community,dslomov/intellij-community,blademainer/intellij-community,michaelgallacher/intellij-community,ernestp/consulo,wreckJ/intellij-community,vladmm/intellij-community,clumsy/intellij-community,ftomassetti/intellij-community,gnuhub/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,ryano144/intellij-community,semonte/intellij-community,ahb0327/intellij-community,ivan-fedorov/intellij-community,samthor/intellij-community,retomerz/intellij-community,youdonghai/intellij-community,michaelgallacher/intellij-community,jagguli/intellij-community,jagguli/intellij-community,fnouama/intellij-community,consulo/consulo,izonder/intellij-community,idea4bsd/idea4bsd,blademainer/intellij-community,ftomassetti/intellij-community,fnouama/intellij-community,holmes/intellij-community,hurricup/intellij-community,muntasirsyed/intellij-community,ThiagoGarciaAlves/intellij-community,akosyakov/intellij-community,signed/intellij-community,nicolargo/intellij-community,Lekanich/intellij-community,tmpgit/intellij-community,ahb0327/intellij-community,petteyg/intellij-community,gnuhub/intellij-community,pwoodworth/intellij-community,orekyuu/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,jexp/idea2,muntasirsyed/intellij-community,michaelgallacher/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,xfournet/intellij-community,dslomov/intellij-community,alphafoobar/intellij-community,adedayo/intellij-community,ol-loginov/intellij-community,fnouama/intellij-community,Distrotech/intellij-community,michaelgallacher/intellij-community,MER-GROUP/intellij-community,akosyakov/intellij-community,ryano144/intellij-community,MER-GROUP/intellij-community,tmpgit/intellij-community,blademainer/intellij-community,supersven/intellij-community,kool79/intellij-community,kdwink/intellij-community,wreckJ/intellij-community,SerCeMan/intellij-community,clumsy/intellij-community,FHannes/intellij-community,robovm/robovm-studio,retomerz/intellij-community,nicolargo/intellij-community,kdwink/intellij-community,hurricup/intellij-community,tmpgit/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,dslomov/intellij-community,asedunov/intellij-community,MichaelNedzelsky/intellij-community,holmes/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,ernestp/consulo,alphafoobar/intellij-community,xfournet/intellij-community,da1z/intellij-community,ibinti/intellij-community,ryano144/intellij-community,vladmm/intellij-community,TangHao1987/intellij-community,blademainer/intellij-community,retomerz/intellij-community,salguarnieri/intellij-community,lucafavatella/intellij-community,vvv1559/intellij-community,wreckJ/intellij-community,amith01994/intellij-community,salguarnieri/intellij-community,asedunov/intellij-community,jagguli/intellij-community,caot/intellij-community,asedunov/intellij-community,semonte/intellij-community,fnouama/intellij-community,michaelgallacher/intellij-community,asedunov/intellij-community,adedayo/intellij-community,caot/intellij-community,pwoodworth/intellij-community,kool79/intellij-community,caot/intellij-community,vladmm/intellij-community,idea4bsd/idea4bsd,lucafavatella/intellij-community,clumsy/intellij-community,tmpgit/intellij-community,izonder/intellij-community,wreckJ/intellij-community,diorcety/intellij-community,petteyg/intellij-community,slisson/intellij-community,dslomov/intellij-community,vvv1559/intellij-community,blademainer/intellij-community,orekyuu/intellij-community,SerCeMan/intellij-community,ivan-fedorov/intellij-community,ahb0327/intellij-community,allotria/intellij-community,hurricup/intellij-community,TangHao1987/intellij-community,gnuhub/intellij-community,holmes/intellij-community,wreckJ/intellij-community,muntasirsyed/intellij-community,MichaelNedzelsky/intellij-community,kdwink/intellij-community,joewalnes/idea-community,youdonghai/intellij-community,apixandru/intellij-community,samthor/intellij-community,izonder/intellij-community,MER-GROUP/intellij-community,hurricup/intellij-community,hurricup/intellij-community,fengbaicanhe/intellij-community,izonder/intellij-community,ahb0327/intellij-community,MichaelNedzelsky/intellij-community,suncycheng/intellij-community,MER-GROUP/intellij-community,caot/intellij-community,akosyakov/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,petteyg/intellij-community,orekyuu/intellij-community,tmpgit/intellij-community,pwoodworth/intellij-community,robovm/robovm-studio,TangHao1987/intellij-community,robovm/robovm-studio,Distrotech/intellij-community,fnouama/intellij-community,retomerz/intellij-community,caot/intellij-community,adedayo/intellij-community,robovm/robovm-studio,robovm/robovm-studio,amith01994/intellij-community,kool79/intellij-community,holmes/intellij-community,amith01994/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,adedayo/intellij-community,mglukhikh/intellij-community,alphafoobar/intellij-community,mglukhikh/intellij-community,TangHao1987/intellij-community,TangHao1987/intellij-community,fitermay/intellij-community,pwoodworth/intellij-community,izonder/intellij-community,joewalnes/idea-community,youdonghai/intellij-community,akosyakov/intellij-community,diorcety/intellij-community,slisson/intellij-community,allotria/intellij-community,TangHao1987/intellij-community,retomerz/intellij-community,Lekanich/intellij-community,caot/intellij-community,apixandru/intellij-community,semonte/intellij-community,caot/intellij-community,lucafavatella/intellij-community,jagguli/intellij-community,apixandru/intellij-community,nicolargo/intellij-community,petteyg/intellij-community,lucafavatella/intellij-community,da1z/intellij-community,signed/intellij-community,slisson/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,kool79/intellij-community,xfournet/intellij-community,alphafoobar/intellij-community,Distrotech/intellij-community,slisson/intellij-community,ol-loginov/intellij-community,fnouama/intellij-community,ftomassetti/intellij-community,signed/intellij-community,holmes/intellij-community,wreckJ/intellij-community,diorcety/intellij-community,diorcety/intellij-community,supersven/intellij-community,Lekanich/intellij-community,adedayo/intellij-community,supersven/intellij-community,slisson/intellij-community,clumsy/intellij-community,gnuhub/intellij-community,vladmm/intellij-community,MichaelNedzelsky/intellij-community,slisson/intellij-community,FHannes/intellij-community,signed/intellij-community,SerCeMan/intellij-community,clumsy/intellij-community,apixandru/intellij-community,da1z/intellij-community,diorcety/intellij-community,SerCeMan/intellij-community,ftomassetti/intellij-community,ivan-fedorov/intellij-community,ibinti/intellij-community,supersven/intellij-community,dslomov/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,clumsy/intellij-community,diorcety/intellij-community,youdonghai/intellij-community,Lekanich/intellij-community,izonder/intellij-community,FHannes/intellij-community,pwoodworth/intellij-community,robovm/robovm-studio,clumsy/intellij-community,jagguli/intellij-community,samthor/intellij-community,petteyg/intellij-community,MichaelNedzelsky/intellij-community,kdwink/intellij-community,akosyakov/intellij-community,holmes/intellij-community,petteyg/intellij-community,akosyakov/intellij-community,blademainer/intellij-community
|
package com.intellij.codeInsight.daemon.impl.quickfix;
import com.intellij.codeInsight.CodeInsightUtil;
import com.intellij.codeInsight.daemon.QuickFixBundle;
import com.intellij.codeInsight.intention.impl.BaseIntentionAction;
import com.intellij.codeInsight.template.Template;
import com.intellij.codeInsight.template.TemplateEditingListener;
import com.intellij.codeInsight.template.TemplateManager;
import com.intellij.ide.util.PsiClassListCellRenderer;
import com.intellij.ide.util.PsiElementListCellRenderer;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.fileEditor.OpenFileDescriptor;
import com.intellij.openapi.fileEditor.ex.IdeDocumentHistory;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.popup.PopupChooserBuilder;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.*;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Vector;
/**
* @author Mike
*/
public abstract class CreateFromUsageBaseFix extends BaseIntentionAction {
private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.daemon.impl.quickfix.CreateFromUsageBaseFix");
protected CreateFromUsageBaseFix() {
}
public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
int offset = editor.getCaretModel().getOffset();
PsiElement element = getElement();
if (element == null) {
return false;
}
List<PsiClass> targetClasses = getTargetClasses(element);
return !targetClasses.isEmpty() && !isValidElement(element) && isAvailableImpl(offset);
}
protected abstract boolean isAvailableImpl(int offset);
protected abstract void invokeImpl(PsiClass targetClass);
protected abstract boolean isValidElement(PsiElement result);
public void invoke(@NotNull Project project, Editor editor, PsiFile file) {
PsiDocumentManager.getInstance(project).commitAllDocuments();
PsiElement element = getElement();
if (LOG.isDebugEnabled()) {
LOG.debug("CreateFromUsage: element =" + element);
}
if (element == null) {
return;
}
List<PsiClass> targetClasses = getTargetClasses(element);
if (targetClasses.isEmpty()) return;
if (targetClasses.size() == 1) {
doInvoke(project, targetClasses.get(0));
} else {
chooseTargetClass(targetClasses, editor);
}
}
private void doInvoke(Project project, PsiClass targetClass) {
if (!CodeInsightUtil.prepareFileForWrite(targetClass.getContainingFile())) {
return;
}
IdeDocumentHistory.getInstance(project).includeCurrentPlaceAsChangePlace();
invokeImpl(targetClass);
}
@Nullable
protected abstract PsiElement getElement();
private void chooseTargetClass(List<PsiClass> classes, final Editor editor) {
final Project project = classes.get(0).getProject();
final JList list = new JList(new Vector<PsiClass>(classes));
PsiElementListCellRenderer renderer = new PsiClassListCellRenderer();
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list.setCellRenderer(renderer);
renderer.installSpeedSearch(list);
Runnable runnable = new Runnable() {
public void run() {
int index = list.getSelectedIndex();
if (index < 0) return;
final PsiClass aClass = (PsiClass) list.getSelectedValue();
CommandProcessor.getInstance().executeCommand(project, new Runnable() {
public void run() {
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
doInvoke(project, aClass);
}
});
}
}, getText(), null);
}
};
new PopupChooserBuilder(list).
setTitle(QuickFixBundle.message("target.class.chooser.title")).
setItemChoosenCallback(runnable).
createPopup().
showInBestPositionFor(editor);
}
protected static Editor positionCursor(Project project, PsiFile targetFile, PsiElement element) {
TextRange range = element.getTextRange();
int textOffset = range.getStartOffset();
OpenFileDescriptor descriptor = new OpenFileDescriptor(project, targetFile.getVirtualFile(), textOffset);
return FileEditorManager.getInstance(project).openTextEditor(descriptor, true);
}
protected static void setupVisibility(PsiClass parentClass, PsiClass targetClass, PsiModifierList list) throws IncorrectOperationException {
if (targetClass.isInterface()) {
list.deleteChildRange(list.getFirstChild(), list.getLastChild());
return;
}
if (parentClass != null && (parentClass.equals(targetClass) || PsiTreeUtil.isAncestor(targetClass, parentClass, true))) {
list.setModifierProperty(PsiModifier.PRIVATE, true);
} else {
list.setModifierProperty(PsiModifier.PUBLIC, true);
}
}
protected static boolean shouldCreateStaticMember(PsiReferenceExpression ref, PsiElement enclosingContext, PsiClass targetClass) {
if (targetClass.isInterface()) {
return false;
}
PsiExpression qualifierExpression = ref.getQualifierExpression();
while (qualifierExpression instanceof PsiParenthesizedExpression) {
qualifierExpression = ((PsiParenthesizedExpression) qualifierExpression).getExpression();
}
if (qualifierExpression instanceof PsiReferenceExpression) {
PsiReferenceExpression referenceExpression = (PsiReferenceExpression) qualifierExpression;
PsiElement resolvedElement = referenceExpression.resolve();
return resolvedElement instanceof PsiClass;
} else if (qualifierExpression instanceof PsiTypeCastExpression) {
return false;
} else if (qualifierExpression instanceof PsiCallExpression) {
return false;
} else {
if (enclosingContext instanceof PsiMethod) {
PsiMethodCallExpression callExpression;
if (ref.getParent() instanceof PsiMethodCallExpression) {
callExpression = PsiTreeUtil.getParentOfType(ref.getParent(), PsiMethodCallExpression.class);
} else {
callExpression = PsiTreeUtil.getParentOfType(ref, PsiMethodCallExpression.class);
}
if (callExpression != null) {
final String callText = callExpression.getMethodExpression().getText();
if (callText.equals(PsiKeyword.SUPER) || callText.equals(PsiKeyword.THIS)) {
return true;
}
}
PsiMethod method = (PsiMethod) enclosingContext;
if (PsiTreeUtil.isAncestor(targetClass, method, false)) {
do {
if (method.hasModifierProperty(PsiModifier.STATIC)) {
return true;
}
if (method.getContainingClass() == targetClass) break;
method = PsiTreeUtil.getParentOfType(method, PsiMethod.class);
}
while(method != null);
}
else {
return method.hasModifierProperty(PsiModifier.STATIC);
}
} else if (enclosingContext instanceof PsiField) {
PsiField field = (PsiField) enclosingContext;
return field.hasModifierProperty(PsiModifier.STATIC);
} else if (enclosingContext instanceof PsiClassInitializer) {
PsiClassInitializer initializer = (PsiClassInitializer) enclosingContext;
return initializer.hasModifierProperty(PsiModifier.STATIC);
}
}
return false;
}
private static PsiExpression getQualifier (PsiElement element) {
if (element instanceof PsiNewExpression) {
PsiJavaCodeReferenceElement ref = ((PsiNewExpression) element).getClassReference();
if (ref instanceof PsiReferenceExpression) {
return ((PsiReferenceExpression) ref).getQualifierExpression();
}
} else if (element instanceof PsiReferenceExpression) {
return ((PsiReferenceExpression) element).getQualifierExpression();
} else if (element instanceof PsiMethodCallExpression) {
return ((PsiMethodCallExpression) element).getMethodExpression().getQualifierExpression();
}
return null;
}
protected static PsiSubstitutor getTargetSubstitutor (PsiElement element) {
if (element instanceof PsiNewExpression) {
JavaResolveResult result = ((PsiNewExpression)element).getClassOrAnonymousClassReference().advancedResolve(false);
PsiSubstitutor substitutor = result.getSubstitutor();
return substitutor == null ? PsiSubstitutor.EMPTY : substitutor;
}
PsiExpression qualifier = getQualifier(element);
if (qualifier != null) {
PsiType type = qualifier.getType();
if (type instanceof PsiClassType) {
return ((PsiClassType)type).resolveGenerics().getSubstitutor();
}
}
return PsiSubstitutor.EMPTY;
}
protected boolean isAllowOuterTargetClass() {
return true;
}
//Should return only valid inproject classes
@NotNull
protected List<PsiClass> getTargetClasses(PsiElement element) {
PsiClass psiClass = null;
PsiExpression qualifier = null;
if (element instanceof PsiNewExpression) {
final PsiNewExpression newExpression = (PsiNewExpression)element;
PsiJavaCodeReferenceElement ref = newExpression.getClassReference();
if (ref != null) {
PsiElement refElement = ref.resolve();
if (refElement instanceof PsiClass) psiClass = (PsiClass)refElement;
}
}
else if (element instanceof PsiReferenceExpression) {
qualifier = ((PsiReferenceExpression)element).getQualifierExpression();
}
else if (element instanceof PsiMethodCallExpression) {
final PsiReferenceExpression methodExpression = ((PsiMethodCallExpression)element).getMethodExpression();
qualifier = methodExpression.getQualifierExpression();
@NonNls final String referenceName = methodExpression.getReferenceName();
if (referenceName == null) return Collections.emptyList();
}
boolean allowOuterClasses = false;
if (qualifier != null) {
PsiType type = qualifier.getType();
if (type instanceof PsiClassType) {
psiClass = ((PsiClassType)type).resolve();
}
if (qualifier instanceof PsiJavaCodeReferenceElement) {
final PsiElement resolved = ((PsiJavaCodeReferenceElement)qualifier).resolve();
if (resolved instanceof PsiClass) {
if (psiClass == null) psiClass = (PsiClass)resolved;
}
}
} else if (psiClass == null) {
psiClass = PsiTreeUtil.getParentOfType(element, PsiClass.class);
allowOuterClasses = true;
}
if (psiClass instanceof PsiTypeParameter) {
PsiClass[] supers = psiClass.getSupers();
List<PsiClass> filtered = new ArrayList<PsiClass>();
for (PsiClass aSuper : supers) {
if (!aSuper.getManager().isInProject(aSuper)) continue;
if (!(aSuper instanceof PsiTypeParameter)) filtered.add(aSuper);
}
return filtered;
}
else {
if (psiClass == null || !psiClass.getManager().isInProject(psiClass)) {
return Collections.emptyList();
}
if (!allowOuterClasses ||
!isAllowOuterTargetClass() ||
ApplicationManager.getApplication().isUnitTestMode())
return Collections.singletonList(psiClass);
List<PsiClass> result = new ArrayList<PsiClass>();
while (psiClass != null) {
result.add(psiClass);
if (psiClass.hasModifierProperty(PsiModifier.STATIC)) break;
psiClass = PsiTreeUtil.getParentOfType(psiClass, PsiClass.class);
}
return result;
}
}
protected static void startTemplate (final Editor editor, final Template template, final Project project) {
Runnable runnable = new Runnable() {
public void run() {
TemplateManager.getInstance(project).startTemplate(editor, template);
}
};
if (!ApplicationManager.getApplication().isUnitTestMode()) {
ApplicationManager.getApplication().invokeLater(runnable);
}
else {
runnable.run();
}
}
protected static void startTemplate (final Editor editor, final Template template, final Project project, final TemplateEditingListener listener) {
Runnable runnable = new Runnable() {
public void run() {
TemplateManager.getInstance(project).startTemplate(editor, template, listener);
}
};
if (!ApplicationManager.getApplication().isUnitTestMode()) {
ApplicationManager.getApplication().invokeLater(runnable);
}
else {
runnable.run();
}
}
}
|
codeInsight/impl/com/intellij/codeInsight/daemon/impl/quickfix/CreateFromUsageBaseFix.java
|
package com.intellij.codeInsight.daemon.impl.quickfix;
import com.intellij.codeInsight.CodeInsightUtil;
import com.intellij.codeInsight.daemon.QuickFixBundle;
import com.intellij.codeInsight.intention.impl.BaseIntentionAction;
import com.intellij.codeInsight.template.Template;
import com.intellij.codeInsight.template.TemplateEditingListener;
import com.intellij.codeInsight.template.TemplateManager;
import com.intellij.ide.util.PsiClassListCellRenderer;
import com.intellij.ide.util.PsiElementListCellRenderer;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.fileEditor.OpenFileDescriptor;
import com.intellij.openapi.fileEditor.ex.IdeDocumentHistory;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.popup.PopupChooserBuilder;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.*;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Vector;
/**
* @author Mike
*/
public abstract class CreateFromUsageBaseFix extends BaseIntentionAction {
private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.daemon.impl.quickfix.CreateFromUsageBaseFix");
protected CreateFromUsageBaseFix() {
}
public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
int offset = editor.getCaretModel().getOffset();
PsiElement element = getElement();
if (element == null) {
return false;
}
List<PsiClass> targetClasses = getTargetClasses(element);
return !targetClasses.isEmpty() && !isValidElement(element) && isAvailableImpl(offset);
}
protected abstract boolean isAvailableImpl(int offset);
protected abstract void invokeImpl(PsiClass targetClass);
protected abstract boolean isValidElement(PsiElement result);
public void invoke(@NotNull Project project, Editor editor, PsiFile file) {
PsiDocumentManager.getInstance(project).commitAllDocuments();
PsiElement element = getElement();
if (LOG.isDebugEnabled()) {
LOG.debug("CreateFromUsage: element =" + element);
}
if (element == null) {
return;
}
List<PsiClass> targetClasses = getTargetClasses(element);
if (targetClasses.isEmpty()) return;
if (targetClasses.size() == 1) {
doInvoke(project, targetClasses.get(0));
} else {
chooseTargetClass(targetClasses, editor);
}
}
private void doInvoke(Project project, PsiClass targetClass) {
if (!CodeInsightUtil.prepareFileForWrite(targetClass.getContainingFile())) {
return;
}
IdeDocumentHistory.getInstance(project).includeCurrentPlaceAsChangePlace();
invokeImpl(targetClass);
}
@Nullable
protected abstract PsiElement getElement();
private void chooseTargetClass(List<PsiClass> classes, final Editor editor) {
final Project project = classes.get(0).getProject();
final JList list = new JList(new Vector<PsiClass>(classes));
PsiElementListCellRenderer renderer = new PsiClassListCellRenderer();
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list.setCellRenderer(renderer);
renderer.installSpeedSearch(list);
Runnable runnable = new Runnable() {
public void run() {
int index = list.getSelectedIndex();
if (index < 0) return;
final PsiClass aClass = (PsiClass) list.getSelectedValue();
CommandProcessor.getInstance().executeCommand(project, new Runnable() {
public void run() {
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
doInvoke(project, aClass);
}
});
}
}, getText(), null);
}
};
new PopupChooserBuilder(list).
setTitle(QuickFixBundle.message("target.class.chooser.title")).
setItemChoosenCallback(runnable).
createPopup().
showInBestPositionFor(editor);
}
protected static Editor positionCursor(Project project, PsiFile targetFile, PsiElement element) {
TextRange range = element.getTextRange();
int textOffset = range.getStartOffset();
OpenFileDescriptor descriptor = new OpenFileDescriptor(project, targetFile.getVirtualFile(), textOffset);
return FileEditorManager.getInstance(project).openTextEditor(descriptor, true);
}
protected static void setupVisibility(PsiClass parentClass, PsiClass targetClass, PsiModifierList list) throws IncorrectOperationException {
if (targetClass.isInterface()) {
list.deleteChildRange(list.getFirstChild(), list.getLastChild());
return;
}
if (parentClass != null && (parentClass.equals(targetClass) || PsiTreeUtil.isAncestor(targetClass, parentClass, true))) {
list.setModifierProperty(PsiModifier.PRIVATE, true);
} else {
list.setModifierProperty(PsiModifier.PUBLIC, true);
}
}
protected static boolean shouldCreateStaticMember(PsiReferenceExpression ref, PsiElement enclosingContext, PsiClass targetClass) {
if (targetClass.isInterface()) {
return false;
}
PsiExpression qualifierExpression = ref.getQualifierExpression();
while (qualifierExpression instanceof PsiParenthesizedExpression) {
qualifierExpression = ((PsiParenthesizedExpression) qualifierExpression).getExpression();
}
if (qualifierExpression instanceof PsiReferenceExpression) {
PsiReferenceExpression referenceExpression = (PsiReferenceExpression) qualifierExpression;
PsiElement resolvedElement = referenceExpression.resolve();
return resolvedElement instanceof PsiClass;
} else if (qualifierExpression instanceof PsiTypeCastExpression) {
return false;
} else if (qualifierExpression instanceof PsiCallExpression) {
return false;
} else {
if (enclosingContext instanceof PsiMethod) {
PsiMethodCallExpression callExpression;
if (ref.getParent() instanceof PsiMethodCallExpression) {
callExpression = PsiTreeUtil.getParentOfType(ref.getParent(), PsiMethodCallExpression.class);
} else {
callExpression = PsiTreeUtil.getParentOfType(ref, PsiMethodCallExpression.class);
}
if (callExpression != null) {
final String callText = callExpression.getMethodExpression().getText();
if (callText.equals(PsiKeyword.SUPER) || callText.equals(PsiKeyword.THIS)) {
return true;
}
}
PsiMethod method = (PsiMethod) enclosingContext;
return method.hasModifierProperty(PsiModifier.STATIC);
} else if (enclosingContext instanceof PsiField) {
PsiField field = (PsiField) enclosingContext;
return field.hasModifierProperty(PsiModifier.STATIC);
} else if (enclosingContext instanceof PsiClassInitializer) {
PsiClassInitializer initializer = (PsiClassInitializer) enclosingContext;
return initializer.hasModifierProperty(PsiModifier.STATIC);
}
}
return false;
}
private static PsiExpression getQualifier (PsiElement element) {
if (element instanceof PsiNewExpression) {
PsiJavaCodeReferenceElement ref = ((PsiNewExpression) element).getClassReference();
if (ref instanceof PsiReferenceExpression) {
return ((PsiReferenceExpression) ref).getQualifierExpression();
}
} else if (element instanceof PsiReferenceExpression) {
return ((PsiReferenceExpression) element).getQualifierExpression();
} else if (element instanceof PsiMethodCallExpression) {
return ((PsiMethodCallExpression) element).getMethodExpression().getQualifierExpression();
}
return null;
}
protected static PsiSubstitutor getTargetSubstitutor (PsiElement element) {
if (element instanceof PsiNewExpression) {
JavaResolveResult result = ((PsiNewExpression)element).getClassOrAnonymousClassReference().advancedResolve(false);
PsiSubstitutor substitutor = result.getSubstitutor();
return substitutor == null ? PsiSubstitutor.EMPTY : substitutor;
}
PsiExpression qualifier = getQualifier(element);
if (qualifier != null) {
PsiType type = qualifier.getType();
if (type instanceof PsiClassType) {
return ((PsiClassType)type).resolveGenerics().getSubstitutor();
}
}
return PsiSubstitutor.EMPTY;
}
protected boolean isAllowOuterTargetClass() {
return true;
}
//Should return only valid inproject classes
@NotNull
protected List<PsiClass> getTargetClasses(PsiElement element) {
PsiClass psiClass = null;
PsiExpression qualifier = null;
if (element instanceof PsiNewExpression) {
final PsiNewExpression newExpression = (PsiNewExpression)element;
PsiJavaCodeReferenceElement ref = newExpression.getClassReference();
if (ref != null) {
PsiElement refElement = ref.resolve();
if (refElement instanceof PsiClass) psiClass = (PsiClass)refElement;
}
}
else if (element instanceof PsiReferenceExpression) {
qualifier = ((PsiReferenceExpression)element).getQualifierExpression();
}
else if (element instanceof PsiMethodCallExpression) {
final PsiReferenceExpression methodExpression = ((PsiMethodCallExpression)element).getMethodExpression();
qualifier = methodExpression.getQualifierExpression();
@NonNls final String referenceName = methodExpression.getReferenceName();
if (referenceName == null) return Collections.emptyList();
}
boolean allowOuterClasses = false;
if (qualifier != null) {
PsiType type = qualifier.getType();
if (type instanceof PsiClassType) {
psiClass = ((PsiClassType)type).resolve();
}
if (qualifier instanceof PsiJavaCodeReferenceElement) {
final PsiElement resolved = ((PsiJavaCodeReferenceElement)qualifier).resolve();
if (resolved instanceof PsiClass) {
if (psiClass == null) psiClass = (PsiClass)resolved;
}
}
} else if (psiClass == null) {
psiClass = PsiTreeUtil.getParentOfType(element, PsiClass.class);
allowOuterClasses = true;
}
if (psiClass instanceof PsiTypeParameter) {
PsiClass[] supers = psiClass.getSupers();
List<PsiClass> filtered = new ArrayList<PsiClass>();
for (PsiClass aSuper : supers) {
if (!aSuper.getManager().isInProject(aSuper)) continue;
if (!(aSuper instanceof PsiTypeParameter)) filtered.add(aSuper);
}
return filtered;
}
else {
if (psiClass == null || !psiClass.getManager().isInProject(psiClass)) {
return Collections.emptyList();
}
if (!allowOuterClasses ||
!isAllowOuterTargetClass() ||
ApplicationManager.getApplication().isUnitTestMode())
return Collections.singletonList(psiClass);
List<PsiClass> result = new ArrayList<PsiClass>();
while (psiClass != null) {
result.add(psiClass);
if (psiClass.hasModifierProperty(PsiModifier.STATIC)) break;
psiClass = PsiTreeUtil.getParentOfType(psiClass, PsiClass.class);
}
return result;
}
}
protected static void startTemplate (final Editor editor, final Template template, final Project project) {
Runnable runnable = new Runnable() {
public void run() {
TemplateManager.getInstance(project).startTemplate(editor, template);
}
};
if (!ApplicationManager.getApplication().isUnitTestMode()) {
ApplicationManager.getApplication().invokeLater(runnable);
}
else {
runnable.run();
}
}
protected static void startTemplate (final Editor editor, final Template template, final Project project, final TemplateEditingListener listener) {
Runnable runnable = new Runnable() {
public void run() {
TemplateManager.getInstance(project).startTemplate(editor, template, listener);
}
};
if (!ApplicationManager.getApplication().isUnitTestMode()) {
ApplicationManager.getApplication().invokeLater(runnable);
}
else {
runnable.run();
}
}
}
|
more correct detection of static context (IDEADEV-20386)
|
codeInsight/impl/com/intellij/codeInsight/daemon/impl/quickfix/CreateFromUsageBaseFix.java
|
more correct detection of static context (IDEADEV-20386)
|
|
Java
|
mit
|
afc28c958558034618b9ab01eadacc05096c8205
| 0
|
bitDecayGames/Jump
|
package com.bitdecay.jump.leveleditor.ui.menus;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.*;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.badlogic.gdx.scenes.scene2d.utils.SpriteDrawable;
import com.badlogic.gdx.scenes.scene2d.utils.TextureRegionDrawable;
import com.badlogic.gdx.utils.Align;
import com.bitdecay.jump.gdx.level.EditorIdentifierObject;
import com.bitdecay.jump.gdx.level.RenderableLevelObject;
import com.bitdecay.jump.leveleditor.EditorHook;
import com.bitdecay.jump.leveleditor.render.LevelEditor;
import com.bitdecay.jump.leveleditor.render.RenderLayer;
import com.bitdecay.jump.leveleditor.ui.ModeType;
import com.bitdecay.jump.leveleditor.ui.OptionsMode;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* This is a separate class from LevelEditor to try to make things easier to read.
* Created by Monday on 10/10/2015.
*/
public class EditorMenus {
private final LevelEditor levelEditor;
private final Stage stage;
private final Skin skin;
private Map<MenuPage, Actor> topMenus = new HashMap<>();
private Map<MenuPage, Actor> rightMenus = new HashMap<>();
private Actor currentTopMenu;
private Actor currentRightMenu;
public EditorMenus(LevelEditor levelEditor, EditorHook hooker) {
this.levelEditor = levelEditor;
TextureAtlas menuAtlas = new TextureAtlas(Gdx.files.internal(LevelEditor.ASSETS_FOLDER + "skins/ui.atlas"));
skin = new Skin(Gdx.files.internal(LevelEditor.ASSETS_FOLDER + "skins/menu-skin.json"), menuAtlas);
stage = new Stage();
topMenus.put(MenuPage.MainMenu, buildMainMenu());
rightMenus.put(MenuPage.TileMenu, buildTilesetMenu(hooker.getTilesets()));
rightMenus.put(MenuPage.LevelObjectMenu, buildObjectMenu(hooker.getCustomObjects()));
rightMenus.put(MenuPage.ThemeMenu, buildThemeMenu(hooker.getThemes()));
rightMenus.put(MenuPage.LayersMenu, buildLayerMenu());
rightMenus.put(MenuPage.RenderMenu, buildRenderMenu());
topMenuTransition(MenuPage.MainMenu);
}
private Actor buildRenderMenu() {
Table menu = new Table();
menu.setVisible(false);
menu.setFillParent(true);
menu.setOrigin(Align.topRight);
menu.align(Align.right);
for (RenderLayer layer : RenderLayer.values()) {
if (layer.userEditable) {
CheckBox checkBox = new CheckBox(layer.name(), skin);
checkBox.setChecked(true);
checkBox.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
layer.enabled = checkBox.isChecked();
}
});
menu.add(checkBox).align(Align.left).padRight(10).padBottom(5);
menu.row();
}
}
stage.addActor(menu);
return menu;
}
private Actor buildMainMenu() {
Table menu = new Table();
menu.setWidth(stage.getWidth());
menu.align(Align.top);
Table miscActionTable = new Table();
for (OptionsMode mode : OptionsMode.values()) {
if (mode.type == ModeType.ACTION) {
buildImageButton(miscActionTable, mode, null);
}
}
menu.add(miscActionTable).padRight(40);
ButtonGroup toolGroup = new ButtonGroup();
toolGroup.setUncheckLast(true);
toolGroup.setMaxCheckCount(1);
toolGroup.setMinCheckCount(1);
Table toolsTable = new Table();
for (OptionsMode mode : OptionsMode.values()) {
if (mode.type == ModeType.MOUSE && mode.icon != null) {
buildImageButton(toolsTable, mode, toolGroup);
}
}
menu.add(toolsTable);
menu.align(Align.topLeft);
menu.setFillParent(true);
menu.setVisible(false);
stage.addActor(menu);
return menu;
}
private void buildImageButton(Table menu, OptionsMode mode, ButtonGroup btnGroup) {
Table itemTable = new Table();
TextureRegion testIcon = new TextureRegion(new Texture(Gdx.files.internal(LevelEditor.ASSETS_FOLDER + mode.icon)));
TextureRegionDrawable upDrawable = new TextureRegionDrawable(new TextureRegionDrawable(new TextureRegion(testIcon)));
SpriteDrawable downSprite = upDrawable.tint(Color.GREEN);
ImageButton button;
if (btnGroup != null) {
button = new ImageButton(upDrawable, downSprite, downSprite);
btnGroup.add(button);
} else {
button = new ImageButton(upDrawable, downSprite);
}
button.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
levelEditor.setMode(mode);
if (!ModeType.ACTION.equals(mode.type)) {
// Actions don't have menus, so only transition for non-action modes
rightMenuTransition(mode.menu);
}
}
});
// If we want to set the size explicitly, do it like this
// itemTable.add(button).width(32).height(32);
itemTable.add(button);
itemTable.row();
Label label = new Label(mode.label, skin);
itemTable.add(label);
menu.add(itemTable);
}
private Actor buildTilesetMenu(List<EditorIdentifierObject> tilesets) {
Table parentMenu = new Table();
parentMenu.setVisible(false);
parentMenu.setFillParent(true);
parentMenu.setOrigin(Align.topRight);
parentMenu.align(Align.right);
Table menu = new Table();
ScrollPane scrollPane = new ScrollPane(menu, skin);
scrollPane.setFadeScrollBars(false);
scrollPane.setScrollingDisabled(true, false);
parentMenu.add(scrollPane);
for (EditorIdentifierObject object : tilesets) {
Table itemTable = new Table();
TextureRegionDrawable upDrawable = new TextureRegionDrawable(new TextureRegionDrawable(object.texture));
SpriteDrawable downSprite = upDrawable.tint(Color.GREEN);
ImageButton button = new ImageButton(upDrawable, downSprite);
button.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
levelEditor.setMaterial(object.id);
}
});
itemTable.add(button).width(32).height(32);
itemTable.row();
Label label = new Label(object.displayName, skin);
itemTable.add(label).padBottom(20);
menu.add(itemTable).padRight(20);
menu.row();
}
menu.padBottom(-20);
stage.addActor(parentMenu);
return parentMenu;
}
private Actor buildLayerMenu() {
Table menu = new Table();
menu.setVisible(false);
menu.setFillParent(true);
menu.setOrigin(Align.topRight);
menu.align(Align.right);
ButtonGroup layersGroup = new ButtonGroup();
layersGroup.setUncheckLast(true);
layersGroup.setMaxCheckCount(1);
layersGroup.setMinCheckCount(1);
CheckBox backgroundCheck = new CheckBox("Background", skin);
layersGroup.add(backgroundCheck);
backgroundCheck.setChecked(false);
backgroundCheck.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
levelEditor.setActiveLayer(-1);
}
});
menu.add(backgroundCheck).align(Align.left).padRight(10).padBottom(5);
menu.row();
CheckBox middlegroundCheck = new CheckBox("Middle Ground", skin);
layersGroup.add(middlegroundCheck);
middlegroundCheck.setChecked(true);
middlegroundCheck.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
levelEditor.setActiveLayer(0);
}
});
menu.add(middlegroundCheck).align(Align.left).padRight(10).padBottom(5);
menu.row();
CheckBox foregroundCheck = new CheckBox("Foreground", skin);
layersGroup.add(foregroundCheck);
foregroundCheck.setChecked(false);
foregroundCheck.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
levelEditor.setActiveLayer(1);
}
});
menu.add(foregroundCheck).align(Align.left).padRight(10).padBottom(5);
menu.row();
stage.addActor(menu);
return menu;
}
private Actor buildThemeMenu(List<EditorIdentifierObject> themes) {
Table parentMenu = new Table();
parentMenu.setVisible(false);
parentMenu.setFillParent(true);
parentMenu.setOrigin(Align.topRight);
parentMenu.align(Align.right);
Table menu = new Table();
ScrollPane scrollPane = new ScrollPane(menu, skin);
scrollPane.setFadeScrollBars(false);
scrollPane.setScrollingDisabled(true, false);
parentMenu.add(scrollPane);
for (EditorIdentifierObject object : themes) {
Table itemTable = new Table();
TextureRegionDrawable upDrawable = new TextureRegionDrawable(new TextureRegionDrawable(object.texture));
SpriteDrawable downSprite = upDrawable.tint(Color.GREEN);
ImageButton button = new ImageButton(upDrawable, downSprite);
button.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
levelEditor.curLevelBuilder.setTheme(object.id);
levelEditor.curLevelBuilder.fireToListeners();
}
});
itemTable.add(button);
itemTable.row();
Label label = new Label(object.displayName, skin);
itemTable.add(label).padBottom(20);
menu.add(itemTable).padRight(20);
menu.row();
}
menu.padBottom(-20);
stage.addActor(parentMenu);
return parentMenu;
}
private Actor buildObjectMenu(List<RenderableLevelObject> objects) {
Table parentMenu = new Table();
parentMenu.setVisible(false);
parentMenu.setFillParent(true);
parentMenu.setOrigin(Align.topRight);
parentMenu.align(Align.right);
Table menu = new Table();
ScrollPane scrollPane = new ScrollPane(menu, skin);
scrollPane.setFadeScrollBars(false);
scrollPane.setScrollingDisabled(true, false);
parentMenu.add(scrollPane);
int column = 1;
for (RenderableLevelObject object : objects) {
Table itemTable = new Table();
TextureRegionDrawable upDrawable = new TextureRegionDrawable(new TextureRegionDrawable(object.texture()));
SpriteDrawable downSprite = upDrawable.tint(Color.GREEN);
ImageButton button = new ImageButton(upDrawable, downSprite);
button.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
levelEditor.dropObject(object);
}
});
itemTable.add(button).width(32).height(32);
itemTable.row();
Label label = new Label(object.name(), skin);
itemTable.add(label).padBottom(20);
if (column % 2 == 0) {
menu.add(itemTable).padRight(20);
menu.row();
} else {
menu.add(itemTable).padLeft(15).padRight(20);
}
column++;
}
menu.padBottom(-20);
stage.addActor(parentMenu);
return parentMenu;
}
private void topMenuTransition(MenuPage to) {
if (currentTopMenu != null) {
currentTopMenu.setVisible(false);
}
if (topMenus.containsKey(to)) {
topMenus.get(to).setVisible(true);
currentTopMenu = topMenus.get(to);
}
}
private void rightMenuTransition(MenuPage to) {
if (currentRightMenu != null) {
currentRightMenu.setVisible(false);
}
if (rightMenus.containsKey(to)) {
rightMenus.get(to).setVisible(true);
currentRightMenu = rightMenus.get(to);
}
}
public Stage getStage() {
return stage;
}
public void updateAndDraw() {
stage.act();
stage.draw();
}
}
|
jump-leveleditor/src/main/java/com/bitdecay/jump/leveleditor/ui/menus/EditorMenus.java
|
package com.bitdecay.jump.leveleditor.ui.menus;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.*;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.badlogic.gdx.scenes.scene2d.utils.SpriteDrawable;
import com.badlogic.gdx.scenes.scene2d.utils.TextureRegionDrawable;
import com.badlogic.gdx.utils.Align;
import com.bitdecay.jump.gdx.level.EditorIdentifierObject;
import com.bitdecay.jump.gdx.level.RenderableLevelObject;
import com.bitdecay.jump.leveleditor.EditorHook;
import com.bitdecay.jump.leveleditor.render.LevelEditor;
import com.bitdecay.jump.leveleditor.render.RenderLayer;
import com.bitdecay.jump.leveleditor.ui.ModeType;
import com.bitdecay.jump.leveleditor.ui.OptionsMode;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* This is a separate class from LevelEditor to try to make things easier to read.
* Created by Monday on 10/10/2015.
*/
public class EditorMenus {
private final LevelEditor levelEditor;
private final Stage stage;
private final Skin skin;
private Map<MenuPage, Actor> topMenus = new HashMap<>();
private Map<MenuPage, Actor> rightMenus = new HashMap<>();
private Actor currentTopMenu;
private Actor currentRightMenu;
public EditorMenus(LevelEditor levelEditor, EditorHook hooker) {
this.levelEditor = levelEditor;
TextureAtlas menuAtlas = new TextureAtlas(Gdx.files.internal(LevelEditor.ASSETS_FOLDER + "skins/ui.atlas"));
skin = new Skin(Gdx.files.internal(LevelEditor.ASSETS_FOLDER + "skins/menu-skin.json"), menuAtlas);
stage = new Stage();
topMenus.put(MenuPage.MainMenu, buildMainMenu());
rightMenus.put(MenuPage.TileMenu, buildTilesetMenu(hooker.getTilesets()));
rightMenus.put(MenuPage.LevelObjectMenu, buildObjectMenu(hooker.getCustomObjects()));
rightMenus.put(MenuPage.ThemeMenu, buildThemeMenu(hooker.getThemes()));
rightMenus.put(MenuPage.LayersMenu, buildLayerMenu());
rightMenus.put(MenuPage.RenderMenu, buildRenderMenu());
topMenuTransition(MenuPage.MainMenu);
}
private Actor buildRenderMenu() {
Table menu = new Table();
menu.setVisible(false);
menu.setFillParent(true);
menu.setOrigin(Align.topRight);
menu.align(Align.right);
for (RenderLayer layer : RenderLayer.values()) {
if (layer.userEditable) {
CheckBox checkBox = new CheckBox(layer.name(), skin);
checkBox.setChecked(true);
checkBox.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
layer.enabled = checkBox.isChecked();
}
});
menu.add(checkBox).align(Align.left).padRight(10).padBottom(5);
menu.row();
}
}
stage.addActor(menu);
return menu;
}
private Actor buildMainMenu() {
Table menu = new Table();
menu.setWidth(stage.getWidth());
menu.align(Align.top);
Table miscActionTable = new Table();
for (OptionsMode mode : OptionsMode.values()) {
if (mode.type == ModeType.ACTION) {
buildImageButton(miscActionTable, mode, null);
}
}
menu.add(miscActionTable).padRight(40);
ButtonGroup toolGroup = new ButtonGroup();
toolGroup.setUncheckLast(true);
toolGroup.setMaxCheckCount(1);
toolGroup.setMinCheckCount(1);
Table toolsTable = new Table();
for (OptionsMode mode : OptionsMode.values()) {
if (mode.type == ModeType.MOUSE && mode.icon != null) {
buildImageButton(toolsTable, mode, toolGroup);
}
}
menu.add(toolsTable);
menu.align(Align.topLeft);
menu.setFillParent(true);
menu.setVisible(false);
stage.addActor(menu);
return menu;
}
private void buildImageButton(Table menu, OptionsMode mode, ButtonGroup btnGroup) {
Table itemTable = new Table();
TextureRegion testIcon = new TextureRegion(new Texture(Gdx.files.internal(LevelEditor.ASSETS_FOLDER + mode.icon)));
TextureRegionDrawable upDrawable = new TextureRegionDrawable(new TextureRegionDrawable(new TextureRegion(testIcon)));
SpriteDrawable downSprite = upDrawable.tint(Color.GREEN);
ImageButton button;
if (btnGroup != null) {
button = new ImageButton(upDrawable, downSprite, downSprite);
btnGroup.add(button);
} else {
button = new ImageButton(upDrawable, downSprite);
}
button.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
levelEditor.setMode(mode);
if (!ModeType.ACTION.equals(mode.type)) {
// Actions don't have menus, so only transition for non-action modes
rightMenuTransition(mode.menu);
}
}
});
// If we want to set the size explicitly, do it like this
// itemTable.add(button).width(32).height(32);
itemTable.add(button);
itemTable.row();
Label label = new Label(mode.label, skin);
itemTable.add(label);
menu.add(itemTable);
}
private Actor buildTilesetMenu(List<EditorIdentifierObject> tilesets) {
Table parentMenu = new Table();
parentMenu.setVisible(false);
parentMenu.setFillParent(true);
parentMenu.setOrigin(Align.topRight);
parentMenu.align(Align.right);
Table menu = new Table();
ScrollPane scrollPane = new ScrollPane(menu, skin);
scrollPane.setFadeScrollBars(false);
scrollPane.setScrollingDisabled(true, false);
parentMenu.add(scrollPane);
for (EditorIdentifierObject object : tilesets) {
Table itemTable = new Table();
TextureRegionDrawable upDrawable = new TextureRegionDrawable(new TextureRegionDrawable(object.texture));
SpriteDrawable downSprite = upDrawable.tint(Color.GREEN);
ImageButton button = new ImageButton(upDrawable, downSprite);
button.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
levelEditor.setMaterial(object.id);
}
});
itemTable.add(button);
itemTable.row();
Label label = new Label(object.displayName, skin);
itemTable.add(label).padBottom(20);
menu.add(itemTable).padRight(20);
menu.row();
}
menu.padBottom(-20);
stage.addActor(parentMenu);
return parentMenu;
}
private Actor buildLayerMenu() {
Table menu = new Table();
menu.setVisible(false);
menu.setFillParent(true);
menu.setOrigin(Align.topRight);
menu.align(Align.right);
ButtonGroup layersGroup = new ButtonGroup();
layersGroup.setUncheckLast(true);
layersGroup.setMaxCheckCount(1);
layersGroup.setMinCheckCount(1);
CheckBox backgroundCheck = new CheckBox("Background", skin);
layersGroup.add(backgroundCheck);
backgroundCheck.setChecked(false);
backgroundCheck.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
levelEditor.setActiveLayer(-1);
}
});
menu.add(backgroundCheck).align(Align.left).padRight(10).padBottom(5);
menu.row();
CheckBox middlegroundCheck = new CheckBox("Middle Ground", skin);
layersGroup.add(middlegroundCheck);
middlegroundCheck.setChecked(true);
middlegroundCheck.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
levelEditor.setActiveLayer(0);
}
});
menu.add(middlegroundCheck).align(Align.left).padRight(10).padBottom(5);
menu.row();
CheckBox foregroundCheck = new CheckBox("Foreground", skin);
layersGroup.add(foregroundCheck);
foregroundCheck.setChecked(false);
foregroundCheck.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
levelEditor.setActiveLayer(1);
}
});
menu.add(foregroundCheck).align(Align.left).padRight(10).padBottom(5);
menu.row();
stage.addActor(menu);
return menu;
}
private Actor buildThemeMenu(List<EditorIdentifierObject> themes) {
Table parentMenu = new Table();
parentMenu.setVisible(false);
parentMenu.setFillParent(true);
parentMenu.setOrigin(Align.topRight);
parentMenu.align(Align.right);
Table menu = new Table();
ScrollPane scrollPane = new ScrollPane(menu, skin);
scrollPane.setFadeScrollBars(false);
scrollPane.setScrollingDisabled(true, false);
parentMenu.add(scrollPane);
for (EditorIdentifierObject object : themes) {
Table itemTable = new Table();
TextureRegionDrawable upDrawable = new TextureRegionDrawable(new TextureRegionDrawable(object.texture));
SpriteDrawable downSprite = upDrawable.tint(Color.GREEN);
ImageButton button = new ImageButton(upDrawable, downSprite);
button.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
levelEditor.curLevelBuilder.setTheme(object.id);
levelEditor.curLevelBuilder.fireToListeners();
}
});
itemTable.add(button);
itemTable.row();
Label label = new Label(object.displayName, skin);
itemTable.add(label).padBottom(20);
menu.add(itemTable).padRight(20);
menu.row();
}
menu.padBottom(-20);
stage.addActor(parentMenu);
return parentMenu;
}
private Actor buildObjectMenu(List<RenderableLevelObject> objects) {
Table parentMenu = new Table();
parentMenu.setVisible(false);
parentMenu.setFillParent(true);
parentMenu.setOrigin(Align.topRight);
parentMenu.align(Align.right);
Table menu = new Table();
ScrollPane scrollPane = new ScrollPane(menu, skin);
scrollPane.setFadeScrollBars(false);
scrollPane.setScrollingDisabled(true, false);
parentMenu.add(scrollPane);
int column = 1;
for (RenderableLevelObject object : objects) {
Table itemTable = new Table();
TextureRegionDrawable upDrawable = new TextureRegionDrawable(new TextureRegionDrawable(object.texture()));
SpriteDrawable downSprite = upDrawable.tint(Color.GREEN);
ImageButton button = new ImageButton(upDrawable, downSprite);
button.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
levelEditor.dropObject(object);
}
});
itemTable.add(button);
itemTable.row();
Label label = new Label(object.name(), skin);
itemTable.add(label).padBottom(20);
if (column % 2 == 0) {
menu.add(itemTable).padRight(20);
menu.row();
} else {
menu.add(itemTable).padLeft(15).padRight(20);
}
column++;
}
menu.padBottom(-20);
stage.addActor(parentMenu);
return parentMenu;
}
private void topMenuTransition(MenuPage to) {
if (currentTopMenu != null) {
currentTopMenu.setVisible(false);
}
if (topMenus.containsKey(to)) {
topMenus.get(to).setVisible(true);
currentTopMenu = topMenus.get(to);
}
}
private void rightMenuTransition(MenuPage to) {
if (currentRightMenu != null) {
currentRightMenu.setVisible(false);
}
if (rightMenus.containsKey(to)) {
rightMenus.get(to).setVisible(true);
currentRightMenu = rightMenus.get(to);
}
}
public Stage getStage() {
return stage;
}
public void updateAndDraw() {
stage.act();
stage.draw();
}
}
|
Have a fixed size for all object/tile images in menus
|
jump-leveleditor/src/main/java/com/bitdecay/jump/leveleditor/ui/menus/EditorMenus.java
|
Have a fixed size for all object/tile images in menus
|
|
Java
|
mit
|
3b42e33044bf86b66a75df4a9fc87768df3a58e8
| 0
|
nickpascucci/CP365_2011,nickpascucci/CP365_2011,nickpascucci/CP365_2011
|
package boids;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.JComponent;
/**
* Provides a drawing surface for the boid flock.
*
* @author Matthew Polk
* @author Nick Pascucci
*/
@SuppressWarnings("serial")
class BoidCanvas extends JComponent implements MouseMotionListener{
final static float MAX_SPEED = 10;
final static int NEIGHBOR_DISTANCE = 300;
int CENTER_WEIGHT = 6;
int AVOID_WEIGHT = 9;
int MATCH_SPEED_WEIGHT = 2;
int MOUSE_WEIGHT = 3;
int mouseX;
int mouseY;
final static int RANDOMOSITY = 50;
int SIZE = 5;
ArrayList<Boid> boids;
Random rand = new Random();
/**
* Creates a new BoidCanvas object with defaults.
*/
public BoidCanvas() {
boids = new ArrayList<Boid>();
mouseX = this.getWidth()/2;
mouseY = this.getHeight()/2;
addMouseMotionListener(this);
}
/**
* Searches the boids ArrayList for nearby boids to this one.
*/
private ArrayList<Boid> getNearbyBoids(Boid b) {
ArrayList<Boid> neighbors = new ArrayList<Boid>();
for (Boid d : boids) {
if (Math.sqrt((d.x - b.x)*(d.x - b.x) + (d.y - b.y)*(d.y - b.y)) < NEIGHBOR_DISTANCE)
neighbors.add(d);
}
return neighbors;
}
/**
* Calculates the combined vectors for each boid.
*/
public void getVectors() {
ArrayList<Boid> newBoids = new ArrayList<Boid>();
for (Boid b : boids) {
// Build a copy of the boids list so we can
// modify the new situation without touching the original.
// Touching the original can mess up future calculations.
newBoids.add(b);
}
for (Boid newBoid : newBoids) {
float[] cv = getCenterVector(newBoid);
float[] av = getAwayVector(newBoid);
float[] ms = getMatchSpeedVector(newBoid);
float[] rv = {(rand.nextFloat()*RANDOMOSITY)+1-RANDOMOSITY/2, (rand.nextFloat()*RANDOMOSITY)+1-RANDOMOSITY/2};
float[] fm = getMouseVector(newBoid);
newBoid.movementVector[0] = CENTER_WEIGHT * cv[0] + AVOID_WEIGHT * av[0] +
MATCH_SPEED_WEIGHT * ms[0] + MOUSE_WEIGHT * fm[0] + rv[0];
newBoid.movementVector[1] = CENTER_WEIGHT * cv[1] + AVOID_WEIGHT * av[1] +
MATCH_SPEED_WEIGHT * ms[1] + MOUSE_WEIGHT * fm[1] + rv[0];
/*
* But, the vector may be very large. We should scale it down a bit.
* Remember to scale uniformly!
*/
newBoid.movementVector = toUnitVector(newBoid.movementVector);
newBoid.movementVector[0] *= MAX_SPEED;
newBoid.movementVector[1] *= MAX_SPEED;
}
boids = newBoids;
}
/*
* Converts a vector to a unit vector.
*/
private float[] toUnitVector(float[] vector){
float x = (float) vector[0];
float y = (float) vector[1];
//Loses some precision here.
float magnitude = (float) Math.sqrt(x*x + y*y);
float newX = (float) x/magnitude;
float newY = (float) y/magnitude;
float[] newVector = {newX, newY};
return newVector;
}
/**
* Generates the vector to the center of the flock.
*
* @param currentBoid
* The boid who is the origin of the vector.
* @return An int array representing the x,y unit vectors.
*/
public float[] getCenterVector(Boid currentBoid) {
int centerX = getSwarmCenter()[0];
int centerY = getSwarmCenter()[1];
float[] centerVec = {centerX - currentBoid.x, centerY - currentBoid.y};
return centerVec;
}
/**
* Calculates the weighted center of the swarm.
* @return
*/
public int[] getSwarmCenter(){
int centerX = 0;
int centerY = 0;
//We calculate the center of the swarm by summing all of
//the x and y coordinates, and then dividing by the number
//of boids.
for (Boid b : boids) {
centerX += b.x;
centerY += b.y;
}
centerX /= boids.size();
centerY /= boids.size();
//System.out.println("Swarm center at " + centerX + " " + centerY);
int[] center = {centerX, centerY};
return center;
}
/**
* Generates a boid-specific vector to avoid neighbors.
*
* @param b
* @return
*/
public float[] getAwayVector(Boid b) {
float[] awayVec = new float[2];
ArrayList<Boid> Neighborhood = getNearbyBoids(b);
int Neighborhood_x = 0;
int Neighborhood_y = 0;
for (Boid d : Neighborhood) {
Neighborhood_x -= (d.x - b.x);
Neighborhood_y -= (d.y - b.y);
}
Neighborhood_x /= Neighborhood.size();
Neighborhood_y /= Neighborhood.size();
awayVec[0] = Neighborhood_x;
awayVec[1] = Neighborhood_y;
return awayVec;
}
/**
* Generates a vector to match the speed of a boid's neighbors.
*
* @param b
* @return
*/
public float[] getMatchSpeedVector(Boid b) {
float[] matchVec = new float[2];
ArrayList<Boid> Neighborhood = getNearbyBoids(b);
int neighborhoodDX = 0;
int neighborhoodDY = 0;
for (Boid d : Neighborhood) {
neighborhoodDX += d.movementVector[0];
neighborhoodDY += d.movementVector[1];
}
neighborhoodDX /= Neighborhood.size();
neighborhoodDY /= Neighborhood.size();
matchVec[0] = neighborhoodDX - b.movementVector[0];
matchVec[1] = neighborhoodDY - b.movementVector[1];
return matchVec;
}
public float[] getMouseVector(Boid b){
float[] ans = {(mouseX - b.x), (mouseY - b.y)};
return ans;
}
/**
* Runs the simulation.
*
* @param num_boids
* @throws InterruptedException
*/
public void run(int num_boids) throws InterruptedException {
for (int i = 0; i < num_boids; i++) {
boids.add(new Boid(rand.nextInt(this.getWidth()), rand.nextInt(this.getWidth()), SIZE));
}
while (true) {
getVectors();
for (Boid b : boids) {
b.x += b.movementVector[0];
b.y += b.movementVector[1];
if(b.x < 0)
b.x = 0;
else if(b.x > this.getWidth()-1)
b.x = this.getWidth()-1;
if(b.y < 0)
b.y = 0;
else if(b.y > this.getHeight()-1)
b.y = this.getHeight()-1;
}
//System.out.println(boids.get(0).x + " " + boids.get(0).y);
repaint();
Thread.sleep(100);
}
}
/**
* Drawing code.
*/
public void paintComponent(Graphics g) {
super.repaint();
for (Boid b : boids) {
b.draw(g);
}
g.setColor(Color.RED);
g.fillRect(getSwarmCenter()[0], getSwarmCenter()[1], 4, 4);
}
@Override
public void mouseDragged(MouseEvent arg0) {}
@Override
public void mouseMoved(MouseEvent e) {
mouseX = e.getX();
mouseY = e.getY();
}
}
|
src/boids/BoidCanvas.java
|
package boids;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.JComponent;
/**
* Provides a drawing surface for the boid flock.
*
* @author Matthew Polk
* @author Nick Pascucci
*/
@SuppressWarnings("serial")
class BoidCanvas extends JComponent implements MouseMotionListener{
final static float MAX_SPEED = 10;
final static int NEIGHBOR_DISTANCE = 300;
int CENTER_WEIGHT = 6;
int AVOID_WEIGHT = 12;
int MATCH_SPEED_WEIGHT = 1;
int MOUSE_WEIGHT = 8;
int mouseX;
int mouseY;
final static int RANDOMOSITY = 30;
int SIZE = 5;
ArrayList<Boid> boids;
Random rand = new Random();
/**
* Creates a new BoidCanvas object with defaults.
*/
public BoidCanvas() {
boids = new ArrayList<Boid>();
mouseX = this.getWidth()/2;
mouseY = this.getHeight()/2;
addMouseMotionListener(this);
}
/**
* Searches the boids ArrayList for nearby boids to this one.
*/
private ArrayList<Boid> getNearbyBoids(Boid b) {
ArrayList<Boid> neighbors = new ArrayList<Boid>();
for (Boid d : boids) {
if (Math.sqrt((d.x - b.x)*(d.x - b.x) + (d.y - b.y)*(d.y - b.y)) < NEIGHBOR_DISTANCE)
neighbors.add(d);
}
return neighbors;
}
/**
* Calculates the combined vectors for each boid.
*/
public void getVectors() {
ArrayList<Boid> newBoids = new ArrayList<Boid>();
for (Boid b : boids) {
// Build a copy of the boids list so we can
// modify the new situation without touching the original.
// Touching the original can mess up future calculations.
newBoids.add(b);
}
for (Boid newBoid : newBoids) {
float[] cv = getCenterVector(newBoid);
float[] av = getAwayVector(newBoid);
float[] ms = getMatchSpeedVector(newBoid);
float[] rv = {(rand.nextFloat()*RANDOMOSITY)+1-RANDOMOSITY/2, (rand.nextFloat()*RANDOMOSITY)+1-RANDOMOSITY/2};
float[] fm = getMouseVector(newBoid);
newBoid.movementVector[0] = CENTER_WEIGHT * cv[0] + AVOID_WEIGHT * av[0] +
MATCH_SPEED_WEIGHT * ms[0] + MOUSE_WEIGHT * fm[0] + rv[0];
newBoid.movementVector[1] = CENTER_WEIGHT * cv[1] + AVOID_WEIGHT * av[1] +
MATCH_SPEED_WEIGHT * ms[1] + MOUSE_WEIGHT * fm[1] + rv[0];
/*
* But, the vector may be very large. We should scale it down a bit.
* Remember to scale uniformly!
*/
newBoid.movementVector = toUnitVector(newBoid.movementVector);
newBoid.movementVector[0] *= MAX_SPEED;
newBoid.movementVector[1] *= MAX_SPEED;
}
boids = newBoids;
}
/*
* Converts a vector to a unit vector.
*/
private float[] toUnitVector(float[] vector){
float x = (float) vector[0];
float y = (float) vector[1];
//Loses some precision here.
float magnitude = (float) Math.sqrt(x*x + y*y);
float newX = (float) x/magnitude;
float newY = (float) y/magnitude;
float[] newVector = {newX, newY};
return newVector;
}
/**
* Generates the vector to the center of the flock.
*
* @param currentBoid
* The boid who is the origin of the vector.
* @return An int array representing the x,y unit vectors.
*/
public float[] getCenterVector(Boid currentBoid) {
int centerX = getSwarmCenter()[0];
int centerY = getSwarmCenter()[1];
float[] centerVec = {centerX - currentBoid.x, centerY - currentBoid.y};
return centerVec;
}
/**
* Calculates the weighted center of the swarm.
* @return
*/
public int[] getSwarmCenter(){
int centerX = 0;
int centerY = 0;
//We calculate the center of the swarm by summing all of
//the x and y coordinates, and then dividing by the number
//of boids.
for (Boid b : boids) {
centerX += b.x;
centerY += b.y;
}
centerX /= boids.size();
centerY /= boids.size();
//System.out.println("Swarm center at " + centerX + " " + centerY);
int[] center = {centerX, centerY};
return center;
}
/**
* Generates a boid-specific vector to avoid neighbors.
*
* @param b
* @return
*/
public float[] getAwayVector(Boid b) {
float[] awayVec = new float[2];
ArrayList<Boid> Neighborhood = getNearbyBoids(b);
int Neighborhood_x = 0;
int Neighborhood_y = 0;
for (Boid d : Neighborhood) {
Neighborhood_x -= (d.x - b.x);
Neighborhood_y -= (d.y - b.y);
}
Neighborhood_x /= Neighborhood.size();
Neighborhood_y /= Neighborhood.size();
awayVec[0] = Neighborhood_x;
awayVec[1] = Neighborhood_y;
return awayVec;
}
/**
* Generates a vector to match the speed of a boid's neighbors.
*
* @param b
* @return
*/
public float[] getMatchSpeedVector(Boid b) {
float[] matchVec = new float[2];
ArrayList<Boid> Neighborhood = getNearbyBoids(b);
int neighborhoodDX = 0;
int neighborhoodDY = 0;
for (Boid d : Neighborhood) {
neighborhoodDX += d.movementVector[0];
neighborhoodDY += d.movementVector[1];
}
neighborhoodDX /= Neighborhood.size();
neighborhoodDY /= Neighborhood.size();
matchVec[0] = neighborhoodDX - b.movementVector[0];
matchVec[1] = neighborhoodDY - b.movementVector[1];
return matchVec;
}
public float[] getMouseVector(Boid b){
float[] ans = {(mouseX - b.x), (mouseY - b.y)};
return ans;
}
/**
* Runs the simulation.
*
* @param num_boids
* @throws InterruptedException
*/
public void run(int num_boids) throws InterruptedException {
for (int i = 0; i < num_boids; i++) {
boids.add(new Boid(rand.nextInt(this.getWidth()), rand.nextInt(this.getWidth()), SIZE));
}
while (true) {
getVectors();
for (Boid b : boids) {
b.x += b.movementVector[0];
b.y += b.movementVector[1];
if(b.x < 0)
b.x = 0;
else if(b.x > this.getWidth()-1)
b.x = this.getWidth()-1;
if(b.y < 0)
b.y = 0;
else if(b.y > this.getHeight()-1)
b.y = this.getHeight()-1;
}
//System.out.println(boids.get(0).x + " " + boids.get(0).y);
repaint();
Thread.sleep(100);
}
}
/**
* Drawing code.
*/
public void paintComponent(Graphics g) {
super.repaint();
for (Boid b : boids) {
b.draw(g);
}
g.setColor(Color.RED);
g.fillRect(getSwarmCenter()[0], getSwarmCenter()[1], 4, 4);
}
@Override
public void mouseDragged(MouseEvent arg0) {}
@Override
public void mouseMoved(MouseEvent e) {
mouseX = e.getX();
mouseY = e.getY();
}
}
|
Added the mouseMotionListener, so the boids follow the mouse.
|
src/boids/BoidCanvas.java
|
Added the mouseMotionListener, so the boids follow the mouse.
|
|
Java
|
mit
|
1b33b474366d6cae30adf3d98904ef16717eb884
| 0
|
dreamhead/moco,dreamhead/moco
|
package com.github.dreamhead.moco.parser.model;
import com.github.dreamhead.moco.RestIdMatcher;
import com.github.dreamhead.moco.RestSettingBuilder;
import com.google.common.base.MoreObjects;
import com.google.common.base.Strings;
import static com.github.dreamhead.moco.parser.model.RestIds.asIdMatcher;
public abstract class RestSingleSetting extends RestBaseSetting {
private String id;
protected abstract RestSettingBuilder doStartRestSetting();
protected final boolean hasId() {
return !Strings.isNullOrEmpty(id);
}
protected final RestIdMatcher id() {
return asIdMatcher(this.id);
}
protected final boolean isIdRequired() {
return false;
}
@Override
protected final RestSettingBuilder startRestSetting() {
if (isIdRequired() && !hasId()) {
throw new IllegalArgumentException("Required id is missing");
}
return doStartRestSetting();
}
@Override
public final String toString() {
return MoreObjects.toStringHelper(this)
.omitNullValues()
.add("id", id)
.add("request", request)
.add("response", response)
.toString();
}
}
|
moco-runner/src/main/java/com/github/dreamhead/moco/parser/model/RestSingleSetting.java
|
package com.github.dreamhead.moco.parser.model;
import com.github.dreamhead.moco.RestIdMatcher;
import com.github.dreamhead.moco.RestSettingBuilder;
import com.google.common.base.MoreObjects;
import com.google.common.base.Strings;
import static com.github.dreamhead.moco.parser.model.RestIds.asIdMatcher;
public abstract class RestSingleSetting extends RestBaseSetting {
private String id;
protected abstract RestSettingBuilder doStartRestSetting();
protected boolean hasId() {
return !Strings.isNullOrEmpty(id);
}
protected RestIdMatcher id() {
return asIdMatcher(this.id);
}
protected boolean isIdRequired() {
return false;
}
@Override
protected RestSettingBuilder startRestSetting() {
if (isIdRequired() && !hasId()) {
throw new IllegalArgumentException("Required id is missing");
}
return doStartRestSetting();
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.omitNullValues()
.add("id", id)
.add("request", request)
.add("response", response)
.toString();
}
}
|
added missing final to rest single setting
|
moco-runner/src/main/java/com/github/dreamhead/moco/parser/model/RestSingleSetting.java
|
added missing final to rest single setting
|
|
Java
|
mit
|
8d0ef5ec67aa8b35323d8c889551cf3ad6513444
| 0
|
fiveham/Sudoku_Solver
|
package common.graph;
import common.Universe;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Stream;
/**
* <p>A base class for implementations of the Graph interface.</p>
* @author fiveham
* @author fiveham
*
* @param <T> the type of the vertices of this Graph
* @param <T> the type of the vertices of this Graph@param <T> the type of the vertices of this
* @param <T> the type of the vertices of this GraphGraph
*/
public abstract class AbstractGraph<T extends Vertex<T>> implements Graph<T>{
/**
* <p>The backing collection of vertices in this Graph.</p>
*/
protected final ArrayList<T> nodes;
/**
* <p>Constructs an AbstractGraph with an empty list of vertices and an empty list of
* connected-component contraction event-listeners.</p>
*/
public AbstractGraph() {
nodes = new ArrayList<>();
}
/**
* <p>Constructs an AbstractGraph whose backing collection of vertices is initialized empty but
* with a capacity of {@code size}.</p>
* @param size the capacity which the backing collection of vertices will have
*/
public AbstractGraph(int size) {
nodes = new ArrayList<>(size);
}
/**
* <p>Constructs an AbstractGraph having the elements of {@code coll} as vertices.</p>
* @param coll vertices for this Graph
*/
public AbstractGraph(Collection<? extends T> coll){
nodes = new ArrayList<>(coll);
}
/**
* <p>Constructs an AbstractGraph having the elements of {@code coll} as vertices and having all
* the elements of {@code factories} as event-listener sources.</p>
* @param coll vertices for this Graph
* @param factories connected-component contraction event-listers for this Graph
*/
public AbstractGraph(Collection<? extends T> coll, List<Supplier<Consumer<Set<T>>>> factories) {
nodes = new ArrayList<>(coll);
}
@Override
public int size(){
return nodes.size();
}
@Override
public Iterator<T> iterator(){
return nodes.iterator();
}
@Override
public Stream<T> nodeStream(){
return nodes.stream();
}
private T stdSeed(List<T> list){
return list.remove(list.size() - 1);
}
@Override
public Collection<Graph<T>> connectedComponents(){
return connectedComponents(this::stdSeed);
}
@Override
public Collection<Graph<T>> connectedComponents(Function<List<T>,T> seedSrc){
List<Graph<T>> result = new ArrayList<>();
List<T> unassignedNodes = new ArrayList<>(nodes);
while( !unassignedNodes.isEmpty() ){
Graph<T> component = component(unassignedNodes, seedSrc);
result.add(component);
}
return result;
}
@Override
public Graph<T> component(List<T> unassignedNodes, Function<List<T>,T> seedSrc){
ConnectedComponent<T> newComponent = new ConnectedComponent<T>(nodes.size(), unassignedNodes);
{
int initUnassignedCount = unassignedNodes.size();
T seed = seedSrc.apply(unassignedNodes);
if(unassignedNodes.size() == initUnassignedCount){
unassignedNodes.remove(seed);
}
newComponent.add(seed); //seed now in cuttingEdge
}
while( !newComponent.cuttingEdgeIsEmpty() ){
newComponent.contract(); //move cuttingEdge into edge and old edge into core
newComponent.grow(); //add unincorporated nodes to cuttingEdge
}
return new BasicGraph<T>(newComponent.contract());
}
@Override
public int distance(T v1, T v2){
int index1 = nodes.indexOf(v1);
int index2 = nodes.indexOf(v2);
if( index1<0 || index2<0 ){
throw new IllegalArgumentException("At least one of the specified nodes is not in this graph.");
}
if(index1==index2){
return 0;
}
final boolean[][] adjacencyMatrix = new boolean[nodes.size()][nodes.size()];
for(int i=0; i<nodes.size(); ++i){
for(int j=0; j<i; ++j){
adjacencyMatrix[i][j] = adjacencyMatrix[j][i] = nodes.get(i).neighbors().contains(nodes.get(j));
}
adjacencyMatrix[i][i] = false;
}
//adjacency matrix raised to a power (initially the power of 1)
boolean[][] adjPower = new boolean[nodes.size()][nodes.size()];
for(int i=0; i<adjPower.length; ++i){
adjPower[i] = Arrays.copyOf(adjacencyMatrix[i], adjacencyMatrix.length);
}
for(int n=1; n<nodes.size(); ++n){
if(adjPower[index1][index2]){
return n;
} else{
adjPower = times(adjPower,adjacencyMatrix);
}
}
return NO_CONNECTION;
}
public static final int NO_CONNECTION = -1;
/**
* <p>Matrix-multiplies the specified boolean matrices under the assumption that they are both
* symmetrical about the main diagonal and that they are both square and both have the same
* dimensions, all of which will be true for all calls to this method because method is private
* and is called from only one place, where those assumptions hold true.</p> <p>Since the
* elements of the matrices involved are boolean values instead of numbers, the operations of
* (scalar) multiplication and addition used in combining the elements of matrices whose
* elements are numbers when multiplying those matrices are replaced here with {@code and (&&)}
* and {@code or (||)}.</p>
* @param a a square symmetrical matrix of boolean values
* @param b a square symmetrical matrix of boolean values
* @return a square symmetrical matrix of boolean values corresponding to the matrix-product of
* {@code a} and {@code b}
*/
private boolean[][] times(boolean[][] a, boolean[][] b){
boolean[][] result = new boolean[a.length][a.length];
for(int i=0; i<nodes.size(); ++i){
for(int j=0; j<i; ++j){
result[i][j] = result[j][i] = dot(a[j],b[i]);
}
result[i][i] = dot(a[i],b[i]);
}
return result;
}
/**
* <p>Returns the dot product of two boolean vectors. Assumes that {@code a} and {@code b} are
* the same length. The operations of multiplication and addition used in calculating the dot
* product of two numerical vectors are replaced with {@code and (&&)} and {@code or (||)}
* respectively.</p>
* @param a a vector
* @param b a vector
* @return the boolean dot product of two boolean vectors
*/
private boolean dot(boolean[] a, boolean[] b){
for(int i=0; i<a.length; ++i){
if( a[i] && b[i] ){
return true;
}
}
return false;
}
@Override
public List<T> path(T t1, T t2){
Branch implicitPath = findPath(t2, t1); //reverse args so parent-path goes in order from t1 to t2
List<T> result = new ArrayList<>();
for(Branch pointer = implicitPath; pointer != null; pointer = pointer.parent){
result.add(pointer.wrapped);
}
return result;
}
/**
* <p>Finds a path from {@code from} to {@code to} in this graph.</p>
* @param to a node in this graph
* @param from a node in this graph
* @return a Branch describing the path from {@code from} to {@code to}
* @throws IllegalStateException if {@code to} and {@code from} are not both nodes in this graph
* @throws IllegalArgumentException if no path is found between {@code to} and {@code from} in
* this graph
*/
private Branch findPath(T to, T from){
if(!(nodes.contains(to) && nodes.contains(from))){
throw new IllegalStateException(to + " and/or " + from + " not present in this graph");
}
Branch init = new Branch(to, null);
if(to.equals(from)){
return init;
}
Set<Branch> cuttingEdge = new HashSet<>();
cuttingEdge.add(init);
Universe<T> nodeUniv = new Universe<>(nodes);
Set<T> unassigned = nodeUniv.back();
unassigned.remove(to);
Set<Branch> edge = new HashSet<>();
while(!cuttingEdge.isEmpty()){
//contract
edge = cuttingEdge;
cuttingEdge = new HashSet<>();
//grow
for(Branch b : edge){
Set<T> n = nodeUniv.back(b.wrapped.neighbors());
n.retainAll(unassigned);
unassigned.removeAll(n);
for(T t : n){
Branch newBranch = new Branch(t, b);
if(t.equals(from)){
return newBranch;
} else{
cuttingEdge.add(newBranch);
}
}
}
}
throw new IllegalArgumentException(
"Cannot find path between specified nodes: " + from + " and " + to);
}
private class Branch{
private final T wrapped;
private final Branch parent;
private Branch(T wrapped, Branch parent){
this.wrapped = wrapped;
this.parent = parent;
}
@Override
public boolean equals(Object o){
if(o instanceof AbstractGraph.Branch){
AbstractGraph<?>.Branch b = (AbstractGraph<?>.Branch)o;
return wrapped.equals(b.wrapped) && (parent == null ? b.parent == null : parent.equals(b.parent));
}
return false;
}
@Override
public int hashCode(){
return wrapped.hashCode();
}
}
@Override
public int hashCode(){
return nodeStream()
.map(Object::hashCode)
.reduce(0, Integer::sum);
}
@Override
public String toString(){
StringBuilder out = new StringBuilder();
out.append(getClass()).append(" size ").append(size()).append(System.lineSeparator()).append(nodes).append(System.lineSeparator());
for(T node : nodes){
out.append(node).append(": ").append(System.lineSeparator()).append(node.neighbors()).append(System.lineSeparator());
}
return out.toString();
}
}
|
src/common/graph/AbstractGraph.java
|
package common.graph;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Stream;
/**
* <p>A base class for implementations of the Graph interface.</p>
* @author fiveham
* @author fiveham
*
* @param <T> the type of the vertices of this Graph
* @param <T> the type of the vertices of this Graph@param <T> the type of the vertices of this
* @param <T> the type of the vertices of this GraphGraph
*/
public abstract class AbstractGraph<T extends Vertex<T>> implements Graph<T>{
/**
* <p>The backing collection of vertices in this Graph.</p>
*/
protected final ArrayList<T> nodes;
/**
* <p>Constructs an AbstractGraph with an empty list of vertices and an empty list of
* connected-component contraction event-listeners.</p>
*/
public AbstractGraph() {
nodes = new ArrayList<>();
}
/**
* <p>Constructs an AbstractGraph whose backing collection of vertices is initialized empty but
* with a capacity of {@code size}.</p>
* @param size the capacity which the backing collection of vertices will have
*/
public AbstractGraph(int size) {
nodes = new ArrayList<>(size);
}
/**
* <p>Constructs an AbstractGraph having the elements of {@code coll} as vertices.</p>
* @param coll vertices for this Graph
*/
public AbstractGraph(Collection<? extends T> coll){
nodes = new ArrayList<>(coll);
}
/**
* <p>Constructs an AbstractGraph having the elements of {@code coll} as vertices and having all
* the elements of {@code factories} as event-listener sources.</p>
* @param coll vertices for this Graph
* @param factories connected-component contraction event-listers for this Graph
*/
public AbstractGraph(Collection<? extends T> coll, List<Supplier<Consumer<Set<T>>>> factories) {
nodes = new ArrayList<>(coll);
}
@Override
public int size(){
return nodes.size();
}
@Override
public Iterator<T> iterator(){
return nodes.iterator();
}
@Override
public Stream<T> nodeStream(){
return nodes.stream();
}
private T stdSeed(List<T> list){
return list.remove(list.size() - 1);
}
@Override
public Collection<Graph<T>> connectedComponents(){
return connectedComponents(this::stdSeed);
}
@Override
public Collection<Graph<T>> connectedComponents(Function<List<T>,T> seedSrc){
List<Graph<T>> result = new ArrayList<>();
List<T> unassignedNodes = new ArrayList<>(nodes);
while( !unassignedNodes.isEmpty() ){
Graph<T> component = component(unassignedNodes, seedSrc);
result.add(component);
}
return result;
}
@Override
public Graph<T> component(List<T> unassignedNodes, Function<List<T>,T> seedSrc){
ConnectedComponent<T> newComponent = new ConnectedComponent<T>(nodes.size(), unassignedNodes);
{
int initUnassignedCount = unassignedNodes.size();
T seed = seedSrc.apply(unassignedNodes);
if(unassignedNodes.size() == initUnassignedCount){
unassignedNodes.remove(seed);
}
newComponent.add(seed); //seed now in cuttingEdge
}
while( !newComponent.cuttingEdgeIsEmpty() ){
newComponent.contract(); //move cuttingEdge into edge and old edge into core
newComponent.grow(); //add unincorporated nodes to cuttingEdge
}
return new BasicGraph<T>(newComponent.contract());
}
@Override
public int distance(T v1, T v2){
int index1 = nodes.indexOf(v1);
int index2 = nodes.indexOf(v2);
if( index1<0 || index2<0 ){
throw new IllegalArgumentException("At least one of the specified nodes is not in this graph.");
}
if(index1==index2){
return 0;
}
final boolean[][] adjacencyMatrix = new boolean[nodes.size()][nodes.size()];
for(int i=0; i<nodes.size(); ++i){
for(int j=0; j<i; ++j){
adjacencyMatrix[i][j] = adjacencyMatrix[j][i] = nodes.get(i).neighbors().contains(nodes.get(j));
}
adjacencyMatrix[i][i] = false;
}
//adjacency matrix raised to a power (initially the power of 1)
boolean[][] adjPower = new boolean[nodes.size()][nodes.size()];
for(int i=0; i<adjPower.length; ++i){
adjPower[i] = Arrays.copyOf(adjacencyMatrix[i], adjacencyMatrix.length);
}
for(int n=1; n<nodes.size(); ++n){
if(adjPower[index1][index2]){
return n;
} else{
adjPower = times(adjPower,adjacencyMatrix);
}
}
return NO_CONNECTION;
}
public static final int NO_CONNECTION = -1;
/**
* <p>Matrix-multiplies the specified boolean matrices under the assumption that they are both
* symmetrical about the main diagonal and that they are both square and both have the same
* dimensions, all of which will be true for all calls to this method because method is private
* and is called from only one place, where those assumptions hold true.</p> <p>Since the
* elements of the matrices involved are boolean values instead of numbers, the operations of
* (scalar) multiplication and addition used in combining the elements of matrices whose
* elements are numbers when multiplying those matrices are replaced here with {@code and (&&)}
* and {@code or (||)}.</p>
* @param a a square symmetrical matrix of boolean values
* @param b a square symmetrical matrix of boolean values
* @return a square symmetrical matrix of boolean values corresponding to the matrix-product of
* {@code a} and {@code b}
*/
private boolean[][] times(boolean[][] a, boolean[][] b){
boolean[][] result = new boolean[a.length][a.length];
for(int i=0; i<nodes.size(); ++i){
for(int j=0; j<i; ++j){
result[i][j] = result[j][i] = dot(a[j],b[i]);
}
result[i][i] = dot(a[i],b[i]);
}
return result;
}
/**
* <p>Returns the dot product of two boolean vectors. Assumes that {@code a} and {@code b} are
* the same length. The operations of multiplication and addition used in calculating the dot
* product of two numerical vectors are replaced with {@code and (&&)} and {@code or (||)}
* respectively.</p>
* @param a a vector
* @param b a vector
* @return the boolean dot product of two boolean vectors
*/
private boolean dot(boolean[] a, boolean[] b){
for(int i=0; i<a.length; ++i){
if( a[i] && b[i] ){
return true;
}
}
return false;
}
@Override
public List<T> path(T t1, T t2){
Branch implicitPath = findPath(t2, t1); //reverse args so parent-path goes in order from t1 to t2
List<T> result = new ArrayList<>();
for(Branch pointer = implicitPath; pointer != null; pointer = pointer.parent){
result.add(pointer.wrapped);
}
return result;
}
private Branch findPath(T to, T from){
if( !(nodes.contains(to) && nodes.contains(from)) ){
throw new IllegalStateException(to + " and/or " + from + " not present in this graph");
}
Set<Branch> cuttingEdge = new HashSet<>();
Branch init = new Branch(to, null);
if(to.equals(from)){
return init;
} else{
cuttingEdge.add(init);
}
Set<Branch> edge = new HashSet<>();
Set<T> unassigned = new HashSet<>(nodes);
unassigned.remove(to);
while(!cuttingEdge.isEmpty()){
//contract
edge = cuttingEdge;
cuttingEdge = new HashSet<>();
//grow
for(Branch b : edge){
Set<? extends T> n = new HashSet<>(b.wrapped.neighbors());
n.retainAll(unassigned);
unassigned.removeAll(n);
for(T t : n){
Branch newBranch = new Branch(t, b);
if(t.equals(from)){
return newBranch;
} else{
cuttingEdge.add(newBranch);
}
}
}
}
throw new IllegalArgumentException("Cannot find path between specified nodes: "+from+" and "+to);
}
private class Branch{
private final T wrapped;
private final Branch parent;
private Branch(T wrapped, Branch parent){
this.wrapped = wrapped;
this.parent = parent;
}
@Override
public boolean equals(Object o){
if(o instanceof AbstractGraph.Branch){
AbstractGraph<?>.Branch b = (AbstractGraph<?>.Branch)o;
return wrapped.equals(b.wrapped) && (parent == null ? b.parent == null : parent.equals(b.parent));
}
return false;
}
@Override
public int hashCode(){
return wrapped.hashCode();
}
}
@Override
public int hashCode(){
return nodeStream()
.map(Object::hashCode)
.reduce(0, Integer::sum);
}
@Override
public String toString(){
StringBuilder out = new StringBuilder();
out.append(getClass()).append(" size ").append(size()).append(System.lineSeparator()).append(nodes).append(System.lineSeparator());
for(T node : nodes){
out.append(node).append(": ").append(System.lineSeparator()).append(node.neighbors()).append(System.lineSeparator());
}
return out.toString();
}
}
|
refactor findPath to use BackedSets for bulk operations
|
src/common/graph/AbstractGraph.java
|
refactor findPath to use BackedSets for bulk operations
|
|
Java
|
mit
|
093129817782e7a6e663722de3d14af00d0caeca
| 0
|
thejavamonk/hackerrankAlgorithms
|
package com.codeprep.diagonaldifference;
import static java.util.stream.Collectors.toList;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream;
import java.util.stream.Stream;
class Result {
/*
* Complete the 'diagonalDifference' function below.
*
* The function is expected to return an INTEGER. The function accepts
* 2D_INTEGER_ARRAY arr as parameter.
*/
public static int diagonalDifference(List<List<Integer>> arr) {
int sum1 = 0;
int sum2 = 0;
int stIndex = 0;
int lstIndex = 1;
for (List<Integer> row : arr) {
sum1 = sum1 + row.get(stIndex);
sum2 = sum2 + row.get(row.size() - lstIndex);
stIndex++;
lstIndex++;
}
return Math.abs(sum1 - sum2);
}
}
public class Solution {
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(bufferedReader.readLine().trim());
List<List<Integer>> arr = new ArrayList<>();
IntStream.range(0, n).forEach(i -> {
try {
arr.add(Stream.of(bufferedReader.readLine().replaceAll("\\s+$", "").split(" ")).map(Integer::parseInt)
.collect(toList()));
} catch (IOException ex) {
throw new RuntimeException(ex);
}
});
int result = Result.diagonalDifference(arr);
System.out.println(String.valueOf(result));
}
}
|
algorithms_warmup/src/com/codeprep/diagonaldifference/Solution.java
|
package com.codeprep.diagonaldifference;
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int sizeOfMatrix = in.nextInt();
int a[][] = new int[sizeOfMatrix][sizeOfMatrix];
for(int a_i=0; a_i < sizeOfMatrix; a_i++){
for(int a_j=0; a_j < sizeOfMatrix; a_j++){
a[a_i][a_j] = in.nextInt();
}
}
int sumOfRight = 0;
int sumOfLeft = 0;
for(int i =0; i < sizeOfMatrix; i++){
sumOfRight = sumOfRight + a[i][i];
}
for(int i =0, j = sizeOfMatrix - 1; i <sizeOfMatrix; i++, j--){
sumOfLeft = sumOfLeft + a[j][i];
}
int sum = sumOfRight - sumOfLeft;
System.out.println(sum);
}
}
|
solution to diagonal difference problem
|
algorithms_warmup/src/com/codeprep/diagonaldifference/Solution.java
|
solution to diagonal difference problem
|
|
Java
|
epl-1.0
|
976002aab2cf460988a3369a9ae0373a354775c3
| 0
|
codenvy/codenvy,codenvy/codenvy,codenvy/codenvy,R-Brain/codenvy,R-Brain/codenvy,codenvy/codenvy,R-Brain/codenvy,codenvy/codenvy,R-Brain/codenvy,codenvy/codenvy,R-Brain/codenvy,R-Brain/codenvy
|
/*
* CODENVY CONFIDENTIAL
* __________________
*
* [2012] - [2015] Codenvy, S.A.
* All Rights Reserved.
*
* NOTICE: All information contained herein is, and remains
* the property of Codenvy S.A. and its suppliers,
* if any. The intellectual and technical concepts contained
* herein are proprietary to Codenvy S.A.
* and its suppliers and may be covered by U.S. and Foreign Patents,
* patents in process, and are protected by trade secret or copyright law.
* Dissemination of this information or reproduction of this material
* is strictly forbidden unless prior written permission is obtained
* from Codenvy S.A..
*/
package com.codenvy.im.agent;
import com.codenvy.im.commands.SimpleCommand;
import com.codenvy.im.testhelper.ssh.SshServerFactory;
import org.apache.sshd.SshServer;
import org.slf4j.LoggerFactory;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import java.io.IOException;
import static org.testng.Assert.assertEquals;
/**
* @author Alexander Reshetnyak
* @author Dmytro Nochevnov
*/
public class TestSecureShellAgent {
private static final String TEST_COMMAND = "echo test";
private static final String TEST_COMMAND_OUTPUT = "test";
private static final String UNEXISTED_HOST = "unexisted";
private SshServer sshd;
private SecureShellAgent testAgent;
@BeforeClass
public void setUp() throws IOException, InterruptedException {
sshd = SshServerFactory.createSshd();
sshd.start();
String env = SimpleCommand.createCommand("env").execute();
LoggerFactory.getLogger(TestSecureShellAgent.class).info("env: " + env + "\n----------- wait about 18 minutes to study the problem 'algorithm negotiation fail'");
Thread.sleep(1000000); // TODO [ndp] wait about 18 minutes to study the problem 'algorithm negotiation fail'
}
@Test
public void testAuthKey() throws Exception {
testAgent = new SecureShellAgent(SshServerFactory.TEST_SSH_HOST, sshd.getPort(), SshServerFactory.TEST_SSH_USER, SshServerFactory.TEST_SSH_AUTH_PRIVATE_KEY);
String result = testAgent.execute(TEST_COMMAND);
assertEquals(result, TEST_COMMAND_OUTPUT);
}
@Test(expectedExceptions = AgentException.class)
public void testAuthKeyError() throws Exception {
testAgent = new SecureShellAgent(UNEXISTED_HOST, sshd.getPort(), SshServerFactory.TEST_SSH_USER, SshServerFactory.TEST_SSH_AUTH_PRIVATE_KEY);
String result = testAgent.execute(TEST_COMMAND);
assertEquals(result, TEST_COMMAND_OUTPUT);
}
@Test(expectedExceptions = AgentException.class,
expectedExceptionsMessageRegExp = ".* Output: ; Error: ls: cannot access unExisted_file: No such file or directory.")
public void testErrorOnCommandExecution() throws Exception {
testAgent = new SecureShellAgent(SshServerFactory.TEST_SSH_HOST, sshd.getPort(), SshServerFactory.TEST_SSH_USER, SshServerFactory.TEST_SSH_AUTH_PRIVATE_KEY);
testAgent.execute("ls unExisted_file");
}
@AfterClass
public void tearDown() throws InterruptedException {
sshd.stop();
}
}
|
installation-manager-core/src/test/java/com/codenvy/im/agent/TestSecureShellAgent.java
|
/*
* CODENVY CONFIDENTIAL
* __________________
*
* [2012] - [2015] Codenvy, S.A.
* All Rights Reserved.
*
* NOTICE: All information contained herein is, and remains
* the property of Codenvy S.A. and its suppliers,
* if any. The intellectual and technical concepts contained
* herein are proprietary to Codenvy S.A.
* and its suppliers and may be covered by U.S. and Foreign Patents,
* patents in process, and are protected by trade secret or copyright law.
* Dissemination of this information or reproduction of this material
* is strictly forbidden unless prior written permission is obtained
* from Codenvy S.A..
*/
package com.codenvy.im.agent;
import com.codenvy.im.testhelper.ssh.SshServerFactory;
import org.apache.sshd.SshServer;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import java.io.IOException;
import static org.testng.Assert.assertEquals;
/**
* @author Alexander Reshetnyak
* @author Dmytro Nochevnov
*/
public class TestSecureShellAgent {
private static final String TEST_COMMAND = "echo test";
private static final String TEST_COMMAND_OUTPUT = "test";
private static final String UNEXISTED_HOST = "unexisted";
private SshServer sshd;
private SecureShellAgent testAgent;
@BeforeClass
public void setUp() throws IOException {
sshd = SshServerFactory.createSshd();
sshd.start();
}
@Test
public void testAuthKey() throws Exception {
testAgent = new SecureShellAgent(SshServerFactory.TEST_SSH_HOST, sshd.getPort(), SshServerFactory.TEST_SSH_USER, SshServerFactory.TEST_SSH_AUTH_PRIVATE_KEY);
String result = testAgent.execute(TEST_COMMAND);
assertEquals(result, TEST_COMMAND_OUTPUT);
}
@Test(expectedExceptions = AgentException.class)
public void testAuthKeyError() throws Exception {
testAgent = new SecureShellAgent(UNEXISTED_HOST, sshd.getPort(), SshServerFactory.TEST_SSH_USER, SshServerFactory.TEST_SSH_AUTH_PRIVATE_KEY);
String result = testAgent.execute(TEST_COMMAND);
assertEquals(result, TEST_COMMAND_OUTPUT);
}
@Test(expectedExceptions = AgentException.class,
expectedExceptionsMessageRegExp = ".* Output: ; Error: ls: cannot access unExisted_file: No such file or directory.")
public void testErrorOnCommandExecution() throws Exception {
testAgent = new SecureShellAgent(SshServerFactory.TEST_SSH_HOST, sshd.getPort(), SshServerFactory.TEST_SSH_USER, SshServerFactory.TEST_SSH_AUTH_PRIVATE_KEY);
testAgent.execute("ls unExisted_file");
}
@AfterClass
public void tearDown() throws InterruptedException {
sshd.stop();
}
}
|
study failing tests of SecureShellAgent on Jenkins
|
installation-manager-core/src/test/java/com/codenvy/im/agent/TestSecureShellAgent.java
|
study failing tests of SecureShellAgent on Jenkins
|
|
Java
|
agpl-3.0
|
12ec10bbbc32ab829b246f1593ca7c5b7fc4713a
| 0
|
imCodePartnerAB/imcms,imCodePartnerAB/imcms,imCodePartnerAB/imcms
|
package com.imcode.imcms.domain.service.api;
import com.imcode.imcms.WebAppSpringTestConfig;
import com.imcode.imcms.api.ValidationLink;
import com.imcode.imcms.components.datainitializer.CommonContentDataInitializer;
import com.imcode.imcms.components.datainitializer.DocumentDataInitializer;
import com.imcode.imcms.components.datainitializer.ImageDataInitializer;
import com.imcode.imcms.components.datainitializer.LanguageDataInitializer;
import com.imcode.imcms.components.datainitializer.LoopDataInitializer;
import com.imcode.imcms.components.datainitializer.UrlDocumentDataInitializer;
import com.imcode.imcms.components.datainitializer.VersionDataInitializer;
import com.imcode.imcms.domain.dto.AuditDTO;
import com.imcode.imcms.domain.dto.ImageDTO;
import com.imcode.imcms.domain.dto.LoopDTO;
import com.imcode.imcms.domain.dto.LoopEntryDTO;
import com.imcode.imcms.domain.dto.UrlDocumentDTO;
import com.imcode.imcms.domain.service.CommonContentService;
import com.imcode.imcms.domain.service.DocumentService;
import com.imcode.imcms.domain.service.ImageService;
import com.imcode.imcms.domain.service.VersionService;
import com.imcode.imcms.model.CommonContent;
import com.imcode.imcms.model.Language;
import com.imcode.imcms.model.LoopEntryRef;
import com.imcode.imcms.persistence.entity.Image;
import com.imcode.imcms.persistence.entity.LanguageJPA;
import com.imcode.imcms.persistence.entity.LoopEntryRefJPA;
import com.imcode.imcms.persistence.entity.TextJPA;
import com.imcode.imcms.persistence.entity.Version;
import com.imcode.imcms.persistence.repository.TextRepository;
import imcode.server.Imcms;
import imcode.server.user.UserDomainObject;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import java.util.Collections;
import java.util.List;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static com.imcode.imcms.model.Text.Type.TEXT;
import static org.junit.jupiter.api.Assertions.*;
@Transactional
public class DefaultLinkValidationServiceTest extends WebAppSpringTestConfig {
private static final String TEXTS = "test";
private static final String TEXT_URL = "<a href=\"https://www.google.com\">Test</a>";
private static final String NOT_FOUND_URL_HTTPS_TEXT = "<a href=\"https://aaa.fff.ddd\">Test</a>";
private static final String NOT_FOUND_URL_HTTP_TEXT = "<a href=\"http://dev.prego.ua\">Test</a>";
private static final String NOT_REACHABLE_URL_IP = "<a href=\"http://a:0:a0a::\"> Test</a>";
private static final Pattern LINK_VALIDATION_PATTERN = Pattern.compile("href\\s*=\\s*\"(.*)\"");
@Autowired
private DocumentDataInitializer documentDataInitializer;
@Autowired
private LanguageDataInitializer languageDataInitializer;
@Autowired
private VersionService versionService;
@Autowired
private TextRepository textRepository;
@Autowired
private ImageDataInitializer imageDataInitializer;
@Autowired
private Function<Image, ImageDTO> imageToImageDTO;
@Autowired
private ImageService imageService;
@Autowired
private UrlDocumentDataInitializer urlDocumentDataInitializer;
@Autowired
private DocumentService<UrlDocumentDTO> urlDocumentService;
@Autowired
private VersionDataInitializer versionDataInitializer;
@Autowired
private LoopDataInitializer loopDataInitializer;
@Autowired
private CommonContentService commonContentService;
@Autowired
private CommonContentDataInitializer commonContentDataInitializer;
@Autowired
private DefaultLinkValidationService defaultLinkValidationService;
private String getLinkFromText(String text) {
Matcher m = LINK_VALIDATION_PATTERN.matcher(text);
m.find();
String extractedLink = m.group(1);
return extractedLink;
}
@AfterEach
public void clearTestData() {
documentDataInitializer.cleanRepositories();
languageDataInitializer.cleanRepositories();
imageDataInitializer.cleanRepositories();
loopDataInitializer.cleanRepositories();
urlDocumentDataInitializer.cleanRepositories();
versionDataInitializer.cleanRepositories();
commonContentDataInitializer.cleanRepositories();
}
@Test
public void validateDocumentLinks_When_TextNotValidUrl_Expected_EmptyResult() {
final int index = 1;
int docId = documentDataInitializer.createData().getId();
final Version latestVersionDoc = versionService.create(docId, 1);
final LanguageJPA languageJPA = new LanguageJPA(languageDataInitializer.createData().get(0));
createText(index, languageJPA, latestVersionDoc, TEXTS);
final boolean displayOnlyBrokenLinks = false;
List<ValidationLink> links = defaultLinkValidationService.validateDocumentsLinks(displayOnlyBrokenLinks, docId, docId);
assertNotNull(links);
assertTrue(links.isEmpty());
}
@Test
public void validateDocumentLinks_When_TextValidUrlButNotFound_Expected_CorrectLinks() {
final int index = 1;
int docId = documentDataInitializer.createData().getId();
final Version latestVersionDoc = versionService.create(docId, 1);
final LanguageJPA languageJPA = new LanguageJPA(languageDataInitializer.createData().get(0));
final List<CommonContent> commonContentDTOS = commonContentDataInitializer.createData(latestVersionDoc);
commonContentDTOS.get(0).setHeadline("Test");
commonContentService.save(docId, commonContentDTOS);
createText(index, languageJPA, latestVersionDoc, NOT_FOUND_URL_HTTP_TEXT);
final boolean displayOnlyBrokenLinks = false;
List<ValidationLink> links = defaultLinkValidationService.validateDocumentsLinks(displayOnlyBrokenLinks,
docId,
docId);
assertNotNull(links);
assertEquals(1, links.size());
ValidationLink link = links.get(0);
assertEquals(commonContentDTOS.get(0).getHeadline(), link.getDocumentData().getTitle());
assertTrue(link.isHostFound());
assertTrue(link.isHostReachable());
assertFalse(link.isPageFound());
assertEquals(getLinkFromText(NOT_FOUND_URL_HTTP_TEXT), link.getUrl());
}
@Test
public void validateDocumentLinks_When_ShowOnlyBrokenLinks_Expected_CorrectLinks() {
final int index = 1;
int doc1Id = documentDataInitializer.createData().getId();
int doc2Id = documentDataInitializer.createData().getId();
final Version versionDoc1 = versionService.create(doc1Id, 1);
final Version versionDoc2 = versionService.create(doc2Id, 1);
final LanguageJPA languageJPA = new LanguageJPA(languageDataInitializer.createData().get(0));
createText(index, languageJPA, versionDoc1, TEXT_URL);
createText(index, languageJPA, versionDoc2, NOT_FOUND_URL_HTTPS_TEXT);
final boolean displayOnlyBrokenLinks = true;
List<ValidationLink> links = defaultLinkValidationService.validateDocumentsLinks(displayOnlyBrokenLinks,
doc1Id,
doc2Id);
assertNotNull(links);
assertEquals(1, links.size());
ValidationLink link = links.get(0);
assertEquals(getLinkFromText(NOT_FOUND_URL_HTTPS_TEXT), link.getUrl());
assertFalse(link.isHostFound());
assertFalse(link.isHostReachable());
assertFalse(link.isPageFound());
}
@Test
public void validateDocumentLinks_When_ValidTextUrl_Expected_CorrectLinks() {
final int index = 1;
int docId = documentDataInitializer.createData().getId();
final Version version = versionService.create(docId, 1);
final LanguageJPA languageJPA = new LanguageJPA(languageDataInitializer.createData().get(0));
final List<CommonContent> commonContentDTOS = commonContentDataInitializer.createData(version);
commonContentDTOS.get(0).setHeadline("Test");
commonContentService.save(docId, commonContentDTOS);
createText(index, languageJPA, version, TEXT_URL);
final boolean displayOnlyBrokenLinks = false;
List<ValidationLink> links = defaultLinkValidationService.validateDocumentsLinks(
displayOnlyBrokenLinks,
docId,
docId);
assertNotNull(links);
assertEquals(1, links.size());
ValidationLink link = links.get(0);
assertEquals(commonContentDTOS.get(0).getHeadline(), link.getDocumentData().getTitle());
assertTrue(link.isHostFound());
assertTrue(link.isHostReachable());
assertTrue(link.isPageFound());
assertEquals(getLinkFromText(TEXT_URL), link.getUrl());
}
@Test
public void validateDocumentLinks_When_ImageValidUrl_Expected_CorrectLinks() {
final int index = 1;
int docId = documentDataInitializer.createData().getId();
final Version versionDoc = versionService.create(docId, 1);
final Image image = imageDataInitializer.createData(index, versionDoc);
image.setLinkUrl(getLinkFromText(TEXT_URL));
final ImageDTO imageDTO = imageToImageDTO.apply(image);
imageService.saveImage(imageDTO);
final boolean displayOnlyBrokenLinks = false;
List<ValidationLink> links = defaultLinkValidationService.validateDocumentsLinks(
displayOnlyBrokenLinks,
docId,
docId);
assertNotNull(links);
assertEquals(1, links.size());
ValidationLink link = links.get(0);
assertTrue(link.isHostFound());
assertTrue(link.isHostReachable());
assertTrue(link.isPageFound());
assertEquals(getLinkFromText(TEXT_URL), link.getUrl());
}
@Test
public void validateDocumentLinks_When_ImageNotReachableUrl_Expected_CorrectLinks() {
final int index = 1;
int doc1Id = documentDataInitializer.createData().getId();
final Version versionDoc = versionService.create(doc1Id, 1);
final Image image = imageDataInitializer.createData(index, versionDoc);
image.setLinkUrl((getLinkFromText(NOT_REACHABLE_URL_IP)));
final ImageDTO imageDTO = imageToImageDTO.apply(image);
imageService.saveImage(imageDTO);
final boolean displayOnlyBrokenLinks = false;
List<ValidationLink> links = defaultLinkValidationService.validateDocumentsLinks(
displayOnlyBrokenLinks,
doc1Id,
doc1Id);
assertNotNull(links);
assertEquals(1, links.size());
ValidationLink link = links.get(0);
assertTrue(link.isHostFound());
assertFalse(link.isHostReachable());
assertFalse(link.isPageFound());
}
@Test
public void validateDocumentLinks_When_UrlDocNotValidUrlOnAllLanguages_Expected_CorrectEntities() {
final int index = 1;
final UrlDocumentDTO urlDocumentDTO = urlDocumentDataInitializer.createUrlDocument(TEXTS);
final int docId = urlDocumentDTO.getId();
final Version version = versionDataInitializer.createData(index, docId);
final UserDomainObject user = new UserDomainObject(1);
Imcms.setUser(user);
urlDocumentDTO.setLatestVersion(AuditDTO.fromVersion(version));
urlDocumentService.save(urlDocumentDTO);
final boolean displayOnlyBrokenLinks = false;
List<ValidationLink> links = defaultLinkValidationService.validateDocumentsLinks(
displayOnlyBrokenLinks,
docId,
docId);
assertNotNull(links);
assertEquals(2, links.size());
ValidationLink link = links.get(0);
assertTrue(link.isHostFound());
assertFalse(link.isHostReachable());
assertFalse(link.isPageFound());
}
@Test
public void validateDocumentLinks_When_UrlDocHasValidUrlOnAllLanguages_Expected_CorrectLinks() {
final int index = 1;
final UrlDocumentDTO urlDocumentDTO = urlDocumentDataInitializer.createUrlDocument(getLinkFromText(TEXT_URL));
final int docId = urlDocumentDTO.getId();
final Version version = versionDataInitializer.createData(index, docId);
final UserDomainObject user = new UserDomainObject(1);
Imcms.setUser(user);
urlDocumentDTO.setLatestVersion(AuditDTO.fromVersion(version));
urlDocumentService.save(urlDocumentDTO);
final boolean displayOnlyBrokenLinks = false;
List<ValidationLink> links = defaultLinkValidationService.validateDocumentsLinks(
displayOnlyBrokenLinks,
docId,
docId);
assertNotNull(links);
assertEquals(2, links.size());
ValidationLink link = links.get(0);
assertTrue(link.isHostFound());
assertTrue(link.isHostReachable());
assertTrue(link.isPageFound());
}
@Test
public void validateDocumentLinks_When_UrlDocValidUrlNotReachableOnAllLanguages_Expected_CorrectLinks() {
final int index = 1;
final UrlDocumentDTO urlDocumentDTO = urlDocumentDataInitializer.createUrlDocument(getLinkFromText(NOT_REACHABLE_URL_IP));
final int docId = urlDocumentDTO.getId();
final Version version = versionDataInitializer.createData(index, docId);
final UserDomainObject user = new UserDomainObject(1);
Imcms.setUser(user);
urlDocumentDTO.setLatestVersion(AuditDTO.fromVersion(version));
urlDocumentService.save(urlDocumentDTO);
final boolean displayOnlyBrokenLinks = false;
List<ValidationLink> links = defaultLinkValidationService.validateDocumentsLinks(
displayOnlyBrokenLinks,
docId,
docId);
assertNotNull(links);
assertEquals(2, links.size());
ValidationLink link = links.get(0);
assertTrue(link.isHostFound());
assertFalse(link.isHostReachable());
assertFalse(link.isPageFound());
}
@Test
public void validateDocumentLinks_When_LoopHasNotValidUrlInTextAndImage_Expected_CorrectLinks() {
final int index = 1;
int docId = documentDataInitializer.createData().getId();
final Version versionDoc = versionService.create(docId, 1);
final LoopEntryRefJPA loopEntryRef = new LoopEntryRefJPA(index, 1);
final LanguageJPA languageJPA = new LanguageJPA(languageDataInitializer.createData().get(0));
final Image image = imageDataInitializer.createData(index, versionDoc);
image.setLinkUrl(TEXTS);
final ImageDTO imageDTO = imageToImageDTO.apply(image);
imageService.saveImage(imageDTO);
createText(index, languageJPA, versionDoc, TEXTS, loopEntryRef);
imageDataInitializer.generateImage(imageDTO.getIndex(), languageJPA, versionDoc, loopEntryRef);
final boolean displayOnlyBrokenLinks = false;
List<ValidationLink> links = defaultLinkValidationService.validateDocumentsLinks(
displayOnlyBrokenLinks,
docId,
docId);
assertNotNull(links);
assertEquals(1, links.size());
ValidationLink link = links.get(0);
assertTrue(link.isHostFound());
assertFalse(link.isHostReachable());
assertFalse(link.isPageFound());
}
@Test
public void validateDocumentLinks_When_LoopHasValidUrlAndImageText_Expected_CorrectLinks() {
final int index = 1;
int docId = documentDataInitializer.createData().getId();
final Version versionDoc = versionService.create(docId, 1);
final LoopDTO loopDTO = new LoopDTO(docId, index, Collections.singletonList(LoopEntryDTO.createEnabled(1)));
final LoopEntryRefJPA loopEntryRef = new LoopEntryRefJPA(1, 1);
loopDataInitializer.createData(loopDTO);
final Language en = languageDataInitializer.createData().get(0);
final LanguageJPA languageJPA = new LanguageJPA(en);
final Image image = imageDataInitializer.createData(index, versionDoc);
image.setLinkUrl(getLinkFromText(TEXT_URL));
final ImageDTO imageDTO = imageToImageDTO.apply(image);
imageService.saveImage(imageDTO);
createText(index, languageJPA, versionDoc, TEXT_URL, loopEntryRef);
imageDataInitializer.generateImage(imageDTO.getIndex(), languageJPA, versionDoc, loopEntryRef);
final boolean displayOnlyBrokenLinks = false;
List<ValidationLink> links = defaultLinkValidationService.validateDocumentsLinks(
displayOnlyBrokenLinks,
docId,
docId);
assertNotNull(links);
assertEquals(2, links.size());
ValidationLink link = links.get(0);
assertTrue(link.isHostFound());
assertTrue(link.isHostReachable());
assertTrue(link.isPageFound());
}
@Test
public void validateDocumentLinks_When_LoopHasNotReachableUrlText_Expected_CorrectLinks() {
final int index = 1;
int doc1Id = documentDataInitializer.createData().getId();
final Version version = versionService.create(doc1Id, 1);
final LoopEntryRefJPA loopEntryRef = new LoopEntryRefJPA(1, 1);
final LanguageJPA languageJPA = new LanguageJPA(languageDataInitializer.createData().get(0));
final Image image = imageDataInitializer.createData(index, version);
image.setLinkUrl(getLinkFromText(NOT_REACHABLE_URL_IP));
final ImageDTO imageDTO1 = imageToImageDTO.apply(image);
imageService.saveImage(imageDTO1);
createText(index, languageJPA, version, NOT_FOUND_URL_HTTP_TEXT, loopEntryRef);
imageDataInitializer.generateImage(imageDTO1.getIndex(), languageJPA, version, loopEntryRef);
final boolean displayOnlyBrokenLinks = false;
List<ValidationLink> links = defaultLinkValidationService.validateDocumentsLinks(
displayOnlyBrokenLinks,
doc1Id,
doc1Id);
assertNotNull(links);
assertEquals(2, links.size());
ValidationLink link = links.get(0);
assertTrue(link.isHostFound());
assertFalse(link.isHostReachable());
assertFalse(link.isPageFound());
}
@Test
public void validateDocumentLinks_When_DocumentIdsHaveThisRange_Expected_CorrectSizeAndLinks() {
final int index = 1;
int doc1Id = documentDataInitializer.createData().getId();
int doc2Id = documentDataInitializer.createData().getId();
int doc3Id = documentDataInitializer.createData().getId();
final Version versionDoc1 = versionService.create(doc1Id, 1);
final Version versionDoc2 = versionService.create(doc2Id, 1);
final Version versionDoc3 = versionService.create(doc3Id, 1);
final LanguageJPA languageJPA = new LanguageJPA(languageDataInitializer.createData().get(0));
createText(index, languageJPA, versionDoc1, TEXT_URL);
createText(index, languageJPA, versionDoc2, TEXT_URL);
createText(index, languageJPA, versionDoc3, TEXT_URL);
final boolean displayOnlyBrokenLinks = false;
List<ValidationLink> links = defaultLinkValidationService.validateDocumentsLinks(displayOnlyBrokenLinks,
doc1Id,
doc3Id);
assertNotNull(links);
assertEquals(3, links.size());
ValidationLink link = links.get(0);
assertTrue(link.isHostFound());
assertTrue(link.isHostReachable());
assertTrue(link.isPageFound());
}
@Test
public void validateDocumentLinks_When_DocumentHasTextImageAndLoopWithValidUrl_Expected_CorrectLinks() {
final int index = 1;
int docId = documentDataInitializer.createData().getId();
final Version versionDoc = versionService.create(docId, 1);
final LoopEntryRefJPA loopEntryRef = new LoopEntryRefJPA(1, 1);
final LanguageJPA languageJPA = new LanguageJPA(languageDataInitializer.createData().get(0));
final Image image = imageDataInitializer.createData(index, versionDoc);
image.setLinkUrl((getLinkFromText(TEXT_URL)));
final ImageDTO imageDTO = imageToImageDTO.apply(image);
imageService.saveImage(imageDTO);
createText(index, languageJPA, versionDoc, TEXT_URL, loopEntryRef);
createText(index, languageJPA, versionDoc, NOT_FOUND_URL_HTTP_TEXT);
imageDataInitializer.generateImage(imageDTO.getIndex(), languageJPA, versionDoc, loopEntryRef);
final boolean displayOnlyBrokenLinks = false;
List<ValidationLink> links = defaultLinkValidationService.validateDocumentsLinks(displayOnlyBrokenLinks,
docId,
docId);
assertNotNull(links);
assertEquals(3, links.size());
}
@Test
public void validateDocumentLinks_When_StartIdMoreThanEndId_Expected_EmptyResult() {
final int index = 1;
int doc1Id = documentDataInitializer.createData().getId();
int doc2Id = documentDataInitializer.createData().getId();
final Version versionDoc1 = versionService.create(doc1Id, 1);
final Version versionDoc2 = versionService.create(doc2Id, 1);
assertTrue(doc2Id > doc1Id);
final LanguageJPA languageJPA = new LanguageJPA(languageDataInitializer.createData().get(0));
createText(index, languageJPA, versionDoc1, TEXT_URL);
createText(index, languageJPA, versionDoc2, NOT_FOUND_URL_HTTPS_TEXT);
final boolean displayOnlyBrokenLinks = false;
List<ValidationLink> links = defaultLinkValidationService.validateDocumentsLinks(displayOnlyBrokenLinks,
doc2Id,
doc1Id);
assertNotNull(links);
assertTrue(links.isEmpty());
}
private void createText(int index, LanguageJPA language, Version version, String testText) {
final TextJPA text = new TextJPA();
text.setIndex(index);
text.setLanguage(language);
text.setText(testText);
text.setType(TEXT);
text.setVersion(version);
textRepository.saveAndFlush(text);
}
private void createText(int index, LanguageJPA language, Version version, String testText, LoopEntryRef loopEntryRef) {
final TextJPA text = new TextJPA();
text.setIndex(index);
text.setLanguage(language);
text.setText(testText);
text.setType(TEXT);
text.setVersion(version);
text.setLoopEntryRef(loopEntryRef);
textRepository.saveAndFlush(text);
}
}
|
src/test/java/com/imcode/imcms/domain/service/api/DefaultLinkValidationServiceTest.java
|
package com.imcode.imcms.domain.service.api;
import com.imcode.imcms.WebAppSpringTestConfig;
import com.imcode.imcms.api.ValidationLink;
import com.imcode.imcms.components.datainitializer.CommonContentDataInitializer;
import com.imcode.imcms.components.datainitializer.DocumentDataInitializer;
import com.imcode.imcms.components.datainitializer.ImageDataInitializer;
import com.imcode.imcms.components.datainitializer.LanguageDataInitializer;
import com.imcode.imcms.components.datainitializer.LoopDataInitializer;
import com.imcode.imcms.components.datainitializer.UrlDocumentDataInitializer;
import com.imcode.imcms.components.datainitializer.VersionDataInitializer;
import com.imcode.imcms.domain.dto.AuditDTO;
import com.imcode.imcms.domain.dto.ImageDTO;
import com.imcode.imcms.domain.dto.LoopDTO;
import com.imcode.imcms.domain.dto.LoopEntryDTO;
import com.imcode.imcms.domain.dto.UrlDocumentDTO;
import com.imcode.imcms.domain.service.CommonContentService;
import com.imcode.imcms.domain.service.DocumentService;
import com.imcode.imcms.domain.service.ImageService;
import com.imcode.imcms.domain.service.VersionService;
import com.imcode.imcms.model.CommonContent;
import com.imcode.imcms.model.Language;
import com.imcode.imcms.model.LoopEntryRef;
import com.imcode.imcms.persistence.entity.Image;
import com.imcode.imcms.persistence.entity.LanguageJPA;
import com.imcode.imcms.persistence.entity.LoopEntryRefJPA;
import com.imcode.imcms.persistence.entity.TextJPA;
import com.imcode.imcms.persistence.entity.Version;
import com.imcode.imcms.persistence.repository.TextRepository;
import imcode.server.Imcms;
import imcode.server.user.UserDomainObject;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import java.util.Collections;
import java.util.List;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static com.imcode.imcms.model.Text.Type.TEXT;
import static org.junit.jupiter.api.Assertions.*;
@Transactional
public class DefaultLinkValidationServiceTest extends WebAppSpringTestConfig {
private static final String TEXTS = "test";
private static final String TEXT_URL = "<a href=\"https://www.google.com\">Test</a>";
private static final String NOT_FOUND_URL_HTTPS_TEXT = "<a href=\"https://aaa.fff.ddd\">Test</a>";
private static final String NOT_FOUND_URL_HTTP_TEXT = "<a href=\"http://dev.prego.ua\">Test</a>";
private static final String NOT_REACHABLE_URL_IP = "<a href=\"http://a:0:a0a::\"> Test</a>";
private static final Pattern LINK_VALIDATION_PATTERN = Pattern.compile("href\\s*=\\s*\"(.*)\"");
@Autowired
private DocumentDataInitializer documentDataInitializer;
@Autowired
private LanguageDataInitializer languageDataInitializer;
@Autowired
private VersionService versionService;
@Autowired
private TextRepository textRepository;
@Autowired
private ImageDataInitializer imageDataInitializer;
@Autowired
private Function<Image, ImageDTO> imageToImageDTO;
@Autowired
private ImageService imageService;
@Autowired
private UrlDocumentDataInitializer urlDocumentDataInitializer;
@Autowired
private DocumentService<UrlDocumentDTO> urlDocumentService;
@Autowired
private VersionDataInitializer versionDataInitializer;
@Autowired
private LoopDataInitializer loopDataInitializer;
@Autowired
private CommonContentService commonContentService;
@Autowired
private CommonContentDataInitializer commonContentDataInitializer;
@Autowired
private DefaultLinkValidationService defaultLinkValidationService;
private String getLinkFromText(String text) {
Matcher m = LINK_VALIDATION_PATTERN.matcher(text);
m.find();
String extractedLink = m.group(1);
return extractedLink;
}
@AfterEach
public void clearTestData() {
documentDataInitializer.cleanRepositories();
languageDataInitializer.cleanRepositories();
imageDataInitializer.cleanRepositories();
loopDataInitializer.cleanRepositories();
urlDocumentDataInitializer.cleanRepositories();
versionDataInitializer.cleanRepositories();
commonContentDataInitializer.cleanRepositories();
}
@Test
public void validateDocumentLinks_When_TextNotValidUrl_Expected_EmptyResult() {
final int index = 1;
int docId = documentDataInitializer.createData().getId();
final Version latestVersionDoc = versionService.create(docId, 1);
final LanguageJPA languageJPA = new LanguageJPA(languageDataInitializer.createData().get(0));
createText(index, languageJPA, latestVersionDoc, TEXTS);
final boolean displayOnlyBrokenLinks = false;
List<ValidationLink> links = defaultLinkValidationService.validateDocumentsLinks(displayOnlyBrokenLinks, docId, docId);
assertNotNull(links);
assertTrue(links.isEmpty());
}
@Test
public void validateDocumentLinks_When_UrlValidButNotFound_Expected_CorrectLinks() {
final int index = 1;
int docId = documentDataInitializer.createData().getId();
final Version latestVersionDoc = versionService.create(docId, 1);
final LanguageJPA languageJPA = new LanguageJPA(languageDataInitializer.createData().get(0));
final List<CommonContent> commonContentDTOS = commonContentDataInitializer.createData(latestVersionDoc);
commonContentDTOS.get(0).setHeadline("Test");
commonContentService.save(docId, commonContentDTOS);
createText(index, languageJPA, latestVersionDoc, NOT_FOUND_URL_HTTP_TEXT);
final boolean displayOnlyBrokenLinks = false;
List<ValidationLink> links = defaultLinkValidationService.validateDocumentsLinks(displayOnlyBrokenLinks,
docId,
docId);
assertNotNull(links);
assertEquals(1, links.size());
ValidationLink link = links.get(0);
assertEquals(commonContentDTOS.get(0).getHeadline(), link.getDocumentData().getTitle());
assertTrue(link.isHostFound());
assertTrue(link.isHostReachable());
assertFalse(link.isPageFound());
assertEquals(getLinkFromText(NOT_FOUND_URL_HTTP_TEXT), link.getUrl());
}
@Test
public void validateDocumentLinks_When_ShowOnlyBrokenLinks_Expected_CorrectLinks() {
final int index = 1;
int doc1Id = documentDataInitializer.createData().getId();
int doc2Id = documentDataInitializer.createData().getId();
final Version versionDoc1 = versionService.create(doc1Id, 1);
final Version versionDoc2 = versionService.create(doc2Id, 1);
final LanguageJPA languageJPA = new LanguageJPA(languageDataInitializer.createData().get(0));
createText(index, languageJPA, versionDoc1, TEXT_URL);
createText(index, languageJPA, versionDoc2, NOT_FOUND_URL_HTTPS_TEXT);
final boolean displayOnlyBrokenLinks = true;
List<ValidationLink> links = defaultLinkValidationService.validateDocumentsLinks(displayOnlyBrokenLinks,
doc1Id,
doc2Id);
assertNotNull(links);
assertEquals(1, links.size());
ValidationLink link = links.get(0);
assertEquals(getLinkFromText(NOT_FOUND_URL_HTTPS_TEXT), link.getUrl());
assertFalse(link.isHostFound());
assertFalse(link.isHostReachable());
assertFalse(link.isPageFound());
}
@Test
public void validateDocumentLinks_When_ValidTextUrl_Expected_CorrectLinks() {
final int index = 1;
int docId = documentDataInitializer.createData().getId();
final Version version = versionService.create(docId, 1);
final LanguageJPA languageJPA = new LanguageJPA(languageDataInitializer.createData().get(0));
final List<CommonContent> commonContentDTOS = commonContentDataInitializer.createData(version);
commonContentDTOS.get(0).setHeadline("Test");
commonContentService.save(docId, commonContentDTOS);
createText(index, languageJPA, version, TEXT_URL);
final boolean displayOnlyBrokenLinks = false;
List<ValidationLink> links = defaultLinkValidationService.validateDocumentsLinks(
displayOnlyBrokenLinks,
docId,
docId);
assertNotNull(links);
assertEquals(1, links.size());
ValidationLink link = links.get(0);
assertEquals(commonContentDTOS.get(0).getHeadline(), link.getDocumentData().getTitle());
assertTrue(link.isHostFound());
assertTrue(link.isHostReachable());
assertTrue(link.isPageFound());
assertEquals(getLinkFromText(TEXT_URL), link.getUrl());
}
@Test
public void validateDocumentLinks_When_ImageValidUrl_Expected_CorrectLinks() {
final int index = 1;
int docId = documentDataInitializer.createData().getId();
final Version versionDoc = versionService.create(docId, 1);
final Image image = imageDataInitializer.createData(index, versionDoc);
image.setLinkUrl(getLinkFromText(TEXT_URL));
final ImageDTO imageDTO = imageToImageDTO.apply(image);
imageService.saveImage(imageDTO);
final boolean displayOnlyBrokenLinks = false;
List<ValidationLink> links = defaultLinkValidationService.validateDocumentsLinks(
displayOnlyBrokenLinks,
docId,
docId);
assertNotNull(links);
assertEquals(1, links.size());
ValidationLink link = links.get(0);
assertTrue(link.isHostFound());
assertTrue(link.isHostReachable());
assertTrue(link.isPageFound());
assertEquals(getLinkFromText(TEXT_URL), link.getUrl());
}
@Test
public void validateDocumentLinks_When_ImageNotReachableUrl_Expected_CorrectLinks() {
final int index = 1;
int doc1Id = documentDataInitializer.createData().getId();
final Version versionDoc = versionService.create(doc1Id, 1);
final Image image = imageDataInitializer.createData(index, versionDoc);
image.setLinkUrl((getLinkFromText(NOT_REACHABLE_URL_IP)));
final ImageDTO imageDTO = imageToImageDTO.apply(image);
imageService.saveImage(imageDTO);
final boolean displayOnlyBrokenLinks = false;
List<ValidationLink> links = defaultLinkValidationService.validateDocumentsLinks(
displayOnlyBrokenLinks,
doc1Id,
doc1Id);
assertNotNull(links);
assertEquals(1, links.size());
ValidationLink link = links.get(0);
assertTrue(link.isHostFound());
assertFalse(link.isHostReachable());
assertFalse(link.isPageFound());
}
@Test
public void validateDocumentLinks_When_UrlDocNotValidUrl_Expected_CorrectEntities() {
final int index = 1;
final UrlDocumentDTO urlDocumentDTO = urlDocumentDataInitializer.createUrlDocument(TEXTS);
final int docId = urlDocumentDTO.getId();
final Version version = versionDataInitializer.createData(index, docId);
final UserDomainObject user = new UserDomainObject(1);
Imcms.setUser(user);
urlDocumentDTO.setLatestVersion(AuditDTO.fromVersion(version));
urlDocumentService.save(urlDocumentDTO);
final boolean displayOnlyBrokenLinks = false;
List<ValidationLink> links = defaultLinkValidationService.validateDocumentsLinks(
displayOnlyBrokenLinks,
docId,
docId);
assertNotNull(links);
assertEquals(1, links.size());
ValidationLink link = links.get(0);
assertFalse(link.isHostFound());
assertFalse(link.isHostReachable());
assertFalse(link.isPageFound());
}
@Test
public void validateDocumentLinks_When_UrlDocHasValidUrl_Expected_CorrectLinks() {
final int index = 1;
final UrlDocumentDTO urlDocumentDTO = urlDocumentDataInitializer.createUrlDocument(TEXT_URL);
final int docId = urlDocumentDTO.getId();
final Version version = versionDataInitializer.createData(index, docId);
final UserDomainObject user = new UserDomainObject(1);
Imcms.setUser(user);
urlDocumentDTO.setLatestVersion(AuditDTO.fromVersion(version));
urlDocumentService.save(urlDocumentDTO);
final boolean displayOnlyBrokenLinks = false;
List<ValidationLink> links = defaultLinkValidationService.validateDocumentsLinks(
displayOnlyBrokenLinks,
docId,
docId);
assertNotNull(links);
assertEquals(1, links.size());
ValidationLink link = links.get(0);
assertTrue(link.isHostFound());
assertTrue(link.isHostReachable());
assertTrue(link.isPageFound());
}
@Test
public void validateDocumentLinks_When_UrlDocValidUrlNotReachable_Expected_CorrectLinks() {
final int index = 1;
final UrlDocumentDTO urlDocumentDTO = urlDocumentDataInitializer.createUrlDocument(NOT_REACHABLE_URL_IP);
final int docId = urlDocumentDTO.getId();
final Version version = versionDataInitializer.createData(index, docId);
final UserDomainObject user = new UserDomainObject(1);
Imcms.setUser(user);
urlDocumentDTO.setLatestVersion(AuditDTO.fromVersion(version));
urlDocumentService.save(urlDocumentDTO);
final boolean displayOnlyBrokenLinks = false;
List<ValidationLink> links = defaultLinkValidationService.validateDocumentsLinks(
displayOnlyBrokenLinks,
docId,
docId);
assertNotNull(links);
assertEquals(1, links.size());
ValidationLink link = links.get(0);
assertTrue(link.isHostFound());
assertFalse(link.isHostReachable());
assertFalse(link.isPageFound());
}
@Test
public void validateDocumentLinks_When_LoopHasNotValidUrlInTextAndImage_Expected_CorrectLinks() {
final int index = 1;
int docId = documentDataInitializer.createData().getId();
final Version versionDoc = versionService.create(docId, 1);
final LoopEntryRefJPA loopEntryRef = new LoopEntryRefJPA(index, 1);
final LanguageJPA languageJPA = new LanguageJPA(languageDataInitializer.createData().get(0));
final Image image = imageDataInitializer.createData(index, versionDoc);
image.setLinkUrl(TEXTS);
final ImageDTO imageDTO = imageToImageDTO.apply(image);
imageService.saveImage(imageDTO);
createText(index, languageJPA, versionDoc, TEXTS, loopEntryRef);
imageDataInitializer.generateImage(imageDTO.getIndex(), languageJPA, versionDoc, loopEntryRef);
final boolean displayOnlyBrokenLinks = false;
List<ValidationLink> links = defaultLinkValidationService.validateDocumentsLinks(
displayOnlyBrokenLinks,
docId,
docId);
assertNotNull(links);
assertEquals(1, links.size());
ValidationLink link = links.get(0);
assertTrue(link.isHostFound());
assertFalse(link.isHostReachable());
assertFalse(link.isPageFound());
}
@Test
public void validateDocumentLinks_When_LoopHasValidUrlAndImageText_Expected_CorrectLinks() {
final int index = 1;
int docId = documentDataInitializer.createData().getId();
final Version versionDoc = versionService.create(docId, 1);
final LoopDTO loopDTO = new LoopDTO(docId, index, Collections.singletonList(LoopEntryDTO.createEnabled(1)));
final LoopEntryRefJPA loopEntryRef = new LoopEntryRefJPA(1, 1);
loopDataInitializer.createData(loopDTO);
final Language en = languageDataInitializer.createData().get(0);
final LanguageJPA languageJPA = new LanguageJPA(en);
final Image image = imageDataInitializer.createData(index, versionDoc);
image.setLinkUrl(getLinkFromText(TEXT_URL));
final ImageDTO imageDTO = imageToImageDTO.apply(image);
imageService.saveImage(imageDTO);
createText(index, languageJPA, versionDoc, TEXT_URL, loopEntryRef);
imageDataInitializer.generateImage(imageDTO.getIndex(), languageJPA, versionDoc, loopEntryRef);
final boolean displayOnlyBrokenLinks = false;
List<ValidationLink> links = defaultLinkValidationService.validateDocumentsLinks(
displayOnlyBrokenLinks,
docId,
docId);
assertNotNull(links);
assertEquals(2, links.size());
ValidationLink link = links.get(0);
assertTrue(link.isHostFound());
assertTrue(link.isHostReachable());
assertTrue(link.isPageFound());
}
@Test
public void validateDocumentLinks_When_LoopHasNotReachableUrlText_Expected_CorrectLinks() {
final int index = 1;
int doc1Id = documentDataInitializer.createData().getId();
final Version version = versionService.create(doc1Id, 1);
final LoopEntryRefJPA loopEntryRef = new LoopEntryRefJPA(1, 1);
final LanguageJPA languageJPA = new LanguageJPA(languageDataInitializer.createData().get(0));
final Image image = imageDataInitializer.createData(index, version);
image.setLinkUrl(getLinkFromText(NOT_REACHABLE_URL_IP));
final ImageDTO imageDTO1 = imageToImageDTO.apply(image);
imageService.saveImage(imageDTO1);
createText(index, languageJPA, version, NOT_FOUND_URL_HTTP_TEXT, loopEntryRef);
imageDataInitializer.generateImage(imageDTO1.getIndex(), languageJPA, version, loopEntryRef);
final boolean displayOnlyBrokenLinks = false;
List<ValidationLink> links = defaultLinkValidationService.validateDocumentsLinks(
displayOnlyBrokenLinks,
doc1Id,
doc1Id);
assertNotNull(links);
assertEquals(2, links.size());
ValidationLink link = links.get(0);
assertTrue(link.isHostFound());
assertFalse(link.isHostReachable());
assertFalse(link.isPageFound());
}
@Test
public void validateDocumentLinks_When_DocumentIdsHaveThisRange_Expected_CorrectSizeAndLinks() {
final int index = 1;
int doc1Id = documentDataInitializer.createData().getId();
int doc2Id = documentDataInitializer.createData().getId();
int doc3Id = documentDataInitializer.createData().getId();
final Version versionDoc1 = versionService.create(doc1Id, 1);
final Version versionDoc2 = versionService.create(doc2Id, 1);
final Version versionDoc3 = versionService.create(doc3Id, 1);
final LanguageJPA languageJPA = new LanguageJPA(languageDataInitializer.createData().get(0));
createText(index, languageJPA, versionDoc1, TEXT_URL);
createText(index, languageJPA, versionDoc2, TEXT_URL);
createText(index, languageJPA, versionDoc3, TEXT_URL);
final boolean displayOnlyBrokenLinks = false;
List<ValidationLink> links = defaultLinkValidationService.validateDocumentsLinks(displayOnlyBrokenLinks,
doc1Id,
doc3Id);
assertNotNull(links);
assertEquals(3, links.size());
ValidationLink link = links.get(0);
assertTrue(link.isHostFound());
assertTrue(link.isHostReachable());
assertTrue(link.isPageFound());
}
@Test
public void validateDocumentLinks_When_DocumentHasTextImageAndLoopWithValidUrl_Expected_CorrectLinks() {
final int index = 1;
int docId = documentDataInitializer.createData().getId();
final Version versionDoc = versionService.create(docId, 1);
final LoopEntryRefJPA loopEntryRef = new LoopEntryRefJPA(1, 1);
final LanguageJPA languageJPA = new LanguageJPA(languageDataInitializer.createData().get(0));
final Image image = imageDataInitializer.createData(index, versionDoc);
image.setLinkUrl((getLinkFromText(TEXT_URL)));
final ImageDTO imageDTO = imageToImageDTO.apply(image);
imageService.saveImage(imageDTO);
createText(index, languageJPA, versionDoc, TEXT_URL, loopEntryRef);
createText(index, languageJPA, versionDoc, NOT_FOUND_URL_HTTP_TEXT);
imageDataInitializer.generateImage(imageDTO.getIndex(), languageJPA, versionDoc, loopEntryRef);
final boolean displayOnlyBrokenLinks = false;
List<ValidationLink> links = defaultLinkValidationService.validateDocumentsLinks(displayOnlyBrokenLinks,
docId,
docId);
assertNotNull(links);
assertEquals(3, links.size());
}
@Test
public void validateDocumentLinks_When_StartIdMoreThanEndId_Expected_EmptyResult() {
final int index = 1;
int doc1Id = documentDataInitializer.createData().getId();
int doc2Id = documentDataInitializer.createData().getId();
final Version versionDoc1 = versionService.create(doc1Id, 1);
final Version versionDoc2 = versionService.create(doc2Id, 1);
assertTrue(doc2Id > doc1Id);
final LanguageJPA languageJPA = new LanguageJPA(languageDataInitializer.createData().get(0));
createText(index, languageJPA, versionDoc1, TEXT_URL);
createText(index, languageJPA, versionDoc2, NOT_FOUND_URL_HTTPS_TEXT);
final boolean displayOnlyBrokenLinks = false;
List<ValidationLink> links = defaultLinkValidationService.validateDocumentsLinks(displayOnlyBrokenLinks,
doc2Id,
doc1Id);
assertNotNull(links);
assertTrue(links.isEmpty());
}
private void createText(int index, LanguageJPA language, Version version, String testText) {
final TextJPA text = new TextJPA();
text.setIndex(index);
text.setLanguage(language);
text.setText(testText);
text.setType(TEXT);
text.setVersion(version);
textRepository.saveAndFlush(text);
}
private void createText(int index, LanguageJPA language, Version version, String testText, LoopEntryRef loopEntryRef) {
final TextJPA text = new TextJPA();
text.setIndex(index);
text.setLanguage(language);
text.setText(testText);
text.setType(TEXT);
text.setVersion(version);
text.setLoopEntryRef(loopEntryRef);
textRepository.saveAndFlush(text);
}
}
|
IMCMS-334 New design to super admin page: link validator tab
- Clean up
|
src/test/java/com/imcode/imcms/domain/service/api/DefaultLinkValidationServiceTest.java
|
IMCMS-334 New design to super admin page: link validator tab - Clean up
|
|
Java
|
agpl-3.0
|
8c72739321fb04bc14b6a5f62a775fd750041b6a
| 0
|
Audiveris/audiveris,Audiveris/audiveris
|
//----------------------------------------------------------------------------//
// //
// S t i c k //
// //
// Copyright (C) Herve Bitteur 2000-2007. All rights reserved. //
// This software is released under the GNU General Public License. //
// Contact author at herve.bitteur@laposte.net to report bugs & suggestions. //
//----------------------------------------------------------------------------//
//
package omr.stick;
import omr.glyph.Glyph;
import omr.glyph.GlyphSection;
import omr.lag.Lag;
import omr.lag.Run;
import omr.lag.SectionView;
import omr.math.BasicLine;
import omr.math.Line;
import omr.score.common.PixelPoint;
import omr.ui.view.Zoom;
import omr.util.Logger;
import java.awt.*;
import java.util.Collection;
import java.util.List;
import javax.xml.bind.annotation.*;
/**
* Class <code>Stick</code> describes a stick, a special kind of glyph, either
* horizontal or vertical, as an aggregation of sections. Besides usual
* positions and coordinates, a stick exhibits its approximating Line which is
* the least-square fitted line on all points contained in the stick.
*
* <ul> <li> Staff lines, ledgers, alternate ends are examples of horizontal
* sticks </li>
*
* <li> Bar lines, stems are examples of vertical sticks </li> </ul>
*
* @author Hervé Bitteur
* @version $Id$
*/
@XmlAccessorType(XmlAccessType.NONE)
@XmlRootElement(name = "stick")
public class Stick
extends Glyph
{
//~ Static fields/initializers ---------------------------------------------
/** Usual logger utility */
private static final Logger logger = Logger.getLogger(Stick.class);
//~ Instance fields --------------------------------------------------------
/** Best line equation */
private Line line;
//~ Constructors -----------------------------------------------------------
//-------//
// Stick //
//-------//
/**
* Create a stick with the related interline value
* @param interline the very important scaling information
*/
public Stick (int interline)
{
super(interline);
}
//-------//
// Stick //
//-------//
/**
* No-arg constructor to please JAXB
*/
private Stick ()
{
}
//~ Methods ----------------------------------------------------------------
//------------------//
// getAlienPixelsIn //
//------------------//
/**
* Report the number of pixels found in the specified rectangle that do not
* belong to the stick.
*
* @param area the rectangular area to investigate, in (coord, pos) form of
* course!
*
* @return the number of alien pixels found
*/
public int getAlienPixelsIn (Rectangle area)
{
int count = 0;
final int posMin = area.y;
final int posMax = (area.y + area.height) - 1;
final List<GlyphSection> neighbors = lag.getSectionsIn(area);
for (GlyphSection section : neighbors) {
// Keep only sections that are not part of the stick
if (section.getGlyph() != this) {
int pos = section.getFirstPos() - 1; // Ordinate for horizontal,
// Abscissa for vertical
for (Run run : section.getRuns()) {
pos++;
if (pos > posMax) {
break;
}
if (pos < posMin) {
continue;
}
int stop = run.getStop();
int coordMin = Math.max(area.x, run.getStart());
int coordMax = Math.min(
(area.x + area.width) - 1,
run.getStop());
if (coordMax >= coordMin) {
count += (coordMax - coordMin + 1);
}
}
}
}
if (logger.isFineEnabled()) {
logger.fine(
"Stick" + getId() + " " + area + " getAlienPixelsIn=" + count);
}
return count;
}
//------------------//
// getAliensAtStart //
//------------------//
/**
* Count alien pixels in the following rectangle...
* <pre>
* +-------+
* | |
* +=======+==================================+
* | |
* +-------+
* </pre>
*
* @param dCoord rectangle size along stick length
* @param dPos retangle size along stick thickness
*
* @return the number of alien pixels found
*/
public int getAliensAtStart (int dCoord,
int dPos)
{
return getAlienPixelsIn(
new Rectangle(
getStart(),
getStartingPos() - dPos,
dCoord,
2 * dPos));
}
//-----------------------//
// getAliensAtStartFirst //
//-----------------------//
/**
* Count alien pixels in the following rectangle...
* <pre>
* +-------+
* | |
* +=======+==================================+
* </pre>
*
* @param dCoord rectangle size along stick length
* @param dPos retangle size along stick thickness
*
* @return the number of alien pixels found
*/
public int getAliensAtStartFirst (int dCoord,
int dPos)
{
return getAlienPixelsIn(
new Rectangle(getStart(), getStartingPos() - dPos, dCoord, dPos));
}
//----------------------//
// getAliensAtStartLast //
//----------------------//
/**
* Count alien pixels in the following rectangle...
* <pre>
* +=======+==================================+
* | |
* +-------+
* </pre>
*
* @param dCoord rectangle size along stick length
* @param dPos retangle size along stick thickness
*
* @return the number of alien pixels found
*/
public int getAliensAtStartLast (int dCoord,
int dPos)
{
return getAlienPixelsIn(
new Rectangle(getStart(), getStartingPos(), dCoord, dPos));
}
//-----------------//
// getAliensAtStop //
//-----------------//
/**
* Count alien pixels in the following rectangle...
* <pre>
* +-------+
* | |
* +==================================+=======+
* | |
* +-------+
* </pre>
*
* @param dCoord rectangle size along stick length
* @param dPos retangle size along stick thickness
*
* @return the number of alien pixels found
*/
public int getAliensAtStop (int dCoord,
int dPos)
{
return getAlienPixelsIn(
new Rectangle(
getStop() - dCoord,
getStoppingPos() - dPos,
dCoord,
2 * dPos));
}
//----------------------//
// getAliensAtStopFirst //
//----------------------//
/**
* Count alien pixels in the following rectangle...
* <pre>
* +-------+
* | |
* +==================================+=======+
* </pre>
*
* @param dCoord rectangle size along stick length
* @param dPos retangle size along stick thickness
*
* @return the number of alien pixels found
*/
public int getAliensAtStopFirst (int dCoord,
int dPos)
{
return getAlienPixelsIn(
new Rectangle(
getStop() - dCoord,
getStoppingPos() - dPos,
dCoord,
dPos));
}
//---------------------//
// getAliensAtStopLast //
//---------------------//
/**
* Count alien pixels in the following rectangle...
* <pre>
* +==================================+=======+
* | |
* +-------+
* </pre>
*
* @param dCoord rectangle size along stick length
* @param dPos retangle size along stick thickness
*
* @return the number of alien pixels found
*/
public int getAliensAtStopLast (int dCoord,
int dPos)
{
return getAlienPixelsIn(
new Rectangle(getStop() - dCoord, getStoppingPos(), dCoord, dPos));
}
//-----------//
// getAspect //
//-----------//
/**
* Report the ratio of length over thickness
*
* @return the "slimness" of the stick
*/
public double getAspect ()
{
return (double) getLength() / (double) getThickness();
}
//------------//
// getDensity //
//------------//
/**
* Report the density of the stick, that is its weight divided by the area
* of its bounding rectangle
*
* @return the density
*/
public double getDensity ()
{
Rectangle rect = getBounds();
int surface = (rect.width + 1) * (rect.height + 1);
return (double) getWeight() / (double) surface;
}
//---------------//
// isExtensionOf //
//---------------//
/**
* Checks whether a provided stick can be considered as an extension of this
* one. Due to some missing points, a long stick can be broken into several
* smaller ones, that we must check for this. This is checked before
* actually merging them.
*
* @param other the other stick
* @param maxDeltaCoord Max gap in coordinate (x for horizontal)
* @param maxDeltaPos Max gap in position (y for horizontal)
* @param maxDeltaSlope Max difference in slope
*
* @return The result of the test
*/
public boolean isExtensionOf (Stick other,
int maxDeltaCoord,
int maxDeltaPos,
double maxDeltaSlope)
{
// Check that a pair of start/stop is compatible
if ((Math.abs(other.getStart() - getStop()) <= maxDeltaCoord) ||
(Math.abs(other.getStop() - getStart()) <= maxDeltaCoord)) {
// Check that a pair of positions is compatible
if ((Math.abs(
other.getLine().yAt(other.getStart()) -
getLine().yAt(other.getStop())) <= maxDeltaPos) ||
(Math.abs(
other.getLine().yAt(other.getStop()) -
getLine().yAt(other.getStart())) <= maxDeltaPos)) {
// Check that slopes are compatible (a useless test ?)
if (Math.abs(other.getLine().getSlope() - getLine().getSlope()) <= maxDeltaSlope) {
return true;
} else if (logger.isFineEnabled()) {
logger.fine("isExtensionOf: Incompatible slopes");
}
} else if (logger.isFineEnabled()) {
logger.fine("isExtensionOf: Incompatible positions");
}
} else if (logger.isFineEnabled()) {
logger.fine("isExtensionOf: Incompatible coordinates");
}
return false;
}
//-------------//
// getFirstPos //
//-------------//
/**
* Return the first position (ordinate for stick of horizontal sections,
* abscissa for stick of vertical sections and runs)
*
* @return the position at the beginning
*/
public int getFirstPos ()
{
return getBounds().y;
}
//---------------//
// getFirstStuck //
//---------------//
/**
* Compute the number of pixels stuck on first side of the stick
*
* @return the number of pixels
*/
public int getFirstStuck ()
{
int stuck = 0;
for (GlyphSection section : getMembers()) {
Run sectionRun = section.getFirstRun();
for (GlyphSection sct : section.getSources()) {
if (!sct.isGlyphMember() || (sct.getGlyph() != this)) {
stuck += sectionRun.getCommonLength(sct.getLastRun());
}
}
}
return stuck;
}
//------------//
// getLastPos //
//------------//
/**
* Return the last position (maximum ordinate for a horizontal stick,
* maximum abscissa for a vertical stick)
*
* @return the position at the end
*/
public int getLastPos ()
{
return (getFirstPos() + getThickness()) - 1;
}
//--------------//
// getLastStuck //
//--------------//
/**
* Compute the nb of pixels stuck on last side of the stick
*
* @return the number of pixels
*/
public int getLastStuck ()
{
int stuck = 0;
for (GlyphSection section : getMembers()) {
Run sectionRun = section.getLastRun();
for (GlyphSection sct : section.getTargets()) {
if (!sct.isGlyphMember() || (sct.getGlyph() != this)) {
stuck += sectionRun.getCommonLength(sct.getFirstRun());
}
}
}
return stuck;
}
//-----------//
// getLength //
//-----------//
/**
* Report the length of the stick
*
* @return the stick length in pixels
*/
public int getLength ()
{
return getBounds().width;
}
//---------//
// getLine //
//---------//
/**
* Return the approximating line computed on the stick.
*
* @return The line
*/
public Line getLine ()
{
if (line == null) {
computeLine();
}
return line;
}
//-----------//
// getMidPos //
//-----------//
/**
* Return the position (ordinate for horizontal stick, abscissa for vertical
* stick) at the middle of the stick
*
* @return the position of the middle of the stick
*/
public int getMidPos ()
{
if (getLine()
.isVertical()) {
// Fall back value
return (int) Math.rint((getFirstPos() + getLastPos()) / 2.0);
} else {
return (int) Math.rint(
getLine().yAt((getStart() + getStop()) / 2.0));
}
}
//----------//
// getStart //
//----------//
/**
* Return the beginning of the stick (xmin for horizontal, ymin for
* vertical)
*
* @return The starting coordinate
*/
public int getStart ()
{
return getBounds().x;
}
//---------------//
// getStartPoint //
//---------------//
/**
* Report the point at the beginning of the approximating line
* @return the starting point of the stick line
*/
public PixelPoint getStartPoint ()
{
Point start = lag.switchRef(
new Point(getStart(), line.yAt(getStart())),
null);
return new PixelPoint(start.x, start.y);
}
//----------------//
// getStartingPos //
//----------------//
/**
* Return the best pos value at starting of the stick
*
* @return mean pos value at stick start
*/
public int getStartingPos ()
{
if ((getThickness() >= 2) && !getLine()
.isVertical()) {
return getLine()
.yAt(getStart());
} else {
return getFirstPos() + (getThickness() / 2);
}
}
//---------//
// getStop //
//---------//
/**
* Return the end of the stick (xmax for horizontal, ymax for vertical)
*
* @return The ending coordinate
*/
public int getStop ()
{
return (getStart() + getLength()) - 1;
}
//--------------//
// getStopPoint //
//--------------//
/**
* Report the point at the end of the approximating line
* @return the ending point of the line
*/
public PixelPoint getStopPoint ()
{
Point stop = lag.switchRef(
new Point(getStop(), line.yAt(getStop())),
null);
return new PixelPoint(stop.x, stop.y);
}
//----------------//
// getStoppingPos //
//----------------//
/**
* Return the best pos value at the stopping end of the stick
*
* @return mean pos value at stick stop
*/
public int getStoppingPos ()
{
if ((getThickness() >= 2) && !getLine()
.isVertical()) {
return getLine()
.yAt(getStop());
} else {
return getFirstPos() + (getThickness() / 2);
}
}
//--------------//
// getThickness //
//--------------//
/**
* Report the stick thickness
*
* @return the thickness in pixels
*/
public int getThickness ()
{
return getBounds().height;
}
//------------------//
// addGlyphSections //
//------------------//
/**
* Add another glyph (with its sections of points) to this one
*
* @param other The merged glyph
* @param linkSections Should we set the link from sections to glyph ?
*/
@Override
public void addGlyphSections (Glyph other,
boolean linkSections)
{
super.addGlyphSections(other, linkSections);
line = null;
}
//------------//
// addSection //
//------------//
/**
* Add a section as a member of this stick.
*
* @param section The section to be included
* @param link should the section point back to this stick?
*/
public void addSection (StickSection section,
boolean link)
{
super.addSection(section, /* link => */
true);
// Include the section points
getLine()
.includeLine(section.getLine());
}
//----------//
// colorize //
//----------//
/**
* Set the display color of all sections that compose this stick.
*
* @param lag the containing lag
* @param viewIndex index in the view list
* @param color color for the whole stick
*/
public void colorize (Lag lag,
int viewIndex,
Color color)
{
if (lag == this.lag) {
colorize(viewIndex, getMembers(), color);
}
}
//----------//
// colorize //
//----------//
/**
* Set the display color of all sections gathered by the provided list
*
* @param viewIndex the proper view index
* @param sections the collection of sections
* @param color the display color
*/
public void colorize (int viewIndex,
Collection<GlyphSection> sections,
Color color)
{
for (GlyphSection section : sections) {
SectionView view = (SectionView) section.getView(viewIndex);
view.setColor(color);
}
}
// //------------------//
// // computeDensities //
// //------------------//
// /**
// * Computes the densities around the stick mean line
// */
// public void computeDensities (int nWidth,
// int nHeight)
// {
// final int maxDist = 20; // TBD of course
//
// // Allocate and initialize density histograms
// int[] histoLeft = new int[maxDist];
// int[] histoRight = new int[maxDist];
//
// for (int i = maxDist - 1; i >= 0; i--) {
// histoLeft[i] = 0;
// histoRight[i] = 0;
// }
//
// // Compute (horizontal) distances
// Line line = getLine();
//
// for (GlyphSection section : getMembers()) {
// int pos = section.getFirstPos(); // Abscissa for vertical
//
// for (Run run : section.getRuns()) {
// int stop = run.getStop();
//
// for (int coord = run.getStart(); coord <= stop; coord++) {
// int dist = (int) Math.rint(line.distanceOf(coord, pos));
//
// if ((dist < 0) && (dist > -maxDist)) {
// histoRight[-dist] += 1;
// }
//
// if ((dist >= 0) && (dist < maxDist)) {
// histoLeft[dist] += 1;
// }
// }
//
// pos++;
// }
// }
//
// System.out.println("computeDensities for Stick #" + id);
//
// int length = getLength();
// boolean started = false;
// boolean stopped = false;
//
// for (int i = maxDist - 1; i >= 0; i--) {
// if (histoLeft[i] != 0) {
// started = true;
// }
//
// if (started) {
// System.out.println(i + " : " + ((histoLeft[i] * 100) / length));
// }
// }
//
// for (int i = -1; i > -maxDist; i--) {
// if (histoRight[-i] == 0) {
// stopped = true;
// }
//
// if (!stopped) {
// System.out.println(
// i + " : " + ((histoRight[-i] * 100) / length));
// }
// }
//
// // Retrieve sections in the neighborhood
// Rectangle neighborhood = new Rectangle(getBounds());
// neighborhood.grow(nWidth, nHeight);
//
// List<GlyphSection> neighbors = lag.getSectionsIn(neighborhood);
//
// for (GlyphSection section : neighbors) {
// // Keep only sections that are not part of the stick
// if (section.getGlyph() != this) {
// System.out.println(section.toString());
// }
// }
// }
//-------------//
// computeLine //
//-------------//
/**
* Computes the least-square fitted line among all the section points of the
* stick.
*/
public void computeLine ()
{
line = new BasicLine();
for (GlyphSection section : getMembers()) {
StickSection ss = (StickSection) section;
line.includeLine(ss.getLine());
}
if (logger.isFineEnabled()) {
logger.fine(
line + " pointNb=" + line.getNumberOfPoints() +
" meanDistance=" + (float) line.getMeanDistance());
}
}
//------//
// dump //
//------//
/**
* Print out glyph internal data
*/
@Override
public void dump ()
{
super.dump();
System.out.println(" line=" + getLine());
}
//------//
// dump //
//------//
/**
* Dump the stick as well as its contained sections is so desired
*
* @param withContent Flag to specify the dump of contained sections
*/
public void dump (boolean withContent)
{
if (withContent) {
System.out.println();
}
StringBuilder sb = new StringBuilder(toString());
if (line != null) {
sb.append(" pointNb=")
.append(line.getNumberOfPoints());
}
sb.append(" start=")
.append(getStart());
sb.append(" stop=")
.append(getStop());
sb.append(" midPos=")
.append(getMidPos());
System.out.println(sb);
if (withContent) {
System.out.println("-members:" + getMembers().size());
for (GlyphSection sct : getMembers()) {
System.out.println(" " + sct.toString());
}
}
}
//-------------//
// overlapWith //
//-------------//
/**
* Check whether this stick overlaps with the other stick along their
* orientation (that is abscissae for horizontal ones, and ordinates for
* vertical ones)
* @param other the other stick to check with
* @return true if overlap, false otherwise
*/
public boolean overlapWith (Stick other)
{
return Math.max(getStart(), other.getStart()) < Math.min(
getStop(),
other.getStop());
}
//------------//
// renderLine //
//------------//
/**
* Render the main guiding line of the stick, using the current foreground
* color.
*
* @param g the graphic context
* @param z the display zoom
*/
public void renderLine (Graphics g,
Zoom z)
{
Rectangle box = z.scaled(getContourBox());
if (box.intersects(g.getClipBounds())) {
Line line = getLine();
Point start = lag.switchRef(
new Point(
z.scaled(getStart()),
z.scaled(line.yAt((double) getStart()) + 0.5)),
null);
Point stop = lag.switchRef(
new Point(
z.scaled(getStop() + 1),
z.scaled(line.yAt((double) getStop() + 1) + 0.5)),
null);
g.drawLine(start.x, start.y, stop.x, stop.y);
}
}
//----------//
// toString //
//----------//
/**
* A readable image of the Stick
*
* @return The image string
*/
@Override
public String toString ()
{
StringBuffer sb = new StringBuffer(256);
sb.append(super.toString());
if (getResult() != null) {
sb.append(" ")
.append(getResult());
}
if (getMembers()
.size() > 0) {
sb.append(" th=")
.append(getThickness());
sb.append(" lg=")
.append(getLength());
sb.append(" l/t=")
.append(String.format("%.2f", getAspect()));
sb.append(" fa=")
.append((100 * getFirstStuck()) / getLength())
.append("%");
sb.append(" la=")
.append((100 * getLastStuck()) / getLength())
.append("%");
}
if ((line != null) && (line.getNumberOfPoints() > 1)) {
try {
sb.append(" start[");
PixelPoint start = getStartPoint();
sb.append(start.x)
.append(",")
.append(start.y);
} catch (Exception ignored) {
sb.append("INVALID");
} finally {
sb.append("]");
}
try {
sb.append(" stop[");
PixelPoint stop = getStopPoint();
sb.append(stop.x)
.append(",")
.append(stop.y);
} catch (Exception ignored) {
sb.append("INVALID");
} finally {
sb.append("]");
}
}
if (this.getClass()
.getName()
.equals(Stick.class.getName())) {
sb.append("}");
}
return sb.toString();
}
//-----------//
// getPrefix //
//-----------//
/**
* Return a distinctive string, to be used as a prefix in toString() for
* example.
*
* @return the prefix string
*/
@Override
protected String getPrefix ()
{
return "Stick";
}
}
|
src/main/omr/stick/Stick.java
|
//----------------------------------------------------------------------------//
// //
// S t i c k //
// //
// Copyright (C) Herve Bitteur 2000-2007. All rights reserved. //
// This software is released under the GNU General Public License. //
// Contact author at herve.bitteur@laposte.net to report bugs & suggestions. //
//----------------------------------------------------------------------------//
//
package omr.stick;
import omr.glyph.Glyph;
import omr.glyph.GlyphSection;
import omr.lag.Lag;
import omr.lag.Run;
import omr.lag.SectionView;
import omr.math.BasicLine;
import omr.math.Line;
import omr.score.common.PixelPoint;
import omr.ui.view.Zoom;
import omr.util.Logger;
import java.awt.*;
import java.util.Collection;
import java.util.List;
import javax.xml.bind.annotation.*;
/**
* Class <code>Stick</code> describes a stick, a special kind of glyph, either
* horizontal or vertical, as an aggregation of sections. Besides usual
* positions and coordinates, a stick exhibits its approximating Line which is
* the least-square fitted line on all points contained in the stick.
*
* <ul> <li> Staff lines, ledgers, alternate ends are examples of horizontal
* sticks </li>
*
* <li> Bar lines, stems are examples of vertical sticks </li> </ul>
*
* @author Hervé Bitteur
* @version $Id$
*/
@XmlAccessorType(XmlAccessType.NONE)
@XmlRootElement(name = "stick")
public class Stick
extends Glyph
{
//~ Static fields/initializers ---------------------------------------------
/** Usual logger utility */
private static final Logger logger = Logger.getLogger(Stick.class);
//~ Instance fields --------------------------------------------------------
/** Best line equation */
private Line line;
//~ Constructors -----------------------------------------------------------
//-------//
// Stick //
//-------//
/**
* Create a stick with the related interline value
* @param interline the very important scaling information
*/
public Stick (int interline)
{
super(interline);
}
//-------//
// Stick //
//-------//
/**
* No-arg constructor to please JAXB
*/
private Stick ()
{
}
//~ Methods ----------------------------------------------------------------
//------------------//
// getAlienPixelsIn //
//------------------//
/**
* Report the number of pixels found in the specified rectangle that do not
* belong to the stick.
*
* @param area the rectangular area to investigate, in (coord, pos) form of
* course!
*
* @return the number of alien pixels found
*/
public int getAlienPixelsIn (Rectangle area)
{
int count = 0;
final int posMin = area.y;
final int posMax = (area.y + area.height) - 1;
final List<GlyphSection> neighbors = lag.getSectionsIn(area);
for (GlyphSection section : neighbors) {
// Keep only sections that are not part of the stick
if (section.getGlyph() != this) {
int pos = section.getFirstPos() - 1; // Ordinate for horizontal,
// Abscissa for vertical
for (Run run : section.getRuns()) {
pos++;
if (pos > posMax) {
break;
}
if (pos < posMin) {
continue;
}
int stop = run.getStop();
int coordMin = Math.max(area.x, run.getStart());
int coordMax = Math.min(
(area.x + area.width) - 1,
run.getStop());
if (coordMax >= coordMin) {
count += (coordMax - coordMin + 1);
}
}
}
}
if (logger.isFineEnabled()) {
logger.fine(
"Stick" + getId() + " " + area + " getAlienPixelsIn=" + count);
}
return count;
}
//------------------//
// getAliensAtStart //
//------------------//
/**
* Count alien pixels in the following rectangle...
* <pre>
* +-------+
* | |
* +=======+==================================+
* | |
* +-------+
* </pre>
*
* @param dCoord rectangle size along stick length
* @param dPos retangle size along stick thickness
*
* @return the number of alien pixels found
*/
public int getAliensAtStart (int dCoord,
int dPos)
{
return getAlienPixelsIn(
new Rectangle(
getStart(),
getStartingPos() - dPos,
dCoord,
2 * dPos));
}
//-----------------------//
// getAliensAtStartFirst //
//-----------------------//
/**
* Count alien pixels in the following rectangle...
* <pre>
* +-------+
* | |
* +=======+==================================+
* </pre>
*
* @param dCoord rectangle size along stick length
* @param dPos retangle size along stick thickness
*
* @return the number of alien pixels found
*/
public int getAliensAtStartFirst (int dCoord,
int dPos)
{
return getAlienPixelsIn(
new Rectangle(getStart(), getStartingPos() - dPos, dCoord, dPos));
}
//----------------------//
// getAliensAtStartLast //
//----------------------//
/**
* Count alien pixels in the following rectangle...
* <pre>
* +=======+==================================+
* | |
* +-------+
* </pre>
*
* @param dCoord rectangle size along stick length
* @param dPos retangle size along stick thickness
*
* @return the number of alien pixels found
*/
public int getAliensAtStartLast (int dCoord,
int dPos)
{
return getAlienPixelsIn(
new Rectangle(getStart(), getStartingPos(), dCoord, dPos));
}
//-----------------//
// getAliensAtStop //
//-----------------//
/**
* Count alien pixels in the following rectangle...
* <pre>
* +-------+
* | |
* +==================================+=======+
* | |
* +-------+
* </pre>
*
* @param dCoord rectangle size along stick length
* @param dPos retangle size along stick thickness
*
* @return the number of alien pixels found
*/
public int getAliensAtStop (int dCoord,
int dPos)
{
return getAlienPixelsIn(
new Rectangle(
getStop() - dCoord,
getStoppingPos() - dPos,
dCoord,
2 * dPos));
}
//----------------------//
// getAliensAtStopFirst //
//----------------------//
/**
* Count alien pixels in the following rectangle...
* <pre>
* +-------+
* | |
* +==================================+=======+
* </pre>
*
* @param dCoord rectangle size along stick length
* @param dPos retangle size along stick thickness
*
* @return the number of alien pixels found
*/
public int getAliensAtStopFirst (int dCoord,
int dPos)
{
return getAlienPixelsIn(
new Rectangle(
getStop() - dCoord,
getStoppingPos() - dPos,
dCoord,
dPos));
}
//---------------------//
// getAliensAtStopLast //
//---------------------//
/**
* Count alien pixels in the following rectangle...
* <pre>
* +==================================+=======+
* | |
* +-------+
* </pre>
*
* @param dCoord rectangle size along stick length
* @param dPos retangle size along stick thickness
*
* @return the number of alien pixels found
*/
public int getAliensAtStopLast (int dCoord,
int dPos)
{
return getAlienPixelsIn(
new Rectangle(getStop() - dCoord, getStoppingPos(), dCoord, dPos));
}
//-----------//
// getAspect //
//-----------//
/**
* Report the ratio of length over thickness
*
* @return the "slimness" of the stick
*/
public double getAspect ()
{
return (double) getLength() / (double) getThickness();
}
//------------//
// getDensity //
//------------//
/**
* Report the density of the stick, that is its weight divided by the area
* of its bounding rectangle
*
* @return the density
*/
public double getDensity ()
{
Rectangle rect = getBounds();
int surface = (rect.width + 1) * (rect.height + 1);
return (double) getWeight() / (double) surface;
}
//---------------//
// isExtensionOf //
//---------------//
/**
* Checks whether a provided stick can be considered as an extension of this
* one. Due to some missing points, a long stick can be broken into several
* smaller ones, that we must check for this. This is checked before
* actually merging them.
*
* @param other the other stick
* @param maxDeltaCoord Max gap in coordinate (x for horizontal)
* @param maxDeltaPos Max gap in position (y for horizontal)
* @param maxDeltaSlope Max difference in slope
*
* @return The result of the test
*/
public boolean isExtensionOf (Stick other,
int maxDeltaCoord,
int maxDeltaPos,
double maxDeltaSlope)
{
// Check that a pair of start/stop is compatible
if ((Math.abs(other.getStart() - getStop()) <= maxDeltaCoord) ||
(Math.abs(other.getStop() - getStart()) <= maxDeltaCoord)) {
// Check that a pair of positions is compatible
if ((Math.abs(
other.getLine().yAt(other.getStart()) -
getLine().yAt(other.getStop())) <= maxDeltaPos) ||
(Math.abs(
other.getLine().yAt(other.getStop()) -
getLine().yAt(other.getStart())) <= maxDeltaPos)) {
// Check that slopes are compatible (a useless test ?)
if (Math.abs(other.getLine().getSlope() - getLine().getSlope()) <= maxDeltaSlope) {
return true;
} else if (logger.isFineEnabled()) {
logger.fine("isExtensionOf: Incompatible slopes");
}
} else if (logger.isFineEnabled()) {
logger.fine("isExtensionOf: Incompatible positions");
}
} else if (logger.isFineEnabled()) {
logger.fine("isExtensionOf: Incompatible coordinates");
}
return false;
}
//-------------//
// getFirstPos //
//-------------//
/**
* Return the first position (ordinate for stick of horizontal sections,
* abscissa for stick of vertical sections and runs)
*
* @return the position at the beginning
*/
public int getFirstPos ()
{
return getBounds().y;
}
//---------------//
// getFirstStuck //
//---------------//
/**
* Compute the number of pixels stuck on first side of the stick
*
* @return the number of pixels
*/
public int getFirstStuck ()
{
int stuck = 0;
for (GlyphSection section : getMembers()) {
Run sectionRun = section.getFirstRun();
for (GlyphSection sct : section.getSources()) {
if (!sct.isGlyphMember() || (sct.getGlyph() != this)) {
stuck += sectionRun.getCommonLength(sct.getLastRun());
}
}
}
return stuck;
}
//------------//
// getLastPos //
//------------//
/**
* Return the last position (maximum ordinate for a horizontal stick,
* maximum abscissa for a vertical stick)
*
* @return the position at the end
*/
public int getLastPos ()
{
return (getFirstPos() + getThickness()) - 1;
}
//--------------//
// getLastStuck //
//--------------//
/**
* Compute the nb of pixels stuck on last side of the stick
*
* @return the number of pixels
*/
public int getLastStuck ()
{
int stuck = 0;
for (GlyphSection section : getMembers()) {
Run sectionRun = section.getLastRun();
for (GlyphSection sct : section.getTargets()) {
if (!sct.isGlyphMember() || (sct.getGlyph() != this)) {
stuck += sectionRun.getCommonLength(sct.getFirstRun());
}
}
}
return stuck;
}
//-----------//
// getLength //
//-----------//
/**
* Report the length of the stick
*
* @return the stick length in pixels
*/
public int getLength ()
{
return getBounds().width;
}
//---------//
// getLine //
//---------//
/**
* Return the approximating line computed on the stick.
*
* @return The line
*/
public Line getLine ()
{
if (line == null) {
computeLine();
}
return line;
}
//-----------//
// getMidPos //
//-----------//
/**
* Return the position (ordinate for horizontal stick, abscissa for vertical
* stick) at the middle of the stick
*
* @return the position of the middle of the stick
*/
public int getMidPos ()
{
if (getLine()
.isVertical()) {
// Fall back value
return (int) Math.rint((getFirstPos() + getLastPos()) / 2.0);
} else {
return (int) Math.rint(
getLine().yAt((getStart() + getStop()) / 2.0));
}
}
//----------//
// getStart //
//----------//
/**
* Return the beginning of the stick (xmin for horizontal, ymin for
* vertical)
*
* @return The starting coordinate
*/
public int getStart ()
{
return getBounds().x;
}
//---------------//
// getStartPoint //
//---------------//
/**
* Report the point at the beginning of the approximating line
* @return the starting point of the stick line
*/
public PixelPoint getStartPoint ()
{
Point start = lag.switchRef(
new Point(getStart(), line.yAt(getStart())),
null);
return new PixelPoint(start.x, start.y);
}
//----------------//
// getStartingPos //
//----------------//
/**
* Return the best pos value at starting of the stick
*
* @return mean pos value at stick start
*/
public int getStartingPos ()
{
if ((getThickness() >= 2) && !getLine()
.isVertical()) {
return getLine()
.yAt(getStart());
} else {
return getFirstPos() + (getThickness() / 2);
}
}
//---------//
// getStop //
//---------//
/**
* Return the end of the stick (xmax for horizontal, ymax for vertical)
*
* @return The ending coordinate
*/
public int getStop ()
{
return (getStart() + getLength()) - 1;
}
//--------------//
// getStopPoint //
//--------------//
/**
* Report the point at the end of the approximating line
* @return the ending point of the line
*/
public PixelPoint getStopPoint ()
{
Point stop = lag.switchRef(
new Point(getStop(), line.yAt(getStop())),
null);
return new PixelPoint(stop.x, stop.y);
}
//----------------//
// getStoppingPos //
//----------------//
/**
* Return the best pos value at the stopping end of the stick
*
* @return mean pos value at stick stop
*/
public int getStoppingPos ()
{
if ((getThickness() >= 2) && !getLine()
.isVertical()) {
return getLine()
.yAt(getStop());
} else {
return getFirstPos() + (getThickness() / 2);
}
}
//--------------//
// getThickness //
//--------------//
/**
* Report the stick thickness
*
* @return the thickness in pixels
*/
public int getThickness ()
{
return getBounds().height;
}
//------------------//
// addGlyphSections //
//------------------//
/**
* Add another glyph (with its sections of points) to this one
*
* @param other The merged glyph
* @param linkSections Should we set the link from sections to glyph ?
*/
@Override
public void addGlyphSections (Glyph other,
boolean linkSections)
{
super.addGlyphSections(other, linkSections);
line = null;
}
//------------//
// addSection //
//------------//
/**
* Add a section as a member of this stick.
*
* @param section The section to be included
* @param link should the section point back to this stick?
*/
public void addSection (StickSection section,
boolean link)
{
super.addSection(section, /* link => */
true);
// Include the section points
getLine()
.includeLine(section.getLine());
}
//----------//
// colorize //
//----------//
/**
* Set the display color of all sections that compose this stick.
*
* @param lag the containing lag
* @param viewIndex index in the view list
* @param color color for the whole stick
*/
public void colorize (Lag lag,
int viewIndex,
Color color)
{
if (lag == this.lag) {
colorize(viewIndex, getMembers(), color);
}
}
//----------//
// colorize //
//----------//
/**
* Set the display color of all sections gathered by the provided list
*
* @param viewIndex the proper view index
* @param sections the collection of sections
* @param color the display color
*/
public void colorize (int viewIndex,
Collection<GlyphSection> sections,
Color color)
{
for (GlyphSection section : sections) {
SectionView view = (SectionView) section.getView(viewIndex);
view.setColor(color);
}
}
// //------------------//
// // computeDensities //
// //------------------//
// /**
// * Computes the densities around the stick mean line
// */
// public void computeDensities (int nWidth,
// int nHeight)
// {
// final int maxDist = 20; // TBD of course
//
// // Allocate and initialize density histograms
// int[] histoLeft = new int[maxDist];
// int[] histoRight = new int[maxDist];
//
// for (int i = maxDist - 1; i >= 0; i--) {
// histoLeft[i] = 0;
// histoRight[i] = 0;
// }
//
// // Compute (horizontal) distances
// Line line = getLine();
//
// for (GlyphSection section : getMembers()) {
// int pos = section.getFirstPos(); // Abscissa for vertical
//
// for (Run run : section.getRuns()) {
// int stop = run.getStop();
//
// for (int coord = run.getStart(); coord <= stop; coord++) {
// int dist = (int) Math.rint(line.distanceOf(coord, pos));
//
// if ((dist < 0) && (dist > -maxDist)) {
// histoRight[-dist] += 1;
// }
//
// if ((dist >= 0) && (dist < maxDist)) {
// histoLeft[dist] += 1;
// }
// }
//
// pos++;
// }
// }
//
// System.out.println("computeDensities for Stick #" + id);
//
// int length = getLength();
// boolean started = false;
// boolean stopped = false;
//
// for (int i = maxDist - 1; i >= 0; i--) {
// if (histoLeft[i] != 0) {
// started = true;
// }
//
// if (started) {
// System.out.println(i + " : " + ((histoLeft[i] * 100) / length));
// }
// }
//
// for (int i = -1; i > -maxDist; i--) {
// if (histoRight[-i] == 0) {
// stopped = true;
// }
//
// if (!stopped) {
// System.out.println(
// i + " : " + ((histoRight[-i] * 100) / length));
// }
// }
//
// // Retrieve sections in the neighborhood
// Rectangle neighborhood = new Rectangle(getBounds());
// neighborhood.grow(nWidth, nHeight);
//
// List<GlyphSection> neighbors = lag.getSectionsIn(neighborhood);
//
// for (GlyphSection section : neighbors) {
// // Keep only sections that are not part of the stick
// if (section.getGlyph() != this) {
// System.out.println(section.toString());
// }
// }
// }
//-------------//
// computeLine //
//-------------//
/**
* Computes the least-square fitted line among all the section points of the
* stick.
*/
public void computeLine ()
{
line = new BasicLine();
for (GlyphSection section : getMembers()) {
StickSection ss = (StickSection) section;
line.includeLine(ss.getLine());
}
if (logger.isFineEnabled()) {
logger.fine(
line + " pointNb=" + line.getNumberOfPoints() +
" meanDistance=" + (float) line.getMeanDistance());
}
}
//------//
// dump //
//------//
/**
* Print out glyph internal data
*/
@Override
public void dump ()
{
super.dump();
System.out.println(" line=" + getLine());
}
//------//
// dump //
//------//
/**
* Dump the stick as well as its contained sections is so desired
*
* @param withContent Flag to specify the dump of contained sections
*/
public void dump (boolean withContent)
{
if (withContent) {
System.out.println();
}
StringBuilder sb = new StringBuilder(toString());
if (line != null) {
sb.append(" pointNb=")
.append(line.getNumberOfPoints());
}
sb.append(" start=")
.append(getStart());
sb.append(" stop=")
.append(getStop());
sb.append(" midPos=")
.append(getMidPos());
System.out.println(sb);
if (withContent) {
System.out.println("-members:" + getMembers().size());
for (GlyphSection sct : getMembers()) {
System.out.println(" " + sct.toString());
}
}
}
//-------------//
// overlapWith //
//-------------//
/**
* Check whether this stick overlaps with the other stick along their
* orientation (that is abscissae for horizontal ones, and ordinates for
* vertical ones)
* @param other the other stick to check with
* @return true if overlap, false otherwise
*/
public boolean overlapWith (Stick other)
{
return Math.max(getStart(), other.getStart()) < Math.min(
getStop(),
other.getStop());
}
//-------------//
// renderChunk //
//-------------//
/**
* Render the chunk area at each end of the stick
*
* @param g the graphic context
* @param z the display zoom
*/
public void renderChunk (Graphics g,
Zoom z,
int length,
int thickness)
{
Rectangle box = z.scaled(getContourBox());
if (box.intersects(g.getClipBounds())) {
Line line = getLine();
Rectangle rect = new Rectangle();
Rectangle rect1 = new Rectangle(
z.scaled(getStart()),
z.scaled(line.yAt(getStart()) - thickness),
z.scaled(length),
z.scaled(2 * thickness));
lag.switchRef(rect1, rect);
g.drawRect(rect.x, rect.y, rect.width, rect.height);
Rectangle rect2 = new Rectangle(
z.scaled((getStop() + 1) - length),
z.scaled(line.yAt(getStop() + 1) - thickness),
z.scaled(length),
z.scaled(2 * thickness));
lag.switchRef(rect2, rect);
g.drawRect(rect.x, rect.y, rect.width, rect.height);
}
}
//------------//
// renderLine //
//------------//
/**
* Render the main guiding line of the stick, using the current foreground
* color.
*
* @param g the graphic context
* @param z the display zoom
*/
public void renderLine (Graphics g,
Zoom z)
{
Rectangle box = z.scaled(getContourBox());
if (box.intersects(g.getClipBounds())) {
Line line = getLine();
Point start = lag.switchRef(
new Point(
z.scaled(getStart()),
z.scaled(line.yAt((double) getStart()) + 0.5)),
null);
Point stop = lag.switchRef(
new Point(
z.scaled(getStop() + 1),
z.scaled(line.yAt((double) getStop() + 1) + 0.5)),
null);
g.drawLine(start.x, start.y, stop.x, stop.y);
}
}
//----------//
// toString //
//----------//
/**
* A readable image of the Stick
*
* @return The image string
*/
@Override
public String toString ()
{
StringBuffer sb = new StringBuffer(256);
sb.append(super.toString());
if (getResult() != null) {
sb.append(" ")
.append(getResult());
}
if (getMembers()
.size() > 0) {
sb.append(" th=")
.append(getThickness());
sb.append(" lg=")
.append(getLength());
sb.append(" l/t=")
.append(String.format("%.2f", getAspect()));
sb.append(" fa=")
.append((100 * getFirstStuck()) / getLength())
.append("%");
sb.append(" la=")
.append((100 * getLastStuck()) / getLength())
.append("%");
}
if ((line != null) && (line.getNumberOfPoints() > 1)) {
try {
sb.append(" start[");
PixelPoint start = getStartPoint();
sb.append(start.x)
.append(",")
.append(start.y);
} catch (Exception ignored) {
sb.append("INVALID");
} finally {
sb.append("]");
}
try {
sb.append(" stop[");
PixelPoint stop = getStopPoint();
sb.append(stop.x)
.append(",")
.append(stop.y);
} catch (Exception ignored) {
sb.append("INVALID");
} finally {
sb.append("]");
}
}
if (this.getClass()
.getName()
.equals(Stick.class.getName())) {
sb.append("}");
}
return sb.toString();
}
//-----------//
// getPrefix //
//-----------//
/**
* Return a distinctive string, to be used as a prefix in toString() for
* example.
*
* @return the prefix string
*/
@Override
protected String getPrefix ()
{
return "Stick";
}
}
|
Cleansing
|
src/main/omr/stick/Stick.java
|
Cleansing
|
|
Java
|
agpl-3.0
|
2c353bc85ffaaf596e223c0097e07351fa2ed7a6
| 0
|
tsdl2013/actor-platform,akingyin1987/actor-platform,KitoHo/actor-platform,darioajr/actor-platform,gale320/actor-platform,bunnyblue/actor-platform,chieryw/actor-platform,zomeelee/actor-platform,boneyao/actor-platform,Havi4/actor-platform,chenbk85/actor-platform,KitoHo/actor-platform,Ajunboys/actor-platform,stonegithubs/actor-platform,Rogerlin2013/actor-platform,chengjunjian/actor-platform,webwlsong/actor-platform,Jeremy-Meng/actor-platform,Just-D/actor-platform,dut3062796s/actor-platform,boneyao/actor-platform,alessandrostone/actor-platform,Dreezydraig/actor-platform,it33/actor-platform,way1989/actor-platform,way1989/actor-platform,changjiashuai/actor-platform,fengshao0907/actor-platform,ketoo/actor-platform,WangCrystal/actor-platform,luoxiaoshenghustedu/actor-platform,boyley/actor-platform,darioajr/actor-platform,webwlsong/actor-platform,way1989/actor-platform,greatdinosaur/actor-platform,ketoo/actor-platform,fengshao0907/actor-platform,v2tmobile/actor-platform,taimur97/actor-platform,damoguyan8844/actor-platform,changjiashuai/actor-platform,yangchenghu/actor-platform,EaglesoftZJ/actor-platform,boyley/actor-platform,zwensoft/actor-platform,chengjunjian/actor-platform,shenhzou654321/actor-platform,shaunstanislaus/actor-platform,dut3062796s/actor-platform,fhchina/actor-platform,lstNull/actor-platform,bensonX/actor-platform,fengchenlianlian/actor-platform,bensonX/actor-platform,zomeelee/actor-platform,liqk2014/actor-platform,cnbin/actor-platform,gaolichuang/actor-platform,darioajr/actor-platform,vanloswang/actor-platform,mitchellporter/actor-platform,hardikamal/actor-platform,wangkang0627/actor-platform,way1989/actor-platform,EaglesoftZJ/actor-platform,liruqi/actor-platform,hejunbinlan/actor-platform,boneyao/actor-platform,akingyin1987/actor-platform,cnbin/actor-platform,yangchenghu/actor-platform,ganquan0910/actor-platform,sc4599/actor-platform,ruikong/actor-platform,webwlsong/actor-platform,akingyin1987/actor-platform,mitchellporter/actor-platform,it33/actor-platform,webwlsong/actor-platform,JeeLiu/actor-platform,tsdl2013/actor-platform,webwlsong/actor-platform,EaglesoftZJ/actor-platform,shenhzou654321/actor-platform,sfshine/actor-platform,daodaoliang/actor-platform,y0ke/actor-platform,suxinde2009/actor-platform,VikingDen/actor-platform,cnbin/actor-platform,mitchellporter/actor-platform,Ajunboys/actor-platform,mxw0417/actor-platform,ONode/actor-platform,liruqi/actor-platform-v0.9,ruikong/actor-platform,wangkang0627/actor-platform,webwlsong/actor-platform,Jeremy-Meng/actor-platform,fengchenlianlian/actor-platform,winiceo/actor-platform,chieryw/actor-platform,dut3062796s/actor-platform,wangkang0627/actor-platform,vanloswang/actor-platform,damoguyan8844/actor-platform,lzpfmh/actor-platform,shenhzou654321/actor-platform,sc4599/actor-platform,supertanglang/actor-platform,liuzwei/actor-platform,WangCrystal/actor-platform,voidException/actor-platform,JamesWatling/actor-platform,lstNull/actor-platform,bunnyblue/actor-platform,yangchaogit/actor-platform,jiguoling/actor-platform,luwei2012/actor-platform,akingyin1987/actor-platform,hardikamal/actor-platform,xiaotaijun/actor-platform,lzpfmh/actor-platform,TimurTarasenko/actor-platform,allengaller/actor-platform,KitoHo/actor-platform,berserkertdl/actor-platform,cnbin/actor-platform,zillachan/actor-platform,TimurTarasenko/actor-platform,stonegithubs/actor-platform,sc4599/actor-platform,suxinde2009/actor-platform,x303597316/actor-platform,ruikong/actor-platform,luoxiaoshenghustedu/actor-platform,berserkertdl/actor-platform,KitoHo/actor-platform,allengaller/actor-platform,v2tmobile/actor-platform,bradparks/actor-platform___im_client_cross_platform,guiquanz/actor-platform,fengshao0907/actor-platform,treejames/actor-platform,EaglesoftZJ/actor-platform,greatdinosaur/actor-platform,Jeremy-Meng/actor-platform,ganquan0910/actor-platform,ketoo/actor-platform,bradparks/actor-platform___im_client_cross_platform,hmoraes/actor-platform,daodaoliang/actor-platform,vanloswang/actor-platform,jamesbond12/actor-platform,WangCrystal/actor-platform,mitchellporter/actor-platform,Havi4/actor-platform,gaolichuang/actor-platform,stonegithubs/actor-platform,guiquanz/actor-platform,ONode/actor-platform,JamesWatling/actor-platform,alessandrostone/actor-platform,lzpfmh/actor-platform,yangchenghu/actor-platform,yangchaogit/actor-platform,daodaoliang/actor-platform,hzy87email/actor-platform,JeeLiu/actor-platform,EaglesoftZJ/actor-platform,ruikong/actor-platform,sfshine/actor-platform,winiceo/actor-platform,luoxiaoshenghustedu/actor-platform,chengjunjian/actor-platform,allengaller/actor-platform,daodaoliang/actor-platform,fhchina/actor-platform,fhchina/actor-platform,lzpfmh/actor-platform,supertanglang/actor-platform,darioajr/actor-platform,luoxiaoshenghustedu/actor-platform,supertanglang/actor-platform,webwlsong/actor-platform,chieryw/actor-platform,voidException/actor-platform,fengshao0907/actor-platform,x303597316/actor-platform,mxw0417/actor-platform,Ajunboys/actor-platform,jiguoling/actor-platform,Rogerlin2013/actor-platform,y0ke/actor-platform,zillachan/actor-platform,bunnyblue/actor-platform,wangkang0627/actor-platform,nguyenhongson03/actor-platform,bunnyblue/actor-platform,gale320/actor-platform,changjiashuai/actor-platform,boneyao/actor-platform,it33/actor-platform,treejames/actor-platform,winiceo/actor-platform,fengchenlianlian/actor-platform,darioajr/actor-platform,x303597316/actor-platform,allengaller/actor-platform,yaoliyc/actor-platform,nguyenhongson03/actor-platform,stonegithubs/actor-platform,TimurTarasenko/actor-platform,JamesWatling/actor-platform,treejames/actor-platform,bradparks/actor-platform___im_client_cross_platform,lstNull/actor-platform,Jaeandroid/actor-platform,stonegithubs/actor-platform,daodaoliang/actor-platform,jiguoling/actor-platform,fengchenlianlian/actor-platform,mxw0417/actor-platform,luoxiaoshenghustedu/actor-platform,Just-D/actor-platform,boyley/actor-platform,chieryw/actor-platform,luoxiaoshenghustedu/actor-platform,chenbk85/actor-platform,liuzwei/actor-platform,hmoraes/actor-platform,greatdinosaur/actor-platform,jamesbond12/actor-platform,yaoliyc/actor-platform,liqk2014/actor-platform,y0ke/actor-platform,cnbin/actor-platform,mitchellporter/actor-platform,hzy87email/actor-platform,HKMOpen/actor-platform,Jeremy-Meng/actor-platform,cnbin/actor-platform,boneyao/actor-platform,yangchaogit/actor-platform,VikingDen/actor-platform,chengjunjian/actor-platform,ruikong/actor-platform,damoguyan8844/actor-platform,sfshine/actor-platform,chenbk85/actor-platform,fengchenlianlian/actor-platform,VikingDen/actor-platform,akingyin1987/actor-platform,zomeelee/actor-platform,changjiashuai/actor-platform,changjiashuai/actor-platform,ONode/actor-platform,chieryw/actor-platform,suxinde2009/actor-platform,liruqi/actor-platform,Johnnywang1221/actor-platform,bunnyblue/actor-platform,taimur97/actor-platform,suxinde2009/actor-platform,hzy87email/actor-platform,treejames/actor-platform,Dreezydraig/actor-platform,chengjunjian/actor-platform,guiquanz/actor-platform,daodaoliang/actor-platform,bensonX/actor-platform,hardikamal/actor-platform,liqk2014/actor-platform,suxinde2009/actor-platform,y0ke/actor-platform,liqk2014/actor-platform,KitoHo/actor-platform,jamesbond12/actor-platform,shaunstanislaus/actor-platform,hardikamal/actor-platform,alihalabyah/actor-platform,zomeelee/actor-platform,Jaeandroid/actor-platform,jiguoling/actor-platform,hejunbinlan/actor-platform,boyley/actor-platform,hzy87email/actor-platform,sc4599/actor-platform,alessandrostone/actor-platform,liuzwei/actor-platform,Havi4/actor-platform,JeeLiu/actor-platform,ONode/actor-platform,Jeremy-Meng/actor-platform,x303597316/actor-platform,chengjunjian/actor-platform,HKMOpen/actor-platform,v2tmobile/actor-platform,v2tmobile/actor-platform,hardikamal/actor-platform,Johnnywang1221/actor-platform,taimur97/actor-platform,tsdl2013/actor-platform,Rogerlin2013/actor-platform,it33/actor-platform,bensonX/actor-platform,Havi4/actor-platform,liruqi/actor-platform-v0.9,boyley/actor-platform,liruqi/actor-platform,Jaeandroid/actor-platform,tsdl2013/actor-platform,fhchina/actor-platform,yaoliyc/actor-platform,it33/actor-platform,sfshine/actor-platform,ONode/actor-platform,alihalabyah/actor-platform,zwensoft/actor-platform,Ajunboys/actor-platform,VikingDen/actor-platform,zillachan/actor-platform,sc4599/actor-platform,ruikong/actor-platform,sc4599/actor-platform,xiaotaijun/actor-platform,darioajr/actor-platform,it33/actor-platform,shenhzou654321/actor-platform,gale320/actor-platform,HKMOpen/actor-platform,ONode/actor-platform,y0ke/actor-platform,hmoraes/actor-platform,ganquan0910/actor-platform,alihalabyah/actor-platform,ganquan0910/actor-platform,lzpfmh/actor-platform,HKMOpen/actor-platform,Johnnywang1221/actor-platform,zwensoft/actor-platform,liuzwei/actor-platform,taimur97/actor-platform,fhchina/actor-platform,way1989/actor-platform,zillachan/actor-platform,v2tmobile/actor-platform,amezcua/actor-platform,alessandrostone/actor-platform,hmoraes/actor-platform,JeeLiu/actor-platform,Jaeandroid/actor-platform,lstNull/actor-platform,supertanglang/actor-platform,yangchenghu/actor-platform,lstNull/actor-platform,ONode/actor-platform,greatdinosaur/actor-platform,zomeelee/actor-platform,berserkertdl/actor-platform,Jeremy-Meng/actor-platform,liruqi/actor-platform,EaglesoftZJ/actor-platform,hzy87email/actor-platform,liruqi/actor-platform-v0.9,dut3062796s/actor-platform,x303597316/actor-platform,hejunbinlan/actor-platform,ganquan0910/actor-platform,liruqi/actor-platform-v0.9,Jaeandroid/actor-platform,jiguoling/actor-platform,changjiashuai/actor-platform,voidException/actor-platform,stonegithubs/actor-platform,chieryw/actor-platform,treejames/actor-platform,xiaotaijun/actor-platform,luwei2012/actor-platform,changjiashuai/actor-platform,nguyenhongson03/actor-platform,Dreezydraig/actor-platform,cnbin/actor-platform,zwensoft/actor-platform,gaolichuang/actor-platform,shaunstanislaus/actor-platform,TimurTarasenko/actor-platform,liuzwei/actor-platform,ketoo/actor-platform,HKMOpen/actor-platform,shenhzou654321/actor-platform,nguyenhongson03/actor-platform,mxw0417/actor-platform,JeeLiu/actor-platform,JeeLiu/actor-platform,supertanglang/actor-platform,TimurTarasenko/actor-platform,akingyin1987/actor-platform,treejames/actor-platform,WangCrystal/actor-platform,nguyenhongson03/actor-platform,Just-D/actor-platform,JamesWatling/actor-platform,boyley/actor-platform,bradparks/actor-platform___im_client_cross_platform,x303597316/actor-platform,voidException/actor-platform,Dreezydraig/actor-platform,ketoo/actor-platform,winiceo/actor-platform,amezcua/actor-platform,x303597316/actor-platform,alessandrostone/actor-platform,hejunbinlan/actor-platform,JamesWatling/actor-platform,tsdl2013/actor-platform,tsdl2013/actor-platform,guiquanz/actor-platform,greatdinosaur/actor-platform,sc4599/actor-platform,liruqi/actor-platform,liqk2014/actor-platform,KitoHo/actor-platform,supertanglang/actor-platform,yaoliyc/actor-platform,luwei2012/actor-platform,jamesbond12/actor-platform,v2tmobile/actor-platform,JamesWatling/actor-platform,stonegithubs/actor-platform,jamesbond12/actor-platform,y0ke/actor-platform,vanloswang/actor-platform,liuzwei/actor-platform,berserkertdl/actor-platform,fhchina/actor-platform,Rogerlin2013/actor-platform,taimur97/actor-platform,alihalabyah/actor-platform,way1989/actor-platform,allengaller/actor-platform,luwei2012/actor-platform,mxw0417/actor-platform,bensonX/actor-platform,vanloswang/actor-platform,xiaotaijun/actor-platform,suxinde2009/actor-platform,vanloswang/actor-platform,boneyao/actor-platform,Rogerlin2013/actor-platform,voidException/actor-platform,gaolichuang/actor-platform,ganquan0910/actor-platform,allengaller/actor-platform,luwei2012/actor-platform,jamesbond12/actor-platform,EaglesoftZJ/actor-platform,xiaotaijun/actor-platform,akingyin1987/actor-platform,liuzwei/actor-platform,Just-D/actor-platform,sfshine/actor-platform,bunnyblue/actor-platform,taimur97/actor-platform,hmoraes/actor-platform,wangkang0627/actor-platform,zillachan/actor-platform,luwei2012/actor-platform,amezcua/actor-platform,amezcua/actor-platform,yaoliyc/actor-platform,liqk2014/actor-platform,Johnnywang1221/actor-platform,mxw0417/actor-platform,Ajunboys/actor-platform,boneyao/actor-platform,Jaeandroid/actor-platform,shaunstanislaus/actor-platform,Dreezydraig/actor-platform,chieryw/actor-platform,Just-D/actor-platform,hejunbinlan/actor-platform,Just-D/actor-platform,zillachan/actor-platform,ruikong/actor-platform,KitoHo/actor-platform,voidException/actor-platform,damoguyan8844/actor-platform,bensonX/actor-platform,JeeLiu/actor-platform,hejunbinlan/actor-platform,Ajunboys/actor-platform,hardikamal/actor-platform,darioajr/actor-platform,bradparks/actor-platform___im_client_cross_platform,bunnyblue/actor-platform,yangchenghu/actor-platform,zwensoft/actor-platform,Havi4/actor-platform,winiceo/actor-platform,yaoliyc/actor-platform,Havi4/actor-platform,luoxiaoshenghustedu/actor-platform,EaglesoftZJ/actor-platform,gale320/actor-platform,Dreezydraig/actor-platform,luwei2012/actor-platform,berserkertdl/actor-platform,Johnnywang1221/actor-platform,xiaotaijun/actor-platform,greatdinosaur/actor-platform,amezcua/actor-platform,gale320/actor-platform,wangkang0627/actor-platform,alessandrostone/actor-platform,chengjunjian/actor-platform,hardikamal/actor-platform,Jeremy-Meng/actor-platform,VikingDen/actor-platform,ganquan0910/actor-platform,amezcua/actor-platform,damoguyan8844/actor-platform,gale320/actor-platform,gaolichuang/actor-platform,Just-D/actor-platform,v2tmobile/actor-platform,alihalabyah/actor-platform,nguyenhongson03/actor-platform,alihalabyah/actor-platform,berserkertdl/actor-platform,y0ke/actor-platform,shaunstanislaus/actor-platform,yangchaogit/actor-platform,Rogerlin2013/actor-platform,Johnnywang1221/actor-platform,ketoo/actor-platform,chenbk85/actor-platform,jiguoling/actor-platform,chenbk85/actor-platform,WangCrystal/actor-platform,guiquanz/actor-platform,taimur97/actor-platform,liruqi/actor-platform,nguyenhongson03/actor-platform,winiceo/actor-platform,damoguyan8844/actor-platform,shenhzou654321/actor-platform,yaoliyc/actor-platform,jiguoling/actor-platform,guiquanz/actor-platform,fhchina/actor-platform,wangkang0627/actor-platform,VikingDen/actor-platform,shenhzou654321/actor-platform,Ajunboys/actor-platform,shaunstanislaus/actor-platform,lzpfmh/actor-platform,VikingDen/actor-platform,WangCrystal/actor-platform,supertanglang/actor-platform,liruqi/actor-platform-v0.9,hmoraes/actor-platform,voidException/actor-platform,sfshine/actor-platform,xiaotaijun/actor-platform,HKMOpen/actor-platform,TimurTarasenko/actor-platform,yangchaogit/actor-platform,HKMOpen/actor-platform,chenbk85/actor-platform,lstNull/actor-platform,fengshao0907/actor-platform,liqk2014/actor-platform,Rogerlin2013/actor-platform,gaolichuang/actor-platform,zwensoft/actor-platform,hzy87email/actor-platform,it33/actor-platform,dut3062796s/actor-platform,mitchellporter/actor-platform,yangchenghu/actor-platform,liruqi/actor-platform-v0.9,yangchaogit/actor-platform,treejames/actor-platform,fengchenlianlian/actor-platform,sfshine/actor-platform,zillachan/actor-platform,y0ke/actor-platform,dut3062796s/actor-platform,greatdinosaur/actor-platform,gale320/actor-platform,bradparks/actor-platform___im_client_cross_platform,lstNull/actor-platform,guiquanz/actor-platform,way1989/actor-platform,boyley/actor-platform,zomeelee/actor-platform,fengshao0907/actor-platform,fengchenlianlian/actor-platform
|
package im.actor.messenger.app.fragment.auth;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.MenuItem;
import im.actor.messenger.R;
import im.actor.messenger.app.AppContext;
import im.actor.messenger.app.activity.MainActivity;
import im.actor.messenger.app.base.BaseFragmentActivity;
import im.actor.model.AuthState;
import im.actor.model.concurrency.Command;
import im.actor.model.concurrency.CommandCallback;
import im.actor.model.network.RpcException;
import im.actor.model.network.RpcInternalException;
import im.actor.model.network.RpcTimeoutException;
import static im.actor.messenger.app.Core.messenger;
public class AuthActivity extends BaseFragmentActivity {
private static final int OAUTH_DIALOG = 1;
private ProgressDialog progressDialog;
private AlertDialog alertDialog;
private AuthState state;
private String authType;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
authType = getIntent().getStringExtra("auth_type");
if (savedInstanceState == null) {
updateState();
}
}
@Override
public void onBackPressed() {
messenger().trackBackPressed();
super.onBackPressed();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
messenger().trackUpPressed();
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onResume() {
super.onResume();
if (messenger().getAuthState() == AuthState.LOGGED_IN) {
finish();
}
}
public void updateState() {
updateState(messenger().getAuthState());
}
private void updateState(AuthState state) {
if (this.state != null && this.state == state) {
return;
}
this.state = state;
switch (state) {
case AUTH_START:
if (authType != null && authType.equals("auth_type_email")) {
showFragment(new SignEmailFragment(), false, false);
} else if (authType != null && authType.equals("auth_type_phone")){
showFragment(new SignPhoneFragment(), false, false);
}
break;
case CODE_VALIDATION_PHONE:
case CODE_VALIDATION_EMAIL:
if((state==AuthState.CODE_VALIDATION_EMAIL && authType.equals("auth_type_phone")) || (state==AuthState.CODE_VALIDATION_PHONE && authType.equals("auth_type_email"))){
updateState(AuthState.AUTH_START);
break;
}
Fragment signInFragment = new SignInFragment();
Bundle args = new Bundle();
args.putString("authType", state==AuthState.CODE_VALIDATION_EMAIL?SignInFragment.AUTH_TYPE_EMAIL : SignInFragment.AUTH_TYPE_PHONE);
signInFragment.setArguments(args);
showFragment(signInFragment, false, false);
break;
case GET_OAUTH_PARAMS:
executeAuth(messenger().requestGetOAuthParams(), "get_oauth_params");
break;
case COMPLETE_OAUTH:
if(authType.equals("auth_type_phone")){
updateState(AuthState.AUTH_START);
break;
}
showFragment(new SignEmailFragment(), false, false);
startActivityForResult(new Intent(this, OAuthDialogActivity.class), OAUTH_DIALOG);
break;
case SIGN_UP:
showFragment(new SignUpFragment(), false, false);
break;
case LOGGED_IN:
messenger().trackAuthSuccess();
finish();
startActivity(new Intent(this, MainActivity.class));
break;
}
}
public void executeAuth(final Command<AuthState> command, final String action) {
dismissProgress();
progressDialog = new ProgressDialog(this);
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.setCancelable(false);
progressDialog.setTitle("Loading...");
progressDialog.show();
command.start(new CommandCallback<AuthState>() {
@Override
public void onResult(final AuthState res) {
dismissProgress();
messenger().trackActionSuccess(action);
updateState(res);
}
@Override
public void onError(final Exception e) {
dismissProgress();
boolean canTryAgain = false;
String message = getString(R.string.error_unknown);
String tag = "UNKNOWN";
if (e instanceof RpcException) {
RpcException re = (RpcException) e;
tag = re.getTag();
if (re instanceof RpcInternalException) {
message = getString(R.string.error_unknown);
canTryAgain = true;
} else if (re instanceof RpcTimeoutException) {
message = getString(R.string.error_connection);
canTryAgain = true;
} else {
if ("PHONE_CODE_EXPIRED".equals(re.getTag())) {
message = getString(R.string.auth_error_code_expired);
canTryAgain = false;
} else if ("PHONE_CODE_INVALID".equals(re.getTag())) {
message = getString(R.string.auth_error_code_invalid);
canTryAgain = false;
} else if ("FAILED_GET_OAUTH2_TOKEN".equals(re.getTag())) {
message = getString(R.string.auth_error_failed_get_oauth2_token);
canTryAgain = false;
}else {
message = re.getMessage();
canTryAgain = re.isCanTryAgain();
}
}
}
messenger().trackActionError(action, tag, message);
if (canTryAgain) {
new AlertDialog.Builder(AuthActivity.this)
.setMessage(message)
.setPositiveButton(R.string.dialog_try_again, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
messenger().trackActionTryAgain(action);
dismissAlert();
executeAuth(command, action);
}
})
.setNegativeButton(R.string.dialog_cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
messenger().trackActionCancel(action);
dismissAlert();
updateState(messenger().getAuthState());
}
}).setCancelable(false)
.show()
.setCanceledOnTouchOutside(false);
} else {
new AlertDialog.Builder(AuthActivity.this)
.setMessage(message)
.setPositiveButton(R.string.dialog_ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
messenger().trackActionCancel(action);
dismissAlert();
updateState(messenger().getAuthState());
}
})
.setCancelable(false)
.show()
.setCanceledOnTouchOutside(false);
}
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode){
case OAUTH_DIALOG:
if(resultCode == RESULT_OK && data!=null){
executeAuth(messenger().requestCompleteOAuth(data.getStringExtra("code")), "Sign in");
}
break;
}
}
@Override
protected void onPause() {
super.onPause();
dismissProgress();
dismissAlert();
}
private void dismissProgress() {
if (progressDialog != null) {
progressDialog.dismiss();
progressDialog = null;
}
}
private void dismissAlert() {
if (alertDialog != null) {
alertDialog.dismiss();
alertDialog = null;
}
}
}
|
actor-apps/app-android/src/main/java/im/actor/messenger/app/fragment/auth/AuthActivity.java
|
package im.actor.messenger.app.fragment.auth;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.MenuItem;
import im.actor.messenger.R;
import im.actor.messenger.app.AppContext;
import im.actor.messenger.app.activity.MainActivity;
import im.actor.messenger.app.base.BaseFragmentActivity;
import im.actor.model.AuthState;
import im.actor.model.concurrency.Command;
import im.actor.model.concurrency.CommandCallback;
import im.actor.model.network.RpcException;
import im.actor.model.network.RpcInternalException;
import im.actor.model.network.RpcTimeoutException;
import static im.actor.messenger.app.Core.messenger;
public class AuthActivity extends BaseFragmentActivity {
private static final int OAUTH_DIALOG = 1;
private ProgressDialog progressDialog;
private AlertDialog alertDialog;
private AuthState state;
private String authType;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
authType = getIntent().getStringExtra("auth_type");
if (savedInstanceState == null) {
updateState();
}
}
@Override
public void onBackPressed() {
messenger().trackBackPressed();
super.onBackPressed();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
messenger().trackUpPressed();
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onResume() {
super.onResume();
if (messenger().getAuthState() == AuthState.LOGGED_IN) {
finish();
}
}
public void updateState() {
updateState(messenger().getAuthState());
}
private void updateState(AuthState state) {
if (this.state != null && this.state == state) {
return;
}
this.state = state;
switch (state) {
case AUTH_START:
if (authType != null && authType.equals("auth_type_email")) {
showFragment(new SignEmailFragment(), false, false);
} else if (authType != null && authType.equals("auth_type_phone")){
showFragment(new SignPhoneFragment(), false, false);
}
break;
case CODE_VALIDATION_PHONE:
case CODE_VALIDATION_EMAIL:
if((state==AuthState.CODE_VALIDATION_EMAIL && authType.equals("auth_type_phone") || state==AuthState.CODE_VALIDATION_PHONE && authType.equals("auth_type_email"))){
updateState(AuthState.AUTH_START);
break;
}
Fragment signInFragment = new SignInFragment();
Bundle args = new Bundle();
args.putString("authType", state==AuthState.CODE_VALIDATION_EMAIL?SignInFragment.AUTH_TYPE_EMAIL : SignInFragment.AUTH_TYPE_PHONE);
signInFragment.setArguments(args);
showFragment(signInFragment, false, false);
break;
case GET_OAUTH_PARAMS:
executeAuth(messenger().requestGetOAuthParams(), "get_oauth_params");
break;
case COMPLETE_OAUTH:
if(authType.equals("auth_type_phone")){
updateState(AuthState.AUTH_START);
break;
}
showFragment(new SignEmailFragment(), false, false);
startActivityForResult(new Intent(this, OAuthDialogActivity.class), OAUTH_DIALOG);
break;
case SIGN_UP:
showFragment(new SignUpFragment(), false, false);
break;
case LOGGED_IN:
messenger().trackAuthSuccess();
finish();
startActivity(new Intent(this, MainActivity.class));
break;
}
}
public void executeAuth(final Command<AuthState> command, final String action) {
dismissProgress();
progressDialog = new ProgressDialog(this);
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.setCancelable(false);
progressDialog.setTitle("Loading...");
progressDialog.show();
command.start(new CommandCallback<AuthState>() {
@Override
public void onResult(final AuthState res) {
dismissProgress();
messenger().trackActionSuccess(action);
updateState(res);
}
@Override
public void onError(final Exception e) {
dismissProgress();
boolean canTryAgain = false;
String message = getString(R.string.error_unknown);
String tag = "UNKNOWN";
if (e instanceof RpcException) {
RpcException re = (RpcException) e;
tag = re.getTag();
if (re instanceof RpcInternalException) {
message = getString(R.string.error_unknown);
canTryAgain = true;
} else if (re instanceof RpcTimeoutException) {
message = getString(R.string.error_connection);
canTryAgain = true;
} else {
if ("PHONE_CODE_EXPIRED".equals(re.getTag())) {
message = getString(R.string.auth_error_code_expired);
canTryAgain = false;
} else if ("PHONE_CODE_INVALID".equals(re.getTag())) {
message = getString(R.string.auth_error_code_invalid);
canTryAgain = false;
} else if ("FAILED_GET_OAUTH2_TOKEN".equals(re.getTag())) {
message = getString(R.string.auth_error_failed_get_oauth2_token);
canTryAgain = false;
}else {
message = re.getMessage();
canTryAgain = re.isCanTryAgain();
}
}
}
messenger().trackActionError(action, tag, message);
if (canTryAgain) {
new AlertDialog.Builder(AuthActivity.this)
.setMessage(message)
.setPositiveButton(R.string.dialog_try_again, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
messenger().trackActionTryAgain(action);
dismissAlert();
executeAuth(command, action);
}
})
.setNegativeButton(R.string.dialog_cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
messenger().trackActionCancel(action);
dismissAlert();
updateState(messenger().getAuthState());
}
}).setCancelable(false)
.show()
.setCanceledOnTouchOutside(false);
} else {
new AlertDialog.Builder(AuthActivity.this)
.setMessage(message)
.setPositiveButton(R.string.dialog_ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
messenger().trackActionCancel(action);
dismissAlert();
updateState(messenger().getAuthState());
}
})
.setCancelable(false)
.show()
.setCanceledOnTouchOutside(false);
}
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode){
case OAUTH_DIALOG:
if(resultCode == RESULT_OK && data!=null){
executeAuth(messenger().requestCompleteOAuth(data.getStringExtra("code")), "Sign in");
}
break;
}
}
@Override
protected void onPause() {
super.onPause();
dismissProgress();
dismissAlert();
}
private void dismissProgress() {
if (progressDialog != null) {
progressDialog.dismiss();
progressDialog = null;
}
}
private void dismissAlert() {
if (alertDialog != null) {
alertDialog.dismiss();
alertDialog = null;
}
}
}
|
fix(android): authState flow
|
actor-apps/app-android/src/main/java/im/actor/messenger/app/fragment/auth/AuthActivity.java
|
fix(android): authState flow
|
|
Java
|
agpl-3.0
|
55286c5b20aa017e9fb8d95d7ab6e607d603ec64
| 0
|
StratusLab/claudia,StratusLab/claudia,StratusLab/claudia,StratusLab/claudia
|
/*
* Claudia Project
* http://claudia.morfeo-project.org
*
* (C) Copyright 2010 Telefonica Investigacion y Desarrollo
* S.A.Unipersonal (Telefonica I+D)
*
* See CREDITS file for info about members and contributors.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the Affero GNU General Public License (AGPL) as
* published by the Free Software Foundation; either version 3 of the License,
* or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the Affero GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* If you want to use this software an plan to distribute a
* proprietary application in any way, and you are not licensing and
* distributing your source code under AGPL, you probably need to
* purchase a commercial license of the product. Please contact
* claudia-support@lists.morfeo-project.org for more information.
*/
package com.telefonica.claudia.smi.provisioning;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.StringTokenizer;
import javax.xml.namespace.QName;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.xmlrpc.XmlRpcException;
import org.apache.xmlrpc.client.XmlRpcClient;
import org.apache.xmlrpc.client.XmlRpcClientConfigImpl;
import org.dmtf.schemas.ovf.envelope._1.ContentType;
import org.dmtf.schemas.ovf.envelope._1.DiskSectionType;
import org.dmtf.schemas.ovf.envelope._1.EnvelopeType;
import org.dmtf.schemas.ovf.envelope._1.FileType;
import org.dmtf.schemas.ovf.envelope._1.ProductSectionType;
import org.dmtf.schemas.ovf.envelope._1.RASDType;
import org.dmtf.schemas.ovf.envelope._1.ReferencesType;
import org.dmtf.schemas.ovf.envelope._1.VirtualDiskDescType;
import org.dmtf.schemas.ovf.envelope._1.VirtualHardwareSectionType;
import org.dmtf.schemas.ovf.envelope._1.VirtualSystemCollectionType;
import org.dmtf.schemas.ovf.envelope._1.VirtualSystemType;
import org.dmtf.schemas.ovf.envelope._1.ProductSectionType.Property;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import com.abiquo.ovf.OVFEnvelopeUtils;
import com.abiquo.ovf.exceptions.EmptyEnvelopeException;
import com.abiquo.ovf.section.OVFProductUtils;
import com.abiquo.ovf.xml.OVFSerializer;
import com.telefonica.claudia.smi.DataTypesUtils;
import com.telefonica.claudia.smi.Main;
import com.telefonica.claudia.smi.TCloudConstants;
import com.telefonica.claudia.smi.URICreation;
import com.telefonica.claudia.smi.task.Task;
import com.telefonica.claudia.smi.task.TaskManager;
public class ONEProvisioningDriver implements ProvisioningDriver {
public static enum ControlActionType {shutdown, hold, release, stop, suspend, resume, finalize};
//public static enum VmStateType {INIT, PENDING, HOLD, ACTIVE, STOPPED, SUSPENDED, DONE, FAILED};
private final static int INIT_STATE = 0;
private final static int PENDING_STATE = 1;
private final static int HOLD_STATE = 2;
private final static int ACTIVE_STATE = 3;
private final static int STOPPED_STATE = 4;
private final static int SUSPENDED_STATE = 5;
private final static int DONE_STATE = 6;
private final static int FAILED_STATE = 7;
// LCM_INIT, PROLOG, BOOT, RUNNING, MIGRATE, SAVE_STOP, SAVE_SUSPEND, SAVE_MIGRATE, PROLOG_MIGRATE, EPILOG_STOP, EPILOG, SHUTDOWN, CANCEL
private final static int INIT_SUBSTATE = 0;
private final static int PROLOG_SUBSTATE = 1;
private final static int BOOT_SUBSTATE = 2;
private final static int RUNNING_SUBSTATE = 3;
private final static int MIGRATE_SUBSTATE = 4;
private final static int SAVE_STOP_SUBSTATE = 5;
private final static int SAVE_SUSPEND_SUBSTATE = 6;
private final static int SAVE_MIGRATE_SUBSTATE = 7;
private final static int PROLOG_MIGRATE_SUBSTATE = 8;
private final static int PROLOG_RESUME_SUBSTATE = 9;
private final static int EPILOG_STOP_SUBSTATE = 10;
private final static int EPILOG_SUBSTATE = 11;
private final static int SHUDTOWN_SUBSTATE = 12;
private final static int CANCEL_SUBSTATE = 13;
private HashMap<String, String> text_migrability = new HashMap();
private static org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger("com.telefonica.claudia.smi.provisioning.ONEProvisioningDriver");
// Tag names of the returning info doc for Virtual machines
public static final String VM_STATE = "STATE";
public static final String VM_SUBSTATE = "LCM_STATE";
// XMLRPC commands to access OpenNebula features
private final static String VM_ALLOCATION_COMMAND = "one.vm.allocate";
private final static String VM_UPDATE_COMMAND = "one.vm.action";
private final static String VM_GETINFO_COMMAND = "one.vm.info";
private final static String VM_GETALL_COMMAND = "one.vmpool.info";
private final static String VM_DELETE_COMMAND = "one.vm.delete";
private final static String NET_ALLOCATION_COMMAND = "one.vn.allocate";
private final static String NET_GETINFO_COMMAND = "one.vn.info";
private final static String NET_GETALL_COMMAND = "one.vnpool.info";
private final static String NET_DELETE_COMMAND = "one.vn.delete";
//private final static String DEBUGGING_CONSOLE = "RAW = [ type =\"kvm\", data =\"<devices><serial type='pty'><source path='/dev/pts/5'/><target port='0'/></serial><console type='pty' tty='/dev/pts/5'><source path='/dev/pts/5'/><target port='0'/></console></devices>\" ]";
/**
* Connection URL for OpenNebula. It defaults to localhost, but can be
* overriden with the property oneURL of the server configuration file.
*/
private String oneURL = "http://localhost:2633/RPC2";
/**
* Server configuration file URL property identifier.
*/
private final static String URL_PROPERTY = "oneUrl";
private final static String USER_PROPERTY = "oneUser";
private final static String PASSWORD_PROPERTY = "onePassword";
private static final String KERNEL_PROPERTY = "oneKernel";
private static final String INITRD_PROPERTY = "oneInitrd";
private static final String ARCH_PROPERTY = "arch";
private static final String ENVIRONMENT_PROPERTY = "oneEnvironmentPath";
private final static String SSHKEY_PROPERTY = "oneSshKey";
private final static String SCRIPTPATH_PROPERTY = "oneScriptPath";
private final static String ETH0_GATEWAY_PROPERTY = "eth0Gateway";
private final static String ETH0_DNS_PROPERTY = "eth0Dns";
private final static String ETH1_GATEWAY_PROPERTY = "eth1Gateway";
private final static String ETH1_DNS_PROPERTY = "eth1Dns";
private final static String NET_INIT_SCRIPT0 = "netInitScript0";
private final static String NET_INIT_SCRIPT1 = "netInitScript1";
private String oneSession = "oneadmin:5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8";
private XmlRpcClient xmlRpcClient = null;
private static final String NETWORK_BRIDGE = "oneNetworkBridge";
private static final String XEN_DISK = "xendisk";
/**
* Collection containing the mapping from fqns to ids. This mapped is used as a cache
* of the getVmId method (vm ids never change once assigned).
*/
private Map<String, Integer> idVmMap = new HashMap<String, Integer>();
/**
* Collection containing the mapping from fqns to ids. This mapped is used as a cache
* of the getVmId method (vm ids never change once assigned).
*/
private Map<String, Integer> idNetMap = new HashMap<String, Integer>();
private String hypervisorInitrd="";
private String arch="";
private String hypervisorKernel="";
private String customizationPort;
private String environmentRepositoryPath;
private static String networkBridge="";
private static String xendisk="";
private static String oneSshKey="";
private static String oneScriptPath="";
private static String eth0Gateway="";
private static String eth1Gateway="";
private static String eth0Dns="";
private static String eth1Dns="";
private static String netInitScript0="";
private static String netInitScript1="";
public static final String ASSIGNATION_SYMBOL = "=";
public static final String LINE_SEPARATOR = System.getProperty("line.separator");
public static final String ONE_VM_ID = "NAME";
public static final String ONE_VM_TYPE = "TYPE";
public static final String ONE_VM_STATE = "STATE";
public static final String ONE_VM_MEMORY = "MEMORY";
public static final String ONE_VM_NAME = "NAME";
public static final String ONE_VM_UUID = "UUID";
public static final String ONE_VM_CPU = "CPU";
public static final String ONE_VM_VCPU = "VCPU";
public static final String ONE_VM_RAW_VMI = "RAW_VMI";
public static final String ONE_VM_OS = "OS";
public static final String ONE_VM_OS_PARAM_KERNEL = "kernel";
public static final String ONE_VM_OS_PARAM_INITRD = "initrd";
public static final String ONE_VM_OS_PARAM_ROOT = "root";
public static final String ONE_VM_OS_PARAM_BOOT = "boot";
public static final String ONE_VM_GRAPHICS = "GRAPHICS";
public static final String ONE_VM_GRAPHICS_TYPE = "type";
public static final String ONE_VM_GRAPHICS_LISTEN = "listen";
public static final String ONE_VM_GRAPHICS_PORT = "port";
public static final String ONE_VM_DISK_COLLECTION = "DISKS";
public static final String ONE_VM_DISK = "DISK";
public static final String ONE_VM_DISK_PARAM_IMAGE = "source";
public static final String ONE_VM_DISK_PARAM_FORMAT = "format";
public static final String ONE_VM_DISK_PARAM_SIZE = "size";
public static final String ONE_VM_DISK_PARAM_TARGET = "target";
public static final String ONE_VM_DISK_PARAM_DIGEST = "digest";
public static final String ONE_VM_DISK_PARAM_TYPE = "type";
public static final String ONE_VM_DISK_PARAM_DRIVER = "driver";
public static final String ONE_VM_NIC_COLLECTION = "NICS";
public static final String ONE_VM_NIC = "NIC";
public static final String ONE_VM_NIC_PARAM_IP = "ip";
public static final String ONE_VM_NIC_PARAM_NETWORK = "NETWORK";
public static final String ONE_NET_ID = "ID";
public static final String ONE_NET_NAME = "NAME";
public static final String ONE_NET_BRIDGE = "BRIDGE";
public static final String ONE_NET_TYPE = "TYPE";
public static final String ONE_NET_ADDRESS = "NETWORK_ADDRESS";
public static final String ONE_NET_SIZE = "NETWORK_SIZE";
public static final String ONE_NET_LEASES = "LEASES";
public static final String ONE_NET_IP = "IP";
public static final String ONE_NET_MAC = "MAC";
public static final String ONE_DISK_ID = "ID";
public static final String ONE_DISK_NAME = "NAME";
public static final String ONE_DISK_URL = "URL";
public static final String ONE_DISK_SIZE = "SIZE";
public static final String ONE_OVF_URL = "OVF";
public static final String ONE_CONTEXT = "CONTEXT";
public static final String RESULT_NET_ID = "ID";
public static final String RESULT_NET_NAME = "NAME";
public static final String RESULT_NET_ADDRESS = "NETWORK_ADDRESS";
public static final String RESULT_NET_BRIDGE = "BRIDGE";
public static final String RESULT_NET_TYPE = "TYPE";
public static final String MULT_CONF_LEFT_DELIMITER = "[";
public static final String MULT_CONF_RIGHT_DELIMITER = "]";
public static final String MULT_CONF_SEPARATOR = ",";
public static final String QUOTE = "\"";
private static final int ResourceTypeCPU = 3;
private static final int ResourceTypeMEMORY = 4;
private static final int ResourceTypeNIC = 10;
private static final int ResourceTypeDISK = 17;
public class DeployVMTask extends Task {
public static final long POLLING_INTERVAL= 10000;
private static final int MAX_CONNECTION_ATEMPTS = 5;
String fqnVm;
String ovf;
public DeployVMTask(String fqn, String ovf) {
super();
this.fqnVm = fqn;
this.ovf = ovf;
}
@Override
public void execute() {
this.status = TaskStatus.RUNNING;
this.startTime = System.currentTimeMillis();
try {
// Create the Virtual Machine
String result = createVirtualMachine();
if (result==null) {
this.status= TaskStatus.ERROR;
this.endTime = System.currentTimeMillis();
return;
}
// Wait until the state is RUNNING
this.status = TaskStatus.WAITING;
int connectionAttempts=0;
while (true) {
try {
Document vmInfo = getVirtualMachineState(result);
Integer state = Integer.parseInt(vmInfo.getElementsByTagName(VM_STATE).item(0).getTextContent());
Integer subState = Integer.parseInt(vmInfo.getElementsByTagName(VM_SUBSTATE).item(0).getTextContent());
if (state == ACTIVE_STATE && subState == RUNNING_SUBSTATE ) {
this.status= TaskStatus.SUCCESS;
this.endTime = System.currentTimeMillis();
break;
} else if (state ==FAILED_STATE) {
this.status= TaskStatus.ERROR;
this.endTime = System.currentTimeMillis();
break;
}
connectionAttempts=0;
} catch (IOException ioe) {
if (connectionAttempts> MAX_CONNECTION_ATEMPTS) {
this.status= TaskStatus.ERROR;
this.endTime = System.currentTimeMillis();
break;
} else
connectionAttempts++;
log.warn("Connection exception accessing ONE. Trying again. Error: " + ioe.getMessage());
}
Thread.sleep(POLLING_INTERVAL);
}
} catch (IOException e) {
log.error("Error connecting to ONE: " + e.getMessage());
this.error = new TaskError();
this.error.message = e.getMessage();
this.status = TaskStatus.ERROR;
this.endTime = System.currentTimeMillis();
return;
} catch (Exception e) {
log.error("Unexpected error creating VM: " + e.getMessage());
this.error = new TaskError();
this.error.message = e.getMessage();
this.status = TaskStatus.ERROR;
this.endTime = System.currentTimeMillis();
e.printStackTrace();
return;
}
}
public String createVirtualMachine() throws Exception {
List<String> rpcParams = new ArrayList<String>();
rpcParams.add(oneSession);
rpcParams.add(TCloud2ONEVM(ovf, fqnVm));
Object[] result = null;
try {
result = (Object[])xmlRpcClient.execute(VM_ALLOCATION_COMMAND, rpcParams);
} catch (XmlRpcException ex) {
throw new IOException ("Error on allocation of VEE replica , XMLRPC call failed: " + ex.getMessage(), ex);
}
boolean success = (Boolean)result[0];
if(success) {
log.debug("Request succeded. Returining: \n\n" + ((Integer)result[1]).toString() + "\n\n");
this.returnMsg = "Virtual machine internal id: " + ((Integer)result[1]).toString();
return ((Integer)result[1]).toString();
} else {
log.error("Error recieved from ONE: " + (String)result[1]);
this.error = new TaskError();
this.error.message = (String)result[1];
return null;
}
}
}
public class DeployNetworkTask extends Task {
String fqnNet;
String ovf;
public DeployNetworkTask(String netFqn, String ovf) {
this.fqnNet = netFqn;
this.ovf = ovf;
}
@Override
public void execute() {
this.status = TaskStatus.RUNNING;
this.startTime = System.currentTimeMillis();
try {
if (!createNetwork()) {
this.status= TaskStatus.ERROR;
return;
}
this.status= TaskStatus.SUCCESS;
} catch (IOException e) {
log.error("Error connecting to ONE: " + e.getMessage());
this.error = new TaskError();
this.error.message = e.getMessage();
this.endTime = System.currentTimeMillis();
this.status = TaskStatus.ERROR;
return;
} catch (Exception e) {
log.error("Unknown error creating network: " + e.getMessage());
this.error = new TaskError();
this.error.message = e.getMessage();
this.endTime = System.currentTimeMillis();
this.status = TaskStatus.ERROR;
}
}
public boolean createNetwork() throws Exception {
List<String> rpcParams = new ArrayList<String>();
rpcParams.add(oneSession);
rpcParams.add(TCloud2ONENet(ovf));
Object[] result = null;
try {
result = (Object[])xmlRpcClient.execute(NET_ALLOCATION_COMMAND, rpcParams);
} catch (XmlRpcException ex) {
log.error("Connection error. Could not reach ONE host: " + ex.getMessage());
throw new IOException ("Error on allocation of the new network , XMLRPC call failed", ex);
}
boolean success = (Boolean)result[0];
if(success) {
log.debug("Network creation request succeded: " + result[1]);
this.returnMsg = ((Integer)result[1]).toString();
return true;
} else {
log.error("Error recieved from ONE: " + (String)result[1]);
this.error = new TaskError();
this.error.message = (String)result[1];
return false;
}
}
}
public class UndeployVMTask extends Task {
String fqnVm;
public UndeployVMTask(String vmFqn) {
this.fqnVm = vmFqn;
}
@Override
public void execute() {
this.status= TaskStatus.RUNNING;
this.startTime = System.currentTimeMillis();
// Undeploy the VM
try {
String id = getVmId(fqnVm).toString();
deleteVirtualMachine(id);
this.status= TaskStatus.SUCCESS;
this.endTime = System.currentTimeMillis();
} catch (IOException e) {
log.error("Error connecting to ONE: " + e.getMessage());
this.error = new TaskError();
this.error.message = e.getMessage();
this.status = TaskStatus.ERROR;
this.endTime = System.currentTimeMillis();
return;
} catch (Exception e) {
log.error("Unknown error undeploying VM: " + e.getMessage());
this.error = new TaskError();
this.error.message = e.getMessage();
this.status = TaskStatus.ERROR;
this.endTime = System.currentTimeMillis();
return;
}
}
@SuppressWarnings("unchecked")
public boolean deleteVirtualMachine(String id) throws IOException {
List rpcParams = new ArrayList ();
ControlActionType controlAction = ControlActionType.finalize;
log.info("PONG deleteVirtualMachine id: "+ id);
rpcParams.add(oneSession);
rpcParams.add(controlAction.toString());
rpcParams.add(Integer.parseInt(id));
Object[] result = null;
try {
result = (Object[])xmlRpcClient.execute(VM_UPDATE_COMMAND, rpcParams);
} catch (XmlRpcException ex) {
log.error("Connection error trying to update VM: " + ex.getMessage());
throw new IOException ("Error updating VEE replica , XMLRPC call failed", ex);
}
if (result==null) {
throw new IOException("No result returned from XMLRPC call");
} else {
return (Boolean)result[0];
}
}
}
public class UndeployNetworkTask extends Task {
String fqnNet;
public UndeployNetworkTask(String netFqn) {
this.fqnNet = netFqn;
}
@Override
public void execute() {
this.status= TaskStatus.RUNNING;
this.startTime = System.currentTimeMillis();
// Undeploy the VM
try {
deleteNetwork(getNetId(fqnNet).toString());
this.status= TaskStatus.SUCCESS;
this.endTime = System.currentTimeMillis();
} catch (IOException e) {
log.error("Error connecting to ONE: " + e.getMessage());
this.error = new TaskError();
this.error.message = e.getMessage();
this.status = TaskStatus.ERROR;
this.endTime = System.currentTimeMillis();
return;
} catch (Exception e) {
log.error("Unknown error undeploying Network: " + e.getMessage());
this.error = new TaskError();
this.error.message = e.getMessage();
this.status = TaskStatus.ERROR;
this.endTime = System.currentTimeMillis();
return;
}
}
@SuppressWarnings("unchecked")
public void deleteNetwork(String id) throws IOException {
List rpcParams = new ArrayList<String>();
rpcParams.add(oneSession);
rpcParams.add(new Integer(id) );
Object[] result = null;
try {
result = (Object[])xmlRpcClient.execute(NET_DELETE_COMMAND, rpcParams);
} catch (XmlRpcException ex) {
throw new IOException ("Error deleting the network , XMLRPC call failed", ex);
}
boolean success = (Boolean)result[0];
if(success) {
} else {
throw new IOException("Unknown error trying to delete network: " + (String)result[1]);
}
}
}
public class ActionVMTask extends Task {
String fqnVM;
String action;
String errorMessage="";
public ActionVMTask(String fqnVM, String action) {
this.fqnVM = fqnVM;
this.action = action;
}
@Override
public void execute() {
this.status= TaskStatus.RUNNING;
this.startTime = System.currentTimeMillis();
// Undeploy the VM
try {
boolean result = doAction();
if (result)
this.status= TaskStatus.SUCCESS;
else {
this.status = TaskStatus.ERROR;
this.error = new TaskError();
this.error.message = errorMessage;
}
this.endTime = System.currentTimeMillis();
} catch (IOException e) {
log.error("Error connecting to VMWare: " + e.getMessage());
this.error = new TaskError();
this.error.message = e.getMessage();
this.status = TaskStatus.ERROR;
this.endTime = System.currentTimeMillis();
return;
} catch (Exception e) {
log.error("Unknown error executing action" + action + ": " + e.getMessage() + " -> " + e.getClass().getCanonicalName());
this.error = new TaskError();
this.error.message = e.getMessage();
this.status = TaskStatus.ERROR;
this.endTime = System.currentTimeMillis();
return;
}
}
public boolean doAction() throws Exception {
System.out.println("Executing action: " + action);
return true;
}
}
protected String TCloud2ONEVM(String xml, String veeFqn) throws Exception {
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new ByteArrayInputStream(xml.getBytes()));
if (!doc.getFirstChild().getNodeName().equals(TCloudConstants.TAG_INSTANTIATE_OVF)) {
log.error("Element <"+TCloudConstants.TAG_INSTANTIATE_OVF+"> not found.");
throw new Exception("Element <"+TCloudConstants.TAG_INSTANTIATE_OVF+"> not found.");
}
Element root = (Element) doc.getFirstChild();
String replicaName = root.getAttribute("name");
NodeList envelopeItems = doc.getElementsByTagNameNS("*", "Envelope");
if (envelopeItems.getLength() != 1) {
log.error("Envelope items not found.");
throw new Exception("Envelope items not found.");
}
// Extract the IP from the aspects section
Map<String, String> ipOnNetworkMap = new HashMap<String, String>();
NodeList aspects = doc.getElementsByTagNameNS("*", "Aspect");
for (int i=0; i < aspects.getLength(); i++) {
Element aspect = (Element) aspects.item(i);
if (aspect.getAttribute("name").equals("IP Config")) {
NodeList properties = aspect.getElementsByTagNameNS("*", "Property");
for (int j=0; j < properties.getLength(); j++) {
Element property = (Element) properties.item(j);
NodeList keys = property.getElementsByTagNameNS("*", "Key");
NodeList values = property.getElementsByTagNameNS("*", "Value");
if (keys.getLength() >0 && values.getLength()>0) {
ipOnNetworkMap.put(keys.item(0).getTextContent(), values.item(0).getTextContent());
}
}
}
}
// Extract the ovf sections and pass them to the OVF manager to be processed.
Document ovfDoc = builder.newDocument();
ovfDoc.appendChild(ovfDoc.importNode(envelopeItems.item(0), true));
OVFSerializer ovfSerializer = OVFSerializer.getInstance();
ovfSerializer.setValidateXML(false);
EnvelopeType envelope = ovfSerializer.readXMLEnvelope(new ByteArrayInputStream(DataTypesUtils.serializeXML(ovfDoc).getBytes()));
ContentType entityInstance = OVFEnvelopeUtils.getTopLevelVirtualSystemContent(envelope);
if (entityInstance instanceof VirtualSystemType) {
VirtualSystemType vs = (VirtualSystemType) entityInstance;
VirtualHardwareSectionType vh = OVFEnvelopeUtils.getSection(vs, VirtualHardwareSectionType.class);
String virtualizationType = vh.getSystem().getVirtualSystemType().getValue();
String scriptListProp = null;
String scriptListTemplate = "";
String hostname=null;
ProductSectionType productSection;
productSection = OVFEnvelopeUtils.getSection(vs, ProductSectionType.class);
try
{
Property prop = OVFProductUtils.getProperty(productSection, "SCRIPT_LIST");
scriptListProp = prop.getValue().toString();
String[] scriptList = scriptListProp.split("/");
scriptListTemplate = "";
for (String scrt: scriptList){
scriptListTemplate = scriptListTemplate + " "+oneScriptPath+"/"+scrt;
}
}
catch (Exception e)
{
//TODO throw PropertyNotFoundException
//logger.error(e);
scriptListProp="";
scriptListTemplate = "";
}
String netcontext=getNetContext(vh, veeFqn,xml, scriptListProp);
try
{
Property prop = OVFProductUtils.getProperty(productSection, "HOSTNAME");
hostname = prop.getValue().toString();
}
catch (Exception e)
{
//TODO throw PropertyNotFoundException
//logger.error(e);
hostname="";
}
StringBuffer allParametersString = new StringBuffer();
// Migrability ....
allParametersString.append(ONE_VM_NAME).append(ASSIGNATION_SYMBOL).append(replicaName).append(LINE_SEPARATOR);
if (virtualizationType.toLowerCase().equals("kvm")) {
allParametersString.append("REQUIREMENTS").append(ASSIGNATION_SYMBOL).append("\"HYPERVISOR=\\\"kvm\\\"\"").append(LINE_SEPARATOR);
} else if (virtualizationType.toLowerCase().equals("xen")) {
allParametersString.append("REQUIREMENTS").append(ASSIGNATION_SYMBOL).append("\"HYPERVISOR=\\\"xen\\\"\"").append(LINE_SEPARATOR);
}
allParametersString.append(ONE_VM_OS).append(ASSIGNATION_SYMBOL).append(MULT_CONF_LEFT_DELIMITER);
String diskRoot;
if (virtualizationType.toLowerCase().equals("kvm")) {
diskRoot = "h";
allParametersString.append(ONE_VM_OS_PARAM_BOOT).append(ASSIGNATION_SYMBOL).append("hd").append(MULT_CONF_SEPARATOR).append(LINE_SEPARATOR);
} else {
diskRoot = xendisk;
allParametersString.append(ONE_VM_OS_PARAM_INITRD).append(ASSIGNATION_SYMBOL).append(hypervisorInitrd).append(MULT_CONF_SEPARATOR).append(LINE_SEPARATOR);
allParametersString.append(ONE_VM_OS_PARAM_KERNEL).append(ASSIGNATION_SYMBOL).append(hypervisorKernel).append(MULT_CONF_SEPARATOR).append(LINE_SEPARATOR);
}
if(arch.length()>0)
allParametersString.append("ARCH").append(ASSIGNATION_SYMBOL).append("\"").append(arch).append("\"").append(MULT_CONF_SEPARATOR).append(LINE_SEPARATOR);
allParametersString.append(ONE_VM_OS_PARAM_ROOT).append(ASSIGNATION_SYMBOL).append(diskRoot + "da1").append(MULT_CONF_RIGHT_DELIMITER).append(LINE_SEPARATOR);
allParametersString.append(ONE_CONTEXT).append(ASSIGNATION_SYMBOL).append(MULT_CONF_LEFT_DELIMITER);
if(hostname.length()>0) {
allParametersString.append("hostname = \""+hostname+"\"").append(MULT_CONF_SEPARATOR).append(LINE_SEPARATOR);
}
if(netcontext.length()>0) {
allParametersString.append(netcontext);
}
allParametersString.append("public_key").append(ASSIGNATION_SYMBOL).append(oneSshKey).append(MULT_CONF_SEPARATOR).append(LINE_SEPARATOR);
allParametersString.append("CustomizationUrl").append(ASSIGNATION_SYMBOL).append("\"" + Main.PROTOCOL + Main.serverHost + ":" + customizationPort + "/"+ replicaName+ "\"").append(MULT_CONF_SEPARATOR).append(LINE_SEPARATOR);
allParametersString.append("files").append(ASSIGNATION_SYMBOL).append("\"" + environmentRepositoryPath + "/"+ replicaName + "/ovf-env.xml" +scriptListTemplate+ "\"").append(MULT_CONF_SEPARATOR).append(LINE_SEPARATOR);
allParametersString.append("target").append(ASSIGNATION_SYMBOL).append("\"" + diskRoot + "dd"+ "\"").append(MULT_CONF_RIGHT_DELIMITER).append(LINE_SEPARATOR);
if (vh.getSystem() != null && vh.getSystem().getVirtualSystemType()!= null &&
vh.getSystem().getVirtualSystemType().getValue() != null &&
vh.getSystem().getVirtualSystemType().getValue().equals("vjsc"))
{
allParametersString.append("HYPERVISOR").append(ASSIGNATION_SYMBOL).append("VJSC").append(LINE_SEPARATOR);
}
char sdaId = 'a';
List<RASDType> items = vh.getItem();
for (Iterator<RASDType> iteratorRASD = items.iterator(); iteratorRASD.hasNext();) {
RASDType item = (RASDType) iteratorRASD.next();
/* Get the resource type and process it accordingly */
int rsType = new Integer(item.getResourceType().getValue());
int quantity = 1;
if (item.getVirtualQuantity() != null) {
quantity = item.getVirtualQuantity().getValue().intValue();
}
switch (rsType) {
case ResourceTypeCPU:
// for (int k = 0; k < quantity; k++) {
allParametersString.append(ONE_VM_CPU).append(ASSIGNATION_SYMBOL).append(quantity).append(LINE_SEPARATOR);
allParametersString.append(ONE_VM_VCPU).append(ASSIGNATION_SYMBOL).append(quantity).append(LINE_SEPARATOR);
// }
break;
case ResourceTypeDISK:
/*
* The rasd:HostResource will follow the pattern
* 'ovf://disk/<id>' where id is the ovf:diskId of some
* <Disk>
*/
String hostRes = item.getHostResource().get(0).getValue();
StringTokenizer st = new StringTokenizer(hostRes, "/");
/*
* Only ovf:/<file|disk>/<n> format is valid, accodring
* OVF spec
*/
if (st.countTokens() != 3) {
throw new IllegalArgumentException("malformed HostResource value (" + hostRes + ")");
}
if (!(st.nextToken().equals("ovf:"))) {
throw new IllegalArgumentException("HostResource must start with ovf: (" + hostRes + ")");
}
String hostResType = st.nextToken();
if (!(hostResType.equals("disk") || hostResType.equals("file"))) {
throw new IllegalArgumentException("HostResource type must be either disk or file: (" + hostRes + ")");
}
String hostResId = st.nextToken();
String fileRef = null;
String capacity = null;
String format = null;
if (hostResType.equals("disk")) {
/* This type involves an indirection level */
DiskSectionType ds = null;
ds = OVFEnvelopeUtils.getSection(envelope, DiskSectionType.class);
List<VirtualDiskDescType> disks = ds.getDisk();
for (Iterator<VirtualDiskDescType> iteratorDk = disks.iterator(); iteratorDk.hasNext();) {
VirtualDiskDescType disk = iteratorDk.next();
String diskId = disk.getDiskId();
if (diskId.equals(hostResId)) {
fileRef = disk.getFileRef();
capacity = disk.getCapacity();
format = disk.getFormat();
break;
}
}
} else {
throw new IllegalArgumentException("File type not supported in Disk sections.");
}
/* Throw exceptions in the case of missing information */
if (fileRef == null) {
log.warn("file reference can not be found for disk: " + hostRes);
}
URL url = null;
String digest = null;
String driver = null;
ReferencesType ref = envelope.getReferences();
List<FileType> files = ref.getFile();
for (Iterator<FileType> iteratorFl = files.iterator(); iteratorFl.hasNext();) {
FileType fl = iteratorFl.next();
if (fileRef!=null)
{
if (fl.getId().equals(fileRef)) {
try {
url = new URL(fl.getHref());
} catch (MalformedURLException e) {
throw new IllegalArgumentException("problems parsing disk href: " + e.getMessage());
}
}
/*
* If capacity was not set using ovf:capacity in
* <Disk>, try to get it know frm <File>
* ovf:size
*/
if (capacity == null && fl.getSize() != null) {
capacity = fl.getSize().toString();
}
/* Try to get the digest */
Map<QName, String> attributesFile = fl.getOtherAttributes();
QName digestAtt = new QName("http://schemas.telefonica.com/claudia/ovf","digest");
digest = attributesFile.get(digestAtt);
Map<QName, String> attributesFile2 = fl.getOtherAttributes();
QName driverAtt = new QName("http://schemas.telefonica.com/claudia/ovf","driver");
driver = attributesFile.get(driverAtt);
break;
}
}
/* Throw exceptions in the case of missing information */
if (capacity == null) {
throw new IllegalArgumentException("capacity can not be set for disk " + hostRes);
}
if (url == null && fileRef!=null) {
throw new IllegalArgumentException("url can not be set for disk " + hostRes);
}
if (digest == null) {
log.debug("md5sum digest was not found for disk " + hostRes);
}
String urlDisk = null;
if (url != null)
{
urlDisk = url.toString();
if (urlDisk.contains("file:/"))
urlDisk = urlDisk.replace("file:/", "file:///");
}
File filesystem = new File("/dev/" + diskRoot + "d" + sdaId);
allParametersString.append(ONE_VM_DISK).append(ASSIGNATION_SYMBOL).append(MULT_CONF_LEFT_DELIMITER);
if (urlDisk!= null)
allParametersString.append(ONE_VM_DISK_PARAM_IMAGE).append(ASSIGNATION_SYMBOL).append(urlDisk).append(MULT_CONF_SEPARATOR);
if (virtualizationType.toLowerCase().equals("kvm")) {
allParametersString.append(ONE_VM_DISK_PARAM_TARGET).append(ASSIGNATION_SYMBOL).append(diskRoot + "d" + sdaId).append(MULT_CONF_SEPARATOR);
} else
allParametersString.append(ONE_VM_DISK_PARAM_TARGET).append(ASSIGNATION_SYMBOL).append(filesystem.getAbsolutePath()).append(MULT_CONF_SEPARATOR);
if (format!=null)
{
if (format.equals("ext3"))
{
allParametersString.append(ONE_VM_DISK_PARAM_TYPE).append(ASSIGNATION_SYMBOL).append("fs").append(MULT_CONF_SEPARATOR);
}
allParametersString.append(ONE_VM_DISK_PARAM_FORMAT).append(ASSIGNATION_SYMBOL).append(format).append(MULT_CONF_SEPARATOR);
}
if (driver!=null)
allParametersString.append(ONE_VM_DISK_PARAM_DRIVER).append(ASSIGNATION_SYMBOL).append(driver).append(MULT_CONF_SEPARATOR);
if (digest!=null)
allParametersString.append(ONE_VM_DISK_PARAM_DIGEST).append(ASSIGNATION_SYMBOL).append(digest).append(MULT_CONF_SEPARATOR);
allParametersString.append(ONE_VM_DISK_PARAM_SIZE).append(ASSIGNATION_SYMBOL).append(capacity);
allParametersString.append(MULT_CONF_RIGHT_DELIMITER).append(LINE_SEPARATOR);
sdaId++;
break;
case ResourceTypeMEMORY:
allParametersString.append(ONE_VM_MEMORY).append(ASSIGNATION_SYMBOL).append(quantity).append(LINE_SEPARATOR);
break;
case ResourceTypeNIC:
String fqnNet = URICreation.getService(veeFqn) + ".networks." + item.getConnection().get(0).getValue();
allParametersString.append(ONE_VM_NIC).append(ASSIGNATION_SYMBOL).append(MULT_CONF_LEFT_DELIMITER).append(LINE_SEPARATOR);
allParametersString.append(ONE_NET_BRIDGE).append(ASSIGNATION_SYMBOL).append(networkBridge).append(MULT_CONF_SEPARATOR).append(LINE_SEPARATOR).
append(ONE_VM_NIC_PARAM_NETWORK).append(ASSIGNATION_SYMBOL).append(fqnNet).append(MULT_CONF_SEPARATOR).append(LINE_SEPARATOR).
append(ONE_VM_NIC_PARAM_IP).append(ASSIGNATION_SYMBOL).append(ipOnNetworkMap.get(fqnNet)).append(LINE_SEPARATOR).
append(MULT_CONF_RIGHT_DELIMITER).append(LINE_SEPARATOR);
break;
default:
throw new IllegalArgumentException("unknown hw type: " + rsType);
}
}
//allParametersString.append(LINE_SEPARATOR).append(DEBUGGING_CONSOLE).append(LINE_SEPARATOR);
log.debug("VM data sent:\n\n" + allParametersString.toString() + "\n\n");
System.out.println("VM data sent:\n\n" + allParametersString.toString() + "\n\n");
return allParametersString.toString();
} else {
throw new IllegalArgumentException("OVF malformed. No VirtualSystemType found.");
}
} catch (IOException e1) {
log.error("OVF of the virtual machine was not well formed or it contained some errors.");
throw new Exception("OVF of the virtual machine was not well formed or it contained some errors: " + e1.getMessage());
} catch (ParserConfigurationException e) {
log.error("Error configuring parser: " + e.getMessage());
throw new Exception("Error configuring parser: " + e.getMessage());
} catch (FactoryConfigurationError e) {
log.error("Error retrieving parser: " + e.getMessage());
throw new Exception("Error retrieving parser: " + e.getMessage());
} catch (Exception e) {
log.error("Error configuring a XML Builder.");
throw new Exception("Error configuring a XML Builder: " + e.getMessage());
}
}
protected static String ONEVM2TCloud(String ONETemplate) {
// TODO: ONE Template to TCloud translation
return "";
}
protected static String getNetContext(VirtualHardwareSectionType vh, String veeFqn,String xml, String scriptListProp) throws Exception {
// log.debug("PONG2 xml" +xml+ "\n");
StringBuffer allParametersString = new StringBuffer();
List<RASDType> items = vh.getItem();
int i=0;
for (Iterator<RASDType> iteratorRASD = items.iterator(); iteratorRASD.hasNext();) {
RASDType item = (RASDType) iteratorRASD.next();
/* Get the resource type and process it accordingly */
int rsType = new Integer(item.getResourceType().getValue());
int quantity = 1;
if (item.getVirtualQuantity() != null) {
quantity = item.getVirtualQuantity().getValue().intValue();
}
switch (rsType) {
case ResourceTypeNIC:
try {
// log.debug("PONG eth0Dns" + eth0Dns + "\n");
// log.debug("PONG eth0Gateway" + eth0Gateway + "\n");
// log.debug("PONG eth1Dns" + eth1Dns + "\n");
// log.debug("PONG eth1Gateway" + eth1Gateway + "\n");
String fqnNet = URICreation.getService(veeFqn) + ".networks." + item.getConnection().get(0).getValue();
allParametersString.append("ip_eth"+i).append(ASSIGNATION_SYMBOL).append("\"$NIC[IP, NETWORK=\\\""+fqnNet+"\\\"]\"").append(MULT_CONF_SEPARATOR).append(LINE_SEPARATOR);
String dns="";
String gateway="";
if(i==0){
dns=eth0Dns;
gateway=eth0Gateway;
}
if(i==1){
dns=eth1Dns;
gateway=eth1Gateway;
}
if(dns.length()>0)
{
allParametersString.append("dns_eth"+i).append(ASSIGNATION_SYMBOL).append(dns).append(MULT_CONF_SEPARATOR).append(LINE_SEPARATOR);
}
if(gateway.length()>0)
{
allParametersString.append("gateway_eth"+i).append(ASSIGNATION_SYMBOL).append(gateway).append(MULT_CONF_SEPARATOR).append(LINE_SEPARATOR);
}
i++;
} catch (FactoryConfigurationError e) {
log.error("Error retrieving parser: " + e.getMessage());
throw new Exception("Error retrieving parser: " + e.getMessage());
} catch (Exception e) {
log.error("Error configuring a XML Builder.");
throw new Exception("Error configuring a XML Builder: " + e.getMessage());
}
break;
default:
//throw new IllegalArgumentException("unknown hw type: " + rsType);
}
}
if (i==1){
if(netInitScript0.length()>0) {
allParametersString.append("SCRIPT_EXEC=\""+netInitScript0);
}
}
if (i==2){
if(netInitScript1.length()>0) {
allParametersString.append("SCRIPT_EXEC=\""+netInitScript1);
}
}
if (scriptListProp != null & scriptListProp.length()!=0)
{
String[] scriptList = scriptListProp.split("/");
String scriptListTemplate = "";
for (String scrt: scriptList){
if (scrt.indexOf(".py")!=-1)
{
if (scrt.equals("OVFParser.py")) {
System.out.println ("python /mnt/stratuslab/"+scrt);
allParametersString.append("; python /mnt/stratuslab/"+scrt+"");
}
if (scrt.equals("restful-server.py")) {
System.out.println ("/etc/init.d/lb_server start");
allParametersString.append("; /etc/init.d/lb_server start");
}
if (scrt.equals("torqueProbe.py")) {
System.out.println ("/etc/init.d/probe start");
allParametersString.append("; /etc/init.d/probe start");
}
}
}
}
allParametersString.append("\"").append(MULT_CONF_SEPARATOR).append(LINE_SEPARATOR);
return allParametersString.toString();
}
protected static String TCloud2ONENet(String xml) throws Exception {
try {
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(new ByteArrayInputStream(xml.getBytes()));
// log.debug("PONG3 doc" +doc.getTextContent()+ "\n");
Element root = (Element) doc.getFirstChild();
String fqn = root.getAttribute(TCloudConstants.ATTR_NETWORK_NAME);
// log.debug("PONG3 fqn" + fqn + "\n");
NodeList macEnabled = doc.getElementsByTagName(TCloudConstants.TAG_NETWORK_MAC_ENABLED);
Element firstmacenElement = (Element)macEnabled.item(0);
NodeList textMacenList = firstmacenElement.getChildNodes();
String macenabled= ((Node)textMacenList.item(0)).getNodeValue().trim();
NodeList netmaskList = doc.getElementsByTagName(TCloudConstants.TAG_NETWORK_NETMASK);
NodeList baseAddressList = doc.getElementsByTagName(TCloudConstants.TAG_NETWORK_BASE_ADDRESS);
StringBuffer allParametersString = new StringBuffer();
String privateNet = null;
if (root.getAttribute(TCloudConstants.ATTR_NETWORK_TYPE).equals("true"))
privateNet = "private";
else
privateNet ="public";
// If there is a netmask, calculate the size of the net counting it's bits.
if (netmaskList.getLength() >0) {
Element netmask = (Element) netmaskList.item(0);
if (!netmask.getTextContent().matches("\\d+\\.\\d+\\.\\d+\\.\\d+"))
throw new IllegalArgumentException("Wrong IPv4 format. Expected example: 192.168.0.0 Got: " + netmask.getTextContent());
String[] ipBytes = netmask.getTextContent().split("\\.");
short[] result = new short[4];
for (int i=0; i < 4; i++) {
try {
result[i] = Short.parseShort(ipBytes[i]);
if (result[i]>255) throw new NumberFormatException("Should be in the range [0-255].");
} catch (NumberFormatException nfe) {
throw new IllegalArgumentException("Number out of bounds. Bytes should be on the range 0-255.");
}
}
// The network can host 2^n where n is the number of bits in the network address,
// substracting the broadcast and the network value (all 1s and all 0s).
int size = (int) Math.pow(2, 32.0-getBitNumber(result));
if (size < 8)
size = 8;
else
size -= 2;
if (macenabled.equals("false"))
allParametersString.append(ONE_NET_SIZE).append(ASSIGNATION_SYMBOL).append(size).append(LINE_SEPARATOR);
}
if (baseAddressList.getLength()>0) {
if (macenabled.equals("false"))
allParametersString.append(ONE_NET_ADDRESS).append(ASSIGNATION_SYMBOL).append(baseAddressList.item(0).getTextContent()).append(LINE_SEPARATOR);
}
// Translate the simple data to RPC format
allParametersString.append(ONE_NET_NAME).append(ASSIGNATION_SYMBOL).append(fqn).append(LINE_SEPARATOR);
// Add the net Type
if (macenabled.equals("false")) {
allParametersString.append(ONE_NET_TYPE).append(ASSIGNATION_SYMBOL).append("RANGED").append(LINE_SEPARATOR);
}
else {
allParametersString.append(ONE_NET_TYPE).append(ASSIGNATION_SYMBOL).append("FIXED").append(LINE_SEPARATOR);
}
allParametersString.append(ONE_NET_BRIDGE).append(ASSIGNATION_SYMBOL).append(networkBridge).append(LINE_SEPARATOR);
NodeList ipLeaseList = doc.getElementsByTagName(TCloudConstants.TAG_NETWORK_IPLEASES);
for (int i=0; i<ipLeaseList .getLength(); i++){
Node firstIpLeaseNode = ipLeaseList.item(i);
if (firstIpLeaseNode.getNodeType() == Node.ELEMENT_NODE){
Element firstIpLeaseElement = (Element)firstIpLeaseNode;
NodeList ipList =firstIpLeaseElement.getElementsByTagName(TCloudConstants.TAG_NETWORK_IP);
Element firstIpElement = (Element)ipList.item(0);
NodeList textIpList = firstIpElement.getChildNodes();
String ipString = ("IP="+((Node)textIpList.item(0)).getNodeValue().trim());
NodeList macList =firstIpLeaseElement.getElementsByTagName(TCloudConstants.TAG_NETWORK_MAC);
Element firstMacElement = (Element)macList.item(0);
NodeList textMacList = firstMacElement.getChildNodes();
String macString = ("MAC="+((Node)textMacList.item(0)).getNodeValue().trim());
allParametersString.append(ONE_NET_LEASES).append(ASSIGNATION_SYMBOL).append(MULT_CONF_LEFT_DELIMITER);
allParametersString.append(ipString).append(MULT_CONF_SEPARATOR).append(macString).append(MULT_CONF_RIGHT_DELIMITER).append(LINE_SEPARATOR);
}
}
log.debug("Network data sent:\n\n" + allParametersString.toString() + "\n\n");
return allParametersString.toString();
} catch (IOException e1) {
log.error("OVF of the virtual machine was not well formed or it contained some errors.");
throw new Exception("OVF of the virtual machine was not well formed or it contained some errors: " + e1.getMessage());
} catch (ParserConfigurationException e) {
log.error("Error configuring parser: " + e.getMessage());
throw new Exception("Error configuring parser: " + e.getMessage());
} catch (FactoryConfigurationError e) {
log.error("Error retrieving parser: " + e.getMessage());
throw new Exception("Error retrieving parser: " + e.getMessage());
} catch (Exception e) {
log.error("Error configuring a XML Builder.");
throw new Exception("Error configuring a XML Builder: " + e.getMessage());
}
}
protected static String ONENet2TCloud(String ONETemplate) {
return "";
}
/**
* Get the number of bits with value 1 in the given IP.
*
* @return
*/
public static int getBitNumber (short[] ip) {
if (ip == null || ip.length != 4)
return 0;
int bits=0;
for (int i=0; i < 4; i++)
for (int j=0; j< 15; j++)
bits += ( ((short)Math.pow(2, j))& ip[i]) / Math.pow(2, j);
return bits;
}
/**
* Retrieve the virtual network id given its fqn.
*
* @param fqn
* FQN of the Virtual Network (mapped to its name property in ONE).
*
* @return
* The internal id of the Virtual Network if it exists or -1 otherwise.
*
* @throws Exception
*
*/
protected Integer getNetId(String fqn) throws Exception {
if (!idNetMap.containsKey(fqn))
idNetMap = getNetworkIds();
if (idNetMap.containsKey(fqn))
return idNetMap.get(fqn);
else
return -1;
}
/**
* Retrieve the vm's id given its fqn.
*
* @param fqn
* FQN of the Virtual Machine (mapped to its name property in ONE).
*
* @return
* The internal id of the Virtual Machine if it exists or -1 otherwise.
*
* @throws Exception
*
*/
protected Integer getVmId(String fqn) throws Exception {
if (!idVmMap.containsKey(fqn))
idVmMap = getVmIds();
if (idVmMap.containsKey(fqn))
return idVmMap.get(fqn);
else
return -1;
}
/**
* Retrieve a map of the currently deployed VMs, and its ids.
*
* @return
* A map where the key is the VM's FQN and the value the VM's id.
* @throws Exception
*/
@SuppressWarnings("unchecked")
protected Map<String, Integer> getVmIds() throws Exception {
List rpcParams = new ArrayList<String>();
rpcParams.add(oneSession);
rpcParams.add(-2);
HashMap<String, Integer> mapResult = new HashMap<String, Integer>();
Object[] result = null;
try {
result = (Object[])xmlRpcClient.execute(VM_GETALL_COMMAND, rpcParams);
} catch (XmlRpcException ex) {
throw new IOException ("Error obtaining the VM list: " + ex.getMessage(), ex);
}
boolean success = (Boolean)result[0];
if(success) {
String resultList = (String) result[1];
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new ByteArrayInputStream(resultList.getBytes()));
NodeList vmList = doc.getElementsByTagName("VM");
for (int i=0; i < vmList.getLength(); i++) {
Element vm = (Element) vmList.item(i);
String fqn = ((Element)vm.getElementsByTagName("NAME").item(0)).getTextContent();
try {
Integer value = Integer.parseInt(((Element)vm.getElementsByTagName("ID").item(0)).getTextContent());
mapResult.put(fqn, value);
} catch(NumberFormatException nfe) {
log.warn("Numerical id expected, got [" + ((Element)vm.getElementsByTagName("ID").item(0)).getTextContent() + "]");
continue;
}
}
return mapResult;
} catch (ParserConfigurationException e) {
log.error("Parser Configuration Error: " + e.getMessage());
throw new IOException ("Parser Configuration Error", e);
} catch (SAXException e) {
log.error("Parse error reading the answer: " + e.getMessage());
throw new IOException ("XML Parse error", e);
}
} else {
log.error("Error recieved from ONE: " + result[1]);
throw new Exception("Error recieved from ONE: " + result[1]);
}
}
@SuppressWarnings("unchecked")
protected HashMap<String, Integer> getNetworkIds() throws IOException {
List rpcParams = new ArrayList();
rpcParams.add(oneSession);
rpcParams.add(-2);
Object[] result = null;
try {
result = (Object[])xmlRpcClient.execute(NET_GETALL_COMMAND, rpcParams);
} catch (XmlRpcException ex) {
throw new IOException ("Error obtaining the network list", ex);
}
boolean success = (Boolean)result[0];
if(success) {
HashMap<String, Integer> mapResult = new HashMap<String, Integer>();
String resultList = (String) result[1];
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new ByteArrayInputStream(resultList.getBytes()));
NodeList vmList = doc.getElementsByTagName("VNET");
for (int i=0; i < vmList.getLength(); i++) {
Element vm = (Element) vmList.item(i);
String fqn = ((Element)vm.getElementsByTagName("NAME").item(0)).getTextContent();
try {
Integer value = Integer.parseInt(((Element)vm.getElementsByTagName("ID").item(0)).getTextContent());
mapResult.put(fqn, value);
} catch(NumberFormatException nfe) {
log.warn("Numerical id expected, got [" + ((Element)vm.getElementsByTagName("ID").item(0)).getTextContent() + "]");
continue;
}
}
return mapResult;
} catch (ParserConfigurationException e) {
throw new IOException ("Parser Configuration Error", e);
} catch (SAXException e) {
throw new IOException ("XML Parse error", e);
}
} else {
throw new IOException("Error recieved from ONE: " +(String)result[1]);
}
}
public ONEProvisioningDriver(Properties prop) {
XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl();
log.info("Creating OpenNebula conector");
if (prop.containsKey(URL_PROPERTY)) {
oneURL = (String) prop.get(URL_PROPERTY);
log.info("URL created: " + oneURL);
}
if (prop.containsKey(USER_PROPERTY)&&prop.containsKey(PASSWORD_PROPERTY)) {
oneSession = ((String) prop.get(USER_PROPERTY)) + ":" + ((String) prop.get(PASSWORD_PROPERTY));
log.info("Session created: " + oneSession);
}
if (prop.containsKey(KERNEL_PROPERTY)) {
hypervisorKernel = ((String) prop.get(KERNEL_PROPERTY));
}
if (prop.containsKey(INITRD_PROPERTY)) {
hypervisorInitrd = ((String) prop.get(INITRD_PROPERTY));
}
if (prop.containsKey(ARCH_PROPERTY)) {
arch = ((String) prop.get(ARCH_PROPERTY));
}
if (prop.containsKey(Main.CUSTOMIZATION_PORT_PROPERTY)) {
customizationPort = ((String) prop.get(Main.CUSTOMIZATION_PORT_PROPERTY));
}
if (prop.containsKey(ENVIRONMENT_PROPERTY)) {
environmentRepositoryPath = (String) prop.get(ENVIRONMENT_PROPERTY);
}
if (prop.containsKey(NETWORK_BRIDGE)) {
networkBridge = ((String) prop.get(NETWORK_BRIDGE));
}
if (prop.containsKey(XEN_DISK)) {
xendisk = ((String) prop.get(XEN_DISK));
}
if (prop.containsKey(SSHKEY_PROPERTY)) {
oneSshKey = ((String) prop.get(SSHKEY_PROPERTY));
}
if (prop.containsKey(SCRIPTPATH_PROPERTY)) {
oneScriptPath = ((String) prop.get(SCRIPTPATH_PROPERTY));
}
if (prop.containsKey(ETH0_GATEWAY_PROPERTY)) {
eth0Gateway= ((String) prop.get(ETH0_GATEWAY_PROPERTY));
}
if (prop.containsKey(ETH0_DNS_PROPERTY)) {
eth0Dns = ((String) prop.get(ETH0_DNS_PROPERTY));
}
if (prop.containsKey(ETH1_GATEWAY_PROPERTY)) {
eth1Gateway = ((String) prop.get(ETH1_GATEWAY_PROPERTY));
}
if (prop.containsKey(ETH1_DNS_PROPERTY)) {
eth1Dns = ((String) prop.get(ETH1_DNS_PROPERTY));
}
if (prop.containsKey(NET_INIT_SCRIPT0)) {
netInitScript0 = ((String) prop.get(NET_INIT_SCRIPT0));
}
if (prop.containsKey(NET_INIT_SCRIPT1)) {
netInitScript1 = ((String) prop.get(NET_INIT_SCRIPT1));
}
try {
config.setServerURL(new URL(oneURL));
} catch (MalformedURLException e) {
log.error("Malformed URL: " + oneURL);
throw new RuntimeException(e);
}
xmlRpcClient = new XmlRpcClient();
log.info("XMLRPC client created");
xmlRpcClient.setConfig(config);
log.info("XMLRPC client configured");
/* MIGRABILITY TAG */
text_migrability.put("cross-host", "HOST");
text_migrability.put("cross-sitehost", "SITE");
text_migrability.put("none", "NONE");
// FULL??
}
@SuppressWarnings("unchecked")
public Document getVirtualMachineState(String id) throws IOException {
List rpcParams = new ArrayList ();
rpcParams.add(oneSession);
rpcParams.add(new Integer(id));
log.debug("Virtual machine info requested for id: " + id);
Object[] result = null;
try {
result = (Object[])xmlRpcClient.execute(VM_GETINFO_COMMAND, rpcParams);
} catch (XmlRpcException ex) {
log.error("Connection error trying to get VM information: " + ex.getMessage());
throw new IOException ("Error on reading VM state , XMLRPC call failed", ex);
}
boolean completed = (Boolean) result[0];
if (completed) {
String resultList = (String) result[1];
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// RESERVOIR ONLY: the info cames with a XML inside the element RAW_VMI, WITH HEADERS
if (resultList.contains("<RAW_VMI>")) {
resultList = resultList.replace(resultList.substring(resultList.indexOf("<RAW_VMI>"), resultList.indexOf("</RAW_VMI>") + 10), "");
}
try {
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new ByteArrayInputStream(resultList.getBytes()));
log.debug("VM Info request succeded");
return doc;
} catch (ParserConfigurationException e) {
log.error("Error configuring parser: " + e.getMessage());
throw new IOException ("Parser Configuration Error", e);
} catch (SAXException e) {
log.error("Parse error obtaining info: " + e.getMessage());
throw new IOException ("XML Parse error", e);
}
} else {
log.error("VM Info request failed: " + result[1]);
return null;
}
}
public String getAtributeVirtualSystem(VirtualSystemType vs, String attribute) throws NumberFormatException {
Iterator itr = vs.getOtherAttributes().entrySet().iterator();
while (itr.hasNext()) {
Map.Entry e = (Map.Entry)itr.next();
if ((e.getKey()).equals(new QName ("http://schemas.telefonica.com/claudia/ovf", attribute)))
return (String)e.getValue();
}
return "";
}
public ArrayList<VirtualSystemType> getVirtualSystem (EnvelopeType envelope) throws Exception {
ContentType entityInstance = null;
ArrayList<VirtualSystemType> virtualSystems = new ArrayList ();
try {
entityInstance = OVFEnvelopeUtils.getTopLevelVirtualSystemContent(envelope);
} catch (EmptyEnvelopeException e) {
log.error(e);
}
HashMap<String,VirtualSystemType> virtualsystems = new HashMap();
if (entityInstance instanceof VirtualSystemType) {
virtualSystems.add((VirtualSystemType)entityInstance);
} else if (entityInstance instanceof VirtualSystemCollectionType) {
VirtualSystemCollectionType virtualSystemCollectionType = (VirtualSystemCollectionType) entityInstance;
for (VirtualSystemType vs : OVFEnvelopeUtils.getVirtualSystems(virtualSystemCollectionType))
{
virtualSystems.add(vs);
}
}//End for
return virtualSystems;
}
@Override
public long deleteNetwork(String netFqn) throws IOException {
return TaskManager.getInstance().addTask(new UndeployNetworkTask(netFqn), URICreation.getVDC(netFqn)).getTaskId();
}
@Override
public long deleteVirtualMachine(String vmFqn) throws IOException {
return TaskManager.getInstance().addTask(new UndeployVMTask(vmFqn), URICreation.getVDC(vmFqn)).getTaskId();
}
@Override
public long deployNetwork(String netFqn, String ovf) throws IOException {
return TaskManager.getInstance().addTask(new DeployNetworkTask(netFqn, ovf), URICreation.getVDC(netFqn)).getTaskId();
}
@Override
public long deployVirtualMachine(String fqn, String ovf) throws IOException {
return TaskManager.getInstance().addTask(new DeployVMTask(fqn, ovf), URICreation.getVDC(fqn)).getTaskId();
}
public long powerActionVirtualMachine(String fqn, String action) throws IOException {
return TaskManager.getInstance().addTask(new ActionVMTask(fqn, action), URICreation.getVDC(fqn)).getTaskId();
}
public String getNetwork(String fqn) throws IOException {
// TODO Auto-generated method stub
return null;
}
@Override
public String getNetworkList() throws IOException {
// TODO Auto-generated method stub
return null;
}
@Override
public String getVirtualMachine(String fqn) throws IOException {
// TODO Auto-generated method stub
return null;
}
}
|
driver-one/src/main/java/com/telefonica/claudia/smi/provisioning/ONEProvisioningDriver.java
|
/*
* Claudia Project
* http://claudia.morfeo-project.org
*
* (C) Copyright 2010 Telefonica Investigacion y Desarrollo
* S.A.Unipersonal (Telefonica I+D)
*
* See CREDITS file for info about members and contributors.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the Affero GNU General Public License (AGPL) as
* published by the Free Software Foundation; either version 3 of the License,
* or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the Affero GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* If you want to use this software an plan to distribute a
* proprietary application in any way, and you are not licensing and
* distributing your source code under AGPL, you probably need to
* purchase a commercial license of the product. Please contact
* claudia-support@lists.morfeo-project.org for more information.
*/
package com.telefonica.claudia.smi.provisioning;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.StringTokenizer;
import javax.xml.namespace.QName;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.xmlrpc.XmlRpcException;
import org.apache.xmlrpc.client.XmlRpcClient;
import org.apache.xmlrpc.client.XmlRpcClientConfigImpl;
import org.dmtf.schemas.ovf.envelope._1.ContentType;
import org.dmtf.schemas.ovf.envelope._1.DiskSectionType;
import org.dmtf.schemas.ovf.envelope._1.EnvelopeType;
import org.dmtf.schemas.ovf.envelope._1.FileType;
import org.dmtf.schemas.ovf.envelope._1.ProductSectionType;
import org.dmtf.schemas.ovf.envelope._1.RASDType;
import org.dmtf.schemas.ovf.envelope._1.ReferencesType;
import org.dmtf.schemas.ovf.envelope._1.VirtualDiskDescType;
import org.dmtf.schemas.ovf.envelope._1.VirtualHardwareSectionType;
import org.dmtf.schemas.ovf.envelope._1.VirtualSystemCollectionType;
import org.dmtf.schemas.ovf.envelope._1.VirtualSystemType;
import org.dmtf.schemas.ovf.envelope._1.ProductSectionType.Property;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import com.abiquo.ovf.OVFEnvelopeUtils;
import com.abiquo.ovf.exceptions.EmptyEnvelopeException;
import com.abiquo.ovf.section.OVFProductUtils;
import com.abiquo.ovf.xml.OVFSerializer;
import com.telefonica.claudia.smi.DataTypesUtils;
import com.telefonica.claudia.smi.Main;
import com.telefonica.claudia.smi.TCloudConstants;
import com.telefonica.claudia.smi.URICreation;
import com.telefonica.claudia.smi.task.Task;
import com.telefonica.claudia.smi.task.TaskManager;
public class ONEProvisioningDriver implements ProvisioningDriver {
public static enum ControlActionType {shutdown, hold, release, stop, suspend, resume, finalize};
//public static enum VmStateType {INIT, PENDING, HOLD, ACTIVE, STOPPED, SUSPENDED, DONE, FAILED};
private final static int INIT_STATE = 0;
private final static int PENDING_STATE = 1;
private final static int HOLD_STATE = 2;
private final static int ACTIVE_STATE = 3;
private final static int STOPPED_STATE = 4;
private final static int SUSPENDED_STATE = 5;
private final static int DONE_STATE = 6;
private final static int FAILED_STATE = 7;
// LCM_INIT, PROLOG, BOOT, RUNNING, MIGRATE, SAVE_STOP, SAVE_SUSPEND, SAVE_MIGRATE, PROLOG_MIGRATE, EPILOG_STOP, EPILOG, SHUTDOWN, CANCEL
private final static int INIT_SUBSTATE = 0;
private final static int PROLOG_SUBSTATE = 1;
private final static int BOOT_SUBSTATE = 2;
private final static int RUNNING_SUBSTATE = 3;
private final static int MIGRATE_SUBSTATE = 4;
private final static int SAVE_STOP_SUBSTATE = 5;
private final static int SAVE_SUSPEND_SUBSTATE = 6;
private final static int SAVE_MIGRATE_SUBSTATE = 7;
private final static int PROLOG_MIGRATE_SUBSTATE = 8;
private final static int PROLOG_RESUME_SUBSTATE = 9;
private final static int EPILOG_STOP_SUBSTATE = 10;
private final static int EPILOG_SUBSTATE = 11;
private final static int SHUDTOWN_SUBSTATE = 12;
private final static int CANCEL_SUBSTATE = 13;
private HashMap<String, String> text_migrability = new HashMap();
private static org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger("com.telefonica.claudia.smi.provisioning.ONEProvisioningDriver");
// Tag names of the returning info doc for Virtual machines
public static final String VM_STATE = "STATE";
public static final String VM_SUBSTATE = "LCM_STATE";
// XMLRPC commands to access OpenNebula features
private final static String VM_ALLOCATION_COMMAND = "one.vm.allocate";
private final static String VM_UPDATE_COMMAND = "one.vm.action";
private final static String VM_GETINFO_COMMAND = "one.vm.info";
private final static String VM_GETALL_COMMAND = "one.vmpool.info";
private final static String VM_DELETE_COMMAND = "one.vm.delete";
private final static String NET_ALLOCATION_COMMAND = "one.vn.allocate";
private final static String NET_GETINFO_COMMAND = "one.vn.info";
private final static String NET_GETALL_COMMAND = "one.vnpool.info";
private final static String NET_DELETE_COMMAND = "one.vn.delete";
//private final static String DEBUGGING_CONSOLE = "RAW = [ type =\"kvm\", data =\"<devices><serial type='pty'><source path='/dev/pts/5'/><target port='0'/></serial><console type='pty' tty='/dev/pts/5'><source path='/dev/pts/5'/><target port='0'/></console></devices>\" ]";
/**
* Connection URL for OpenNebula. It defaults to localhost, but can be
* overriden with the property oneURL of the server configuration file.
*/
private String oneURL = "http://localhost:2633/RPC2";
/**
* Server configuration file URL property identifier.
*/
private final static String URL_PROPERTY = "oneUrl";
private final static String USER_PROPERTY = "oneUser";
private final static String PASSWORD_PROPERTY = "onePassword";
private static final String KERNEL_PROPERTY = "oneKernel";
private static final String INITRD_PROPERTY = "oneInitrd";
private static final String ARCH_PROPERTY = "arch";
private static final String ENVIRONMENT_PROPERTY = "oneEnvironmentPath";
private final static String SSHKEY_PROPERTY = "oneSshKey";
private final static String SCRIPTPATH_PROPERTY = "oneScriptPath";
private final static String ETH0_GATEWAY_PROPERTY = "eth0Gateway";
private final static String ETH0_DNS_PROPERTY = "eth0Dns";
private final static String ETH1_GATEWAY_PROPERTY = "eth1Gateway";
private final static String ETH1_DNS_PROPERTY = "eth1Dns";
private final static String NET_INIT_SCRIPT0 = "netInitScript0";
private final static String NET_INIT_SCRIPT1 = "netInitScript1";
private String oneSession = "oneadmin:5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8";
private XmlRpcClient xmlRpcClient = null;
private static final String NETWORK_BRIDGE = "oneNetworkBridge";
private static final String XEN_DISK = "xendisk";
/**
* Collection containing the mapping from fqns to ids. This mapped is used as a cache
* of the getVmId method (vm ids never change once assigned).
*/
private Map<String, Integer> idVmMap = new HashMap<String, Integer>();
/**
* Collection containing the mapping from fqns to ids. This mapped is used as a cache
* of the getVmId method (vm ids never change once assigned).
*/
private Map<String, Integer> idNetMap = new HashMap<String, Integer>();
private String hypervisorInitrd="";
private String arch="";
private String hypervisorKernel="";
private String customizationPort;
private String environmentRepositoryPath;
private static String networkBridge="";
private static String xendisk="";
private static String oneSshKey="";
private static String oneScriptPath="";
private static String eth0Gateway="";
private static String eth1Gateway="";
private static String eth0Dns="";
private static String eth1Dns="";
private static String netInitScript0="";
private static String netInitScript1="";
public static final String ASSIGNATION_SYMBOL = "=";
public static final String LINE_SEPARATOR = System.getProperty("line.separator");
public static final String ONE_VM_ID = "NAME";
public static final String ONE_VM_TYPE = "TYPE";
public static final String ONE_VM_STATE = "STATE";
public static final String ONE_VM_MEMORY = "MEMORY";
public static final String ONE_VM_NAME = "NAME";
public static final String ONE_VM_UUID = "UUID";
public static final String ONE_VM_CPU = "CPU";
public static final String ONE_VM_VCPU = "VCPU";
public static final String ONE_VM_RAW_VMI = "RAW_VMI";
public static final String ONE_VM_OS = "OS";
public static final String ONE_VM_OS_PARAM_KERNEL = "kernel";
public static final String ONE_VM_OS_PARAM_INITRD = "initrd";
public static final String ONE_VM_OS_PARAM_ROOT = "root";
public static final String ONE_VM_OS_PARAM_BOOT = "boot";
public static final String ONE_VM_GRAPHICS = "GRAPHICS";
public static final String ONE_VM_GRAPHICS_TYPE = "type";
public static final String ONE_VM_GRAPHICS_LISTEN = "listen";
public static final String ONE_VM_GRAPHICS_PORT = "port";
public static final String ONE_VM_DISK_COLLECTION = "DISKS";
public static final String ONE_VM_DISK = "DISK";
public static final String ONE_VM_DISK_PARAM_IMAGE = "source";
public static final String ONE_VM_DISK_PARAM_FORMAT = "format";
public static final String ONE_VM_DISK_PARAM_SIZE = "size";
public static final String ONE_VM_DISK_PARAM_TARGET = "target";
public static final String ONE_VM_DISK_PARAM_DIGEST = "digest";
public static final String ONE_VM_DISK_PARAM_TYPE = "type";
public static final String ONE_VM_DISK_PARAM_DRIVER = "driver";
public static final String ONE_VM_NIC_COLLECTION = "NICS";
public static final String ONE_VM_NIC = "NIC";
public static final String ONE_VM_NIC_PARAM_IP = "ip";
public static final String ONE_VM_NIC_PARAM_NETWORK = "NETWORK";
public static final String ONE_NET_ID = "ID";
public static final String ONE_NET_NAME = "NAME";
public static final String ONE_NET_BRIDGE = "BRIDGE";
public static final String ONE_NET_TYPE = "TYPE";
public static final String ONE_NET_ADDRESS = "NETWORK_ADDRESS";
public static final String ONE_NET_SIZE = "NETWORK_SIZE";
public static final String ONE_NET_LEASES = "LEASES";
public static final String ONE_NET_IP = "IP";
public static final String ONE_NET_MAC = "MAC";
public static final String ONE_DISK_ID = "ID";
public static final String ONE_DISK_NAME = "NAME";
public static final String ONE_DISK_URL = "URL";
public static final String ONE_DISK_SIZE = "SIZE";
public static final String ONE_OVF_URL = "OVF";
public static final String ONE_CONTEXT = "CONTEXT";
public static final String RESULT_NET_ID = "ID";
public static final String RESULT_NET_NAME = "NAME";
public static final String RESULT_NET_ADDRESS = "NETWORK_ADDRESS";
public static final String RESULT_NET_BRIDGE = "BRIDGE";
public static final String RESULT_NET_TYPE = "TYPE";
public static final String MULT_CONF_LEFT_DELIMITER = "[";
public static final String MULT_CONF_RIGHT_DELIMITER = "]";
public static final String MULT_CONF_SEPARATOR = ",";
public static final String QUOTE = "\"";
private static final int ResourceTypeCPU = 3;
private static final int ResourceTypeMEMORY = 4;
private static final int ResourceTypeNIC = 10;
private static final int ResourceTypeDISK = 17;
public class DeployVMTask extends Task {
public static final long POLLING_INTERVAL= 10000;
private static final int MAX_CONNECTION_ATEMPTS = 5;
String fqnVm;
String ovf;
public DeployVMTask(String fqn, String ovf) {
super();
this.fqnVm = fqn;
this.ovf = ovf;
}
@Override
public void execute() {
this.status = TaskStatus.RUNNING;
this.startTime = System.currentTimeMillis();
try {
// Create the Virtual Machine
String result = createVirtualMachine();
if (result==null) {
this.status= TaskStatus.ERROR;
this.endTime = System.currentTimeMillis();
return;
}
// Wait until the state is RUNNING
this.status = TaskStatus.WAITING;
int connectionAttempts=0;
while (true) {
try {
Document vmInfo = getVirtualMachineState(result);
Integer state = Integer.parseInt(vmInfo.getElementsByTagName(VM_STATE).item(0).getTextContent());
Integer subState = Integer.parseInt(vmInfo.getElementsByTagName(VM_SUBSTATE).item(0).getTextContent());
if (state == ACTIVE_STATE && subState == RUNNING_SUBSTATE ) {
this.status= TaskStatus.SUCCESS;
this.endTime = System.currentTimeMillis();
break;
} else if (state ==FAILED_STATE) {
this.status= TaskStatus.ERROR;
this.endTime = System.currentTimeMillis();
break;
}
connectionAttempts=0;
} catch (IOException ioe) {
if (connectionAttempts> MAX_CONNECTION_ATEMPTS) {
this.status= TaskStatus.ERROR;
this.endTime = System.currentTimeMillis();
break;
} else
connectionAttempts++;
log.warn("Connection exception accessing ONE. Trying again. Error: " + ioe.getMessage());
}
Thread.sleep(POLLING_INTERVAL);
}
} catch (IOException e) {
log.error("Error connecting to ONE: " + e.getMessage());
this.error = new TaskError();
this.error.message = e.getMessage();
this.status = TaskStatus.ERROR;
this.endTime = System.currentTimeMillis();
return;
} catch (Exception e) {
log.error("Unexpected error creating VM: " + e.getMessage());
this.error = new TaskError();
this.error.message = e.getMessage();
this.status = TaskStatus.ERROR;
this.endTime = System.currentTimeMillis();
e.printStackTrace();
return;
}
}
public String createVirtualMachine() throws Exception {
List<String> rpcParams = new ArrayList<String>();
rpcParams.add(oneSession);
rpcParams.add(TCloud2ONEVM(ovf, fqnVm));
Object[] result = null;
try {
result = (Object[])xmlRpcClient.execute(VM_ALLOCATION_COMMAND, rpcParams);
} catch (XmlRpcException ex) {
throw new IOException ("Error on allocation of VEE replica , XMLRPC call failed: " + ex.getMessage(), ex);
}
boolean success = (Boolean)result[0];
if(success) {
log.debug("Request succeded. Returining: \n\n" + ((Integer)result[1]).toString() + "\n\n");
this.returnMsg = "Virtual machine internal id: " + ((Integer)result[1]).toString();
return ((Integer)result[1]).toString();
} else {
log.error("Error recieved from ONE: " + (String)result[1]);
this.error = new TaskError();
this.error.message = (String)result[1];
return null;
}
}
}
public class DeployNetworkTask extends Task {
String fqnNet;
String ovf;
public DeployNetworkTask(String netFqn, String ovf) {
this.fqnNet = netFqn;
this.ovf = ovf;
}
@Override
public void execute() {
this.status = TaskStatus.RUNNING;
this.startTime = System.currentTimeMillis();
try {
if (!createNetwork()) {
this.status= TaskStatus.ERROR;
return;
}
this.status= TaskStatus.SUCCESS;
} catch (IOException e) {
log.error("Error connecting to ONE: " + e.getMessage());
this.error = new TaskError();
this.error.message = e.getMessage();
this.endTime = System.currentTimeMillis();
this.status = TaskStatus.ERROR;
return;
} catch (Exception e) {
log.error("Unknown error creating network: " + e.getMessage());
this.error = new TaskError();
this.error.message = e.getMessage();
this.endTime = System.currentTimeMillis();
this.status = TaskStatus.ERROR;
}
}
public boolean createNetwork() throws Exception {
List<String> rpcParams = new ArrayList<String>();
rpcParams.add(oneSession);
rpcParams.add(TCloud2ONENet(ovf));
Object[] result = null;
try {
result = (Object[])xmlRpcClient.execute(NET_ALLOCATION_COMMAND, rpcParams);
} catch (XmlRpcException ex) {
log.error("Connection error. Could not reach ONE host: " + ex.getMessage());
throw new IOException ("Error on allocation of the new network , XMLRPC call failed", ex);
}
boolean success = (Boolean)result[0];
if(success) {
log.debug("Network creation request succeded: " + result[1]);
this.returnMsg = ((Integer)result[1]).toString();
return true;
} else {
log.error("Error recieved from ONE: " + (String)result[1]);
this.error = new TaskError();
this.error.message = (String)result[1];
return false;
}
}
}
public class UndeployVMTask extends Task {
String fqnVm;
public UndeployVMTask(String vmFqn) {
this.fqnVm = vmFqn;
}
@Override
public void execute() {
this.status= TaskStatus.RUNNING;
this.startTime = System.currentTimeMillis();
// Undeploy the VM
try {
String id = getVmId(fqnVm).toString();
deleteVirtualMachine(id);
this.status= TaskStatus.SUCCESS;
this.endTime = System.currentTimeMillis();
} catch (IOException e) {
log.error("Error connecting to ONE: " + e.getMessage());
this.error = new TaskError();
this.error.message = e.getMessage();
this.status = TaskStatus.ERROR;
this.endTime = System.currentTimeMillis();
return;
} catch (Exception e) {
log.error("Unknown error undeploying VM: " + e.getMessage());
this.error = new TaskError();
this.error.message = e.getMessage();
this.status = TaskStatus.ERROR;
this.endTime = System.currentTimeMillis();
return;
}
}
@SuppressWarnings("unchecked")
public boolean deleteVirtualMachine(String id) throws IOException {
List rpcParams = new ArrayList ();
ControlActionType controlAction = ControlActionType.finalize;
log.info("PONG deleteVirtualMachine id: "+ id);
rpcParams.add(oneSession);
rpcParams.add(controlAction.toString());
rpcParams.add(Integer.parseInt(id));
Object[] result = null;
try {
result = (Object[])xmlRpcClient.execute(VM_UPDATE_COMMAND, rpcParams);
} catch (XmlRpcException ex) {
log.error("Connection error trying to update VM: " + ex.getMessage());
throw new IOException ("Error updating VEE replica , XMLRPC call failed", ex);
}
if (result==null) {
throw new IOException("No result returned from XMLRPC call");
} else {
return (Boolean)result[0];
}
}
}
public class UndeployNetworkTask extends Task {
String fqnNet;
public UndeployNetworkTask(String netFqn) {
this.fqnNet = netFqn;
}
@Override
public void execute() {
this.status= TaskStatus.RUNNING;
this.startTime = System.currentTimeMillis();
// Undeploy the VM
try {
deleteNetwork(getNetId(fqnNet).toString());
this.status= TaskStatus.SUCCESS;
this.endTime = System.currentTimeMillis();
} catch (IOException e) {
log.error("Error connecting to ONE: " + e.getMessage());
this.error = new TaskError();
this.error.message = e.getMessage();
this.status = TaskStatus.ERROR;
this.endTime = System.currentTimeMillis();
return;
} catch (Exception e) {
log.error("Unknown error undeploying Network: " + e.getMessage());
this.error = new TaskError();
this.error.message = e.getMessage();
this.status = TaskStatus.ERROR;
this.endTime = System.currentTimeMillis();
return;
}
}
@SuppressWarnings("unchecked")
public void deleteNetwork(String id) throws IOException {
List rpcParams = new ArrayList<String>();
rpcParams.add(oneSession);
rpcParams.add(new Integer(id) );
Object[] result = null;
try {
result = (Object[])xmlRpcClient.execute(NET_DELETE_COMMAND, rpcParams);
} catch (XmlRpcException ex) {
throw new IOException ("Error deleting the network , XMLRPC call failed", ex);
}
boolean success = (Boolean)result[0];
if(success) {
} else {
throw new IOException("Unknown error trying to delete network: " + (String)result[1]);
}
}
}
public class ActionVMTask extends Task {
String fqnVM;
String action;
String errorMessage="";
public ActionVMTask(String fqnVM, String action) {
this.fqnVM = fqnVM;
this.action = action;
}
@Override
public void execute() {
this.status= TaskStatus.RUNNING;
this.startTime = System.currentTimeMillis();
// Undeploy the VM
try {
boolean result = doAction();
if (result)
this.status= TaskStatus.SUCCESS;
else {
this.status = TaskStatus.ERROR;
this.error = new TaskError();
this.error.message = errorMessage;
}
this.endTime = System.currentTimeMillis();
} catch (IOException e) {
log.error("Error connecting to VMWare: " + e.getMessage());
this.error = new TaskError();
this.error.message = e.getMessage();
this.status = TaskStatus.ERROR;
this.endTime = System.currentTimeMillis();
return;
} catch (Exception e) {
log.error("Unknown error executing action" + action + ": " + e.getMessage() + " -> " + e.getClass().getCanonicalName());
this.error = new TaskError();
this.error.message = e.getMessage();
this.status = TaskStatus.ERROR;
this.endTime = System.currentTimeMillis();
return;
}
}
public boolean doAction() throws Exception {
System.out.println("Executing action: " + action);
return true;
}
}
protected String TCloud2ONEVM(String xml, String veeFqn) throws Exception {
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new ByteArrayInputStream(xml.getBytes()));
if (!doc.getFirstChild().getNodeName().equals(TCloudConstants.TAG_INSTANTIATE_OVF)) {
log.error("Element <"+TCloudConstants.TAG_INSTANTIATE_OVF+"> not found.");
throw new Exception("Element <"+TCloudConstants.TAG_INSTANTIATE_OVF+"> not found.");
}
Element root = (Element) doc.getFirstChild();
String replicaName = root.getAttribute("name");
NodeList envelopeItems = doc.getElementsByTagNameNS("*", "Envelope");
if (envelopeItems.getLength() != 1) {
log.error("Envelope items not found.");
throw new Exception("Envelope items not found.");
}
// Extract the IP from the aspects section
Map<String, String> ipOnNetworkMap = new HashMap<String, String>();
NodeList aspects = doc.getElementsByTagNameNS("*", "Aspect");
for (int i=0; i < aspects.getLength(); i++) {
Element aspect = (Element) aspects.item(i);
if (aspect.getAttribute("name").equals("IP Config")) {
NodeList properties = aspect.getElementsByTagNameNS("*", "Property");
for (int j=0; j < properties.getLength(); j++) {
Element property = (Element) properties.item(j);
NodeList keys = property.getElementsByTagNameNS("*", "Key");
NodeList values = property.getElementsByTagNameNS("*", "Value");
if (keys.getLength() >0 && values.getLength()>0) {
ipOnNetworkMap.put(keys.item(0).getTextContent(), values.item(0).getTextContent());
}
}
}
}
// Extract the ovf sections and pass them to the OVF manager to be processed.
Document ovfDoc = builder.newDocument();
ovfDoc.appendChild(ovfDoc.importNode(envelopeItems.item(0), true));
OVFSerializer ovfSerializer = OVFSerializer.getInstance();
ovfSerializer.setValidateXML(false);
EnvelopeType envelope = ovfSerializer.readXMLEnvelope(new ByteArrayInputStream(DataTypesUtils.serializeXML(ovfDoc).getBytes()));
ContentType entityInstance = OVFEnvelopeUtils.getTopLevelVirtualSystemContent(envelope);
if (entityInstance instanceof VirtualSystemType) {
VirtualSystemType vs = (VirtualSystemType) entityInstance;
VirtualHardwareSectionType vh = OVFEnvelopeUtils.getSection(vs, VirtualHardwareSectionType.class);
String virtualizationType = vh.getSystem().getVirtualSystemType().getValue();
String scriptListProp = null;
String scriptListTemplate = "";
String hostname=null;
ProductSectionType productSection;
productSection = OVFEnvelopeUtils.getSection(vs, ProductSectionType.class);
try
{
Property prop = OVFProductUtils.getProperty(productSection, "SCRIPT_LIST");
scriptListProp = prop.getValue().toString();
String[] scriptList = scriptListProp.split("/");
scriptListTemplate = "";
for (String scrt: scriptList){
scriptListTemplate = scriptListTemplate + " "+oneScriptPath+"/"+scrt;
}
}
catch (Exception e)
{
//TODO throw PropertyNotFoundException
//logger.error(e);
scriptListProp="";
scriptListTemplate = "";
}
String netcontext=getNetContext(vh, veeFqn,xml, scriptListProp);
try
{
Property prop = OVFProductUtils.getProperty(productSection, "HOSTNAME");
hostname = prop.getValue().toString();
}
catch (Exception e)
{
//TODO throw PropertyNotFoundException
//logger.error(e);
hostname="";
}
StringBuffer allParametersString = new StringBuffer();
// Migrability ....
allParametersString.append(ONE_VM_NAME).append(ASSIGNATION_SYMBOL).append(replicaName).append(LINE_SEPARATOR);
if (virtualizationType.toLowerCase().equals("kvm")) {
allParametersString.append("REQUIREMENTS").append(ASSIGNATION_SYMBOL).append("\"HYPERVISOR=\\\"kvm\\\"\"").append(LINE_SEPARATOR);
} else if (virtualizationType.toLowerCase().equals("xen")) {
allParametersString.append("REQUIREMENTS").append(ASSIGNATION_SYMBOL).append("\"HYPERVISOR=\\\"xen\\\"\"").append(LINE_SEPARATOR);
}
allParametersString.append(ONE_VM_OS).append(ASSIGNATION_SYMBOL).append(MULT_CONF_LEFT_DELIMITER);
String diskRoot;
if (virtualizationType.toLowerCase().equals("kvm")) {
diskRoot = "h";
allParametersString.append(ONE_VM_OS_PARAM_BOOT).append(ASSIGNATION_SYMBOL).append("hd").append(MULT_CONF_SEPARATOR).append(LINE_SEPARATOR);
} else {
diskRoot = xendisk;
allParametersString.append(ONE_VM_OS_PARAM_INITRD).append(ASSIGNATION_SYMBOL).append(hypervisorInitrd).append(MULT_CONF_SEPARATOR).append(LINE_SEPARATOR);
allParametersString.append(ONE_VM_OS_PARAM_KERNEL).append(ASSIGNATION_SYMBOL).append(hypervisorKernel).append(MULT_CONF_SEPARATOR).append(LINE_SEPARATOR);
}
if(arch.length()>0)
allParametersString.append("ARCH").append(ASSIGNATION_SYMBOL).append("\"").append(arch).append("\"").append(MULT_CONF_SEPARATOR).append(LINE_SEPARATOR);
allParametersString.append(ONE_VM_OS_PARAM_ROOT).append(ASSIGNATION_SYMBOL).append(diskRoot + "da1").append(MULT_CONF_RIGHT_DELIMITER).append(LINE_SEPARATOR);
allParametersString.append(ONE_CONTEXT).append(ASSIGNATION_SYMBOL).append(MULT_CONF_LEFT_DELIMITER);
if(hostname.length()>0) {
allParametersString.append("hostname = \""+hostname+"\"").append(MULT_CONF_SEPARATOR).append(LINE_SEPARATOR);
}
allParametersString.append(netcontext);
allParametersString.append("public_key").append(ASSIGNATION_SYMBOL).append(oneSshKey).append(MULT_CONF_SEPARATOR).append(LINE_SEPARATOR);
allParametersString.append("CustomizationUrl").append(ASSIGNATION_SYMBOL).append("\"" + Main.PROTOCOL + Main.serverHost + ":" + customizationPort + "/"+ replicaName+ "\"").append(MULT_CONF_SEPARATOR).append(LINE_SEPARATOR);
allParametersString.append("files").append(ASSIGNATION_SYMBOL).append("\"" + environmentRepositoryPath + "/"+ replicaName + "/ovf-env.xml" +scriptListTemplate+ "\"").append(MULT_CONF_SEPARATOR).append(LINE_SEPARATOR);
allParametersString.append("target").append(ASSIGNATION_SYMBOL).append("\"" + diskRoot + "dd"+ "\"").append(MULT_CONF_RIGHT_DELIMITER).append(LINE_SEPARATOR);
if (vh.getSystem() != null && vh.getSystem().getVirtualSystemType()!= null &&
vh.getSystem().getVirtualSystemType().getValue() != null &&
vh.getSystem().getVirtualSystemType().getValue().equals("vjsc"))
{
allParametersString.append("HYPERVISOR").append(ASSIGNATION_SYMBOL).append("VJSC").append(LINE_SEPARATOR);
}
char sdaId = 'a';
List<RASDType> items = vh.getItem();
for (Iterator<RASDType> iteratorRASD = items.iterator(); iteratorRASD.hasNext();) {
RASDType item = (RASDType) iteratorRASD.next();
/* Get the resource type and process it accordingly */
int rsType = new Integer(item.getResourceType().getValue());
int quantity = 1;
if (item.getVirtualQuantity() != null) {
quantity = item.getVirtualQuantity().getValue().intValue();
}
switch (rsType) {
case ResourceTypeCPU:
// for (int k = 0; k < quantity; k++) {
allParametersString.append(ONE_VM_CPU).append(ASSIGNATION_SYMBOL).append(quantity).append(LINE_SEPARATOR);
allParametersString.append(ONE_VM_VCPU).append(ASSIGNATION_SYMBOL).append(quantity).append(LINE_SEPARATOR);
// }
break;
case ResourceTypeDISK:
/*
* The rasd:HostResource will follow the pattern
* 'ovf://disk/<id>' where id is the ovf:diskId of some
* <Disk>
*/
String hostRes = item.getHostResource().get(0).getValue();
StringTokenizer st = new StringTokenizer(hostRes, "/");
/*
* Only ovf:/<file|disk>/<n> format is valid, accodring
* OVF spec
*/
if (st.countTokens() != 3) {
throw new IllegalArgumentException("malformed HostResource value (" + hostRes + ")");
}
if (!(st.nextToken().equals("ovf:"))) {
throw new IllegalArgumentException("HostResource must start with ovf: (" + hostRes + ")");
}
String hostResType = st.nextToken();
if (!(hostResType.equals("disk") || hostResType.equals("file"))) {
throw new IllegalArgumentException("HostResource type must be either disk or file: (" + hostRes + ")");
}
String hostResId = st.nextToken();
String fileRef = null;
String capacity = null;
String format = null;
if (hostResType.equals("disk")) {
/* This type involves an indirection level */
DiskSectionType ds = null;
ds = OVFEnvelopeUtils.getSection(envelope, DiskSectionType.class);
List<VirtualDiskDescType> disks = ds.getDisk();
for (Iterator<VirtualDiskDescType> iteratorDk = disks.iterator(); iteratorDk.hasNext();) {
VirtualDiskDescType disk = iteratorDk.next();
String diskId = disk.getDiskId();
if (diskId.equals(hostResId)) {
fileRef = disk.getFileRef();
capacity = disk.getCapacity();
format = disk.getFormat();
break;
}
}
} else {
throw new IllegalArgumentException("File type not supported in Disk sections.");
}
/* Throw exceptions in the case of missing information */
if (fileRef == null) {
log.warn("file reference can not be found for disk: " + hostRes);
}
URL url = null;
String digest = null;
String driver = null;
ReferencesType ref = envelope.getReferences();
List<FileType> files = ref.getFile();
for (Iterator<FileType> iteratorFl = files.iterator(); iteratorFl.hasNext();) {
FileType fl = iteratorFl.next();
if (fileRef!=null)
{
if (fl.getId().equals(fileRef)) {
try {
url = new URL(fl.getHref());
} catch (MalformedURLException e) {
throw new IllegalArgumentException("problems parsing disk href: " + e.getMessage());
}
}
/*
* If capacity was not set using ovf:capacity in
* <Disk>, try to get it know frm <File>
* ovf:size
*/
if (capacity == null && fl.getSize() != null) {
capacity = fl.getSize().toString();
}
/* Try to get the digest */
Map<QName, String> attributesFile = fl.getOtherAttributes();
QName digestAtt = new QName("http://schemas.telefonica.com/claudia/ovf","digest");
digest = attributesFile.get(digestAtt);
Map<QName, String> attributesFile2 = fl.getOtherAttributes();
QName driverAtt = new QName("http://schemas.telefonica.com/claudia/ovf","driver");
driver = attributesFile.get(driverAtt);
break;
}
}
/* Throw exceptions in the case of missing information */
if (capacity == null) {
throw new IllegalArgumentException("capacity can not be set for disk " + hostRes);
}
if (url == null && fileRef!=null) {
throw new IllegalArgumentException("url can not be set for disk " + hostRes);
}
if (digest == null) {
log.debug("md5sum digest was not found for disk " + hostRes);
}
String urlDisk = null;
if (url != null)
{
urlDisk = url.toString();
if (urlDisk.contains("file:/"))
urlDisk = urlDisk.replace("file:/", "file:///");
}
File filesystem = new File("/dev/" + diskRoot + "d" + sdaId);
allParametersString.append(ONE_VM_DISK).append(ASSIGNATION_SYMBOL).append(MULT_CONF_LEFT_DELIMITER);
if (urlDisk!= null)
allParametersString.append(ONE_VM_DISK_PARAM_IMAGE).append(ASSIGNATION_SYMBOL).append(urlDisk).append(MULT_CONF_SEPARATOR);
if (virtualizationType.toLowerCase().equals("kvm")) {
allParametersString.append(ONE_VM_DISK_PARAM_TARGET).append(ASSIGNATION_SYMBOL).append(diskRoot + "d" + sdaId).append(MULT_CONF_SEPARATOR);
} else
allParametersString.append(ONE_VM_DISK_PARAM_TARGET).append(ASSIGNATION_SYMBOL).append(filesystem.getAbsolutePath()).append(MULT_CONF_SEPARATOR);
if (format!=null)
{
if (format.equals("ext3"))
{
allParametersString.append(ONE_VM_DISK_PARAM_TYPE).append(ASSIGNATION_SYMBOL).append("fs").append(MULT_CONF_SEPARATOR);
}
allParametersString.append(ONE_VM_DISK_PARAM_FORMAT).append(ASSIGNATION_SYMBOL).append(format).append(MULT_CONF_SEPARATOR);
}
if (driver!=null)
allParametersString.append(ONE_VM_DISK_PARAM_DRIVER).append(ASSIGNATION_SYMBOL).append(driver).append(MULT_CONF_SEPARATOR);
if (digest!=null)
allParametersString.append(ONE_VM_DISK_PARAM_DIGEST).append(ASSIGNATION_SYMBOL).append(digest).append(MULT_CONF_SEPARATOR);
allParametersString.append(ONE_VM_DISK_PARAM_SIZE).append(ASSIGNATION_SYMBOL).append(capacity);
allParametersString.append(MULT_CONF_RIGHT_DELIMITER).append(LINE_SEPARATOR);
sdaId++;
break;
case ResourceTypeMEMORY:
allParametersString.append(ONE_VM_MEMORY).append(ASSIGNATION_SYMBOL).append(quantity).append(LINE_SEPARATOR);
break;
case ResourceTypeNIC:
String fqnNet = URICreation.getService(veeFqn) + ".networks." + item.getConnection().get(0).getValue();
allParametersString.append(ONE_VM_NIC).append(ASSIGNATION_SYMBOL).append(MULT_CONF_LEFT_DELIMITER).append(LINE_SEPARATOR);
allParametersString.append(ONE_NET_BRIDGE).append(ASSIGNATION_SYMBOL).append(networkBridge).append(MULT_CONF_SEPARATOR).append(LINE_SEPARATOR).
append(ONE_VM_NIC_PARAM_NETWORK).append(ASSIGNATION_SYMBOL).append(fqnNet).append(MULT_CONF_SEPARATOR).append(LINE_SEPARATOR).
append(ONE_VM_NIC_PARAM_IP).append(ASSIGNATION_SYMBOL).append(ipOnNetworkMap.get(fqnNet)).append(LINE_SEPARATOR).
append(MULT_CONF_RIGHT_DELIMITER).append(LINE_SEPARATOR);
break;
default:
throw new IllegalArgumentException("unknown hw type: " + rsType);
}
}
//allParametersString.append(LINE_SEPARATOR).append(DEBUGGING_CONSOLE).append(LINE_SEPARATOR);
log.debug("VM data sent:\n\n" + allParametersString.toString() + "\n\n");
System.out.println("VM data sent:\n\n" + allParametersString.toString() + "\n\n");
return allParametersString.toString();
} else {
throw new IllegalArgumentException("OVF malformed. No VirtualSystemType found.");
}
} catch (IOException e1) {
log.error("OVF of the virtual machine was not well formed or it contained some errors.");
throw new Exception("OVF of the virtual machine was not well formed or it contained some errors: " + e1.getMessage());
} catch (ParserConfigurationException e) {
log.error("Error configuring parser: " + e.getMessage());
throw new Exception("Error configuring parser: " + e.getMessage());
} catch (FactoryConfigurationError e) {
log.error("Error retrieving parser: " + e.getMessage());
throw new Exception("Error retrieving parser: " + e.getMessage());
} catch (Exception e) {
log.error("Error configuring a XML Builder.");
throw new Exception("Error configuring a XML Builder: " + e.getMessage());
}
}
protected static String ONEVM2TCloud(String ONETemplate) {
// TODO: ONE Template to TCloud translation
return "";
}
protected static String getNetContext(VirtualHardwareSectionType vh, String veeFqn,String xml, String scriptListProp) throws Exception {
// log.debug("PONG2 xml" +xml+ "\n");
StringBuffer allParametersString = new StringBuffer();
List<RASDType> items = vh.getItem();
int i=0;
for (Iterator<RASDType> iteratorRASD = items.iterator(); iteratorRASD.hasNext();) {
RASDType item = (RASDType) iteratorRASD.next();
/* Get the resource type and process it accordingly */
int rsType = new Integer(item.getResourceType().getValue());
int quantity = 1;
if (item.getVirtualQuantity() != null) {
quantity = item.getVirtualQuantity().getValue().intValue();
}
switch (rsType) {
case ResourceTypeNIC:
try {
// log.debug("PONG eth0Dns" + eth0Dns + "\n");
// log.debug("PONG eth0Gateway" + eth0Gateway + "\n");
// log.debug("PONG eth1Dns" + eth1Dns + "\n");
// log.debug("PONG eth1Gateway" + eth1Gateway + "\n");
String fqnNet = URICreation.getService(veeFqn) + ".networks." + item.getConnection().get(0).getValue();
allParametersString.append("ip_eth"+i).append(ASSIGNATION_SYMBOL).append("\"$NIC[IP, NETWORK=\\\""+fqnNet+"\\\"]\"").append(MULT_CONF_SEPARATOR).append(LINE_SEPARATOR);
String dns="";
String gateway="";
if(i==0){
dns=eth0Dns;
gateway=eth0Gateway;
}
if(i==1){
dns=eth1Dns;
gateway=eth1Gateway;
}
if(dns.length()>0)
{
allParametersString.append("dns_eth"+i).append(ASSIGNATION_SYMBOL).append(dns).append(MULT_CONF_SEPARATOR).append(LINE_SEPARATOR);
}
if(gateway.length()>0)
{
allParametersString.append("gateway_eth"+i).append(ASSIGNATION_SYMBOL).append(gateway).append(MULT_CONF_SEPARATOR).append(LINE_SEPARATOR);
}
i++;
} catch (FactoryConfigurationError e) {
log.error("Error retrieving parser: " + e.getMessage());
throw new Exception("Error retrieving parser: " + e.getMessage());
} catch (Exception e) {
log.error("Error configuring a XML Builder.");
throw new Exception("Error configuring a XML Builder: " + e.getMessage());
}
break;
default:
//throw new IllegalArgumentException("unknown hw type: " + rsType);
}
}
if (i==1){
if(netInitScript0.length()>0) {
allParametersString.append("SCRIPT_EXEC=\""+netInitScript0);
}
}
if (i==2){
if(netInitScript1.length()>0) {
allParametersString.append("SCRIPT_EXEC=\""+netInitScript1);
}
}
if (scriptListProp != null & scriptListProp.length()!=0)
{
String[] scriptList = scriptListProp.split("/");
String scriptListTemplate = "";
for (String scrt: scriptList){
if (scrt.indexOf(".py")!=-1)
{
if (scrt.equals("OVFParser.py")) {
System.out.println ("python /mnt/stratuslab/"+scrt);
allParametersString.append("; python /mnt/stratuslab/"+scrt+"");
}
if (scrt.equals("restful-server.py")) {
System.out.println ("/etc/init.d/lb_server start");
allParametersString.append("; /etc/init.d/lb_server start");
}
if (scrt.equals("torqueProbe.py")) {
System.out.println ("/etc/init.d/probe start");
allParametersString.append("; /etc/init.d/probe start");
}
}
}
}
allParametersString.append("\"").append(MULT_CONF_SEPARATOR).append(LINE_SEPARATOR);
return allParametersString.toString();
}
protected static String TCloud2ONENet(String xml) throws Exception {
try {
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(new ByteArrayInputStream(xml.getBytes()));
// log.debug("PONG3 doc" +doc.getTextContent()+ "\n");
Element root = (Element) doc.getFirstChild();
String fqn = root.getAttribute(TCloudConstants.ATTR_NETWORK_NAME);
// log.debug("PONG3 fqn" + fqn + "\n");
NodeList macEnabled = doc.getElementsByTagName(TCloudConstants.TAG_NETWORK_MAC_ENABLED);
Element firstmacenElement = (Element)macEnabled.item(0);
NodeList textMacenList = firstmacenElement.getChildNodes();
String macenabled= ((Node)textMacenList.item(0)).getNodeValue().trim();
NodeList netmaskList = doc.getElementsByTagName(TCloudConstants.TAG_NETWORK_NETMASK);
NodeList baseAddressList = doc.getElementsByTagName(TCloudConstants.TAG_NETWORK_BASE_ADDRESS);
StringBuffer allParametersString = new StringBuffer();
String privateNet = null;
if (root.getAttribute(TCloudConstants.ATTR_NETWORK_TYPE).equals("true"))
privateNet = "private";
else
privateNet ="public";
// If there is a netmask, calculate the size of the net counting it's bits.
if (netmaskList.getLength() >0) {
Element netmask = (Element) netmaskList.item(0);
if (!netmask.getTextContent().matches("\\d+\\.\\d+\\.\\d+\\.\\d+"))
throw new IllegalArgumentException("Wrong IPv4 format. Expected example: 192.168.0.0 Got: " + netmask.getTextContent());
String[] ipBytes = netmask.getTextContent().split("\\.");
short[] result = new short[4];
for (int i=0; i < 4; i++) {
try {
result[i] = Short.parseShort(ipBytes[i]);
if (result[i]>255) throw new NumberFormatException("Should be in the range [0-255].");
} catch (NumberFormatException nfe) {
throw new IllegalArgumentException("Number out of bounds. Bytes should be on the range 0-255.");
}
}
// The network can host 2^n where n is the number of bits in the network address,
// substracting the broadcast and the network value (all 1s and all 0s).
int size = (int) Math.pow(2, 32.0-getBitNumber(result));
if (size < 8)
size = 8;
else
size -= 2;
if (macenabled.equals("false"))
allParametersString.append(ONE_NET_SIZE).append(ASSIGNATION_SYMBOL).append(size).append(LINE_SEPARATOR);
}
if (baseAddressList.getLength()>0) {
if (macenabled.equals("false"))
allParametersString.append(ONE_NET_ADDRESS).append(ASSIGNATION_SYMBOL).append(baseAddressList.item(0).getTextContent()).append(LINE_SEPARATOR);
}
// Translate the simple data to RPC format
allParametersString.append(ONE_NET_NAME).append(ASSIGNATION_SYMBOL).append(fqn).append(LINE_SEPARATOR);
// Add the net Type
if (macenabled.equals("false")) {
allParametersString.append(ONE_NET_TYPE).append(ASSIGNATION_SYMBOL).append("RANGED").append(LINE_SEPARATOR);
}
else {
allParametersString.append(ONE_NET_TYPE).append(ASSIGNATION_SYMBOL).append("FIXED").append(LINE_SEPARATOR);
}
allParametersString.append(ONE_NET_BRIDGE).append(ASSIGNATION_SYMBOL).append(networkBridge).append(LINE_SEPARATOR);
NodeList ipLeaseList = doc.getElementsByTagName(TCloudConstants.TAG_NETWORK_IPLEASES);
for (int i=0; i<ipLeaseList .getLength(); i++){
Node firstIpLeaseNode = ipLeaseList.item(i);
if (firstIpLeaseNode.getNodeType() == Node.ELEMENT_NODE){
Element firstIpLeaseElement = (Element)firstIpLeaseNode;
NodeList ipList =firstIpLeaseElement.getElementsByTagName(TCloudConstants.TAG_NETWORK_IP);
Element firstIpElement = (Element)ipList.item(0);
NodeList textIpList = firstIpElement.getChildNodes();
String ipString = ("IP="+((Node)textIpList.item(0)).getNodeValue().trim());
NodeList macList =firstIpLeaseElement.getElementsByTagName(TCloudConstants.TAG_NETWORK_MAC);
Element firstMacElement = (Element)macList.item(0);
NodeList textMacList = firstMacElement.getChildNodes();
String macString = ("MAC="+((Node)textMacList.item(0)).getNodeValue().trim());
allParametersString.append(ONE_NET_LEASES).append(ASSIGNATION_SYMBOL).append(MULT_CONF_LEFT_DELIMITER);
allParametersString.append(ipString).append(MULT_CONF_SEPARATOR).append(macString).append(MULT_CONF_RIGHT_DELIMITER).append(LINE_SEPARATOR);
}
}
log.debug("Network data sent:\n\n" + allParametersString.toString() + "\n\n");
return allParametersString.toString();
} catch (IOException e1) {
log.error("OVF of the virtual machine was not well formed or it contained some errors.");
throw new Exception("OVF of the virtual machine was not well formed or it contained some errors: " + e1.getMessage());
} catch (ParserConfigurationException e) {
log.error("Error configuring parser: " + e.getMessage());
throw new Exception("Error configuring parser: " + e.getMessage());
} catch (FactoryConfigurationError e) {
log.error("Error retrieving parser: " + e.getMessage());
throw new Exception("Error retrieving parser: " + e.getMessage());
} catch (Exception e) {
log.error("Error configuring a XML Builder.");
throw new Exception("Error configuring a XML Builder: " + e.getMessage());
}
}
protected static String ONENet2TCloud(String ONETemplate) {
return "";
}
/**
* Get the number of bits with value 1 in the given IP.
*
* @return
*/
public static int getBitNumber (short[] ip) {
if (ip == null || ip.length != 4)
return 0;
int bits=0;
for (int i=0; i < 4; i++)
for (int j=0; j< 15; j++)
bits += ( ((short)Math.pow(2, j))& ip[i]) / Math.pow(2, j);
return bits;
}
/**
* Retrieve the virtual network id given its fqn.
*
* @param fqn
* FQN of the Virtual Network (mapped to its name property in ONE).
*
* @return
* The internal id of the Virtual Network if it exists or -1 otherwise.
*
* @throws Exception
*
*/
protected Integer getNetId(String fqn) throws Exception {
if (!idNetMap.containsKey(fqn))
idNetMap = getNetworkIds();
if (idNetMap.containsKey(fqn))
return idNetMap.get(fqn);
else
return -1;
}
/**
* Retrieve the vm's id given its fqn.
*
* @param fqn
* FQN of the Virtual Machine (mapped to its name property in ONE).
*
* @return
* The internal id of the Virtual Machine if it exists or -1 otherwise.
*
* @throws Exception
*
*/
protected Integer getVmId(String fqn) throws Exception {
if (!idVmMap.containsKey(fqn))
idVmMap = getVmIds();
if (idVmMap.containsKey(fqn))
return idVmMap.get(fqn);
else
return -1;
}
/**
* Retrieve a map of the currently deployed VMs, and its ids.
*
* @return
* A map where the key is the VM's FQN and the value the VM's id.
* @throws Exception
*/
@SuppressWarnings("unchecked")
protected Map<String, Integer> getVmIds() throws Exception {
List rpcParams = new ArrayList<String>();
rpcParams.add(oneSession);
rpcParams.add(-2);
HashMap<String, Integer> mapResult = new HashMap<String, Integer>();
Object[] result = null;
try {
result = (Object[])xmlRpcClient.execute(VM_GETALL_COMMAND, rpcParams);
} catch (XmlRpcException ex) {
throw new IOException ("Error obtaining the VM list: " + ex.getMessage(), ex);
}
boolean success = (Boolean)result[0];
if(success) {
String resultList = (String) result[1];
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new ByteArrayInputStream(resultList.getBytes()));
NodeList vmList = doc.getElementsByTagName("VM");
for (int i=0; i < vmList.getLength(); i++) {
Element vm = (Element) vmList.item(i);
String fqn = ((Element)vm.getElementsByTagName("NAME").item(0)).getTextContent();
try {
Integer value = Integer.parseInt(((Element)vm.getElementsByTagName("ID").item(0)).getTextContent());
mapResult.put(fqn, value);
} catch(NumberFormatException nfe) {
log.warn("Numerical id expected, got [" + ((Element)vm.getElementsByTagName("ID").item(0)).getTextContent() + "]");
continue;
}
}
return mapResult;
} catch (ParserConfigurationException e) {
log.error("Parser Configuration Error: " + e.getMessage());
throw new IOException ("Parser Configuration Error", e);
} catch (SAXException e) {
log.error("Parse error reading the answer: " + e.getMessage());
throw new IOException ("XML Parse error", e);
}
} else {
log.error("Error recieved from ONE: " + result[1]);
throw new Exception("Error recieved from ONE: " + result[1]);
}
}
@SuppressWarnings("unchecked")
protected HashMap<String, Integer> getNetworkIds() throws IOException {
List rpcParams = new ArrayList();
rpcParams.add(oneSession);
rpcParams.add(-2);
Object[] result = null;
try {
result = (Object[])xmlRpcClient.execute(NET_GETALL_COMMAND, rpcParams);
} catch (XmlRpcException ex) {
throw new IOException ("Error obtaining the network list", ex);
}
boolean success = (Boolean)result[0];
if(success) {
HashMap<String, Integer> mapResult = new HashMap<String, Integer>();
String resultList = (String) result[1];
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new ByteArrayInputStream(resultList.getBytes()));
NodeList vmList = doc.getElementsByTagName("VNET");
for (int i=0; i < vmList.getLength(); i++) {
Element vm = (Element) vmList.item(i);
String fqn = ((Element)vm.getElementsByTagName("NAME").item(0)).getTextContent();
try {
Integer value = Integer.parseInt(((Element)vm.getElementsByTagName("ID").item(0)).getTextContent());
mapResult.put(fqn, value);
} catch(NumberFormatException nfe) {
log.warn("Numerical id expected, got [" + ((Element)vm.getElementsByTagName("ID").item(0)).getTextContent() + "]");
continue;
}
}
return mapResult;
} catch (ParserConfigurationException e) {
throw new IOException ("Parser Configuration Error", e);
} catch (SAXException e) {
throw new IOException ("XML Parse error", e);
}
} else {
throw new IOException("Error recieved from ONE: " +(String)result[1]);
}
}
public ONEProvisioningDriver(Properties prop) {
XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl();
log.info("Creating OpenNebula conector");
if (prop.containsKey(URL_PROPERTY)) {
oneURL = (String) prop.get(URL_PROPERTY);
log.info("URL created: " + oneURL);
}
if (prop.containsKey(USER_PROPERTY)&&prop.containsKey(PASSWORD_PROPERTY)) {
oneSession = ((String) prop.get(USER_PROPERTY)) + ":" + ((String) prop.get(PASSWORD_PROPERTY));
log.info("Session created: " + oneSession);
}
if (prop.containsKey(KERNEL_PROPERTY)) {
hypervisorKernel = ((String) prop.get(KERNEL_PROPERTY));
}
if (prop.containsKey(INITRD_PROPERTY)) {
hypervisorInitrd = ((String) prop.get(INITRD_PROPERTY));
}
if (prop.containsKey(ARCH_PROPERTY)) {
arch = ((String) prop.get(ARCH_PROPERTY));
}
if (prop.containsKey(Main.CUSTOMIZATION_PORT_PROPERTY)) {
customizationPort = ((String) prop.get(Main.CUSTOMIZATION_PORT_PROPERTY));
}
if (prop.containsKey(ENVIRONMENT_PROPERTY)) {
environmentRepositoryPath = (String) prop.get(ENVIRONMENT_PROPERTY);
}
if (prop.containsKey(NETWORK_BRIDGE)) {
networkBridge = ((String) prop.get(NETWORK_BRIDGE));
}
if (prop.containsKey(XEN_DISK)) {
xendisk = ((String) prop.get(XEN_DISK));
}
if (prop.containsKey(SSHKEY_PROPERTY)) {
oneSshKey = ((String) prop.get(SSHKEY_PROPERTY));
}
if (prop.containsKey(SCRIPTPATH_PROPERTY)) {
oneScriptPath = ((String) prop.get(SCRIPTPATH_PROPERTY));
}
if (prop.containsKey(ETH0_GATEWAY_PROPERTY)) {
eth0Gateway= ((String) prop.get(ETH0_GATEWAY_PROPERTY));
}
if (prop.containsKey(ETH0_DNS_PROPERTY)) {
eth0Dns = ((String) prop.get(ETH0_DNS_PROPERTY));
}
if (prop.containsKey(ETH1_GATEWAY_PROPERTY)) {
eth1Gateway = ((String) prop.get(ETH1_GATEWAY_PROPERTY));
}
if (prop.containsKey(ETH1_DNS_PROPERTY)) {
eth1Dns = ((String) prop.get(ETH1_DNS_PROPERTY));
}
if (prop.containsKey(NET_INIT_SCRIPT0)) {
netInitScript0 = ((String) prop.get(NET_INIT_SCRIPT0));
}
if (prop.containsKey(NET_INIT_SCRIPT1)) {
netInitScript1 = ((String) prop.get(NET_INIT_SCRIPT1));
}
try {
config.setServerURL(new URL(oneURL));
} catch (MalformedURLException e) {
log.error("Malformed URL: " + oneURL);
throw new RuntimeException(e);
}
xmlRpcClient = new XmlRpcClient();
log.info("XMLRPC client created");
xmlRpcClient.setConfig(config);
log.info("XMLRPC client configured");
/* MIGRABILITY TAG */
text_migrability.put("cross-host", "HOST");
text_migrability.put("cross-sitehost", "SITE");
text_migrability.put("none", "NONE");
// FULL??
}
@SuppressWarnings("unchecked")
public Document getVirtualMachineState(String id) throws IOException {
List rpcParams = new ArrayList ();
rpcParams.add(oneSession);
rpcParams.add(new Integer(id));
log.debug("Virtual machine info requested for id: " + id);
Object[] result = null;
try {
result = (Object[])xmlRpcClient.execute(VM_GETINFO_COMMAND, rpcParams);
} catch (XmlRpcException ex) {
log.error("Connection error trying to get VM information: " + ex.getMessage());
throw new IOException ("Error on reading VM state , XMLRPC call failed", ex);
}
boolean completed = (Boolean) result[0];
if (completed) {
String resultList = (String) result[1];
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// RESERVOIR ONLY: the info cames with a XML inside the element RAW_VMI, WITH HEADERS
if (resultList.contains("<RAW_VMI>")) {
resultList = resultList.replace(resultList.substring(resultList.indexOf("<RAW_VMI>"), resultList.indexOf("</RAW_VMI>") + 10), "");
}
try {
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new ByteArrayInputStream(resultList.getBytes()));
log.debug("VM Info request succeded");
return doc;
} catch (ParserConfigurationException e) {
log.error("Error configuring parser: " + e.getMessage());
throw new IOException ("Parser Configuration Error", e);
} catch (SAXException e) {
log.error("Parse error obtaining info: " + e.getMessage());
throw new IOException ("XML Parse error", e);
}
} else {
log.error("VM Info request failed: " + result[1]);
return null;
}
}
public String getAtributeVirtualSystem(VirtualSystemType vs, String attribute) throws NumberFormatException {
Iterator itr = vs.getOtherAttributes().entrySet().iterator();
while (itr.hasNext()) {
Map.Entry e = (Map.Entry)itr.next();
if ((e.getKey()).equals(new QName ("http://schemas.telefonica.com/claudia/ovf", attribute)))
return (String)e.getValue();
}
return "";
}
public ArrayList<VirtualSystemType> getVirtualSystem (EnvelopeType envelope) throws Exception {
ContentType entityInstance = null;
ArrayList<VirtualSystemType> virtualSystems = new ArrayList ();
try {
entityInstance = OVFEnvelopeUtils.getTopLevelVirtualSystemContent(envelope);
} catch (EmptyEnvelopeException e) {
log.error(e);
}
HashMap<String,VirtualSystemType> virtualsystems = new HashMap();
if (entityInstance instanceof VirtualSystemType) {
virtualSystems.add((VirtualSystemType)entityInstance);
} else if (entityInstance instanceof VirtualSystemCollectionType) {
VirtualSystemCollectionType virtualSystemCollectionType = (VirtualSystemCollectionType) entityInstance;
for (VirtualSystemType vs : OVFEnvelopeUtils.getVirtualSystems(virtualSystemCollectionType))
{
virtualSystems.add(vs);
}
}//End for
return virtualSystems;
}
@Override
public long deleteNetwork(String netFqn) throws IOException {
return TaskManager.getInstance().addTask(new UndeployNetworkTask(netFqn), URICreation.getVDC(netFqn)).getTaskId();
}
@Override
public long deleteVirtualMachine(String vmFqn) throws IOException {
return TaskManager.getInstance().addTask(new UndeployVMTask(vmFqn), URICreation.getVDC(vmFqn)).getTaskId();
}
@Override
public long deployNetwork(String netFqn, String ovf) throws IOException {
return TaskManager.getInstance().addTask(new DeployNetworkTask(netFqn, ovf), URICreation.getVDC(netFqn)).getTaskId();
}
@Override
public long deployVirtualMachine(String fqn, String ovf) throws IOException {
return TaskManager.getInstance().addTask(new DeployVMTask(fqn, ovf), URICreation.getVDC(fqn)).getTaskId();
}
public long powerActionVirtualMachine(String fqn, String action) throws IOException {
return TaskManager.getInstance().addTask(new ActionVMTask(fqn, action), URICreation.getVDC(fqn)).getTaskId();
}
public String getNetwork(String fqn) throws IOException {
// TODO Auto-generated method stub
return null;
}
@Override
public String getNetworkList() throws IOException {
// TODO Auto-generated method stub
return null;
}
@Override
public String getVirtualMachine(String fqn) throws IOException {
// TODO Auto-generated method stub
return null;
}
}
|
fix empty netcontext syntax
|
driver-one/src/main/java/com/telefonica/claudia/smi/provisioning/ONEProvisioningDriver.java
|
fix empty netcontext syntax
|
|
Java
|
agpl-3.0
|
ab64ae60eb3db9b417a331b39c839a98e73996df
| 0
|
Chikachi/DiscordIntegration,Chikachi/DiscordIntegration,Chikachi/ChikachiDiscord
|
/*
* Copyright (C) 2017 Chikachi
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see http://www.gnu.org/licenses.
*/
package chikachi.discord.listener;
import chikachi.discord.DiscordIntegrationLogger;
import chikachi.discord.core.DiscordClient;
import chikachi.discord.core.Message;
import chikachi.discord.core.config.Configuration;
import com.google.common.base.Joiner;
import net.minecraft.command.ICommandSender;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.stats.Achievement;
import net.minecraft.stats.StatisticsManagerServer;
import net.minecraft.util.text.translation.I18n;
import net.minecraftforge.common.util.FakePlayer;
import net.minecraftforge.event.CommandEvent;
import net.minecraftforge.event.ServerChatEvent;
import net.minecraftforge.event.entity.living.LivingDeathEvent;
import net.minecraftforge.event.entity.player.AchievementEvent;
import net.minecraftforge.fml.common.eventhandler.EventPriority;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.gameevent.PlayerEvent;
import java.util.HashMap;
public class MinecraftListener {
@SubscribeEvent(priority = EventPriority.LOWEST)
public void onCommand(CommandEvent event) {
if (event.isCanceled()) return;
String commandName = event.getCommand().getName();
if (commandName.equalsIgnoreCase("say")) {
ICommandSender sender = event.getSender();
if (sender != null && Configuration.getConfig().minecraft.dimensions.generic.ignoreFakePlayerChat && sender instanceof FakePlayer)
return;
HashMap<String, String> arguments = new HashMap<>();
arguments.put("MESSAGE", Joiner.on(" ").join(event.getParameters()));
DiscordClient.getInstance().broadcast(
new Message(
sender != null ? sender.getName() : null,
sender != null && sender instanceof EntityPlayer ? "https://minotar.net/avatar/" + sender.getName() + "/128.png" : null,
Configuration.getConfig().minecraft.messages.chatMessage,
arguments
),
Configuration.getConfig().minecraft.dimensions.generic.discordChannel.getChannels()
);
}
}
@SubscribeEvent(priority = EventPriority.LOWEST)
public void onChatMessage(ServerChatEvent event) {
if (event.isCanceled() || event.getPlayer() == null) return;
if (Configuration.getConfig().minecraft.dimensions.generic.ignoreFakePlayerChat && event.getPlayer() instanceof FakePlayer)
return;
HashMap<String, String> arguments = new HashMap<>();
arguments.put("MESSAGE", event.getMessage());
// TODO: Change to use dimension
DiscordClient.getInstance().broadcast(
new Message(
event.getUsername(),
"https://minotar.net/avatar/" + event.getUsername() + "/128.png",
Configuration.getConfig().minecraft.messages.chatMessage,
arguments
),
Configuration.getConfig().minecraft.dimensions.generic.discordChannel.getChannels()
);
}
@SubscribeEvent(priority = EventPriority.LOWEST)
public void onPlayerAchievement(AchievementEvent event) {
if (event.isCanceled()) return;
EntityPlayer entityPlayer = event.getEntityPlayer();
if (entityPlayer != null && entityPlayer instanceof EntityPlayerMP) {
StatisticsManagerServer playerStats = ((EntityPlayerMP) entityPlayer).getStatFile();
if (playerStats.hasAchievementUnlocked(event.getAchievement()) || !playerStats.canUnlockAchievement(event.getAchievement())) {
return;
}
Achievement achievement = event.getAchievement();
HashMap<String, String> arguments = new HashMap<>();
arguments.put("ACHIEVEMENT", achievement.getStatName().getUnformattedText());
// TODO: Change to use dimension
// TODO: Figure out what to do with I18n - Might remove the description...
//noinspection deprecation
arguments.put("DESCRIPTION", I18n.translateToLocalFormatted(achievement.achievementDescription, "KEY"));
DiscordClient.getInstance().broadcast(
new Message(
entityPlayer.getDisplayNameString(),
"https://minotar.net/avatar/" + entityPlayer.getName() + "/128.png",
Configuration.getConfig().minecraft.messages.achievement,
arguments
),
Configuration.getConfig().minecraft.dimensions.generic.discordChannel.getChannels()
);
}
}
@SubscribeEvent(priority = EventPriority.LOWEST)
public void onPlayerJoin(PlayerEvent.PlayerLoggedInEvent event) {
if (event.isCanceled() || event.player == null) return;
DiscordClient.getInstance().broadcast(
new Message(
event.player.getDisplayNameString(),
"https://minotar.net/avatar/" + event.player.getName() + "/128.png",
Configuration.getConfig().minecraft.messages.playerJoin
),
Configuration.getConfig().minecraft.dimensions.generic.discordChannel.getChannels()
);
}
@SubscribeEvent(priority = EventPriority.LOWEST)
public void onPlayerLeave(PlayerEvent.PlayerLoggedOutEvent event) {
if (event.isCanceled() || event.player == null) return;
DiscordClient.getInstance().broadcast(
new Message(
event.player.getDisplayNameString(),
"https://minotar.net/avatar/" + event.player.getName() + "/128.png",
Configuration.getConfig().minecraft.messages.playerLeave
),
Configuration.getConfig().minecraft.dimensions.generic.discordChannel.getChannels()
);
}
@SubscribeEvent(priority = EventPriority.LOWEST, receiveCanceled = true)
public void onPlayerDeath(LivingDeathEvent event) {
EntityLivingBase entityLiving = event.getEntityLiving();
if (entityLiving == null) return;
if (entityLiving instanceof EntityPlayer) {
EntityPlayer entityPlayer = (EntityPlayer) entityLiving;
HashMap<String, String> arguments = new HashMap<>();
arguments.put("REASON", entityPlayer.getCombatTracker().getDeathMessage().getUnformattedText().replace(entityPlayer.getDisplayNameString(), "").trim());
DiscordClient.getInstance().broadcast(
new Message(
entityPlayer.getDisplayNameString(),
"https://minotar.net/avatar/" + entityPlayer.getName() + "/128.png",
Configuration.getConfig().minecraft.messages.playerDeath,
arguments
),
Configuration.getConfig().minecraft.dimensions.generic.discordChannel.getChannels()
);
}
}
}
|
src/main/java/chikachi/discord/listener/MinecraftListener.java
|
/*
* Copyright (C) 2017 Chikachi
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see http://www.gnu.org/licenses.
*/
package chikachi.discord.listener;
import chikachi.discord.core.DiscordClient;
import chikachi.discord.core.Message;
import chikachi.discord.core.config.Configuration;
import com.google.common.base.Joiner;
import net.minecraft.command.ICommandSender;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.stats.Achievement;
import net.minecraft.stats.StatisticsManagerServer;
import net.minecraft.util.text.translation.I18n;
import net.minecraftforge.common.util.FakePlayer;
import net.minecraftforge.event.CommandEvent;
import net.minecraftforge.event.ServerChatEvent;
import net.minecraftforge.event.entity.player.AchievementEvent;
import net.minecraftforge.fml.common.eventhandler.EventPriority;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.gameevent.PlayerEvent;
import java.util.HashMap;
public class MinecraftListener {
@SubscribeEvent(priority = EventPriority.LOWEST)
public void onCommand(CommandEvent event) {
if (event.isCanceled()) return;
String commandName = event.getCommand().getName();
if (commandName.equalsIgnoreCase("say")) {
ICommandSender sender = event.getSender();
if (sender != null && Configuration.getConfig().minecraft.dimensions.generic.ignoreFakePlayerChat && sender instanceof FakePlayer)
return;
HashMap<String, String> arguments = new HashMap<>();
arguments.put("MESSAGE", Joiner.on(" ").join(event.getParameters()));
DiscordClient.getInstance().broadcast(
new Message(
sender != null ? sender.getName() : null,
sender != null && sender instanceof EntityPlayer ? "https://minotar.net/avatar/" + sender.getName() + "/128.png" : null,
Configuration.getConfig().minecraft.messages.chatMessage,
arguments
),
Configuration.getConfig().minecraft.dimensions.generic.discordChannel.getChannels()
);
}
}
@SubscribeEvent(priority = EventPriority.LOWEST)
public void onChatMessage(ServerChatEvent event) {
if (event.isCanceled() || event.getPlayer() == null) return;
if (Configuration.getConfig().minecraft.dimensions.generic.ignoreFakePlayerChat && event.getPlayer() instanceof FakePlayer)
return;
HashMap<String, String> arguments = new HashMap<>();
arguments.put("MESSAGE", event.getMessage());
// TODO: Change to use dimension
DiscordClient.getInstance().broadcast(
new Message(
event.getUsername(),
"https://minotar.net/avatar/" + event.getUsername() + "/128.png",
Configuration.getConfig().minecraft.messages.chatMessage,
arguments
),
Configuration.getConfig().minecraft.dimensions.generic.discordChannel.getChannels()
);
}
@SubscribeEvent(priority = EventPriority.LOWEST)
public void onPlayerAchievement(AchievementEvent event) {
if (event.isCanceled()) return;
EntityPlayer entityPlayer = event.getEntityPlayer();
if (entityPlayer != null && entityPlayer instanceof EntityPlayerMP) {
StatisticsManagerServer playerStats = ((EntityPlayerMP) entityPlayer).getStatFile();
if (playerStats.hasAchievementUnlocked(event.getAchievement()) || !playerStats.canUnlockAchievement(event.getAchievement())) {
return;
}
Achievement achievement = event.getAchievement();
HashMap<String, String> arguments = new HashMap<>();
arguments.put("ACHIEVEMENT", achievement.getStatName().getUnformattedText());
// TODO: Change to use dimension
// TODO: Figure out what to do with I18n - Might remove the description...
//noinspection deprecation
arguments.put("DESCRIPTION", I18n.translateToLocalFormatted(achievement.achievementDescription, "KEY"));
DiscordClient.getInstance().broadcast(
new Message(
entityPlayer.getDisplayNameString(),
"https://minotar.net/avatar/" + entityPlayer.getName() + "/128.png",
Configuration.getConfig().minecraft.messages.achievement,
arguments
),
Configuration.getConfig().minecraft.dimensions.generic.discordChannel.getChannels()
);
}
}
@SubscribeEvent(priority = EventPriority.LOWEST)
public void onPlayerJoin(PlayerEvent.PlayerLoggedInEvent event) {
if (event.isCanceled() || event.player == null) return;
DiscordClient.getInstance().broadcast(
new Message(
event.player.getDisplayNameString(),
"https://minotar.net/avatar/" + event.player.getName() + "/128.png",
Configuration.getConfig().minecraft.messages.playerJoin
),
Configuration.getConfig().minecraft.dimensions.generic.discordChannel.getChannels()
);
}
@SubscribeEvent(priority = EventPriority.LOWEST)
public void onPlayerLeave(PlayerEvent.PlayerLoggedOutEvent event) {
if (event.isCanceled() || event.player == null) return;
DiscordClient.getInstance().broadcast(
new Message(
event.player.getDisplayNameString(),
"https://minotar.net/avatar/" + event.player.getName() + "/128.png",
Configuration.getConfig().minecraft.messages.playerLeave
),
Configuration.getConfig().minecraft.dimensions.generic.discordChannel.getChannels()
);
}
// TODO: Add playerDeath
}
|
Added Player Death event listener
|
src/main/java/chikachi/discord/listener/MinecraftListener.java
|
Added Player Death event listener
|
|
Java
|
lgpl-2.1
|
6b5ab34944f2aa95cbbaf101efdf0357c3089ea6
| 0
|
exedio/copernica,exedio/copernica,exedio/copernica
|
/*
* Copyright (C) 2004-2005 exedio GmbH (www.exedio.com)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package com.exedio.cope.instrument;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
final class JavaRepository
{
private boolean buildStage = true;
private final ArrayList files = new ArrayList();
private final HashMap copeTypeByShortClassName = new HashMap();
private HashMap rtvalues = new HashMap();
void endBuildStage()
{
assert buildStage;
buildStage = false;
}
void add(final JavaFile file)
{
assert buildStage;
files.add(file);
}
final List getFiles()
{
assert !buildStage;
return files;
}
void add(final CopeType copeClass)
{
assert buildStage;
final String name = JavaFile.extractClassName(copeClass.javaClass.name);
if(copeTypeByShortClassName.put(name, copeClass)!=null)
throw new RuntimeException(name);
//System.out.println("--------- put cope class: "+name);
}
CopeType getCopeType(final String className)
{
assert !buildStage;
final CopeType result = (CopeType)copeTypeByShortClassName.get(className);
if(result==null)
throw new RuntimeException("no cope type for "+className);
return result;
}
void putRtValue(final JavaAttribute attribute, final JavaClass.Value rtvalue)
{
rtvalues.put(rtvalue.instance, attribute);
}
final JavaAttribute getByRtValue(final Object rtvalue)
{
return (JavaAttribute)rtvalues.get(rtvalue);
}
}
|
instrument/src/com/exedio/cope/instrument/JavaRepository.java
|
/*
* Copyright (C) 2004-2005 exedio GmbH (www.exedio.com)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package com.exedio.cope.instrument;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
final class JavaRepository
{
private boolean buildStage = true;
private final ArrayList files = new ArrayList();
private final HashMap copeClasses = new HashMap();
private HashMap rtvalues = new HashMap();
void endBuildStage()
{
assert buildStage;
buildStage = false;
}
void add(final JavaFile file)
{
assert buildStage;
files.add(file);
}
final List getFiles()
{
assert !buildStage;
return files;
}
void add(final CopeType copeClass)
{
assert buildStage;
final String name = JavaFile.extractClassName(copeClass.javaClass.name);
if(copeClasses.put(name, copeClass)!=null)
throw new RuntimeException(name);
//System.out.println("--------- put cope class: "+name);
}
CopeType getCopeType(final String className)
{
assert !buildStage;
final CopeType result = (CopeType)copeClasses.get(className);
if(result==null)
throw new RuntimeException("no cope type for "+className);
return result;
}
void putRtValue(final JavaAttribute attribute, final JavaClass.Value rtvalue)
{
rtvalues.put(rtvalue.instance, attribute);
}
final JavaAttribute getByRtValue(final Object rtvalue)
{
return (JavaAttribute)rtvalues.get(rtvalue);
}
}
|
rename copeClasses to copeTypeByShortClassName
git-svn-id: 9dbc6da3594b32e13bcf3b3752e372ea5bc7c2cc@4181 e7d4fc99-c606-0410-b9bf-843393a9eab7
|
instrument/src/com/exedio/cope/instrument/JavaRepository.java
|
rename copeClasses to copeTypeByShortClassName
|
|
Java
|
lgpl-2.1
|
9e8bf7961353e611e369330246ac602b04855a60
| 0
|
anddann/soot,cfallin/soot,xph906/SootNew,cfallin/soot,mbenz89/soot,mbenz89/soot,anddann/soot,mbenz89/soot,cfallin/soot,xph906/SootNew,xph906/SootNew,plast-lab/soot,mbenz89/soot,xph906/SootNew,plast-lab/soot,plast-lab/soot,anddann/soot,anddann/soot,cfallin/soot
|
/* Soot - a J*va Optimization Framework
* Copyright (C) 2010 Eric Bodden
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
package soot.jimple.toolkits.reflection;
import java.util.Collections;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import soot.Body;
import soot.BooleanType;
import soot.Local;
import soot.PatchingChain;
import soot.PhaseOptions;
import soot.RefType;
import soot.Scene;
import soot.SceneTransformer;
import soot.SootClass;
import soot.SootMethod;
import soot.SootMethodRef;
import soot.Type;
import soot.Unit;
import soot.Value;
import soot.ValueBox;
import soot.VoidType;
import soot.javaToJimple.LocalGenerator;
import soot.jimple.AssignStmt;
import soot.jimple.ClassConstant;
import soot.jimple.GotoStmt;
import soot.jimple.IfStmt;
import soot.jimple.InstanceInvokeExpr;
import soot.jimple.IntConstant;
import soot.jimple.InvokeExpr;
import soot.jimple.InvokeStmt;
import soot.jimple.Jimple;
import soot.jimple.NewExpr;
import soot.jimple.NopStmt;
import soot.jimple.SpecialInvokeExpr;
import soot.jimple.Stmt;
import soot.jimple.StringConstant;
import soot.jimple.ThrowStmt;
import soot.jimple.VirtualInvokeExpr;
import soot.jimple.toolkits.reflection.ReflectionTraceInfo.Kind;
import soot.options.CGOptions;
import soot.rtlib.SootSig;
import soot.util.Chain;
import soot.util.HashChain;
public class ReflectiveCallsInliner extends SceneTransformer {
private SootClass SOOT_SIG_CLASS;
private SootMethodRef EQUALS;
private SootMethodRef ERROR_CONSTRUCTOR;
private SootMethodRef CLASS_GET_NAME;
boolean initialized = false;
@SuppressWarnings("unchecked")
@Override
protected void internalTransform(String phaseName, Map options) {
if(!initialized) {
SOOT_SIG_CLASS = Scene.v().getSootClass(SootSig.class.getName());
SOOT_SIG_CLASS.setApplicationClass();
EQUALS = Scene.v().makeMethodRef(Scene.v().getSootClass("java.lang.Object"), "equals", Collections.<Type>singletonList(RefType.v("java.lang.Object")), BooleanType.v(), false);
ERROR_CONSTRUCTOR = Scene.v().makeMethodRef(Scene.v().getSootClass("java.lang.Error"), SootMethod.constructorName, Collections.<Type>singletonList(RefType.v("java.lang.String")), VoidType.v(), false);
CLASS_GET_NAME = Scene.v().makeMethodRef(Scene.v().getSootClass("java.lang.Class"), "getName", Collections.<Type>emptyList(), RefType.v("java.lang.String"), false);
initialized = true;
}
CGOptions cgOptions = new CGOptions( PhaseOptions.v().getPhaseOptions("cg") );
String logFilePath = cgOptions.reflection_log();
ReflectionTraceInfo rti = new ReflectionTraceInfo(logFilePath);
for(SootMethod m: rti.methodsContainingReflectiveCalls()) {
Set<String> classForNameClassNames = rti.classForNameClassNames(m);
if(!classForNameClassNames.isEmpty()) {
m.retrieveActiveBody();
inlineRelectiveCalls(m.getActiveBody(),classForNameClassNames, ReflectionTraceInfo.Kind.ClassForName);
m.getActiveBody().validate();
}
Set<String> classNewInstanceClassNames = rti.classNewInstanceClassNames(m);
if(!classNewInstanceClassNames.isEmpty()) {
m.retrieveActiveBody();
inlineRelectiveCalls(m.getActiveBody(),classNewInstanceClassNames, ReflectionTraceInfo.Kind.ClassNewInstance);
m.getActiveBody().validate();
}
Set<String> constructorNewInstanceSignatures = rti.constructorNewInstanceSignatures(m);
if(!constructorNewInstanceSignatures.isEmpty()) {
m.retrieveActiveBody();
inlineRelectiveCalls(m.getActiveBody(), constructorNewInstanceSignatures, ReflectionTraceInfo.Kind.ConstructorNewInstance);
m.getActiveBody().validate();
}
}
}
/* Replaces "c = Class.forName(arg)" by:
*
* if(arg.equals("C1")) goto l1
* if(arg.equals("C2")) goto l2
* throw new Error (arg)
* l1: c = C1.class;
* goto E;
* l2: c = C2.class;
* goto E;
* E;
*/
private void inlineRelectiveCalls(Body b, Set<String> targets, Kind callKind) {
PatchingChain<Unit> units = b.getUnits();
Iterator<Unit> iter = units.snapshotIterator();
LocalGenerator localGen = new LocalGenerator(b);
while(iter.hasNext()) {
Chain<Unit> newUnits = new HashChain<Unit>();
Stmt s = (Stmt) iter.next();
if(s.containsInvokeExpr()) {
InvokeExpr ie = s.getInvokeExpr();
Local targetNameLocal = null;
if(callKind==Kind.ClassForName && ie.getMethodRef().getSignature().equals("<java.lang.Class: java.lang.Class forName(java.lang.String)>")) {
Value classNameValue = ie.getArg(0);
if(classNameValue instanceof StringConstant) {
StringConstant stringConstant = (StringConstant) classNameValue;
ValueBox argBox = s.getInvokeExprBox();
argBox.setValue(ClassConstant.v(stringConstant.value));
continue; //we are done already in that case
}
targetNameLocal = (Local) classNameValue;
} else if(callKind==Kind.ClassNewInstance && ie.getMethodRef().getSignature().equals("<java.lang.Class: java.lang.Object newInstance()>")) {
Local classLocal = (Local) ((InstanceInvokeExpr)ie).getBase();
VirtualInvokeExpr getNameExpr = Jimple.v().newVirtualInvokeExpr(classLocal, CLASS_GET_NAME);
targetNameLocal = localGen.generateLocal(RefType.v("java.lang.String"));
AssignStmt assignStmt = Jimple.v().newAssignStmt(targetNameLocal, getNameExpr);
newUnits.add(assignStmt);
}
if(targetNameLocal==null) continue; //if the invoke expression is no reflective call, continue
NopStmt endLabel = Jimple.v().newNopStmt();
for(String target : targets) {
VirtualInvokeExpr equalsCall = Jimple.v().newVirtualInvokeExpr(targetNameLocal,EQUALS,StringConstant.v(target));
Local resultLocal = localGen.generateLocal(BooleanType.v());
AssignStmt equalsAssignStmt = Jimple.v().newAssignStmt(resultLocal, equalsCall);
newUnits.add(equalsAssignStmt);
NopStmt jumpTarget = Jimple.v().newNopStmt();
IfStmt ifStmt = Jimple.v().newIfStmt(Jimple.v().newEqExpr(IntConstant.v(0), resultLocal), jumpTarget);
newUnits.add(ifStmt);
Local freshLocal;
Value replacement=null;
if(callKind==Kind.ClassForName) {
freshLocal = localGen.generateLocal(RefType.v("java.lang.Class"));
replacement = ClassConstant.v(target.replace('.','/'));
} else if(callKind==Kind.ClassNewInstance) {
RefType targetType = RefType.v(target);
freshLocal = localGen.generateLocal(targetType);
replacement = Jimple.v().newNewExpr(targetType);
} else throw new InternalError();
AssignStmt replStmt = Jimple.v().newAssignStmt(freshLocal, replacement);
newUnits.add(replStmt);
if(callKind==Kind.ClassNewInstance) {
SootClass targetClass = Scene.v().getSootClass(target);
SpecialInvokeExpr constrCallExpr = Jimple.v().newSpecialInvokeExpr(freshLocal, Scene.v().makeMethodRef(targetClass, SootMethod.constructorName, Collections.<Type>emptyList(), VoidType.v(), false));
InvokeStmt constrCallStmt2 = Jimple.v().newInvokeStmt(constrCallExpr);
newUnits.add(constrCallStmt2);
}
if(s instanceof AssignStmt) {
AssignStmt assignStmt = (AssignStmt) s;
Value leftOp = assignStmt.getLeftOp();
AssignStmt newAssignStmt = Jimple.v().newAssignStmt(leftOp, freshLocal);
newUnits.add(newAssignStmt);
}
GotoStmt gotoStmt = Jimple.v().newGotoStmt(endLabel);
newUnits.add(gotoStmt);
newUnits.add(jumpTarget);
}
Local exceptionLocal = localGen.generateLocal(RefType.v("java.lang.Error"));
NewExpr newExpr = Jimple.v().newNewExpr(RefType.v("java.lang.Error"));
AssignStmt newExceptionStmt = Jimple.v().newAssignStmt(exceptionLocal, newExpr);
newUnits.add(newExceptionStmt);
SpecialInvokeExpr constrCall = Jimple.v().newSpecialInvokeExpr(exceptionLocal, ERROR_CONSTRUCTOR, targetNameLocal);
InvokeStmt constrCallStmt = Jimple.v().newInvokeStmt(constrCall);
newUnits.add(constrCallStmt);
ThrowStmt throwStmt = Jimple.v().newThrowStmt(exceptionLocal);
newUnits.add(throwStmt);
newUnits.add(endLabel);
units.insertAfter(newUnits, s);
units.remove(s);
}
}
}
}
|
src/soot/jimple/toolkits/reflection/ReflectiveCallsInliner.java
|
/* Soot - a J*va Optimization Framework
* Copyright (C) 2010 Eric Bodden
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
package soot.jimple.toolkits.reflection;
import java.util.Collections;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import soot.Body;
import soot.BooleanType;
import soot.Local;
import soot.PatchingChain;
import soot.PhaseOptions;
import soot.RefType;
import soot.Scene;
import soot.SceneTransformer;
import soot.SootClass;
import soot.SootMethod;
import soot.SootMethodRef;
import soot.Type;
import soot.Unit;
import soot.Value;
import soot.ValueBox;
import soot.VoidType;
import soot.javaToJimple.LocalGenerator;
import soot.jimple.AssignStmt;
import soot.jimple.ClassConstant;
import soot.jimple.GotoStmt;
import soot.jimple.IfStmt;
import soot.jimple.InstanceInvokeExpr;
import soot.jimple.IntConstant;
import soot.jimple.InvokeExpr;
import soot.jimple.InvokeStmt;
import soot.jimple.Jimple;
import soot.jimple.NewExpr;
import soot.jimple.NopStmt;
import soot.jimple.SpecialInvokeExpr;
import soot.jimple.Stmt;
import soot.jimple.StringConstant;
import soot.jimple.ThrowStmt;
import soot.jimple.VirtualInvokeExpr;
import soot.jimple.toolkits.reflection.ReflectionTraceInfo.Kind;
import soot.options.CGOptions;
import soot.rtlib.SootSig;
import soot.util.Chain;
import soot.util.HashChain;
public class ReflectiveCallsInliner extends SceneTransformer {
private SootMethodRef EQUALS;
private SootMethodRef ERROR_CONSTRUCTOR;
private SootMethodRef CLASS_GET_NAME;
@SuppressWarnings("unchecked")
@Override
protected void internalTransform(String phaseName, Map options) {
Scene.v().getSootClass(SootSig.class.getName()).setApplicationClass();
EQUALS = Scene.v().makeMethodRef(Scene.v().getSootClass("java.lang.Object"), "equals", Collections.<Type>singletonList(RefType.v("java.lang.Object")), BooleanType.v(), false);
ERROR_CONSTRUCTOR = Scene.v().makeMethodRef(Scene.v().getSootClass("java.lang.Error"), SootMethod.constructorName, Collections.<Type>singletonList(RefType.v("java.lang.String")), VoidType.v(), false);
CLASS_GET_NAME = Scene.v().makeMethodRef(Scene.v().getSootClass("java.lang.Class"), "getName", Collections.<Type>emptyList(), RefType.v("java.lang.String"), false);
CGOptions cgOptions = new CGOptions( PhaseOptions.v().getPhaseOptions("cg") );
String logFilePath = cgOptions.reflection_log();
ReflectionTraceInfo rti = new ReflectionTraceInfo(logFilePath);
for(SootMethod m: rti.methodsContainingReflectiveCalls()) {
Set<String> classForNameClassNames = rti.classForNameClassNames(m);
if(!classForNameClassNames.isEmpty()) {
m.retrieveActiveBody();
inlineRelectiveCalls(m.getActiveBody(),classForNameClassNames, ReflectionTraceInfo.Kind.ClassForName);
m.getActiveBody().validate();
}
Set<String> classNewInstanceClassNames = rti.classNewInstanceClassNames(m);
if(!classNewInstanceClassNames.isEmpty()) {
m.retrieveActiveBody();
inlineRelectiveCalls(m.getActiveBody(),classNewInstanceClassNames, ReflectionTraceInfo.Kind.ClassNewInstance);
m.getActiveBody().validate();
}
Set<String> constructorNewInstanceSignatures = rti.constructorNewInstanceSignatures(m);
if(!constructorNewInstanceSignatures.isEmpty()) {
m.retrieveActiveBody();
inlineRelectiveCalls(m.getActiveBody(), constructorNewInstanceSignatures, ReflectionTraceInfo.Kind.ConstructorNewInstance);
m.getActiveBody().validate();
}
}
}
/* Replaces "c = Class.forName(arg)" by:
*
* if(arg.equals("C1")) goto l1
* if(arg.equals("C2")) goto l2
* throw new Error (arg)
* l1: c = C1.class;
* goto E;
* l2: c = C2.class;
* goto E;
* E;
*/
private void inlineRelectiveCalls(Body b, Set<String> targets, Kind callKind) {
PatchingChain<Unit> units = b.getUnits();
Iterator<Unit> iter = units.snapshotIterator();
LocalGenerator localGen = new LocalGenerator(b);
while(iter.hasNext()) {
Chain<Unit> newUnits = new HashChain<Unit>();
Stmt s = (Stmt) iter.next();
if(s.containsInvokeExpr()) {
InvokeExpr ie = s.getInvokeExpr();
Local targetNameLocal = null;
if(callKind==Kind.ClassForName && ie.getMethodRef().getSignature().equals("<java.lang.Class: java.lang.Class forName(java.lang.String)>")) {
Value classNameValue = ie.getArg(0);
if(classNameValue instanceof StringConstant) {
StringConstant stringConstant = (StringConstant) classNameValue;
ValueBox argBox = s.getInvokeExprBox();
argBox.setValue(ClassConstant.v(stringConstant.value));
continue; //we are done already in that case
}
targetNameLocal = (Local) classNameValue;
} else if(callKind==Kind.ClassNewInstance && ie.getMethodRef().getSignature().equals("<java.lang.Class: java.lang.Object newInstance()>")) {
Local classLocal = (Local) ((InstanceInvokeExpr)ie).getBase();
VirtualInvokeExpr getNameExpr = Jimple.v().newVirtualInvokeExpr(classLocal, CLASS_GET_NAME);
targetNameLocal = localGen.generateLocal(RefType.v("java.lang.String"));
AssignStmt assignStmt = Jimple.v().newAssignStmt(targetNameLocal, getNameExpr);
newUnits.add(assignStmt);
}
if(targetNameLocal==null) continue; //if the invoke expression is no reflective call, continue
NopStmt endLabel = Jimple.v().newNopStmt();
for(String target : targets) {
VirtualInvokeExpr equalsCall = Jimple.v().newVirtualInvokeExpr(targetNameLocal,EQUALS,StringConstant.v(target));
Local resultLocal = localGen.generateLocal(BooleanType.v());
AssignStmt equalsAssignStmt = Jimple.v().newAssignStmt(resultLocal, equalsCall);
newUnits.add(equalsAssignStmt);
NopStmt jumpTarget = Jimple.v().newNopStmt();
IfStmt ifStmt = Jimple.v().newIfStmt(Jimple.v().newEqExpr(IntConstant.v(0), resultLocal), jumpTarget);
newUnits.add(ifStmt);
Local freshLocal;
Value replacement=null;
if(callKind==Kind.ClassForName) {
freshLocal = localGen.generateLocal(RefType.v("java.lang.Class"));
replacement = ClassConstant.v(target.replace('.','/'));
} else if(callKind==Kind.ClassNewInstance) {
RefType targetType = RefType.v(target);
freshLocal = localGen.generateLocal(targetType);
replacement = Jimple.v().newNewExpr(targetType);
} else throw new InternalError();
AssignStmt replStmt = Jimple.v().newAssignStmt(freshLocal, replacement);
newUnits.add(replStmt);
if(callKind==Kind.ClassNewInstance) {
SootClass targetClass = Scene.v().getSootClass(target);
SpecialInvokeExpr constrCallExpr = Jimple.v().newSpecialInvokeExpr(freshLocal, Scene.v().makeMethodRef(targetClass, SootMethod.constructorName, Collections.<Type>emptyList(), VoidType.v(), false));
InvokeStmt constrCallStmt2 = Jimple.v().newInvokeStmt(constrCallExpr);
newUnits.add(constrCallStmt2);
}
if(s instanceof AssignStmt) {
AssignStmt assignStmt = (AssignStmt) s;
Value leftOp = assignStmt.getLeftOp();
AssignStmt newAssignStmt = Jimple.v().newAssignStmt(leftOp, freshLocal);
newUnits.add(newAssignStmt);
}
GotoStmt gotoStmt = Jimple.v().newGotoStmt(endLabel);
newUnits.add(gotoStmt);
newUnits.add(jumpTarget);
}
Local exceptionLocal = localGen.generateLocal(RefType.v("java.lang.Error"));
NewExpr newExpr = Jimple.v().newNewExpr(RefType.v("java.lang.Error"));
AssignStmt newExceptionStmt = Jimple.v().newAssignStmt(exceptionLocal, newExpr);
newUnits.add(newExceptionStmt);
SpecialInvokeExpr constrCall = Jimple.v().newSpecialInvokeExpr(exceptionLocal, ERROR_CONSTRUCTOR, targetNameLocal);
InvokeStmt constrCallStmt = Jimple.v().newInvokeStmt(constrCall);
newUnits.add(constrCallStmt);
ThrowStmt throwStmt = Jimple.v().newThrowStmt(exceptionLocal);
newUnits.add(throwStmt);
newUnits.add(endLabel);
units.insertAfter(newUnits, s);
units.remove(s);
}
}
}
}
|
cleaned up initialization code
|
src/soot/jimple/toolkits/reflection/ReflectiveCallsInliner.java
|
cleaned up initialization code
|
|
Java
|
lgpl-2.1
|
ceee6fa78ca8033df955385909d679a715a00064
| 0
|
meg0man/languagetool,janissl/languagetool,jimregan/languagetool,janissl/languagetool,lopescan/languagetool,languagetool-org/languagetool,janissl/languagetool,meg0man/languagetool,meg0man/languagetool,languagetool-org/languagetool,languagetool-org/languagetool,lopescan/languagetool,janissl/languagetool,lopescan/languagetool,meg0man/languagetool,meg0man/languagetool,janissl/languagetool,lopescan/languagetool,lopescan/languagetool,jimregan/languagetool,jimregan/languagetool,jimregan/languagetool,janissl/languagetool,languagetool-org/languagetool,languagetool-org/languagetool,jimregan/languagetool
|
/* LanguageTool, a natural language style checker
* Copyright (C) 2005 Daniel Naber (http://www.danielnaber.de)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package de.danielnaber.languagetool.rules.patterns;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;
import junit.framework.TestCase;
import de.danielnaber.languagetool.AnalyzedSentence;
import de.danielnaber.languagetool.JLanguageTool;
import de.danielnaber.languagetool.Language;
import de.danielnaber.languagetool.TestTools;
import de.danielnaber.languagetool.rules.IncorrectExample;
import de.danielnaber.languagetool.rules.Rule;
import de.danielnaber.languagetool.rules.RuleMatch;
/**
* @author Daniel Naber
*/
public class PatternRuleTest extends TestCase {
private static JLanguageTool langTool;
private static final Pattern PROBABLE_REGEX = Pattern.compile("[^\\[\\]\\*\\+\\|\\^\\{\\}\\?][\\[\\]\\*\\+\\|\\^\\{\\}\\?]|\\\\[^0-9]|\\(.+\\)");
@Override
public void setUp() throws IOException {
if (langTool == null) {
langTool = new JLanguageTool(Language.ENGLISH);
}
}
public void testGrammarRulesFromXML() throws IOException {
testGrammarRulesFromXML(null, false);
}
private void testGrammarRulesFromXML(final Set<Language> ignoredLanguages,
final boolean verbose) throws IOException {
for (final Language lang : Language.LANGUAGES) {
if (ignoredLanguages != null && ignoredLanguages.contains(lang)) {
if (verbose) {
System.out.println("Ignoring tests for " + lang.getName());
}
continue;
}
if (verbose) {
System.out.println("Running tests for " + lang.getName() + "...");
}
final PatternRuleLoader ruleLoader = new PatternRuleLoader();
final JLanguageTool languageTool = new JLanguageTool(lang);
final String name = "/rules/" + lang.getShortName() + "/grammar.xml";
final List<PatternRule> rules = ruleLoader.getRules(this.getClass()
.getResourceAsStream(name), name);
warnIfRegexpSyntax(rules, lang);
testGrammarRulesFromXML(rules, languageTool, lang);
}
}
// TODO: probably this would be more useful for exceptions
// instead of adding next methods to PatternRule
// we can probably validate using XSD and specify regexes straight there
private void warnIfRegexpSyntax(final List<PatternRule> rules,
final Language lang) {
for (final PatternRule rule : rules) {
for (final Element element : rule.getElements()) {
if (!element.isRegularExpression()
&& (PROBABLE_REGEX.matcher(element.getString())
.find())) {
System.err.println("The " + lang.toString() + " rule: "
+ rule.getId() + " contains element " + "\"" + element
+ "\" that is not marked as regular expression"
+ " but probably is one.");
}
if (element.isRegularExpression()
&& (element.getString() == null || (!PROBABLE_REGEX.matcher(element.getString())
.find()))) {
System.err.println("The " + lang.toString() + " rule: "
+ rule.getId() + " contains element " + "\"" + element
+ "\" that is marked as regular expression"
+ " but probably is not one.");
}
}
}
}
private void testGrammarRulesFromXML(final List<PatternRule> rules,
final JLanguageTool languageTool, final Language lang) throws IOException {
int noSuggestionCount = 0;
final HashMap<String, PatternRule> complexRules = new HashMap<String, PatternRule>();
for (final PatternRule rule : rules) {
final List<String> goodSentences = rule.getCorrectExamples();
for (String goodSentence : goodSentences) {
// enable indentation use
goodSentence = goodSentence.replaceAll("[\\n\\t]+", "");
goodSentence = cleanXML(goodSentence);
assertTrue(goodSentence.trim().length() > 0);
assertFalse(lang + ": Did not expect error in: " + goodSentence
+ " (Rule: " + rule + ")", match(rule, goodSentence, languageTool));
}
final List<IncorrectExample> badSentences = rule.getIncorrectExamples();
for (IncorrectExample origBadExample : badSentences) {
// enable indentation use
String origBadSentence = origBadExample.getExample().replaceAll(
"[\\n\\t]+", "");
final List<String> suggestedCorrection = origBadExample
.getCorrections();
final int expectedMatchStart = origBadSentence.indexOf("<marker>");
final int expectedMatchEnd = origBadSentence.indexOf("</marker>")
- "<marker>".length();
if (expectedMatchStart == -1 || expectedMatchEnd == -1) {
fail(lang
+ ": No error position markup ('<marker>...</marker>') in bad example in rule "
+ rule);
}
final String badSentence = cleanXML(origBadSentence);
assertTrue(badSentence.trim().length() > 0);
RuleMatch[] matches = getMatches(rule, badSentence, languageTool);
if (!rule.isWithComplexPhrase()) {
assertTrue(lang + ": Did expect one error in: \"" + badSentence
+ "\" (Rule: " + rule + "), got " + matches.length
+ ". Additional info:" + rule.getMessage(), matches.length == 1);
assertEquals(lang
+ ": Incorrect match position markup (start) for rule " + rule,
expectedMatchStart, matches[0].getFromPos());
assertEquals(lang
+ ": Incorrect match position markup (end) for rule " + rule,
expectedMatchEnd, matches[0].getToPos());
// make sure suggestion is what we expect it to be
if (suggestedCorrection != null && suggestedCorrection.size() > 0) {
assertTrue(lang + ": Incorrect suggestions: "
+ suggestedCorrection.toString() + " != "
+ matches[0].getSuggestedReplacements() + " for rule " + rule,
suggestedCorrection.equals(matches[0]
.getSuggestedReplacements()));
}
// make sure the suggested correction doesn't produce an error:
if (matches[0].getSuggestedReplacements().size() > 0) {
final int fromPos = matches[0].getFromPos();
final int toPos = matches[0].getToPos();
for (final String repl : matches[0].getSuggestedReplacements()) {
final String fixedSentence = badSentence.substring(0, fromPos)
+ repl + badSentence.substring(toPos);
matches = getMatches(rule, fixedSentence, languageTool);
assertEquals("Corrected sentence for rule " + rule
+ " triggered error: " + fixedSentence, 0, matches.length);
}
} else {
noSuggestionCount++;
}
} else { // for multiple rules created with complex phrases
matches = getMatches(rule, badSentence, languageTool);
if (matches.length == 0
&& !complexRules.containsKey(rule.getId() + badSentence)) {
complexRules.put(rule.getId() + badSentence, rule);
}
if (matches.length != 0) {
complexRules.put(rule.getId() + badSentence, null);
assertTrue(lang + ": Did expect one error in: \"" + badSentence
+ "\" (Rule: " + rule + "), got " + matches.length,
matches.length == 1);
assertEquals(lang
+ ": Incorrect match position markup (start) for rule " + rule,
expectedMatchStart, matches[0].getFromPos());
assertEquals(lang
+ ": Incorrect match position markup (end) for rule " + rule,
expectedMatchEnd, matches[0].getToPos());
// make sure suggestion is what we expect it to be
if (suggestedCorrection != null && suggestedCorrection.size() > 0) {
assertTrue(
lang + ": Incorrect suggestions: "
+ suggestedCorrection.toString() + " != "
+ matches[0].getSuggestedReplacements() + " for rule "
+ rule, suggestedCorrection.equals(matches[0]
.getSuggestedReplacements()));
}
// make sure the suggested correction doesn't produce an error:
if (matches[0].getSuggestedReplacements().size() > 0) {
final int fromPos = matches[0].getFromPos();
final int toPos = matches[0].getToPos();
for (final String repl : matches[0].getSuggestedReplacements()) {
final String fixedSentence = badSentence.substring(0, fromPos)
+ repl + badSentence.substring(toPos);
matches = getMatches(rule, fixedSentence, languageTool);
assertEquals("Corrected sentence for rule " + rule
+ " triggered error: " + fixedSentence, 0, matches.length);
}
} else {
noSuggestionCount++;
}
}
}
}
}
if (!complexRules.isEmpty()) {
final Set<String> set = complexRules.keySet();
final List<PatternRule> badRules = new ArrayList<PatternRule>();
final Iterator<String> iter = set.iterator();
while (iter.hasNext()) {
final PatternRule badRule = complexRules.get(iter.next());
if (badRule != null) {
badRule.notComplexPhrase();
badRule
.setMessage("The rule contains a phrase that never matched any incorrect example.");
badRules.add(badRule);
}
}
if (!badRules.isEmpty()) {
testGrammarRulesFromXML(badRules, languageTool, lang);
}
}
}
protected String cleanXML(final String str) {
return str.replaceAll("<([^<].*?)>", "");
}
private boolean match(final Rule rule, final String sentence,
final JLanguageTool languageTool) throws IOException {
final AnalyzedSentence text = languageTool.getAnalyzedSentence(sentence);
final RuleMatch[] matches = rule.match(text);
/*
* for (int i = 0; i < matches.length; i++) {
* System.err.println(matches[i]); }
*/
return matches.length > 0;
}
private RuleMatch[] getMatches(final Rule rule, final String sentence,
final JLanguageTool languageTool) throws IOException {
final AnalyzedSentence text = languageTool.getAnalyzedSentence(sentence);
final RuleMatch[] matches = rule.match(text);
/*
* for (int i = 0; i < matches.length; i++) {
* System.err.println(matches[i]); }
*/
return matches;
}
public void testUppercasingSuggestion() throws IOException {
final JLanguageTool langTool = new JLanguageTool(Language.ENGLISH);
langTool.activateDefaultPatternRules();
final List<RuleMatch> matches = langTool
.check("Were are in the process of ...");
assertEquals(1, matches.size());
final RuleMatch match = matches.get(0);
final List<String> sugg = match.getSuggestedReplacements();
assertEquals(2, sugg.size());
assertEquals("Where", sugg.get(0));
assertEquals("We", sugg.get(1));
}
public void testRule() throws IOException {
PatternRule pr;
RuleMatch[] matches;
pr = makePatternRule("one");
matches = pr
.match(langTool.getAnalyzedSentence("A non-matching sentence."));
assertEquals(0, matches.length);
matches = pr.match(langTool
.getAnalyzedSentence("A matching sentence with one match."));
assertEquals(1, matches.length);
assertEquals(25, matches[0].getFromPos());
assertEquals(28, matches[0].getToPos());
// these two are not set if the rule is called standalone (not via
// JLanguageTool):
assertEquals(-1, matches[0].getColumn());
assertEquals(-1, matches[0].getLine());
assertEquals("ID1", matches[0].getRule().getId());
assertTrue(matches[0].getMessage().equals("user visible message"));
assertTrue(matches[0].getShortMessage().equals("short comment"));
matches = pr.match(langTool
.getAnalyzedSentence("one one and one: three matches"));
assertEquals(3, matches.length);
pr = makePatternRule("one two");
matches = pr.match(langTool.getAnalyzedSentence("this is one not two"));
assertEquals(0, matches.length);
matches = pr.match(langTool.getAnalyzedSentence("this is two one"));
assertEquals(0, matches.length);
matches = pr.match(langTool.getAnalyzedSentence("this is one two three"));
assertEquals(1, matches.length);
matches = pr.match(langTool.getAnalyzedSentence("one two"));
assertEquals(1, matches.length);
pr = makePatternRule("one|foo|xxxx two", false, true);
matches = pr.match(langTool.getAnalyzedSentence("one foo three"));
assertEquals(0, matches.length);
matches = pr.match(langTool.getAnalyzedSentence("one two"));
assertEquals(1, matches.length);
matches = pr.match(langTool.getAnalyzedSentence("foo two"));
assertEquals(1, matches.length);
matches = pr.match(langTool.getAnalyzedSentence("one foo two"));
assertEquals(1, matches.length);
matches = pr.match(langTool.getAnalyzedSentence("y x z one two blah foo"));
assertEquals(1, matches.length);
pr = makePatternRule("one|foo|xxxx two|yyy", false, true);
matches = pr.match(langTool.getAnalyzedSentence("one, yyy"));
assertEquals(0, matches.length);
matches = pr.match(langTool.getAnalyzedSentence("one yyy"));
assertEquals(1, matches.length);
matches = pr.match(langTool.getAnalyzedSentence("xxxx two"));
assertEquals(1, matches.length);
matches = pr.match(langTool.getAnalyzedSentence("xxxx yyy"));
assertEquals(1, matches.length);
}
private PatternRule makePatternRule(final String s) {
return makePatternRule(s, false, false);
}
private PatternRule makePatternRule(final String s,
final boolean caseSensitive, final boolean regex) {
final List<Element> elems = new ArrayList<Element>();
final String[] parts = s.split(" ");
boolean pos = false;
Element se = null;
for (final String element : parts) {
if (element.equals("SENT_START")) {
pos = true;
}
if (!pos) {
se = new Element(element, caseSensitive, regex, false);
} else {
se = new Element("", caseSensitive, regex, false);
}
if (pos) {
se.setPosElement(element, false, false);
}
elems.add(se);
pos = false;
}
final PatternRule rule = new PatternRule("ID1", Language.ENGLISH, elems,
"test rule", "user visible message", "short comment");
return rule;
}
public void testSentenceStart() throws IOException {
PatternRule pr;
RuleMatch[] matches;
pr = makePatternRule("SENT_START One");
matches = pr.match(langTool.getAnalyzedSentence("Not One word."));
assertEquals(0, matches.length);
matches = pr.match(langTool.getAnalyzedSentence("One word."));
assertEquals(1, matches.length);
}
private static String callFormatMultipleSynthesis(final String[] suggs,
final String left, final String right) throws IllegalArgumentException,
SecurityException, InvocationTargetException, IllegalAccessException,
NoSuchMethodException {
Class[] argClasses = { String[].class, String.class, String.class };
Object[] argObjects = { suggs, left, right };
return TestTools.callStringStaticMethod(PatternRule.class,
"formatMultipleSynthesis", argClasses, argObjects);
}
/* test private methods as well */
public void testformatMultipleSynthesis() throws IllegalArgumentException,
SecurityException, InvocationTargetException, IllegalAccessException,
NoSuchMethodException {
final String[] suggArray = { "blah blah", "foo bar" };
assertEquals(
"This is how you should write: <suggestion>blah blah</suggestion>, <suggestion>foo bar</suggestion>.",
callFormatMultipleSynthesis(suggArray,
"This is how you should write: <suggestion>", "</suggestion>."));
final String[] suggArray2 = { "test", " " };
assertEquals(
"This is how you should write: <suggestion>test</suggestion>, <suggestion> </suggestion>.",
callFormatMultipleSynthesis(suggArray2,
"This is how you should write: <suggestion>", "</suggestion>."));
}
/**
* Test XML patterns, as a help for people developing rules that are not
* programmers.
*/
public static void main(final String[] args) throws IOException {
final PatternRuleTest prt = new PatternRuleTest();
System.out.println("Running XML pattern tests...");
prt.setUp();
final Set<Language> ignoredLanguages = new HashSet<Language>();
// ignoredLanguages.add(Language.CZECH); // has no XML rules yet
prt.testGrammarRulesFromXML(ignoredLanguages, true);
System.out.println("Tests successful.");
}
}
|
trunk/JLanguageTool/src/test/de/danielnaber/languagetool/rules/patterns/PatternRuleTest.java
|
/* LanguageTool, a natural language style checker
* Copyright (C) 2005 Daniel Naber (http://www.danielnaber.de)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package de.danielnaber.languagetool.rules.patterns;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;
import junit.framework.TestCase;
import de.danielnaber.languagetool.AnalyzedSentence;
import de.danielnaber.languagetool.JLanguageTool;
import de.danielnaber.languagetool.Language;
import de.danielnaber.languagetool.TestTools;
import de.danielnaber.languagetool.rules.IncorrectExample;
import de.danielnaber.languagetool.rules.Rule;
import de.danielnaber.languagetool.rules.RuleMatch;
/**
* @author Daniel Naber
*/
public class PatternRuleTest extends TestCase {
private static JLanguageTool langTool;
private static final Pattern PROBABLE_REGEX = Pattern.compile("[\\[\\]\\*\\+\\|\\^\\{\\}]|\\\\[^0-9]|\\(.+\\)");
@Override
public void setUp() throws IOException {
if (langTool == null) {
langTool = new JLanguageTool(Language.ENGLISH);
}
}
public void testGrammarRulesFromXML() throws IOException {
testGrammarRulesFromXML(null, false);
}
private void testGrammarRulesFromXML(final Set<Language> ignoredLanguages,
final boolean verbose) throws IOException {
for (final Language lang : Language.LANGUAGES) {
if (ignoredLanguages != null && ignoredLanguages.contains(lang)) {
if (verbose) {
System.out.println("Ignoring tests for " + lang.getName());
}
continue;
}
if (verbose) {
System.out.println("Running tests for " + lang.getName() + "...");
}
final PatternRuleLoader ruleLoader = new PatternRuleLoader();
final JLanguageTool languageTool = new JLanguageTool(lang);
final String name = "/rules/" + lang.getShortName() + "/grammar.xml";
final List<PatternRule> rules = ruleLoader.getRules(this.getClass()
.getResourceAsStream(name), name);
warnIfRegexpSyntax(rules, lang);
testGrammarRulesFromXML(rules, languageTool, lang);
}
}
// TODO: probably this would be more useful for exceptions
// instead of adding next methods to PatternRule
// we can probably validate using XSD and specify regexes straight there
private void warnIfRegexpSyntax(final List<PatternRule> rules,
final Language lang) {
for (final PatternRule rule : rules) {
for (final Element element : rule.getElements()) {
if (!element.isRegularExpression()
&& (PROBABLE_REGEX.matcher(element.getString())
.find())) {
System.err.println("The " + lang.toString() + " rule: "
+ rule.getId() + " contains element " + "\"" + element
+ "\" that is not marked as regular expression"
+ " but probably is one.");
}
if (element.isRegularExpression()
&& (element.getString() == null || (!PROBABLE_REGEX.matcher(element.getString())
.find()))) {
System.err.println("The " + lang.toString() + " rule: "
+ rule.getId() + " contains element " + "\"" + element
+ "\" that is marked as regular expression"
+ " but probably is not one.");
}
}
}
}
private void testGrammarRulesFromXML(final List<PatternRule> rules,
final JLanguageTool languageTool, final Language lang) throws IOException {
int noSuggestionCount = 0;
final HashMap<String, PatternRule> complexRules = new HashMap<String, PatternRule>();
for (final PatternRule rule : rules) {
final List<String> goodSentences = rule.getCorrectExamples();
for (String goodSentence : goodSentences) {
// enable indentation use
goodSentence = goodSentence.replaceAll("[\\n\\t]+", "");
goodSentence = cleanXML(goodSentence);
assertTrue(goodSentence.trim().length() > 0);
assertFalse(lang + ": Did not expect error in: " + goodSentence
+ " (Rule: " + rule + ")", match(rule, goodSentence, languageTool));
}
final List<IncorrectExample> badSentences = rule.getIncorrectExamples();
for (IncorrectExample origBadExample : badSentences) {
// enable indentation use
String origBadSentence = origBadExample.getExample().replaceAll(
"[\\n\\t]+", "");
final List<String> suggestedCorrection = origBadExample
.getCorrections();
final int expectedMatchStart = origBadSentence.indexOf("<marker>");
final int expectedMatchEnd = origBadSentence.indexOf("</marker>")
- "<marker>".length();
if (expectedMatchStart == -1 || expectedMatchEnd == -1) {
fail(lang
+ ": No error position markup ('<marker>...</marker>') in bad example in rule "
+ rule);
}
final String badSentence = cleanXML(origBadSentence);
assertTrue(badSentence.trim().length() > 0);
RuleMatch[] matches = getMatches(rule, badSentence, languageTool);
if (!rule.isWithComplexPhrase()) {
assertTrue(lang + ": Did expect one error in: \"" + badSentence
+ "\" (Rule: " + rule + "), got " + matches.length
+ ". Additional info:" + rule.getMessage(), matches.length == 1);
assertEquals(lang
+ ": Incorrect match position markup (start) for rule " + rule,
expectedMatchStart, matches[0].getFromPos());
assertEquals(lang
+ ": Incorrect match position markup (end) for rule " + rule,
expectedMatchEnd, matches[0].getToPos());
// make sure suggestion is what we expect it to be
if (suggestedCorrection != null && suggestedCorrection.size() > 0) {
assertTrue(lang + ": Incorrect suggestions: "
+ suggestedCorrection.toString() + " != "
+ matches[0].getSuggestedReplacements() + " for rule " + rule,
suggestedCorrection.equals(matches[0]
.getSuggestedReplacements()));
}
// make sure the suggested correction doesn't produce an error:
if (matches[0].getSuggestedReplacements().size() > 0) {
final int fromPos = matches[0].getFromPos();
final int toPos = matches[0].getToPos();
for (final String repl : matches[0].getSuggestedReplacements()) {
final String fixedSentence = badSentence.substring(0, fromPos)
+ repl + badSentence.substring(toPos);
matches = getMatches(rule, fixedSentence, languageTool);
assertEquals("Corrected sentence for rule " + rule
+ " triggered error: " + fixedSentence, 0, matches.length);
}
} else {
noSuggestionCount++;
}
} else { // for multiple rules created with complex phrases
matches = getMatches(rule, badSentence, languageTool);
if (matches.length == 0
&& !complexRules.containsKey(rule.getId() + badSentence)) {
complexRules.put(rule.getId() + badSentence, rule);
}
if (matches.length != 0) {
complexRules.put(rule.getId() + badSentence, null);
assertTrue(lang + ": Did expect one error in: \"" + badSentence
+ "\" (Rule: " + rule + "), got " + matches.length,
matches.length == 1);
assertEquals(lang
+ ": Incorrect match position markup (start) for rule " + rule,
expectedMatchStart, matches[0].getFromPos());
assertEquals(lang
+ ": Incorrect match position markup (end) for rule " + rule,
expectedMatchEnd, matches[0].getToPos());
// make sure suggestion is what we expect it to be
if (suggestedCorrection != null && suggestedCorrection.size() > 0) {
assertTrue(
lang + ": Incorrect suggestions: "
+ suggestedCorrection.toString() + " != "
+ matches[0].getSuggestedReplacements() + " for rule "
+ rule, suggestedCorrection.equals(matches[0]
.getSuggestedReplacements()));
}
// make sure the suggested correction doesn't produce an error:
if (matches[0].getSuggestedReplacements().size() > 0) {
final int fromPos = matches[0].getFromPos();
final int toPos = matches[0].getToPos();
for (final String repl : matches[0].getSuggestedReplacements()) {
final String fixedSentence = badSentence.substring(0, fromPos)
+ repl + badSentence.substring(toPos);
matches = getMatches(rule, fixedSentence, languageTool);
assertEquals("Corrected sentence for rule " + rule
+ " triggered error: " + fixedSentence, 0, matches.length);
}
} else {
noSuggestionCount++;
}
}
}
}
}
if (!complexRules.isEmpty()) {
final Set<String> set = complexRules.keySet();
final List<PatternRule> badRules = new ArrayList<PatternRule>();
final Iterator<String> iter = set.iterator();
while (iter.hasNext()) {
final PatternRule badRule = complexRules.get(iter.next());
if (badRule != null) {
badRule.notComplexPhrase();
badRule
.setMessage("The rule contains a phrase that never matched any incorrect example.");
badRules.add(badRule);
}
}
if (!badRules.isEmpty()) {
testGrammarRulesFromXML(badRules, languageTool, lang);
}
}
}
protected String cleanXML(final String str) {
return str.replaceAll("<([^<].*?)>", "");
}
private boolean match(final Rule rule, final String sentence,
final JLanguageTool languageTool) throws IOException {
final AnalyzedSentence text = languageTool.getAnalyzedSentence(sentence);
final RuleMatch[] matches = rule.match(text);
/*
* for (int i = 0; i < matches.length; i++) {
* System.err.println(matches[i]); }
*/
return matches.length > 0;
}
private RuleMatch[] getMatches(final Rule rule, final String sentence,
final JLanguageTool languageTool) throws IOException {
final AnalyzedSentence text = languageTool.getAnalyzedSentence(sentence);
final RuleMatch[] matches = rule.match(text);
/*
* for (int i = 0; i < matches.length; i++) {
* System.err.println(matches[i]); }
*/
return matches;
}
public void testUppercasingSuggestion() throws IOException {
final JLanguageTool langTool = new JLanguageTool(Language.ENGLISH);
langTool.activateDefaultPatternRules();
final List<RuleMatch> matches = langTool
.check("Were are in the process of ...");
assertEquals(1, matches.size());
final RuleMatch match = matches.get(0);
final List<String> sugg = match.getSuggestedReplacements();
assertEquals(2, sugg.size());
assertEquals("Where", sugg.get(0));
assertEquals("We", sugg.get(1));
}
public void testRule() throws IOException {
PatternRule pr;
RuleMatch[] matches;
pr = makePatternRule("one");
matches = pr
.match(langTool.getAnalyzedSentence("A non-matching sentence."));
assertEquals(0, matches.length);
matches = pr.match(langTool
.getAnalyzedSentence("A matching sentence with one match."));
assertEquals(1, matches.length);
assertEquals(25, matches[0].getFromPos());
assertEquals(28, matches[0].getToPos());
// these two are not set if the rule is called standalone (not via
// JLanguageTool):
assertEquals(-1, matches[0].getColumn());
assertEquals(-1, matches[0].getLine());
assertEquals("ID1", matches[0].getRule().getId());
assertTrue(matches[0].getMessage().equals("user visible message"));
assertTrue(matches[0].getShortMessage().equals("short comment"));
matches = pr.match(langTool
.getAnalyzedSentence("one one and one: three matches"));
assertEquals(3, matches.length);
pr = makePatternRule("one two");
matches = pr.match(langTool.getAnalyzedSentence("this is one not two"));
assertEquals(0, matches.length);
matches = pr.match(langTool.getAnalyzedSentence("this is two one"));
assertEquals(0, matches.length);
matches = pr.match(langTool.getAnalyzedSentence("this is one two three"));
assertEquals(1, matches.length);
matches = pr.match(langTool.getAnalyzedSentence("one two"));
assertEquals(1, matches.length);
pr = makePatternRule("one|foo|xxxx two", false, true);
matches = pr.match(langTool.getAnalyzedSentence("one foo three"));
assertEquals(0, matches.length);
matches = pr.match(langTool.getAnalyzedSentence("one two"));
assertEquals(1, matches.length);
matches = pr.match(langTool.getAnalyzedSentence("foo two"));
assertEquals(1, matches.length);
matches = pr.match(langTool.getAnalyzedSentence("one foo two"));
assertEquals(1, matches.length);
matches = pr.match(langTool.getAnalyzedSentence("y x z one two blah foo"));
assertEquals(1, matches.length);
pr = makePatternRule("one|foo|xxxx two|yyy", false, true);
matches = pr.match(langTool.getAnalyzedSentence("one, yyy"));
assertEquals(0, matches.length);
matches = pr.match(langTool.getAnalyzedSentence("one yyy"));
assertEquals(1, matches.length);
matches = pr.match(langTool.getAnalyzedSentence("xxxx two"));
assertEquals(1, matches.length);
matches = pr.match(langTool.getAnalyzedSentence("xxxx yyy"));
assertEquals(1, matches.length);
}
private PatternRule makePatternRule(final String s) {
return makePatternRule(s, false, false);
}
private PatternRule makePatternRule(final String s,
final boolean caseSensitive, final boolean regex) {
final List<Element> elems = new ArrayList<Element>();
final String[] parts = s.split(" ");
boolean pos = false;
Element se = null;
for (final String element : parts) {
if (element.equals("SENT_START")) {
pos = true;
}
if (!pos) {
se = new Element(element, caseSensitive, regex, false);
} else {
se = new Element("", caseSensitive, regex, false);
}
if (pos) {
se.setPosElement(element, false, false);
}
elems.add(se);
pos = false;
}
final PatternRule rule = new PatternRule("ID1", Language.ENGLISH, elems,
"test rule", "user visible message", "short comment");
return rule;
}
public void testSentenceStart() throws IOException {
PatternRule pr;
RuleMatch[] matches;
pr = makePatternRule("SENT_START One");
matches = pr.match(langTool.getAnalyzedSentence("Not One word."));
assertEquals(0, matches.length);
matches = pr.match(langTool.getAnalyzedSentence("One word."));
assertEquals(1, matches.length);
}
private static String callFormatMultipleSynthesis(final String[] suggs,
final String left, final String right) throws IllegalArgumentException,
SecurityException, InvocationTargetException, IllegalAccessException,
NoSuchMethodException {
Class[] argClasses = { String[].class, String.class, String.class };
Object[] argObjects = { suggs, left, right };
return TestTools.callStringStaticMethod(PatternRule.class,
"formatMultipleSynthesis", argClasses, argObjects);
}
/* test private methods as well */
public void testformatMultipleSynthesis() throws IllegalArgumentException,
SecurityException, InvocationTargetException, IllegalAccessException,
NoSuchMethodException {
final String[] suggArray = { "blah blah", "foo bar" };
assertEquals(
"This is how you should write: <suggestion>blah blah</suggestion>, <suggestion>foo bar</suggestion>.",
callFormatMultipleSynthesis(suggArray,
"This is how you should write: <suggestion>", "</suggestion>."));
final String[] suggArray2 = { "test", " " };
assertEquals(
"This is how you should write: <suggestion>test</suggestion>, <suggestion> </suggestion>.",
callFormatMultipleSynthesis(suggArray2,
"This is how you should write: <suggestion>", "</suggestion>."));
}
/**
* Test XML patterns, as a help for people developing rules that are not
* programmers.
*/
public static void main(final String[] args) throws IOException {
final PatternRuleTest prt = new PatternRuleTest();
System.out.println("Running XML pattern tests...");
prt.setUp();
final Set<Language> ignoredLanguages = new HashSet<Language>();
// ignoredLanguages.add(Language.CZECH); // has no XML rules yet
prt.testGrammarRulesFromXML(ignoredLanguages, true);
System.out.println("Tests successful.");
}
}
|
tweak regex warning
|
trunk/JLanguageTool/src/test/de/danielnaber/languagetool/rules/patterns/PatternRuleTest.java
|
tweak regex warning
|
|
Java
|
apache-2.0
|
7f643bfb9a43fb5fb29cb6e1ee2323dc5cdb427c
| 0
|
tombolaltd/cordova-plugin-inappbrowser,tombolaltd/cordova-plugin-inappbrowser,tombolaltd/cordova-plugin-inappbrowser
|
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
package org.apache.cordova.inappbrowser;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.provider.Browser;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.InputType;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.HttpAuthHandler;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.Config;
import org.apache.cordova.CordovaArgs;
import org.apache.cordova.CordovaHttpAuthHandler;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.LOG;
import org.apache.cordova.PluginManager;
import org.apache.cordova.PluginResult;
import org.json.JSONException;
import org.json.JSONObject;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.StringTokenizer;
@SuppressLint("SetJavaScriptEnabled")
public class InAppBrowser extends CordovaPlugin {
private static final String NULL = "null";
protected static final String LOG_TAG = "InAppBrowser";
private static final String SELF = "_self";
private static final String SYSTEM = "_system";
private static final String EXIT_EVENT = "exit";
private static final String LOCATION = "location";
private static final String ZOOM = "zoom";
private static final String HIDDEN = "hidden";
private static final String LOAD_START_EVENT = "loadstart";
private static final String LOAD_STOP_EVENT = "loadstop";
private static final String LOAD_ERROR_EVENT = "loaderror";
private static final String CLEAR_ALL_CACHE = "clearcache";
private static final String CLEAR_SESSION_CACHE = "clearsessioncache";
private static final String HARDWARE_BACK_BUTTON = "hardwareback";
private static final String MEDIA_PLAYBACK_REQUIRES_USER_ACTION = "mediaPlaybackRequiresUserAction";
private static final String SHOULD_PAUSE = "shouldPauseOnSuspend";
private InAppBrowserDialog dialog;
private WebView inAppWebView;
private EditText edittext;
private CallbackContext callbackContext;
private boolean showLocationBar = true;
private boolean showZoomControls = true;
private boolean openWindowHidden = false;
private boolean clearAllCache = false;
private boolean clearSessionCache = false;
private boolean hadwareBackButton = true;
private boolean mediaPlaybackRequiresUserGesture = false;
private boolean shouldPauseInAppBrowser = false;
boolean reOpenOnNextPageFinished = false;
/**
* Executes the request and returns PluginResult.
*
* @param action the action to execute.
* @param args JSONArry of arguments for the plugin.
* @param callbackContext the callbackContext used when calling back into JavaScript.
* @return A PluginResult object with a status and message.
*/
public boolean execute(String action, CordovaArgs args, final CallbackContext callbackContext) throws JSONException {
if (action.equals("open")) {
this.callbackContext = callbackContext;
final String url = args.getString(0);
String t = args.optString(1);
if (t == null || t.equals("") || t.equals(NULL)) {
t = SELF;
}
final String target = t;
final HashMap<String, Boolean> features = parseFeature(args.optString(2));
LOG.d(LOG_TAG, "target = " + target);
this.cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
String result = "";
// SELF
if (SELF.equals(target)) {
LOG.d(LOG_TAG, "in self");
/* This code exists for compatibility between 3.x and 4.x versions of Cordova.
* Previously the Config class had a static method, isUrlWhitelisted(). That
* responsibility has been moved to the plugins, with an aggregating method in
* PluginManager.
*/
Boolean shouldAllowNavigation = shouldAllowNavigation(url);
// load in webview
if (Boolean.TRUE.equals(shouldAllowNavigation)) {
LOG.d(LOG_TAG, "loading in webview");
webView.loadUrl(url);
}
//Load the dialer
else if (url.startsWith(WebView.SCHEME_TEL))
{
try {
LOG.d(LOG_TAG, "loading in dialer");
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse(url));
cordova.getActivity().startActivity(intent);
} catch (android.content.ActivityNotFoundException e) {
LOG.e(LOG_TAG, "Error dialing " + url + ": " + e.toString());
}
}
// load in InAppBrowser
else {
LOG.d(LOG_TAG, "loading in InAppBrowser");
result = showWebPage(url, features);
}
}
// SYSTEM
else if (SYSTEM.equals(target)) {
LOG.d(LOG_TAG, "in system");
result = openExternal(url);
}
// BLANK - or anything else
else {
LOG.d(LOG_TAG, "in blank");
result = showWebPage(url, features);
}
PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, result);
pluginResult.setKeepCallback(true);
callbackContext.sendPluginResult(pluginResult);
}
});
}
else if (action.equals("close")) {
closeDialog();
}
else if (action.equals("reveal")) {
reveal();
}
else if (action.equals("hide")) {
hide();
}
else if (action.equals("injectScriptCode")) {
String jsWrapper = null;
if (args.getBoolean(1)) {
jsWrapper = String.format("(function(){prompt(JSON.stringify([eval(%%s)]), 'gap-iab://%s')})()", callbackContext.getCallbackId());
}
injectDeferredObject(args.getString(0), jsWrapper);
}
else if (action.equals("injectScriptFile")) {
String jsWrapper;
if (args.getBoolean(1)) {
jsWrapper = String.format("(function(d) { var c = d.createElement('script'); c.src = %%s; c.onload = function() { prompt('', 'gap-iab://%s'); }; d.body.appendChild(c); })(document)", callbackContext.getCallbackId());
} else {
jsWrapper = "(function(d) { var c = d.createElement('script'); c.src = %s; d.body.appendChild(c); })(document)";
}
injectDeferredObject(args.getString(0), jsWrapper);
}
else if (action.equals("injectStyleCode")) {
String jsWrapper;
if (args.getBoolean(1)) {
jsWrapper = String.format("(function(d) { var c = d.createElement('style'); c.innerHTML = %%s; d.body.appendChild(c); prompt('', 'gap-iab://%s');})(document)", callbackContext.getCallbackId());
} else {
jsWrapper = "(function(d) { var c = d.createElement('style'); c.innerHTML = %s; d.body.appendChild(c); })(document)";
}
injectDeferredObject(args.getString(0), jsWrapper);
}
else if (action.equals("injectStyleFile")) {
String jsWrapper;
if (args.getBoolean(1)) {
jsWrapper = String.format("(function(d) { var c = d.createElement('link'); c.rel='stylesheet'; c.type='text/css'; c.href = %%s; d.head.appendChild(c); prompt('', 'gap-iab://%s');})(document)", callbackContext.getCallbackId());
} else {
jsWrapper = "(function(d) { var c = d.createElement('link'); c.rel='stylesheet'; c.type='text/css'; c.href = %s; d.head.appendChild(c); })(document)";
}
injectDeferredObject(args.getString(0), jsWrapper);
}
else if (action.equals("show")) {
showDialogue();
}
else if (action.equals("hide")) {
hideDialog(args);
}
else if (action.equals("reveal")) {
revealDialog(args);
}
else {
return false;
}
return true;
}
public void hideDialog(CordovaArgs args) throws JSONException {
final boolean goToBlank = args.isNull(0) ? false : args.getBoolean(0);
this.cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
if(null == inAppWebView){
return;
}
if(dialog != null) {
dialog.hide();
if(goToBlank){
inAppWebView.loadUrl("about:blank");
}
}
}
});
PluginResult pluginResult = new PluginResult(PluginResult.Status.OK);
pluginResult.setKeepCallback(true);
this.callbackContext.sendPluginResult(pluginResult);
}
public void revealDialog(CordovaArgs args) throws JSONException {
if(args.isNull(0)) {
showDialogue();
return;
}
final String url = args.getString(0);
if (url == null || url.equals("") || url.equals(NULL)) {
showDialogue();
return;
}
if(!shouldAllowNavigation(url, "shouldAllowRequest") ) {
return;
}
this.cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
if(null == inAppWebView || null == inAppWebView.getUrl()){
return;
}
if(inAppWebView.getUrl().equals(url)){
showDialogue();
}
else {
reOpenOnNextPageFinished = true;
navigate(url);
}
}
});
}
public void showDialogue() {
this.cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
if(dialog != null) {
dialog.show();
}
}
});
PluginResult pluginResult = new PluginResult(PluginResult.Status.OK);
pluginResult.setKeepCallback(true);
this.callbackContext.sendPluginResult(pluginResult);
}
public Boolean shouldAllowNavigation(String url) {
return shouldAllowNavigation(url, "shouldAllowNavigation");
}
public Boolean shouldAllowNavigation(String url, String pluginManagerMethod) {
Boolean shouldAllowNavigation = null;
if (url.startsWith("javascript:")) {
shouldAllowNavigation = true;
}
if (shouldAllowNavigation == null) {
try {
Method iuw = Config.class.getMethod("isUrlWhiteListed", String.class);
shouldAllowNavigation = (Boolean)iuw.invoke(null, url);
} catch (NoSuchMethodException e) {
LOG.d(LOG_TAG, e.getLocalizedMessage());
} catch (IllegalAccessException e) {
LOG.d(LOG_TAG, e.getLocalizedMessage());
} catch (InvocationTargetException e) {
LOG.d(LOG_TAG, e.getLocalizedMessage());
}
}
if (shouldAllowNavigation == null) {
try {
Method gpm = webView.getClass().getMethod("getPluginManager");
PluginManager pm = (PluginManager)gpm.invoke(webView);
Method san = pm.getClass().getMethod(pluginManagerMethod, String.class);
shouldAllowNavigation = (Boolean)san.invoke(pm, url);
} catch (NoSuchMethodException e) {
LOG.d(LOG_TAG, e.getLocalizedMessage());
} catch (IllegalAccessException e) {
LOG.d(LOG_TAG, e.getLocalizedMessage());
} catch (InvocationTargetException e) {
LOG.d(LOG_TAG, e.getLocalizedMessage());
}
}
return shouldAllowNavigation;
}
/**
* Called when the view navigates.
*/
@Override
public void onReset() {
closeDialog();
}
/**
* Called when the system is about to start resuming a previous activity.
*/
@Override
public void onPause(boolean multitasking) {
if (shouldPauseInAppBrowser) {
inAppWebView.onPause();
}
}
/**
* Called when the activity will start interacting with the user.
*/
@Override
public void onResume(boolean multitasking) {
if (shouldPauseInAppBrowser) {
inAppWebView.onResume();
}
}
/**
* Called by AccelBroker when listener is to be shut down.
* Stop listener.
*/
public void onDestroy() {
closeDialog();
}
/**
* Inject an object (script or style) into the InAppBrowser WebView.
*
* This is a helper method for the inject{Script|Style}{Code|File} API calls, which
* provides a consistent method for injecting JavaScript code into the document.
*
* If a wrapper string is supplied, then the source string will be JSON-encoded (adding
* quotes) and wrapped using string formatting. (The wrapper string should have a single
* '%s' marker)
*
* @param source The source object (filename or script/style text) to inject into
* the document.
* @param jsWrapper A JavaScript string to wrap the source string in, so that the object
* is properly injected, or null if the source string is JavaScript text
* which should be executed directly.
*/
private void injectDeferredObject(String source, String jsWrapper) {
String scriptToInject;
if (jsWrapper != null) {
org.json.JSONArray jsonEsc = new org.json.JSONArray();
jsonEsc.put(source);
String jsonRepr = jsonEsc.toString();
String jsonSourceString = jsonRepr.substring(1, jsonRepr.length()-1);
scriptToInject = String.format(jsWrapper, jsonSourceString);
} else {
scriptToInject = source;
}
final String finalScriptToInject = scriptToInject;
this.cordova.getActivity().runOnUiThread(new Runnable() {
@SuppressLint("NewApi")
@Override
public void run() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
// This action will have the side-effect of blurring the currently focused element
inAppWebView.loadUrl("javascript:" + finalScriptToInject);
} else {
inAppWebView.evaluateJavascript(finalScriptToInject, null);
}
}
});
}
/**
* Put the list of features into a hash map
*
* @param optString
* @return
*/
private HashMap<String, Boolean> parseFeature(String optString) {
if (optString.equals(NULL)) {
return null;
} else {
HashMap<String, Boolean> map = new HashMap<String, Boolean>();
StringTokenizer features = new StringTokenizer(optString, ",");
StringTokenizer option;
while(features.hasMoreElements()) {
option = new StringTokenizer(features.nextToken(), "=");
if (option.hasMoreElements()) {
String key = option.nextToken();
Boolean value = option.nextToken().equals("no") ? Boolean.FALSE : Boolean.TRUE;
map.put(key, value);
}
}
return map;
}
}
/**
* Display a new browser with the specified URL.
*
* @param url the url to load.
* @return "" if ok, or error message.
*/
public String openExternal(String url) {
try {
Intent intent = null;
intent = new Intent(Intent.ACTION_VIEW);
// Omitting the MIME type for file: URLs causes "No Activity found to handle Intent".
// Adding the MIME type to http: URLs causes them to not be handled by the downloader.
Uri uri = Uri.parse(url);
if ("file".equals(uri.getScheme())) {
intent.setDataAndType(uri, webView.getResourceApi().getMimeType(uri));
} else {
intent.setData(uri);
}
intent.putExtra(Browser.EXTRA_APPLICATION_ID, cordova.getActivity().getPackageName());
this.cordova.getActivity().startActivity(intent);
return "";
} catch (android.content.ActivityNotFoundException e) {
LOG.d(LOG_TAG, "InAppBrowser: Error loading url "+url+":"+ e.toString());
return e.toString();
}
}
/**
* Closes the dialog
*/
public void closeDialog() {
this.cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
final WebView childView = inAppWebView;
// The JS protects against multiple calls, so this should happen only when
// closeDialog() is called by other native code.
if (childView == null) {
return;
}
childView.setWebViewClient(new WebViewClient() {
// NB: wait for about:blank before dismissing
public void onPageFinished(WebView view, String url) {
if (dialog != null) {
dialog.dismiss();
dialog = null;
}
}
});
// NB: From SDK 19: "If you call methods on WebView from any thread
// other than your app's UI thread, it can cause unexpected results."
// http://developer.android.com/guide/webapps/migrating.html#Threads
childView.loadUrl("about:blank");
childView.destroy();
try {
JSONObject obj = new JSONObject();
obj.put("type", EXIT_EVENT);
sendUpdate(obj, false);
} catch (JSONException ex) {
LOG.d(LOG_TAG, "Should never happen");
}
}
});
}
/**
* Checks to see if it is possible to go back one page in history, then does so.
*/
public void goBack() {
if (this.inAppWebView.canGoBack()) {
this.inAppWebView.goBack();
}
}
/**
* Can the web browser go back?
* @return boolean
*/
public boolean canGoBack() {
return this.inAppWebView.canGoBack();
}
/**
* Has the user set the hardware back button to go back
* @return boolean
*/
public boolean hardwareBack() {
return hadwareBackButton;
}
/**
* Checks to see if it is possible to go forward one page in history, then does so.
*/
private void goForward() {
if (this.inAppWebView.canGoForward()) {
this.inAppWebView.goForward();
}
}
/**
* Navigate to the new page
*
* @param url to load
*/
private void navigate(String url) {
InputMethodManager imm = (InputMethodManager)this.cordova.getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(edittext.getWindowToken(), 0);
if (!url.startsWith("http") && !url.startsWith("file:")) {
this.inAppWebView.loadUrl("http://" + url);
} else {
this.inAppWebView.loadUrl(url);
}
this.inAppWebView.requestFocus();
}
/**
* Should we show the location bar?
*
* @return boolean
*/
private boolean getShowLocationBar() {
return this.showLocationBar;
}
private InAppBrowser getInAppBrowser(){
return this;
}
/**
* Display a new browser with the specified URL.
*
* @param url the url to load.
* @param features jsonObject
*/
public String showWebPage(final String url, HashMap<String, Boolean> features) {
// Determine if we should hide the location bar.
showLocationBar = true;
showZoomControls = true;
openWindowHidden = false;
mediaPlaybackRequiresUserGesture = false;
if (features != null) {
Boolean show = features.get(LOCATION);
if (show != null) {
showLocationBar = show.booleanValue();
}
Boolean zoom = features.get(ZOOM);
if (zoom != null) {
showZoomControls = zoom.booleanValue();
}
Boolean hidden = features.get(HIDDEN);
if (hidden != null) {
openWindowHidden = hidden.booleanValue();
}
Boolean hardwareBack = features.get(HARDWARE_BACK_BUTTON);
if (hardwareBack != null) {
hadwareBackButton = hardwareBack.booleanValue();
}
Boolean mediaPlayback = features.get(MEDIA_PLAYBACK_REQUIRES_USER_ACTION);
if (mediaPlayback != null) {
mediaPlaybackRequiresUserGesture = mediaPlayback.booleanValue();
}
Boolean cache = features.get(CLEAR_ALL_CACHE);
if (cache != null) {
clearAllCache = cache.booleanValue();
} else {
cache = features.get(CLEAR_SESSION_CACHE);
if (cache != null) {
clearSessionCache = cache.booleanValue();
}
}
Boolean shouldPause = features.get(SHOULD_PAUSE);
if (shouldPause != null) {
shouldPauseInAppBrowser = shouldPause.booleanValue();
}
}
final CordovaWebView thatWebView = this.webView;
// Create dialog in new thread
Runnable runnable = new Runnable() {
/**
* Convert our DIP units to Pixels
*
* @return int
*/
private int dpToPixels(int dipValue) {
int value = (int) TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP,
(float) dipValue,
cordova.getActivity().getResources().getDisplayMetrics()
);
return value;
}
@SuppressLint("NewApi")
public void run() {
// CB-6702 InAppBrowser hangs when opening more than one instance
if (dialog != null) {
dialog.dismiss();
};
// Let's create the main dialog
dialog = new InAppBrowserDialog(cordova.getActivity(), android.R.style.Theme_NoTitleBar);
dialog.getWindow().getAttributes().windowAnimations = android.R.style.Animation_Dialog;
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCancelable(true);
dialog.setInAppBroswer(getInAppBrowser());
// Main container layout
LinearLayout main = new LinearLayout(cordova.getActivity());
main.setOrientation(LinearLayout.VERTICAL);
// Toolbar layout
RelativeLayout toolbar = new RelativeLayout(cordova.getActivity());
//Please, no more black!
toolbar.setBackgroundColor(android.graphics.Color.LTGRAY);
toolbar.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, this.dpToPixels(44)));
toolbar.setPadding(this.dpToPixels(2), this.dpToPixels(2), this.dpToPixels(2), this.dpToPixels(2));
toolbar.setHorizontalGravity(Gravity.LEFT);
toolbar.setVerticalGravity(Gravity.TOP);
// Action Button Container layout
RelativeLayout actionButtonContainer = new RelativeLayout(cordova.getActivity());
actionButtonContainer.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
actionButtonContainer.setHorizontalGravity(Gravity.LEFT);
actionButtonContainer.setVerticalGravity(Gravity.CENTER_VERTICAL);
actionButtonContainer.setId(Integer.valueOf(1));
// Back button
ImageButton back = new ImageButton(cordova.getActivity());
RelativeLayout.LayoutParams backLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
backLayoutParams.addRule(RelativeLayout.ALIGN_LEFT);
back.setLayoutParams(backLayoutParams);
back.setContentDescription("Back Button");
back.setId(Integer.valueOf(2));
Resources activityRes = cordova.getActivity().getResources();
int backResId = activityRes.getIdentifier("ic_action_previous_item", "drawable", cordova.getActivity().getPackageName());
Drawable backIcon = activityRes.getDrawable(backResId);
if (Build.VERSION.SDK_INT >= 16)
back.setBackground(null);
else
back.setBackgroundDrawable(null);
back.setImageDrawable(backIcon);
back.setScaleType(ImageView.ScaleType.FIT_CENTER);
back.setPadding(0, this.dpToPixels(10), 0, this.dpToPixels(10));
if (Build.VERSION.SDK_INT >= 16)
back.getAdjustViewBounds();
back.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
goBack();
}
});
// Forward button
ImageButton forward = new ImageButton(cordova.getActivity());
RelativeLayout.LayoutParams forwardLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
forwardLayoutParams.addRule(RelativeLayout.RIGHT_OF, 2);
forward.setLayoutParams(forwardLayoutParams);
forward.setContentDescription("Forward Button");
forward.setId(Integer.valueOf(3));
int fwdResId = activityRes.getIdentifier("ic_action_next_item", "drawable", cordova.getActivity().getPackageName());
Drawable fwdIcon = activityRes.getDrawable(fwdResId);
if (Build.VERSION.SDK_INT >= 16)
forward.setBackground(null);
else
forward.setBackgroundDrawable(null);
forward.setImageDrawable(fwdIcon);
forward.setScaleType(ImageView.ScaleType.FIT_CENTER);
forward.setPadding(0, this.dpToPixels(10), 0, this.dpToPixels(10));
if (Build.VERSION.SDK_INT >= 16)
forward.getAdjustViewBounds();
forward.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
goForward();
}
});
// Edit Text Box
edittext = new EditText(cordova.getActivity());
RelativeLayout.LayoutParams textLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
textLayoutParams.addRule(RelativeLayout.RIGHT_OF, 1);
textLayoutParams.addRule(RelativeLayout.LEFT_OF, 5);
edittext.setLayoutParams(textLayoutParams);
edittext.setId(Integer.valueOf(4));
edittext.setSingleLine(true);
edittext.setText(url);
edittext.setInputType(InputType.TYPE_TEXT_VARIATION_URI);
edittext.setImeOptions(EditorInfo.IME_ACTION_GO);
edittext.setInputType(InputType.TYPE_NULL); // Will not except input... Makes the text NON-EDITABLE
edittext.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
// If the event is a key-down event on the "enter" button
if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
navigate(edittext.getText().toString());
return true;
}
return false;
}
});
// Close/Done button
ImageButton close = new ImageButton(cordova.getActivity());
RelativeLayout.LayoutParams closeLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
closeLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
close.setLayoutParams(closeLayoutParams);
forward.setContentDescription("Close Button");
close.setId(Integer.valueOf(5));
int closeResId = activityRes.getIdentifier("ic_action_remove", "drawable", cordova.getActivity().getPackageName());
Drawable closeIcon = activityRes.getDrawable(closeResId);
if (Build.VERSION.SDK_INT >= 16)
close.setBackground(null);
else
close.setBackgroundDrawable(null);
close.setImageDrawable(closeIcon);
close.setScaleType(ImageView.ScaleType.FIT_CENTER);
back.setPadding(0, this.dpToPixels(10), 0, this.dpToPixels(10));
if (Build.VERSION.SDK_INT >= 16)
close.getAdjustViewBounds();
close.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
closeDialog();
}
});
// WebView
inAppWebView = new WebView(cordova.getActivity());
inAppWebView.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
inAppWebView.setId(Integer.valueOf(6));
inAppWebView.setWebChromeClient(new InAppChromeClient(thatWebView));
WebViewClient client = new InAppBrowserClient(thatWebView, edittext);
inAppWebView.setWebViewClient(client);
WebSettings settings = inAppWebView.getSettings();
settings.setJavaScriptEnabled(true);
settings.setJavaScriptCanOpenWindowsAutomatically(true);
settings.setBuiltInZoomControls(showZoomControls);
settings.setPluginState(android.webkit.WebSettings.PluginState.ON);
if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1) {
settings.setMediaPlaybackRequiresUserGesture(mediaPlaybackRequiresUserGesture);
}
String overrideUserAgent = preferences.getString("OverrideUserAgent", null);
String appendUserAgent = preferences.getString("AppendUserAgent", null);
if (overrideUserAgent != null) {
settings.setUserAgentString(overrideUserAgent);
}
if (appendUserAgent != null) {
settings.setUserAgentString(settings.getUserAgentString() + appendUserAgent);
}
//Toggle whether this is enabled or not!
Bundle appSettings = cordova.getActivity().getIntent().getExtras();
boolean enableDatabase = appSettings == null ? true : appSettings.getBoolean("InAppBrowserStorageEnabled", true);
if (enableDatabase) {
String databasePath = cordova.getActivity().getApplicationContext().getDir("inAppBrowserDB", Context.MODE_PRIVATE).getPath();
settings.setDatabasePath(databasePath);
settings.setDatabaseEnabled(true);
}
settings.setDomStorageEnabled(true);
if (clearAllCache) {
CookieManager.getInstance().removeAllCookie();
} else if (clearSessionCache) {
CookieManager.getInstance().removeSessionCookie();
}
inAppWebView.loadUrl(url);
inAppWebView.setId(Integer.valueOf(6));
inAppWebView.getSettings().setLoadWithOverviewMode(true);
inAppWebView.getSettings().setUseWideViewPort(true);
inAppWebView.requestFocus();
inAppWebView.requestFocusFromTouch();
// Add the back and forward buttons to our action button container layout
actionButtonContainer.addView(back);
actionButtonContainer.addView(forward);
// Add the views to our toolbar
toolbar.addView(actionButtonContainer);
toolbar.addView(edittext);
toolbar.addView(close);
// Don't add the toolbar if its been disabled
if (getShowLocationBar()) {
// Add our toolbar to our main view/layout
main.addView(toolbar);
}
// Add our webview to our main view/layout
main.addView(inAppWebView);
WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
lp.copyFrom(dialog.getWindow().getAttributes());
lp.width = WindowManager.LayoutParams.MATCH_PARENT;
lp.height = WindowManager.LayoutParams.MATCH_PARENT;
dialog.setContentView(main);
dialog.show();
dialog.getWindow().setAttributes(lp);
// the goal of openhidden is to load the url and not display it
// Show() needs to be called to cause the URL to be loaded
if(openWindowHidden) {
dialog.hide();
}
}
};
this.cordova.getActivity().runOnUiThread(runnable);
return "";
}
/**
* Create a new plugin success result and send it back to JavaScript
*
* @param obj a JSONObject contain event payload information
*/
private void sendUpdate(JSONObject obj, boolean keepCallback) {
sendUpdate(obj, keepCallback, PluginResult.Status.OK);
}
/**
* Create a new plugin result and send it back to JavaScript
*
* @param obj a JSONObject contain event payload information
* @param status the status code to return to the JavaScript environment
*/
private void sendUpdate(JSONObject obj, boolean keepCallback, PluginResult.Status status) {
if (callbackContext != null) {
PluginResult result = new PluginResult(status, obj);
result.setKeepCallback(keepCallback);
callbackContext.sendPluginResult(result);
if (!keepCallback) {
callbackContext = null;
}
}
}
/**
* The webview client receives notifications about appView
*/
public class InAppBrowserClient extends WebViewClient {
EditText edittext;
CordovaWebView webView;
/**
* Constructor.
*
* @param webView
* @param mEditText
*/
public InAppBrowserClient(CordovaWebView webView, EditText mEditText) {
this.webView = webView;
this.edittext = mEditText;
}
/**
* Override the URL that should be loaded
*
* This handles a small subset of all the URIs that would be encountered.
*
* @param webView
* @param url
*/
@Override
public boolean shouldOverrideUrlLoading(WebView webView, String url) {
if (url.startsWith(WebView.SCHEME_TEL)) {
try {
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse(url));
cordova.getActivity().startActivity(intent);
return true;
} catch (android.content.ActivityNotFoundException e) {
LOG.e(LOG_TAG, "Error dialing " + url + ": " + e.toString());
}
} else if (url.startsWith("geo:") || url.startsWith(WebView.SCHEME_MAILTO) || url.startsWith("market:") || url.startsWith("intent:")) {
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
cordova.getActivity().startActivity(intent);
return true;
} catch (android.content.ActivityNotFoundException e) {
LOG.e(LOG_TAG, "Error with " + url + ": " + e.toString());
}
}
// If sms:5551212?body=This is the message
else if (url.startsWith("sms:")) {
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
// Get address
String address = null;
int parmIndex = url.indexOf('?');
if (parmIndex == -1) {
address = url.substring(4);
} else {
address = url.substring(4, parmIndex);
// If body, then set sms body
Uri uri = Uri.parse(url);
String query = uri.getQuery();
if (query != null) {
if (query.startsWith("body=")) {
intent.putExtra("sms_body", query.substring(5));
}
}
}
intent.setData(Uri.parse("sms:" + address));
intent.putExtra("address", address);
intent.setType("vnd.android-dir/mms-sms");
cordova.getActivity().startActivity(intent);
return true;
} catch (android.content.ActivityNotFoundException e) {
LOG.e(LOG_TAG, "Error sending sms " + url + ":" + e.toString());
}
}
return false;
}
/*
* onPageStarted fires the LOAD_START_EVENT
*
* @param view
* @param url
* @param favicon
*/
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
String newloc = "";
if (url.startsWith("http:") || url.startsWith("https:") || url.startsWith("file:")) {
newloc = url;
}
else
{
// Assume that everything is HTTP at this point, because if we don't specify,
// it really should be. Complain loudly about this!!!
LOG.e(LOG_TAG, "Possible Uncaught/Unknown URI");
newloc = "http://" + url;
}
// Update the UI if we haven't already
if (!newloc.equals(edittext.getText().toString())) {
edittext.setText(newloc);
}
try {
JSONObject obj = new JSONObject();
obj.put("type", LOAD_START_EVENT);
obj.put("url", newloc);
sendUpdate(obj, true);
} catch (JSONException ex) {
LOG.e(LOG_TAG, "URI passed in has caused a JSON error.");
}
}
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
// CB-10395 InAppBrowser's WebView not storing cookies reliable to local device storage
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
CookieManager.getInstance().flush();
} else {
CookieSyncManager.getInstance().sync();
}
if(reOpenOnNextPageFinished){
reOpenOnNextPageFinished = false;
showDialogue();
}
try {
JSONObject obj = new JSONObject();
obj.put("type", LOAD_STOP_EVENT);
obj.put("url", url);
sendUpdate(obj, true);
} catch (JSONException ex) {
LOG.d(LOG_TAG, "Should never happen");
}
}
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
super.onReceivedError(view, errorCode, description, failingUrl);
try {
JSONObject obj = new JSONObject();
obj.put("type", LOAD_ERROR_EVENT);
obj.put("url", failingUrl);
obj.put("code", errorCode);
obj.put("message", description);
sendUpdate(obj, true, PluginResult.Status.ERROR);
} catch (JSONException ex) {
LOG.d(LOG_TAG, "Should never happen");
}
}
/**
* On received http auth request.
*/
@Override
public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
// Check if there is some plugin which can resolve this auth challenge
PluginManager pluginManager = null;
try {
Method gpm = webView.getClass().getMethod("getPluginManager");
pluginManager = (PluginManager)gpm.invoke(webView);
} catch (NoSuchMethodException e) {
LOG.d(LOG_TAG, e.getLocalizedMessage());
} catch (IllegalAccessException e) {
LOG.d(LOG_TAG, e.getLocalizedMessage());
} catch (InvocationTargetException e) {
LOG.d(LOG_TAG, e.getLocalizedMessage());
}
if (pluginManager == null) {
try {
Field pmf = webView.getClass().getField("pluginManager");
pluginManager = (PluginManager)pmf.get(webView);
} catch (NoSuchFieldException e) {
LOG.d(LOG_TAG, e.getLocalizedMessage());
} catch (IllegalAccessException e) {
LOG.d(LOG_TAG, e.getLocalizedMessage());
}
}
if (pluginManager != null && pluginManager.onReceivedHttpAuthRequest(webView, new CordovaHttpAuthHandler(handler), host, realm)) {
return;
}
// By default handle 401 like we'd normally do!
super.onReceivedHttpAuthRequest(view, handler, host, realm);
}
}
}
|
src/android/InAppBrowser.java
|
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
package org.apache.cordova.inappbrowser;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.provider.Browser;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.InputType;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.HttpAuthHandler;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.Config;
import org.apache.cordova.CordovaArgs;
import org.apache.cordova.CordovaHttpAuthHandler;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.LOG;
import org.apache.cordova.PluginManager;
import org.apache.cordova.PluginResult;
import org.json.JSONException;
import org.json.JSONObject;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.StringTokenizer;
@SuppressLint("SetJavaScriptEnabled")
public class InAppBrowser extends CordovaPlugin {
private static final String NULL = "null";
protected static final String LOG_TAG = "InAppBrowser";
private static final String SELF = "_self";
private static final String SYSTEM = "_system";
private static final String EXIT_EVENT = "exit";
private static final String LOCATION = "location";
private static final String ZOOM = "zoom";
private static final String HIDDEN = "hidden";
private static final String LOAD_START_EVENT = "loadstart";
private static final String LOAD_STOP_EVENT = "loadstop";
private static final String LOAD_ERROR_EVENT = "loaderror";
private static final String CLEAR_ALL_CACHE = "clearcache";
private static final String CLEAR_SESSION_CACHE = "clearsessioncache";
private static final String HARDWARE_BACK_BUTTON = "hardwareback";
private static final String MEDIA_PLAYBACK_REQUIRES_USER_ACTION = "mediaPlaybackRequiresUserAction";
private static final String SHOULD_PAUSE = "shouldPauseOnSuspend";
private InAppBrowserDialog dialog;
private WebView inAppWebView;
private EditText edittext;
private CallbackContext callbackContext;
private boolean showLocationBar = true;
private boolean showZoomControls = true;
private boolean openWindowHidden = false;
private boolean clearAllCache = false;
private boolean clearSessionCache = false;
private boolean hadwareBackButton = true;
private boolean mediaPlaybackRequiresUserGesture = false;
private boolean shouldPauseInAppBrowser = false;
boolean reOpenOnNextPageFinished = false;
/**
* Executes the request and returns PluginResult.
*
* @param action the action to execute.
* @param args JSONArry of arguments for the plugin.
* @param callbackContext the callbackContext used when calling back into JavaScript.
* @return A PluginResult object with a status and message.
*/
public boolean execute(String action, CordovaArgs args, final CallbackContext callbackContext) throws JSONException {
if (action.equals("open")) {
this.callbackContext = callbackContext;
final String url = args.getString(0);
String t = args.optString(1);
if (t == null || t.equals("") || t.equals(NULL)) {
t = SELF;
}
final String target = t;
final HashMap<String, Boolean> features = parseFeature(args.optString(2));
LOG.d(LOG_TAG, "target = " + target);
this.cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
String result = "";
// SELF
if (SELF.equals(target)) {
LOG.d(LOG_TAG, "in self");
/* This code exists for compatibility between 3.x and 4.x versions of Cordova.
* Previously the Config class had a static method, isUrlWhitelisted(). That
* responsibility has been moved to the plugins, with an aggregating method in
* PluginManager.
*/
Boolean shouldAllowNavigation = shouldAllowNavigation(url);
// load in webview
if (Boolean.TRUE.equals(shouldAllowNavigation)) {
LOG.d(LOG_TAG, "loading in webview");
webView.loadUrl(url);
}
//Load the dialer
else if (url.startsWith(WebView.SCHEME_TEL))
{
try {
LOG.d(LOG_TAG, "loading in dialer");
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse(url));
cordova.getActivity().startActivity(intent);
} catch (android.content.ActivityNotFoundException e) {
LOG.e(LOG_TAG, "Error dialing " + url + ": " + e.toString());
}
}
// load in InAppBrowser
else {
LOG.d(LOG_TAG, "loading in InAppBrowser");
result = showWebPage(url, features);
}
}
// SYSTEM
else if (SYSTEM.equals(target)) {
LOG.d(LOG_TAG, "in system");
result = openExternal(url);
}
// BLANK - or anything else
else {
LOG.d(LOG_TAG, "in blank");
result = showWebPage(url, features);
}
PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, result);
pluginResult.setKeepCallback(true);
callbackContext.sendPluginResult(pluginResult);
}
});
}
else if (action.equals("close")) {
closeDialog();
}
else if (action.equals("injectScriptCode")) {
String jsWrapper = null;
if (args.getBoolean(1)) {
jsWrapper = String.format("(function(){prompt(JSON.stringify([eval(%%s)]), 'gap-iab://%s')})()", callbackContext.getCallbackId());
}
injectDeferredObject(args.getString(0), jsWrapper);
}
else if (action.equals("injectScriptFile")) {
String jsWrapper;
if (args.getBoolean(1)) {
jsWrapper = String.format("(function(d) { var c = d.createElement('script'); c.src = %%s; c.onload = function() { prompt('', 'gap-iab://%s'); }; d.body.appendChild(c); })(document)", callbackContext.getCallbackId());
} else {
jsWrapper = "(function(d) { var c = d.createElement('script'); c.src = %s; d.body.appendChild(c); })(document)";
}
injectDeferredObject(args.getString(0), jsWrapper);
}
else if (action.equals("injectStyleCode")) {
String jsWrapper;
if (args.getBoolean(1)) {
jsWrapper = String.format("(function(d) { var c = d.createElement('style'); c.innerHTML = %%s; d.body.appendChild(c); prompt('', 'gap-iab://%s');})(document)", callbackContext.getCallbackId());
} else {
jsWrapper = "(function(d) { var c = d.createElement('style'); c.innerHTML = %s; d.body.appendChild(c); })(document)";
}
injectDeferredObject(args.getString(0), jsWrapper);
}
else if (action.equals("injectStyleFile")) {
String jsWrapper;
if (args.getBoolean(1)) {
jsWrapper = String.format("(function(d) { var c = d.createElement('link'); c.rel='stylesheet'; c.type='text/css'; c.href = %%s; d.head.appendChild(c); prompt('', 'gap-iab://%s');})(document)", callbackContext.getCallbackId());
} else {
jsWrapper = "(function(d) { var c = d.createElement('link'); c.rel='stylesheet'; c.type='text/css'; c.href = %s; d.head.appendChild(c); })(document)";
}
injectDeferredObject(args.getString(0), jsWrapper);
}
else if (action.equals("show")) {
showDialogue();
}
else if (action.equals("hide")) {
hideDialog(args);
}
else if (action.equals("reveal")) {
revealDialog(args);
}
else {
return false;
}
return true;
}
public void hideDialog(CordovaArgs args) throws JSONException {
final boolean goToBlank = args.isNull(0) ? false : args.getBoolean(0);
this.cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
if(null == inAppWebView){
return;
}
if(dialog != null) {
dialog.hide();
if(goToBlank){
inAppWebView.loadUrl("about:blank");
}
}
}
});
PluginResult pluginResult = new PluginResult(PluginResult.Status.OK);
pluginResult.setKeepCallback(true);
this.callbackContext.sendPluginResult(pluginResult);
}
public void revealDialog(CordovaArgs args) throws JSONException {
if(args.isNull(0)) {
showDialogue();
return;
}
final String url = args.getString(0);
if (url == null || url.equals("") || url.equals(NULL)) {
showDialogue();
return;
}
if(!shouldAllowNavigation(url, "shouldAllowRequest") ) {
return;
}
this.cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
if(null == inAppWebView || null == inAppWebView.getUrl()){
return;
}
if(inAppWebView.getUrl().equals(url)){
showDialogue();
}
else {
reOpenOnNextPageFinished = true;
navigate(url);
}
}
});
}
public void showDialogue() {
this.cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
if(dialog != null) {
dialog.show();
}
}
});
PluginResult pluginResult = new PluginResult(PluginResult.Status.OK);
pluginResult.setKeepCallback(true);
this.callbackContext.sendPluginResult(pluginResult);
}
public Boolean shouldAllowNavigation(String url) {
return shouldAllowNavigation(url, "shouldAllowNavigation");
}
public Boolean shouldAllowNavigation(String url, String pluginManagerMethod) {
Boolean shouldAllowNavigation = null;
if (url.startsWith("javascript:")) {
shouldAllowNavigation = true;
}
if (shouldAllowNavigation == null) {
try {
Method iuw = Config.class.getMethod("isUrlWhiteListed", String.class);
shouldAllowNavigation = (Boolean)iuw.invoke(null, url);
} catch (NoSuchMethodException e) {
LOG.d(LOG_TAG, e.getLocalizedMessage());
} catch (IllegalAccessException e) {
LOG.d(LOG_TAG, e.getLocalizedMessage());
} catch (InvocationTargetException e) {
LOG.d(LOG_TAG, e.getLocalizedMessage());
}
}
if (shouldAllowNavigation == null) {
try {
Method gpm = webView.getClass().getMethod("getPluginManager");
PluginManager pm = (PluginManager)gpm.invoke(webView);
Method san = pm.getClass().getMethod(pluginManagerMethod, String.class);
shouldAllowNavigation = (Boolean)san.invoke(pm, url);
} catch (NoSuchMethodException e) {
LOG.d(LOG_TAG, e.getLocalizedMessage());
} catch (IllegalAccessException e) {
LOG.d(LOG_TAG, e.getLocalizedMessage());
} catch (InvocationTargetException e) {
LOG.d(LOG_TAG, e.getLocalizedMessage());
}
}
return shouldAllowNavigation;
}
/**
* Called when the view navigates.
*/
@Override
public void onReset() {
closeDialog();
}
/**
* Called when the system is about to start resuming a previous activity.
*/
@Override
public void onPause(boolean multitasking) {
if (shouldPauseInAppBrowser) {
inAppWebView.onPause();
}
}
/**
* Called when the activity will start interacting with the user.
*/
@Override
public void onResume(boolean multitasking) {
if (shouldPauseInAppBrowser) {
inAppWebView.onResume();
}
}
/**
* Called by AccelBroker when listener is to be shut down.
* Stop listener.
*/
public void onDestroy() {
closeDialog();
}
/**
* Inject an object (script or style) into the InAppBrowser WebView.
*
* This is a helper method for the inject{Script|Style}{Code|File} API calls, which
* provides a consistent method for injecting JavaScript code into the document.
*
* If a wrapper string is supplied, then the source string will be JSON-encoded (adding
* quotes) and wrapped using string formatting. (The wrapper string should have a single
* '%s' marker)
*
* @param source The source object (filename or script/style text) to inject into
* the document.
* @param jsWrapper A JavaScript string to wrap the source string in, so that the object
* is properly injected, or null if the source string is JavaScript text
* which should be executed directly.
*/
private void injectDeferredObject(String source, String jsWrapper) {
String scriptToInject;
if (jsWrapper != null) {
org.json.JSONArray jsonEsc = new org.json.JSONArray();
jsonEsc.put(source);
String jsonRepr = jsonEsc.toString();
String jsonSourceString = jsonRepr.substring(1, jsonRepr.length()-1);
scriptToInject = String.format(jsWrapper, jsonSourceString);
} else {
scriptToInject = source;
}
final String finalScriptToInject = scriptToInject;
this.cordova.getActivity().runOnUiThread(new Runnable() {
@SuppressLint("NewApi")
@Override
public void run() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
// This action will have the side-effect of blurring the currently focused element
inAppWebView.loadUrl("javascript:" + finalScriptToInject);
} else {
inAppWebView.evaluateJavascript(finalScriptToInject, null);
}
}
});
}
/**
* Put the list of features into a hash map
*
* @param optString
* @return
*/
private HashMap<String, Boolean> parseFeature(String optString) {
if (optString.equals(NULL)) {
return null;
} else {
HashMap<String, Boolean> map = new HashMap<String, Boolean>();
StringTokenizer features = new StringTokenizer(optString, ",");
StringTokenizer option;
while(features.hasMoreElements()) {
option = new StringTokenizer(features.nextToken(), "=");
if (option.hasMoreElements()) {
String key = option.nextToken();
Boolean value = option.nextToken().equals("no") ? Boolean.FALSE : Boolean.TRUE;
map.put(key, value);
}
}
return map;
}
}
/**
* Display a new browser with the specified URL.
*
* @param url the url to load.
* @return "" if ok, or error message.
*/
public String openExternal(String url) {
try {
Intent intent = null;
intent = new Intent(Intent.ACTION_VIEW);
// Omitting the MIME type for file: URLs causes "No Activity found to handle Intent".
// Adding the MIME type to http: URLs causes them to not be handled by the downloader.
Uri uri = Uri.parse(url);
if ("file".equals(uri.getScheme())) {
intent.setDataAndType(uri, webView.getResourceApi().getMimeType(uri));
} else {
intent.setData(uri);
}
intent.putExtra(Browser.EXTRA_APPLICATION_ID, cordova.getActivity().getPackageName());
this.cordova.getActivity().startActivity(intent);
return "";
} catch (android.content.ActivityNotFoundException e) {
LOG.d(LOG_TAG, "InAppBrowser: Error loading url "+url+":"+ e.toString());
return e.toString();
}
}
/**
* Closes the dialog
*/
public void closeDialog() {
this.cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
final WebView childView = inAppWebView;
// The JS protects against multiple calls, so this should happen only when
// closeDialog() is called by other native code.
if (childView == null) {
return;
}
childView.setWebViewClient(new WebViewClient() {
// NB: wait for about:blank before dismissing
public void onPageFinished(WebView view, String url) {
if (dialog != null) {
dialog.dismiss();
dialog = null;
}
}
});
// NB: From SDK 19: "If you call methods on WebView from any thread
// other than your app's UI thread, it can cause unexpected results."
// http://developer.android.com/guide/webapps/migrating.html#Threads
childView.loadUrl("about:blank");
childView.destroy();
try {
JSONObject obj = new JSONObject();
obj.put("type", EXIT_EVENT);
sendUpdate(obj, false);
} catch (JSONException ex) {
LOG.d(LOG_TAG, "Should never happen");
}
}
});
}
/**
* Checks to see if it is possible to go back one page in history, then does so.
*/
public void goBack() {
if (this.inAppWebView.canGoBack()) {
this.inAppWebView.goBack();
}
}
/**
* Can the web browser go back?
* @return boolean
*/
public boolean canGoBack() {
return this.inAppWebView.canGoBack();
}
/**
* Has the user set the hardware back button to go back
* @return boolean
*/
public boolean hardwareBack() {
return hadwareBackButton;
}
/**
* Checks to see if it is possible to go forward one page in history, then does so.
*/
private void goForward() {
if (this.inAppWebView.canGoForward()) {
this.inAppWebView.goForward();
}
}
/**
* Navigate to the new page
*
* @param url to load
*/
private void navigate(String url) {
InputMethodManager imm = (InputMethodManager)this.cordova.getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(edittext.getWindowToken(), 0);
if (!url.startsWith("http") && !url.startsWith("file:")) {
this.inAppWebView.loadUrl("http://" + url);
} else {
this.inAppWebView.loadUrl(url);
}
this.inAppWebView.requestFocus();
}
/**
* Should we show the location bar?
*
* @return boolean
*/
private boolean getShowLocationBar() {
return this.showLocationBar;
}
private InAppBrowser getInAppBrowser(){
return this;
}
/**
* Display a new browser with the specified URL.
*
* @param url the url to load.
* @param features jsonObject
*/
public String showWebPage(final String url, HashMap<String, Boolean> features) {
// Determine if we should hide the location bar.
showLocationBar = true;
showZoomControls = true;
openWindowHidden = false;
mediaPlaybackRequiresUserGesture = false;
if (features != null) {
Boolean show = features.get(LOCATION);
if (show != null) {
showLocationBar = show.booleanValue();
}
Boolean zoom = features.get(ZOOM);
if (zoom != null) {
showZoomControls = zoom.booleanValue();
}
Boolean hidden = features.get(HIDDEN);
if (hidden != null) {
openWindowHidden = hidden.booleanValue();
}
Boolean hardwareBack = features.get(HARDWARE_BACK_BUTTON);
if (hardwareBack != null) {
hadwareBackButton = hardwareBack.booleanValue();
}
Boolean mediaPlayback = features.get(MEDIA_PLAYBACK_REQUIRES_USER_ACTION);
if (mediaPlayback != null) {
mediaPlaybackRequiresUserGesture = mediaPlayback.booleanValue();
}
Boolean cache = features.get(CLEAR_ALL_CACHE);
if (cache != null) {
clearAllCache = cache.booleanValue();
} else {
cache = features.get(CLEAR_SESSION_CACHE);
if (cache != null) {
clearSessionCache = cache.booleanValue();
}
}
Boolean shouldPause = features.get(SHOULD_PAUSE);
if (shouldPause != null) {
shouldPauseInAppBrowser = shouldPause.booleanValue();
}
}
final CordovaWebView thatWebView = this.webView;
// Create dialog in new thread
Runnable runnable = new Runnable() {
/**
* Convert our DIP units to Pixels
*
* @return int
*/
private int dpToPixels(int dipValue) {
int value = (int) TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP,
(float) dipValue,
cordova.getActivity().getResources().getDisplayMetrics()
);
return value;
}
@SuppressLint("NewApi")
public void run() {
// CB-6702 InAppBrowser hangs when opening more than one instance
if (dialog != null) {
dialog.dismiss();
};
// Let's create the main dialog
dialog = new InAppBrowserDialog(cordova.getActivity(), android.R.style.Theme_NoTitleBar);
dialog.getWindow().getAttributes().windowAnimations = android.R.style.Animation_Dialog;
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCancelable(true);
dialog.setInAppBroswer(getInAppBrowser());
// Main container layout
LinearLayout main = new LinearLayout(cordova.getActivity());
main.setOrientation(LinearLayout.VERTICAL);
// Toolbar layout
RelativeLayout toolbar = new RelativeLayout(cordova.getActivity());
//Please, no more black!
toolbar.setBackgroundColor(android.graphics.Color.LTGRAY);
toolbar.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, this.dpToPixels(44)));
toolbar.setPadding(this.dpToPixels(2), this.dpToPixels(2), this.dpToPixels(2), this.dpToPixels(2));
toolbar.setHorizontalGravity(Gravity.LEFT);
toolbar.setVerticalGravity(Gravity.TOP);
// Action Button Container layout
RelativeLayout actionButtonContainer = new RelativeLayout(cordova.getActivity());
actionButtonContainer.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
actionButtonContainer.setHorizontalGravity(Gravity.LEFT);
actionButtonContainer.setVerticalGravity(Gravity.CENTER_VERTICAL);
actionButtonContainer.setId(Integer.valueOf(1));
// Back button
ImageButton back = new ImageButton(cordova.getActivity());
RelativeLayout.LayoutParams backLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
backLayoutParams.addRule(RelativeLayout.ALIGN_LEFT);
back.setLayoutParams(backLayoutParams);
back.setContentDescription("Back Button");
back.setId(Integer.valueOf(2));
Resources activityRes = cordova.getActivity().getResources();
int backResId = activityRes.getIdentifier("ic_action_previous_item", "drawable", cordova.getActivity().getPackageName());
Drawable backIcon = activityRes.getDrawable(backResId);
if (Build.VERSION.SDK_INT >= 16)
back.setBackground(null);
else
back.setBackgroundDrawable(null);
back.setImageDrawable(backIcon);
back.setScaleType(ImageView.ScaleType.FIT_CENTER);
back.setPadding(0, this.dpToPixels(10), 0, this.dpToPixels(10));
if (Build.VERSION.SDK_INT >= 16)
back.getAdjustViewBounds();
back.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
goBack();
}
});
// Forward button
ImageButton forward = new ImageButton(cordova.getActivity());
RelativeLayout.LayoutParams forwardLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
forwardLayoutParams.addRule(RelativeLayout.RIGHT_OF, 2);
forward.setLayoutParams(forwardLayoutParams);
forward.setContentDescription("Forward Button");
forward.setId(Integer.valueOf(3));
int fwdResId = activityRes.getIdentifier("ic_action_next_item", "drawable", cordova.getActivity().getPackageName());
Drawable fwdIcon = activityRes.getDrawable(fwdResId);
if (Build.VERSION.SDK_INT >= 16)
forward.setBackground(null);
else
forward.setBackgroundDrawable(null);
forward.setImageDrawable(fwdIcon);
forward.setScaleType(ImageView.ScaleType.FIT_CENTER);
forward.setPadding(0, this.dpToPixels(10), 0, this.dpToPixels(10));
if (Build.VERSION.SDK_INT >= 16)
forward.getAdjustViewBounds();
forward.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
goForward();
}
});
// Edit Text Box
edittext = new EditText(cordova.getActivity());
RelativeLayout.LayoutParams textLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
textLayoutParams.addRule(RelativeLayout.RIGHT_OF, 1);
textLayoutParams.addRule(RelativeLayout.LEFT_OF, 5);
edittext.setLayoutParams(textLayoutParams);
edittext.setId(Integer.valueOf(4));
edittext.setSingleLine(true);
edittext.setText(url);
edittext.setInputType(InputType.TYPE_TEXT_VARIATION_URI);
edittext.setImeOptions(EditorInfo.IME_ACTION_GO);
edittext.setInputType(InputType.TYPE_NULL); // Will not except input... Makes the text NON-EDITABLE
edittext.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
// If the event is a key-down event on the "enter" button
if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
navigate(edittext.getText().toString());
return true;
}
return false;
}
});
// Close/Done button
ImageButton close = new ImageButton(cordova.getActivity());
RelativeLayout.LayoutParams closeLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
closeLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
close.setLayoutParams(closeLayoutParams);
forward.setContentDescription("Close Button");
close.setId(Integer.valueOf(5));
int closeResId = activityRes.getIdentifier("ic_action_remove", "drawable", cordova.getActivity().getPackageName());
Drawable closeIcon = activityRes.getDrawable(closeResId);
if (Build.VERSION.SDK_INT >= 16)
close.setBackground(null);
else
close.setBackgroundDrawable(null);
close.setImageDrawable(closeIcon);
close.setScaleType(ImageView.ScaleType.FIT_CENTER);
back.setPadding(0, this.dpToPixels(10), 0, this.dpToPixels(10));
if (Build.VERSION.SDK_INT >= 16)
close.getAdjustViewBounds();
close.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
closeDialog();
}
});
// WebView
inAppWebView = new WebView(cordova.getActivity());
inAppWebView.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
inAppWebView.setId(Integer.valueOf(6));
inAppWebView.setWebChromeClient(new InAppChromeClient(thatWebView));
WebViewClient client = new InAppBrowserClient(thatWebView, edittext);
inAppWebView.setWebViewClient(client);
WebSettings settings = inAppWebView.getSettings();
settings.setJavaScriptEnabled(true);
settings.setJavaScriptCanOpenWindowsAutomatically(true);
settings.setBuiltInZoomControls(showZoomControls);
settings.setPluginState(android.webkit.WebSettings.PluginState.ON);
if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1) {
settings.setMediaPlaybackRequiresUserGesture(mediaPlaybackRequiresUserGesture);
}
String overrideUserAgent = preferences.getString("OverrideUserAgent", null);
String appendUserAgent = preferences.getString("AppendUserAgent", null);
if (overrideUserAgent != null) {
settings.setUserAgentString(overrideUserAgent);
}
if (appendUserAgent != null) {
settings.setUserAgentString(settings.getUserAgentString() + appendUserAgent);
}
//Toggle whether this is enabled or not!
Bundle appSettings = cordova.getActivity().getIntent().getExtras();
boolean enableDatabase = appSettings == null ? true : appSettings.getBoolean("InAppBrowserStorageEnabled", true);
if (enableDatabase) {
String databasePath = cordova.getActivity().getApplicationContext().getDir("inAppBrowserDB", Context.MODE_PRIVATE).getPath();
settings.setDatabasePath(databasePath);
settings.setDatabaseEnabled(true);
}
settings.setDomStorageEnabled(true);
if (clearAllCache) {
CookieManager.getInstance().removeAllCookie();
} else if (clearSessionCache) {
CookieManager.getInstance().removeSessionCookie();
}
inAppWebView.loadUrl(url);
inAppWebView.setId(Integer.valueOf(6));
inAppWebView.getSettings().setLoadWithOverviewMode(true);
inAppWebView.getSettings().setUseWideViewPort(true);
inAppWebView.requestFocus();
inAppWebView.requestFocusFromTouch();
// Add the back and forward buttons to our action button container layout
actionButtonContainer.addView(back);
actionButtonContainer.addView(forward);
// Add the views to our toolbar
toolbar.addView(actionButtonContainer);
toolbar.addView(edittext);
toolbar.addView(close);
// Don't add the toolbar if its been disabled
if (getShowLocationBar()) {
// Add our toolbar to our main view/layout
main.addView(toolbar);
}
// Add our webview to our main view/layout
main.addView(inAppWebView);
WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
lp.copyFrom(dialog.getWindow().getAttributes());
lp.width = WindowManager.LayoutParams.MATCH_PARENT;
lp.height = WindowManager.LayoutParams.MATCH_PARENT;
dialog.setContentView(main);
dialog.show();
dialog.getWindow().setAttributes(lp);
// the goal of openhidden is to load the url and not display it
// Show() needs to be called to cause the URL to be loaded
if(openWindowHidden) {
dialog.hide();
}
}
};
this.cordova.getActivity().runOnUiThread(runnable);
return "";
}
/**
* Create a new plugin success result and send it back to JavaScript
*
* @param obj a JSONObject contain event payload information
*/
private void sendUpdate(JSONObject obj, boolean keepCallback) {
sendUpdate(obj, keepCallback, PluginResult.Status.OK);
}
/**
* Create a new plugin result and send it back to JavaScript
*
* @param obj a JSONObject contain event payload information
* @param status the status code to return to the JavaScript environment
*/
private void sendUpdate(JSONObject obj, boolean keepCallback, PluginResult.Status status) {
if (callbackContext != null) {
PluginResult result = new PluginResult(status, obj);
result.setKeepCallback(keepCallback);
callbackContext.sendPluginResult(result);
if (!keepCallback) {
callbackContext = null;
}
}
}
/**
* The webview client receives notifications about appView
*/
public class InAppBrowserClient extends WebViewClient {
EditText edittext;
CordovaWebView webView;
/**
* Constructor.
*
* @param webView
* @param mEditText
*/
public InAppBrowserClient(CordovaWebView webView, EditText mEditText) {
this.webView = webView;
this.edittext = mEditText;
}
/**
* Override the URL that should be loaded
*
* This handles a small subset of all the URIs that would be encountered.
*
* @param webView
* @param url
*/
@Override
public boolean shouldOverrideUrlLoading(WebView webView, String url) {
if (url.startsWith(WebView.SCHEME_TEL)) {
try {
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse(url));
cordova.getActivity().startActivity(intent);
return true;
} catch (android.content.ActivityNotFoundException e) {
LOG.e(LOG_TAG, "Error dialing " + url + ": " + e.toString());
}
} else if (url.startsWith("geo:") || url.startsWith(WebView.SCHEME_MAILTO) || url.startsWith("market:") || url.startsWith("intent:")) {
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
cordova.getActivity().startActivity(intent);
return true;
} catch (android.content.ActivityNotFoundException e) {
LOG.e(LOG_TAG, "Error with " + url + ": " + e.toString());
}
}
// If sms:5551212?body=This is the message
else if (url.startsWith("sms:")) {
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
// Get address
String address = null;
int parmIndex = url.indexOf('?');
if (parmIndex == -1) {
address = url.substring(4);
} else {
address = url.substring(4, parmIndex);
// If body, then set sms body
Uri uri = Uri.parse(url);
String query = uri.getQuery();
if (query != null) {
if (query.startsWith("body=")) {
intent.putExtra("sms_body", query.substring(5));
}
}
}
intent.setData(Uri.parse("sms:" + address));
intent.putExtra("address", address);
intent.setType("vnd.android-dir/mms-sms");
cordova.getActivity().startActivity(intent);
return true;
} catch (android.content.ActivityNotFoundException e) {
LOG.e(LOG_TAG, "Error sending sms " + url + ":" + e.toString());
}
}
return false;
}
/*
* onPageStarted fires the LOAD_START_EVENT
*
* @param view
* @param url
* @param favicon
*/
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
String newloc = "";
if (url.startsWith("http:") || url.startsWith("https:") || url.startsWith("file:")) {
newloc = url;
}
else
{
// Assume that everything is HTTP at this point, because if we don't specify,
// it really should be. Complain loudly about this!!!
LOG.e(LOG_TAG, "Possible Uncaught/Unknown URI");
newloc = "http://" + url;
}
// Update the UI if we haven't already
if (!newloc.equals(edittext.getText().toString())) {
edittext.setText(newloc);
}
try {
JSONObject obj = new JSONObject();
obj.put("type", LOAD_START_EVENT);
obj.put("url", newloc);
sendUpdate(obj, true);
} catch (JSONException ex) {
LOG.e(LOG_TAG, "URI passed in has caused a JSON error.");
}
}
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
// CB-10395 InAppBrowser's WebView not storing cookies reliable to local device storage
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
CookieManager.getInstance().flush();
} else {
CookieSyncManager.getInstance().sync();
}
if(reOpenOnNextPageFinished){
reOpenOnNextPageFinished = false;
showDialogue();
}
try {
JSONObject obj = new JSONObject();
obj.put("type", LOAD_STOP_EVENT);
obj.put("url", url);
sendUpdate(obj, true);
} catch (JSONException ex) {
LOG.d(LOG_TAG, "Should never happen");
}
}
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
super.onReceivedError(view, errorCode, description, failingUrl);
try {
JSONObject obj = new JSONObject();
obj.put("type", LOAD_ERROR_EVENT);
obj.put("url", failingUrl);
obj.put("code", errorCode);
obj.put("message", description);
sendUpdate(obj, true, PluginResult.Status.ERROR);
} catch (JSONException ex) {
LOG.d(LOG_TAG, "Should never happen");
}
}
/**
* On received http auth request.
*/
@Override
public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
// Check if there is some plugin which can resolve this auth challenge
PluginManager pluginManager = null;
try {
Method gpm = webView.getClass().getMethod("getPluginManager");
pluginManager = (PluginManager)gpm.invoke(webView);
} catch (NoSuchMethodException e) {
LOG.d(LOG_TAG, e.getLocalizedMessage());
} catch (IllegalAccessException e) {
LOG.d(LOG_TAG, e.getLocalizedMessage());
} catch (InvocationTargetException e) {
LOG.d(LOG_TAG, e.getLocalizedMessage());
}
if (pluginManager == null) {
try {
Field pmf = webView.getClass().getField("pluginManager");
pluginManager = (PluginManager)pmf.get(webView);
} catch (NoSuchFieldException e) {
LOG.d(LOG_TAG, e.getLocalizedMessage());
} catch (IllegalAccessException e) {
LOG.d(LOG_TAG, e.getLocalizedMessage());
}
}
if (pluginManager != null && pluginManager.onReceivedHttpAuthRequest(webView, new CordovaHttpAuthHandler(handler), host, realm)) {
return;
}
// By default handle 401 like we'd normally do!
super.onReceivedHttpAuthRequest(view, handler, host, realm);
}
}
}
|
Added action handler for IAB pointing at stubs
|
src/android/InAppBrowser.java
|
Added action handler for IAB pointing at stubs
|
|
Java
|
apache-2.0
|
e070ec34286d509da693321213aa9f7305a5bc5a
| 0
|
euler-projects/euler-common
|
package net.eulerframework.common.util;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import net.sourceforge.pinyin4j.PinyinHelper;
public abstract class StringUtils {
protected static final Logger logger = LogManager.getLogger();
private static final String REGEX_MULTISPACE = "[^\\S\\r\\n]+";// 除换行外的连续空白字符
/**
* 判断字符串是否为<code>null<code>,<code>""</code>,<code>"null"</code>(忽略大小写)
* @param str 待判断的字符串
* @return 判断结果
*/
public final static boolean isNull(String str) {
return hasText(str) && !str.trim().toLowerCase().equals("null");
}
/**
* Check whether the given {@code String} is empty.
* <p>This method accepts any Object as an argument, comparing it to
* {@code null} and the empty String. As a consequence, this method
* will never return {@code true} for a non-null non-String object.
* <p>The Object signature is useful for general attribute handling code
* that commonly deals with Strings but generally has to iterate over
* Objects since attributes may e.g. be primitive value objects as well.
* @param str the candidate String
* @since 3.2.1
*/
public static boolean isEmpty(Object str) {
return (str == null || "".equals(str));
}
/**
* Check that the given {@code CharSequence} is neither {@code null} nor
* of length 0.
* <p>Note: this method returns {@code true} for a {@code CharSequence}
* that purely consists of whitespace.
* <p><pre class="code">
* StringUtils.hasLength(null) = false
* StringUtils.hasLength("") = false
* StringUtils.hasLength(" ") = true
* StringUtils.hasLength("Hello") = true
* </pre>
* @param str the {@code CharSequence} to check (may be {@code null})
* @return {@code true} if the {@code CharSequence} is not {@code null} and has length
* @see #hasText(String)
*/
public static boolean hasLength(CharSequence str) {
return (str != null && str.length() > 0);
}
/**
* Check that the given {@code String} is neither {@code null} nor of length 0.
* <p>Note: this method returns {@code true} for a {@code String} that
* purely consists of whitespace.
* @param str the {@code String} to check (may be {@code null})
* @return {@code true} if the {@code String} is not {@code null} and has length
* @see #hasLength(CharSequence)
* @see #hasText(String)
*/
public static boolean hasLength(String str) {
return hasLength((CharSequence) str);
}
/**
* Check whether the given {@code CharSequence} contains actual <em>text</em>.
* <p>More specifically, this method returns {@code true} if the
* {@code CharSequence} is not {@code null}, its length is greater than
* 0, and it contains at least one non-whitespace character.
* <p><pre class="code">
* StringUtils.hasText(null) = false
* StringUtils.hasText("") = false
* StringUtils.hasText(" ") = false
* StringUtils.hasText("12345") = true
* StringUtils.hasText(" 12345 ") = true
* </pre>
* @param str the {@code CharSequence} to check (may be {@code null})
* @return {@code true} if the {@code CharSequence} is not {@code null},
* its length is greater than 0, and it does not contain whitespace only
* @see Character#isWhitespace
*/
public static boolean hasText(CharSequence str) {
if (!hasLength(str)) {
return false;
}
int strLen = str.length();
for (int i = 0; i < strLen; i++) {
if (!Character.isWhitespace(str.charAt(i))) {
return true;
}
}
return false;
}
/**
* Check whether the given {@code String} contains actual <em>text</em>.
* <p>More specifically, this method returns {@code true} if the
* {@code String} is not {@code null}, its length is greater than 0,
* and it contains at least one non-whitespace character.
* @param str the {@code String} to check (may be {@code null})
* @return {@code true} if the {@code String} is not {@code null}, its
* length is greater than 0, and it does not contain whitespace only
* @see #hasText(CharSequence)
*/
public static boolean hasText(String str) {
return hasText((CharSequence) str);
}
/**
* 获取字符串的字节数
* @param string 待判断的字符串
* @return 字符串的字节数
*/
public final static int getStringBytesLength(String string) {
if (string == null)
return 0;
return string.getBytes().length;
}
/**
* 按字节长度截取字符串
*
* @param string 要截取的字符串
* @param subBytes 截取字节长度
* @param suffix 如果发生截取,在结果后添加的后缀,为<code>null</code>表示不添加
* @return 截取后字符串
*/
public static String subStringByBytes(String string, int subBytes, String suffix) {
byte[] stringBytes = string.getBytes();
if (stringBytes.length <= subBytes)
return string;
byte[] subStringBytes = Arrays.copyOf(stringBytes, subBytes);
String subString;
try {
subString = new String(subStringBytes, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
subString = subString.substring(0, subString.length() - 1);
if (!StringUtils.isNull(suffix)) {
subString += suffix;
}
return subString;
}
/**
* 将制表符和多个连续的空格用一个空格替代
*
* @param string 待处理的字符串
* @return 处理后的字符串
*/
public static String earseMultiSpcases(String string) {
if (string == null)
return string;
Pattern p_space = Pattern.compile(REGEX_MULTISPACE, Pattern.CASE_INSENSITIVE);
Matcher m_space = p_space.matcher(string);
string = m_space.replaceAll(" "); // 过滤空格制表符标签
return string.trim(); // 返回文本字符串
}
/**
* 删除制表符和空格
*
* @param string 待处理的字符串
* @return 处理后的字符串
*/
public static String earseAllSpcases(String string) {
if (string == null)
return string;
return earseMultiSpcases(string).replace(" ", "");
}
/**
* 将CRLF和CR换行符转换为LF换行符
*
* @param string 待处理的字符串
* @return 处理后的字符串
*/
public static String convertToLF(String string) {
if (string == null)
return string;
return string.replace("\r\n", "\n").replace("\r", "\n");
}
/**
* 将换行符替换为空格
*
* @param string 待处理的字符串
* @return 处理后的字符串
*/
public static String convertReturnToSpace(String string) {
if (string == null)
return string;
return convertToLF(string).replace("\n", " ");
}
/**
* 删除换行符
*
* @param string 待处理的字符串
* @return 处理后的字符串
*/
public static String earseReturn(String string) {
if (string == null)
return string;
return convertToLF(string).replace("\n", "");
}
/**
* 将纯ASCII打印字符串(0x20-0x7e)转为下划线命名法,连续的空白字符会被转换为一个下划线表示,如果待转换的字符串含有非ASCII字符,则放弃转换,原样返回
* @param string 待转换的字符串
* @return 转换后的字符串
*/
public static String toUnderlineNomenclature(String string) {
if(string == null || string.length() == 0)
return string;
if (!string.matches("^[\\u0020-\\u007e]+$")) {
logger.warn("只能转换ASCII打印字符串(0x20-0x7e),函数将返回未修改的字符串");
return string;
}
string = StringUtils.earseMultiSpcases(string);
string = string.replace(' ', '_');
return string;
}
/**
* 首字母转小写
* @param string 待转换的字符串
* @return 转换后的字符串
*/
public static String toLowerCaseFirstChar(String string) {
if(string == null || string.length() == 0)
return string;
if (Character.isLowerCase(string.charAt(0)))
return string;
if(string.length() == 1)
return string.toLowerCase();
else
return (new StringBuilder()).append(Character.toLowerCase(string.charAt(0))).append(string.substring(1)).toString();
}
/**
* 首字母转大写
* @param string 待转换的字符串
* @return 转换后的字符串
*/
public static String toUpperCaseFirstChar(String string) {
if(string == null || string.length() == 0)
return string;
if (Character.isUpperCase(string.charAt(0)))
return string;
if(string.length() == 1)
return string.toUpperCase();
else
return (new StringBuilder()).append(Character.toUpperCase(string.charAt(0))).append(string.substring(1)).toString();
}
/**
* 随机生成字符串,字符串可能的取值在ASCII 0x21-0x7e之间
* @param length 生成的字符串长度
* @return
*/
public static String randomString(int length) {
StringBuffer stringBuffer = new StringBuffer();
Random random = new Random();
for(; length > 0; length--) {
stringBuffer.append((char)(random.nextInt(93)+33));
}
return stringBuffer.toString();
}
/**
* 去除字符串头尾的空白,与<code>String.trim()</code>的区别在于可以处理空对象
* @param string 待处理的字符串
* @return 处理后的字符串
*/
public static String trim(String string) {
if(string == null || string.length() == 0)
return string;
return string.trim();
}
/**
* 将字符串转换为拼音
* @param str 原字符串
* @return 拼音
*/
public static String toPinYinString(String str){
StringBuilder sb=new StringBuilder();
String[] arr=null;
for(int i=0;i<str.length();i++){
arr=PinyinHelper.toHanyuPinyinStringArray(str.charAt(i));
if(arr!=null && arr.length>0){
for (String string : arr) {
sb.append(string);
}
} else {
sb.append(str.charAt(i));
}
}
return sb.toString().toLowerCase();
}
}
|
src/main/java/net/eulerframework/common/util/StringUtils.java
|
package net.eulerframework.common.util;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import net.sourceforge.pinyin4j.PinyinHelper;
public abstract class StringUtils {
protected static final Logger logger = LogManager.getLogger();
private static final String REGEX_MULTISPACE = "[^\\S\\r\\n]+";// 除换行外的连续空白字符
/**
* 判断字符串是否为<code>null<code>,<code>""</code>,<code>"null"</code>(忽略大小写)
* @param string 待判断的字符串
* @return 判断结果
*/
public final static boolean isNull(String string) {
return string == null || string.trim().equals("") || string.trim().toLowerCase().equals("null");
}
/**
* Check that the given {@code CharSequence} is neither {@code null} nor
* of length 0.
* <p>Note: this method returns {@code true} for a {@code CharSequence}
* that purely consists of whitespace.
* <p><pre class="code">
* StringUtils.hasLength(null) = false
* StringUtils.hasLength("") = false
* StringUtils.hasLength(" ") = true
* StringUtils.hasLength("Hello") = true
* </pre>
* @param str the {@code CharSequence} to check (may be {@code null})
* @return {@code true} if the {@code CharSequence} is not {@code null} and has length
* @see #hasText(String)
*/
public static boolean hasLength(CharSequence str) {
return (str != null && str.length() > 0);
}
/**
* Check that the given {@code String} is neither {@code null} nor of length 0.
* <p>Note: this method returns {@code true} for a {@code String} that
* purely consists of whitespace.
* @param str the {@code String} to check (may be {@code null})
* @return {@code true} if the {@code String} is not {@code null} and has length
* @see #hasLength(CharSequence)
* @see #hasText(String)
*/
public static boolean hasLength(String str) {
return hasLength((CharSequence) str);
}
/**
* Check whether the given {@code CharSequence} contains actual <em>text</em>.
* <p>More specifically, this method returns {@code true} if the
* {@code CharSequence} is not {@code null}, its length is greater than
* 0, and it contains at least one non-whitespace character.
* <p><pre class="code">
* StringUtils.hasText(null) = false
* StringUtils.hasText("") = false
* StringUtils.hasText(" ") = false
* StringUtils.hasText("12345") = true
* StringUtils.hasText(" 12345 ") = true
* </pre>
* @param str the {@code CharSequence} to check (may be {@code null})
* @return {@code true} if the {@code CharSequence} is not {@code null},
* its length is greater than 0, and it does not contain whitespace only
* @see Character#isWhitespace
*/
public static boolean hasText(CharSequence str) {
if (!hasLength(str)) {
return false;
}
int strLen = str.length();
for (int i = 0; i < strLen; i++) {
if (!Character.isWhitespace(str.charAt(i))) {
return true;
}
}
return false;
}
/**
* Check whether the given {@code String} contains actual <em>text</em>.
* <p>More specifically, this method returns {@code true} if the
* {@code String} is not {@code null}, its length is greater than 0,
* and it contains at least one non-whitespace character.
* @param str the {@code String} to check (may be {@code null})
* @return {@code true} if the {@code String} is not {@code null}, its
* length is greater than 0, and it does not contain whitespace only
* @see #hasText(CharSequence)
*/
public static boolean hasText(String str) {
return hasText((CharSequence) str);
}
/**
* 获取字符串的字节数
* @param string 待判断的字符串
* @return 字符串的字节数
*/
public final static int getStringBytesLength(String string) {
if (string == null)
return 0;
return string.getBytes().length;
}
/**
* 按字节长度截取字符串
*
* @param string 要截取的字符串
* @param subBytes 截取字节长度
* @param suffix 如果发生截取,在结果后添加的后缀,为<code>null</code>表示不添加
* @return 截取后字符串
*/
public static String subStringByBytes(String string, int subBytes, String suffix) {
byte[] stringBytes = string.getBytes();
if (stringBytes.length <= subBytes)
return string;
byte[] subStringBytes = Arrays.copyOf(stringBytes, subBytes);
String subString;
try {
subString = new String(subStringBytes, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
subString = subString.substring(0, subString.length() - 1);
if (!StringUtils.isNull(suffix)) {
subString += suffix;
}
return subString;
}
/**
* 将制表符和多个连续的空格用一个空格替代
*
* @param string 待处理的字符串
* @return 处理后的字符串
*/
public static String earseMultiSpcases(String string) {
if (string == null)
return string;
Pattern p_space = Pattern.compile(REGEX_MULTISPACE, Pattern.CASE_INSENSITIVE);
Matcher m_space = p_space.matcher(string);
string = m_space.replaceAll(" "); // 过滤空格制表符标签
return string.trim(); // 返回文本字符串
}
/**
* 删除制表符和空格
*
* @param string 待处理的字符串
* @return 处理后的字符串
*/
public static String earseAllSpcases(String string) {
if (string == null)
return string;
return earseMultiSpcases(string).replace(" ", "");
}
/**
* 将CRLF和CR换行符转换为LF换行符
*
* @param string 待处理的字符串
* @return 处理后的字符串
*/
public static String convertToLF(String string) {
if (string == null)
return string;
return string.replace("\r\n", "\n").replace("\r", "\n");
}
/**
* 将换行符替换为空格
*
* @param string 待处理的字符串
* @return 处理后的字符串
*/
public static String convertReturnToSpace(String string) {
if (string == null)
return string;
return convertToLF(string).replace("\n", " ");
}
/**
* 删除换行符
*
* @param string 待处理的字符串
* @return 处理后的字符串
*/
public static String earseReturn(String string) {
if (string == null)
return string;
return convertToLF(string).replace("\n", "");
}
/**
* 将纯ASCII打印字符串(0x20-0x7e)转为下划线命名法,连续的空白字符会被转换为一个下划线表示,如果待转换的字符串含有非ASCII字符,则放弃转换,原样返回
* @param string 待转换的字符串
* @return 转换后的字符串
*/
public static String toUnderlineNomenclature(String string) {
if(string == null || string.length() == 0)
return string;
if (!string.matches("^[\\u0020-\\u007e]+$")) {
logger.warn("只能转换ASCII打印字符串(0x20-0x7e),函数将返回未修改的字符串");
return string;
}
string = StringUtils.earseMultiSpcases(string);
string = string.replace(' ', '_');
return string;
}
/**
* 首字母转小写
* @param string 待转换的字符串
* @return 转换后的字符串
*/
public static String toLowerCaseFirstChar(String string) {
if(string == null || string.length() == 0)
return string;
if (Character.isLowerCase(string.charAt(0)))
return string;
if(string.length() == 1)
return string.toLowerCase();
else
return (new StringBuilder()).append(Character.toLowerCase(string.charAt(0))).append(string.substring(1)).toString();
}
/**
* 首字母转大写
* @param string 待转换的字符串
* @return 转换后的字符串
*/
public static String toUpperCaseFirstChar(String string) {
if(string == null || string.length() == 0)
return string;
if (Character.isUpperCase(string.charAt(0)))
return string;
if(string.length() == 1)
return string.toUpperCase();
else
return (new StringBuilder()).append(Character.toUpperCase(string.charAt(0))).append(string.substring(1)).toString();
}
/**
* 随机生成字符串,字符串可能的取值在ASCII 0x21-0x7e之间
* @param length 生成的字符串长度
* @return
*/
public static String randomString(int length) {
StringBuffer stringBuffer = new StringBuffer();
Random random = new Random();
for(; length > 0; length--) {
stringBuffer.append((char)(random.nextInt(93)+33));
}
return stringBuffer.toString();
}
/**
* 去除字符串头尾的空白,与<code>String.trim()</code>的区别在于可以处理空对象
* @param string 待处理的字符串
* @return 处理后的字符串
*/
public static String trim(String string) {
if(string == null || string.length() == 0)
return string;
return string.trim();
}
/**
* 将字符串转换为拼音
* @param str 原字符串
* @return 拼音
*/
public static String toPinYinString(String str){
StringBuilder sb=new StringBuilder();
String[] arr=null;
for(int i=0;i<str.length();i++){
arr=PinyinHelper.toHanyuPinyinStringArray(str.charAt(i));
if(arr!=null && arr.length>0){
for (String string : arr) {
sb.append(string);
}
} else {
sb.append(str.charAt(i));
}
}
return sb.toString().toLowerCase();
}
}
|
common
|
src/main/java/net/eulerframework/common/util/StringUtils.java
|
common
|
|
Java
|
apache-2.0
|
159be7158389abd2d21c82f8824d43caf9c185ad
| 0
|
laborautonomo/jitsi,dkcreinoso/jitsi,ringdna/jitsi,procandi/jitsi,laborautonomo/jitsi,cobratbq/jitsi,jibaro/jitsi,level7systems/jitsi,procandi/jitsi,martin7890/jitsi,tuijldert/jitsi,jitsi/jitsi,marclaporte/jitsi,pplatek/jitsi,damencho/jitsi,procandi/jitsi,procandi/jitsi,bebo/jitsi,tuijldert/jitsi,ringdna/jitsi,gpolitis/jitsi,martin7890/jitsi,459below/jitsi,jitsi/jitsi,marclaporte/jitsi,459below/jitsi,dkcreinoso/jitsi,pplatek/jitsi,iant-gmbh/jitsi,level7systems/jitsi,marclaporte/jitsi,iant-gmbh/jitsi,laborautonomo/jitsi,jibaro/jitsi,bhatvv/jitsi,iant-gmbh/jitsi,bebo/jitsi,gpolitis/jitsi,cobratbq/jitsi,HelioGuilherme66/jitsi,laborautonomo/jitsi,mckayclarey/jitsi,level7systems/jitsi,bhatvv/jitsi,procandi/jitsi,ringdna/jitsi,Metaswitch/jitsi,Metaswitch/jitsi,ringdna/jitsi,dkcreinoso/jitsi,HelioGuilherme66/jitsi,laborautonomo/jitsi,tuijldert/jitsi,damencho/jitsi,gpolitis/jitsi,bhatvv/jitsi,jitsi/jitsi,level7systems/jitsi,damencho/jitsi,jitsi/jitsi,ibauersachs/jitsi,bhatvv/jitsi,HelioGuilherme66/jitsi,iant-gmbh/jitsi,martin7890/jitsi,ibauersachs/jitsi,Metaswitch/jitsi,level7systems/jitsi,mckayclarey/jitsi,gpolitis/jitsi,459below/jitsi,marclaporte/jitsi,ibauersachs/jitsi,459below/jitsi,tuijldert/jitsi,jibaro/jitsi,ringdna/jitsi,pplatek/jitsi,pplatek/jitsi,bhatvv/jitsi,cobratbq/jitsi,459below/jitsi,dkcreinoso/jitsi,HelioGuilherme66/jitsi,damencho/jitsi,damencho/jitsi,mckayclarey/jitsi,gpolitis/jitsi,bebo/jitsi,tuijldert/jitsi,jibaro/jitsi,jibaro/jitsi,martin7890/jitsi,pplatek/jitsi,bebo/jitsi,bebo/jitsi,ibauersachs/jitsi,ibauersachs/jitsi,mckayclarey/jitsi,marclaporte/jitsi,mckayclarey/jitsi,Metaswitch/jitsi,cobratbq/jitsi,iant-gmbh/jitsi,dkcreinoso/jitsi,martin7890/jitsi,HelioGuilherme66/jitsi,cobratbq/jitsi,jitsi/jitsi
|
/*
* SIP Communicator, the OpenSource Java VoIP and Instant Messaging client.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package net.java.sip.communicator.impl.protocol.jabber;
import java.util.*;
import net.java.sip.communicator.impl.protocol.jabber.extensions.jingle.*;
import net.java.sip.communicator.impl.protocol.jabber.extensions.jingle.ContentPacketExtension.*;
import net.java.sip.communicator.impl.protocol.jabber.jinglesdp.*;
import net.java.sip.communicator.service.neomedia.*;
import net.java.sip.communicator.service.neomedia.device.*;
import net.java.sip.communicator.service.neomedia.format.*;
import net.java.sip.communicator.service.protocol.*;
import net.java.sip.communicator.service.protocol.media.*;
import net.java.sip.communicator.util.*;
/**
* An XMPP specific extension of the generic media handler.
*
* @author Emil Ivov
*/
public class CallPeerMediaHandlerJabberImpl
extends CallPeerMediaHandler<CallPeerJabberImpl>
{
/**
* The <tt>Logger</tt> used by the <tt>CallPeerMediaHandlerJabberImpl</tt>
* class and its instances for logging output.
*/
private static final Logger logger = Logger
.getLogger(CallPeerMediaHandlerJabberImpl.class.getName());
/**
* A temporarily single transport manager that we use for generating
* addresses until we properly implement both ICE and Raw UDP managers.
*/
private final TransportManagerJabberImpl transportManager;
/**
* The current description of the streams that we have going toward the
* remote side. We use {@link LinkedHashMap}s to make sure that we preserve
* the order of the individual content extensions.
*/
private Map<String, ContentPacketExtension> localContentMap
= new LinkedHashMap<String, ContentPacketExtension>();
/**
* The current description of the streams that the remote side has with us.
* We use {@link LinkedHashMap}s to make sure that we preserve
* the order of the individual content extensions.
*/
private Map<String, ContentPacketExtension> remoteContentMap
= new LinkedHashMap<String, ContentPacketExtension>();
/**
* Indicates whether the remote party has placed us on hold.
*/
private boolean remotelyOnHold = false;
/**
* Creates a new handler that will be managing media streams for
* <tt>peer</tt>.
*
* @param peer that <tt>CallPeerSipImpl</tt> instance that we will be
* managing media for.
*/
public CallPeerMediaHandlerJabberImpl(CallPeerJabberImpl peer)
{
super(peer, peer);
transportManager = new RawUdpTransportManager(peer);
}
/**
* Lets the underlying implementation take note of this error and only
* then throws it to the using bundles.
*
* @param message the message to be logged and then wrapped in a new
* <tt>OperationFailedException</tt>
* @param errorCode the error code to be assigned to the new
* <tt>OperationFailedException</tt>
* @param cause the <tt>Throwable</tt> that has caused the necessity to log
* an error and have a new <tt>OperationFailedException</tt> thrown
*
* @throws OperationFailedException the exception that we wanted this method
* to throw.
*/
@Override
protected void throwOperationFailedException(String message, int errorCode,
Throwable cause) throws OperationFailedException
{
ProtocolProviderServiceJabberImpl.throwOperationFailedException(
message, errorCode, cause, logger);
}
/**
* Creates if necessary, and configures the stream that this
* <tt>MediaHandler</tt> is using for the <tt>MediaType</tt> matching the
* one of the <tt>MediaDevice</tt>. This method extends the one already
* available by adding a stream name, corresponding to a stream's content
* name.
*
* @param streamName the name of the stream as indicated in the XMPP
* <tt>content</tt> element.
* @param connector the <tt>MediaConnector</tt> that we'd like to bind the
* newly created stream to.
* @param device the <tt>MediaDevice</tt> that we'd like to attach the newly
* created <tt>MediaStream</tt> to.
* @param format the <tt>MediaFormat</tt> that we'd like the new
* <tt>MediaStream</tt> to be set to transmit in.
* @param target the <tt>MediaStreamTarget</tt> containing the RTP and RTCP
* address:port couples that the new stream would be sending packets to.
* @param direction the <tt>MediaDirection</tt> that we'd like the new
* stream to use (i.e. sendonly, sendrecv, recvonly, or inactive).
* @param rtpExtensions the list of <tt>RTPExtension</tt>s that should be
* enabled for this stream.
*
* @return the newly created <tt>MediaStream</tt>.
*
* @throws OperationFailedException if creating the stream fails for any
* reason (like for example accessing the device or setting the format).
*/
protected MediaStream initStream(String streamName,
StreamConnector connector,
MediaDevice device,
MediaFormat format,
MediaStreamTarget target,
MediaDirection direction,
List<RTPExtension> rtpExtensions)
throws OperationFailedException
{
MediaStream stream = super.initStream(connector, device, format,
target, direction, rtpExtensions);
if(stream != null)
stream.setName(streamName);
return stream;
}
/**
* Parses and handles the specified <tt>offer</tt> and returns a content
* extension representing the current state of this media handler. This
* method MUST only be called when <tt>offer</tt> is the first session
* description that this <tt>MediaHandler</tt> is seeing.
*
* @param offer the offer that we'd like to parse, handle and get an answer
* for.
*
* @throws OperationFailedException if we have a problem satisfying the
* description received in <tt>offer</tt> (e.g. failed to open a device or
* initialize a stream ...).
* @throws IllegalArgumentException if there's a problem with
* <tt>offer</tt>'s format or semantics.
*/
public void processOffer(List<ContentPacketExtension> offer)
throws OperationFailedException,
IllegalArgumentException
{
// prepare to generate answers to all the incoming descriptions
List<ContentPacketExtension> answerContentList
= new ArrayList<ContentPacketExtension>(offer.size());
boolean atLeastOneValidDescription = false;
for (ContentPacketExtension content : offer)
{
remoteContentMap.put(content.getName(), content);
RtpDescriptionPacketExtension description
= JingleUtils.getRtpDescription(content);
MediaType mediaType
= MediaType.parseString( description.getMedia() );
List<MediaFormat> remoteFormats = JingleUtils.extractFormats(
description, getDynamicPayloadTypes());
MediaDevice dev = getDefaultDevice(mediaType);
MediaDirection devDirection = (dev == null)
? MediaDirection.INACTIVE
: dev.getDirection();
// Take the preference of the user with respect to streaming
// mediaType into account.
devDirection
= devDirection.and(getDirectionUserPreference(mediaType));
// determine the direction that we need to announce.
MediaDirection remoteDirection = JingleUtils.getDirection(
content, getPeer().isInitiator());
MediaDirection direction = devDirection
.getDirectionForAnswer(remoteDirection);
// intersect the MediaFormats of our device with remote ones
List<MediaFormat> mutuallySupportedFormats
= intersectFormats(remoteFormats, dev.getSupportedFormats());
// check whether we will be exchanging any RTP extensions.
List<RTPExtension> offeredRTPExtensions
= JingleUtils.extractRTPExtensions(
description, this.getRtpExtensionsRegistry());
List<RTPExtension> supportedExtensions
= getExtensionsForType(mediaType);
List<RTPExtension> rtpExtensions = intersectRTPExtensions(
offeredRTPExtensions, supportedExtensions);
// stream target
MediaStreamTarget target
= JingleUtils.extractDefaultTarget(content);
int targetDataPort = target.getDataAddress().getPort();
if (mutuallySupportedFormats.isEmpty()
|| (devDirection == MediaDirection.INACTIVE)
|| (targetDataPort == 0))
{
// skip stream and continue. contrary to sip we don't seem to
// need to send per-stream disabling answer and only one at the
// end.
//close the stream in case it already exists
closeStream(mediaType);
continue;
}
// create the answer description
ContentPacketExtension ourContent = JingleUtils.createDescription(
content.getCreator(), content.getName(),
JingleUtils.getSenders(direction, !getPeer().isInitiator()) ,
mutuallySupportedFormats, rtpExtensions,
getDynamicPayloadTypes(), getRtpExtensionsRegistry());
answerContentList.add(ourContent);
localContentMap.put(content.getName(), ourContent);
atLeastOneValidDescription = true;
}
if (!atLeastOneValidDescription)
ProtocolProviderServiceJabberImpl
.throwOperationFailedException("Offer contained no media "
+ " formats or no valid media descriptions.",
OperationFailedException.ILLEGAL_ARGUMENT, null, logger);
//now, before we go, tell the transport manager to start our candidate
//harvest
getTransportManager().startCandidateHarvest(offer, answerContentList);
}
/**
* Wraps up any ongoing candidate harvests and returns our response to the
* last offer we've received, so that the peer could use it to send a
* <tt>session-accept</tt>.
*
* @return the last generated list of {@link ContentPacketExtension}s that
* the call peer could use to send a <tt>session-accept</tt>.
*
* @throws OperationFailedException if we fail to configure the media stream
*/
protected List<ContentPacketExtension> generateSessionAccept()
throws OperationFailedException
{
List<ContentPacketExtension> sessAccept
= getTransportManager().wrapupHarvest();
//user answered an incoming call so we go through whatever content
//entries we are initializing and init their corresponding streams
for(ContentPacketExtension ourContent : sessAccept)
{
RtpDescriptionPacketExtension description
= JingleUtils.getRtpDescription(ourContent);
MediaType type = MediaType.parseString(description.getMedia());
//
StreamConnector connector
= getTransportManager().getStreamConnector(type);
//the device this stream would be reading from and writing to.
MediaDevice dev = getDefaultDevice(type);
// stream target
ContentPacketExtension theirContent
= this.remoteContentMap.get(ourContent.getName());
MediaStreamTarget target
= JingleUtils.extractDefaultTarget(theirContent);
//stream direction
MediaDirection direction = JingleUtils.getDirection(
ourContent, !getPeer().isInitiator());
//let's now see what was the format we announced as first and
//configure the stream with it.
MediaFormat format = JingleUtils.payloadTypeToMediaFormat(
description.getPayloadTypes().get(0), getDynamicPayloadTypes());
//extract the extensions that we are advertising:
// check whether we will be exchanging any RTP extensions.
List<RTPExtension> rtpExtensions
= JingleUtils.extractRTPExtensions(
description, this.getRtpExtensionsRegistry());
// create the corresponding stream...
initStream(ourContent.getName(), connector, dev, format, target,
direction, rtpExtensions);
}
return sessAccept;
}
/**
* Creates a <tt>List</tt> containing the {@link ContentPacketExtension}s of
* the streams that this handler is prepared to initiate depending on
* available <tt>MediaDevice</tt>s and local on-hold and video transmission
* preferences.
*
* @return a {@link List} containing the {@link ContentPacketExtension}s of
* streams that this handler is prepared to initiate.
*
* @throws OperationFailedException if we fail to create the descriptions
* for reasons like - problems with device interaction, allocating ports,
* etc.
*/
public List<ContentPacketExtension> createContentList()
throws OperationFailedException
{
//Audio Media Description
List<ContentPacketExtension> mediaDescs
= new ArrayList<ContentPacketExtension>();
for (MediaType mediaType : MediaType.values())
{
MediaDevice dev = getDefaultDevice(mediaType);
if (dev != null)
{
MediaDirection direction = dev.getDirection().and(
getDirectionUserPreference(mediaType));
if(isLocallyOnHold())
direction = direction.and(MediaDirection.SENDONLY);
if(direction != MediaDirection.INACTIVE)
{
ContentPacketExtension content = createContentForOffer(
dev.getSupportedFormats(), direction,
dev.getSupportedExtensions());
//ZRTP
if(getPeer().getCall().isSipZrtpAttribute())
{
ZrtpControl control = getZrtpControls().get(mediaType);
if(control == null)
{
control = JabberActivator.getMediaService()
.createZrtpControl();
getZrtpControls().put(mediaType, control);
}
String helloHash = control.getHelloHash();
if(helloHash != null && helloHash.length() > 0)
{
ZrtpHashPacketExtension hash
= new ZrtpHashPacketExtension();
hash.setValue(helloHash);
//we are currently disabling ZRTP until we find the
//time to fix it
content.addChildExtension(hash);
}
}
mediaDescs.add(content);
}
}
}
//fail if all devices were inactive
if(mediaDescs.isEmpty())
{
ProtocolProviderServiceJabberImpl
.throwOperationFailedException(
"We couldn't find any active Audio/Video devices and "
+ "couldn't create a call",
OperationFailedException.GENERAL_ERROR, null, logger);
}
//now add the transport elements
getTransportManager().startCandidateHarvest(mediaDescs);
//XXX ideally we wouldn't wrapup that quickluy. we need to revisit this
return getTransportManager().wrapupHarvest();
}
/**
* Generates an SDP {@link ContentPacketExtension} for the specified
* {@link MediaFormat} list, direction and RTP extensions taking account
* the local streaming preference for the corresponding media type.
*
* @param supportedFormats the list of <tt>MediaFormats</tt> that we'd
* like to advertise.
* @param direction the <tt>MediaDirection</tt> that we'd like to establish
* the stream in.
* @param supportedExtensions the list of <tt>RTPExtension</tt>s that we'd
* like to advertise in the <tt>MediaDescription</tt>.
*
* @return a newly created {@link ContentPacketExtension} representing
* streams that we'd be able to handle.
*/
private ContentPacketExtension createContentForOffer(
List<MediaFormat> supportedFormats,
MediaDirection direction,
List<RTPExtension> supportedExtensions)
{
ContentPacketExtension content = JingleUtils.createDescription(
CreatorEnum.initiator,
supportedFormats.get(0).getMediaType().toString(),
JingleUtils.getSenders(direction, !getPeer().isInitiator()),
supportedFormats,
supportedExtensions,
getDynamicPayloadTypes(),
getRtpExtensionsRegistry());
this.localContentMap.put(content.getName(), content);
return content;
}
/**
* Handles the specified <tt>answer</tt> by creating and initializing the
* corresponding <tt>MediaStream</tt>s.
*
* @param answer the SDP <tt>SessionDescription</tt>.
*
* @throws OperationFailedException if we fail to handle <tt>answer</tt> for
* reasons like failing to initialize media devices or streams.
* @throws IllegalArgumentException if there's a problem with the syntax or
* the semantics of <tt>answer</tt>. Method is synchronized in order to
* avoid closing mediaHandler when we are currently in process of
* initializing, configuring and starting streams and anybody interested
* in this operation can synchronize to the mediaHandler instance to wait
* processing to stop (method setState in CallPeer).
*/
public void processAnswer(List<ContentPacketExtension> answer)
throws OperationFailedException,
IllegalArgumentException
{
for ( ContentPacketExtension content : answer)
{
remoteContentMap.put(content.getName(), content);
RtpDescriptionPacketExtension description
= JingleUtils.getRtpDescription(content);
MediaType mediaType
= MediaType.parseString( description.getMedia() );
//stream target
MediaStreamTarget target
= JingleUtils.extractDefaultTarget(content);
// no target port - try next media description
if(target.getDataAddress().getPort() == 0)
{
closeStream(mediaType);
continue;
}
List<MediaFormat> supportedFormats = JingleUtils.extractFormats(
description, getDynamicPayloadTypes());
MediaDevice dev = getDefaultDevice(mediaType);
if(dev == null)
{
closeStream(mediaType);
continue;
}
MediaDirection devDirection
= (dev == null) ? MediaDirection.INACTIVE : dev.getDirection();
// Take the preference of the user with respect to streaming
// mediaType into account.
devDirection
= devDirection.and(getDirectionUserPreference(mediaType));
if (supportedFormats.isEmpty())
{
//remote party must have messed up our SDP. throw an exception.
ProtocolProviderServiceJabberImpl.throwOperationFailedException(
"Remote party sent an invalid SDP answer.",
OperationFailedException.ILLEGAL_ARGUMENT, null, logger);
}
StreamConnector connector
= getTransportManager().getStreamConnector(mediaType);
//determine the direction that we need to announce.
MediaDirection remoteDirection
= JingleUtils.getDirection(content, getPeer().isInitiator());
MediaDirection direction
= devDirection.getDirectionForAnswer(remoteDirection);
// update the RTP extensions that we will be exchanging.
List<RTPExtension> remoteRTPExtensions
= JingleUtils.extractRTPExtensions(
description, getRtpExtensionsRegistry());
List<RTPExtension> supportedExtensions
= getExtensionsForType(mediaType);
List<RTPExtension> rtpExtensions = intersectRTPExtensions(
remoteRTPExtensions, supportedExtensions);
// create the corresponding stream...
initStream(content.getName(), connector, dev,
supportedFormats.get(0), target, direction, rtpExtensions);
}
}
/**
* Returns the transport manager that is handling our address management.
*
* @return the transport manager that is handling our address management.
*/
@Override
public TransportManagerJabberImpl getTransportManager()
{
return transportManager;
}
/**
* Acts upon a notification received from the remote party indicating that
* they've put us on/off hold.
*
* @param onHold <tt>true</tt> if the remote party has put us on hold
* and <tt>false</tt> if they've just put us off hold.
*/
public void setRemotelyOnHold(boolean onHold)
{
this.remotelyOnHold = onHold;
MediaStream audioStream = getStream(MediaType.AUDIO);
MediaStream videoStream = getStream(MediaType.VIDEO);
if(remotelyOnHold)
{
if(audioStream != null)
{
audioStream.setDirection(audioStream.getDirection()
.and(MediaDirection.RECVONLY));
}
if(videoStream != null)
{
videoStream.setDirection(videoStream.getDirection()
.and(MediaDirection.RECVONLY));
}
}
else
{
//off hold - make sure that we re-enable sending if that's
if(audioStream != null)
{
calculatePostHoldDirection(audioStream);
}
if(videoStream != null)
{
calculatePostHoldDirection(videoStream);
}
}
}
/**
* Determines the direction that a stream, which has been place on hold by
* the remote party, would need to go back to after being re-activated. If
* the stream is not currently on hold (i.e. it is still sending media),
* this method simply returns its current direction.
*
* @param stream the {@link MediaStreamTarget} whose post-hold direction
* we'd like to determine.
*
* @return the {@link MediaDirection} that we need to set on <txt>stream</tt>
* once it is reactivate.
*/
private MediaDirection calculatePostHoldDirection(MediaStream stream)
{
MediaDirection deviceDir = stream.getDirection();
if(deviceDir.allowsSending())
return deviceDir;
//when calculating a direction we need to take into account 1) what
//direction the remote party had asked for before putting us on hold,
//2) what the user preference is for the stream's media type, 3) our
//local hold status, 4) the direction supported by the device this
//stream is reading from.
//1. check what the remote party originally told us (from our persp.)
ContentPacketExtension content = remoteContentMap.get(stream.getName());
MediaDirection remoteDirection = JingleUtils.getDirection(content,
!getPeer().isInitiator());
deviceDir = deviceDir.and(remoteDirection);
//2. check the user preference.
MediaDevice device = stream.getDevice();
deviceDir = deviceDir
.and(getDirectionUserPreference(device.getMediaType()));
//3. check our local hold status.
if(isLocallyOnHold())
deviceDir.and(MediaDirection.SENDONLY);
//4. check the device direction.
deviceDir = deviceDir.and(device.getDirection());
return deviceDir;
}
}
|
src/net/java/sip/communicator/impl/protocol/jabber/CallPeerMediaHandlerJabberImpl.java
|
/*
* SIP Communicator, the OpenSource Java VoIP and Instant Messaging client.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package net.java.sip.communicator.impl.protocol.jabber;
import java.util.*;
import net.java.sip.communicator.impl.protocol.jabber.extensions.jingle.*;
import net.java.sip.communicator.impl.protocol.jabber.extensions.jingle.ContentPacketExtension.*;
import net.java.sip.communicator.impl.protocol.jabber.jinglesdp.*;
import net.java.sip.communicator.service.neomedia.*;
import net.java.sip.communicator.service.neomedia.device.*;
import net.java.sip.communicator.service.neomedia.format.*;
import net.java.sip.communicator.service.protocol.*;
import net.java.sip.communicator.service.protocol.media.*;
import net.java.sip.communicator.util.*;
/**
* An XMPP specific extension of the generic media handler.
*
* @author Emil Ivov
*/
public class CallPeerMediaHandlerJabberImpl
extends CallPeerMediaHandler<CallPeerJabberImpl>
{
/**
* The <tt>Logger</tt> used by the <tt>CallPeerMediaHandlerJabberImpl</tt>
* class and its instances for logging output.
*/
private static final Logger logger = Logger
.getLogger(CallPeerMediaHandlerJabberImpl.class.getName());
/**
* A temporarily single transport manager that we use for generating
* addresses until we properly implement both ICE and Raw UDP managers.
*/
private final TransportManagerJabberImpl transportManager;
/**
* The current description of the streams that we have going toward the
* remote side. We use {@link LinkedHashMap}s to make sure that we preserve
* the order of the individual content extensions.
*/
private Map<String, ContentPacketExtension> localContentMap
= new LinkedHashMap<String, ContentPacketExtension>();
/**
* The current description of the streams that the remote side has with us.
* We use {@link LinkedHashMap}s to make sure that we preserve
* the order of the individual content extensions.
*/
private Map<String, ContentPacketExtension> remoteContentMap
= new LinkedHashMap<String, ContentPacketExtension>();
/**
* Indicates whether the remote party has placed us on hold.
*/
private boolean remotelyOnHold = false;
/**
* Creates a new handler that will be managing media streams for
* <tt>peer</tt>.
*
* @param peer that <tt>CallPeerSipImpl</tt> instance that we will be
* managing media for.
*/
public CallPeerMediaHandlerJabberImpl(CallPeerJabberImpl peer)
{
super(peer, peer);
transportManager = new RawUdpTransportManager(peer);
}
/**
* Lets the underlying implementation take note of this error and only
* then throws it to the using bundles.
*
* @param message the message to be logged and then wrapped in a new
* <tt>OperationFailedException</tt>
* @param errorCode the error code to be assigned to the new
* <tt>OperationFailedException</tt>
* @param cause the <tt>Throwable</tt> that has caused the necessity to log
* an error and have a new <tt>OperationFailedException</tt> thrown
*
* @throws OperationFailedException the exception that we wanted this method
* to throw.
*/
@Override
protected void throwOperationFailedException(String message, int errorCode,
Throwable cause) throws OperationFailedException
{
ProtocolProviderServiceJabberImpl.throwOperationFailedException(
message, errorCode, cause, logger);
}
/**
* Creates if necessary, and configures the stream that this
* <tt>MediaHandler</tt> is using for the <tt>MediaType</tt> matching the
* one of the <tt>MediaDevice</tt>. This method extends the one already
* available by adding a stream name, corresponding to a stream's content
* name.
*
* @param streamName the name of the stream as indicated in the XMPP
* <tt>content</tt> element.
* @param connector the <tt>MediaConnector</tt> that we'd like to bind the
* newly created stream to.
* @param device the <tt>MediaDevice</tt> that we'd like to attach the newly
* created <tt>MediaStream</tt> to.
* @param format the <tt>MediaFormat</tt> that we'd like the new
* <tt>MediaStream</tt> to be set to transmit in.
* @param target the <tt>MediaStreamTarget</tt> containing the RTP and RTCP
* address:port couples that the new stream would be sending packets to.
* @param direction the <tt>MediaDirection</tt> that we'd like the new
* stream to use (i.e. sendonly, sendrecv, recvonly, or inactive).
* @param rtpExtensions the list of <tt>RTPExtension</tt>s that should be
* enabled for this stream.
*
* @return the newly created <tt>MediaStream</tt>.
*
* @throws OperationFailedException if creating the stream fails for any
* reason (like for example accessing the device or setting the format).
*/
protected MediaStream initStream(String streamName,
StreamConnector connector,
MediaDevice device,
MediaFormat format,
MediaStreamTarget target,
MediaDirection direction,
List<RTPExtension> rtpExtensions)
throws OperationFailedException
{
MediaStream stream = super.initStream(connector, device, format,
target, direction, rtpExtensions);
if(stream != null)
stream.setName(streamName);
return stream;
}
/**
* Parses and handles the specified <tt>offer</tt> and returns a content
* extension representing the current state of this media handler. This
* method MUST only be called when <tt>offer</tt> is the first session
* description that this <tt>MediaHandler</tt> is seeing.
*
* @param offer the offer that we'd like to parse, handle and get an answer
* for.
*
* @throws OperationFailedException if we have a problem satisfying the
* description received in <tt>offer</tt> (e.g. failed to open a device or
* initialize a stream ...).
* @throws IllegalArgumentException if there's a problem with
* <tt>offer</tt>'s format or semantics.
*/
public void processOffer(List<ContentPacketExtension> offer)
throws OperationFailedException,
IllegalArgumentException
{
// prepare to generate answers to all the incoming descriptions
List<ContentPacketExtension> answerContentList
= new ArrayList<ContentPacketExtension>(offer.size());
boolean atLeastOneValidDescription = false;
for (ContentPacketExtension content : offer)
{
remoteContentMap.put(content.getName(), content);
RtpDescriptionPacketExtension description
= JingleUtils.getRtpDescription(content);
MediaType mediaType
= MediaType.parseString( description.getMedia() );
List<MediaFormat> remoteFormats = JingleUtils.extractFormats(
description, getDynamicPayloadTypes());
MediaDevice dev = getDefaultDevice(mediaType);
MediaDirection devDirection = (dev == null)
? MediaDirection.INACTIVE
: dev.getDirection();
// Take the preference of the user with respect to streaming
// mediaType into account.
devDirection
= devDirection.and(getDirectionUserPreference(mediaType));
// determine the direction that we need to announce.
MediaDirection remoteDirection = JingleUtils.getDirection(
content, getPeer().isInitiator());
MediaDirection direction = devDirection
.getDirectionForAnswer(remoteDirection);
// intersect the MediaFormats of our device with remote ones
List<MediaFormat> mutuallySupportedFormats
= intersectFormats(remoteFormats, dev.getSupportedFormats());
// check whether we will be exchanging any RTP extensions.
List<RTPExtension> offeredRTPExtensions
= JingleUtils.extractRTPExtensions(
description, this.getRtpExtensionsRegistry());
List<RTPExtension> supportedExtensions
= getExtensionsForType(mediaType);
List<RTPExtension> rtpExtensions = intersectRTPExtensions(
offeredRTPExtensions, supportedExtensions);
// stream target
MediaStreamTarget target
= JingleUtils.extractDefaultTarget(content);
int targetDataPort = target.getDataAddress().getPort();
if (mutuallySupportedFormats.isEmpty()
|| (devDirection == MediaDirection.INACTIVE)
|| (targetDataPort == 0))
{
// skip stream and continue. contrary to sip we don't seem to
// need to send per-stream disabling answer and only one at the
// end.
//close the stream in case it already exists
closeStream(mediaType);
continue;
}
// create the answer description
ContentPacketExtension ourContent = JingleUtils.createDescription(
content.getCreator(), content.getName(),
JingleUtils.getSenders(direction, !getPeer().isInitiator()) ,
mutuallySupportedFormats, rtpExtensions,
getDynamicPayloadTypes(), getRtpExtensionsRegistry());
answerContentList.add(ourContent);
localContentMap.put(content.getName(), ourContent);
atLeastOneValidDescription = true;
}
if (!atLeastOneValidDescription)
ProtocolProviderServiceJabberImpl
.throwOperationFailedException("Offer contained no media "
+ " formats or no valid media descriptions.",
OperationFailedException.ILLEGAL_ARGUMENT, null, logger);
//now, before we go, tell the transport manager to start our candidate
//harvest
getTransportManager().startCandidateHarvest(offer, answerContentList);
}
/**
* Wraps up any ongoing candidate harvests and returns our response to the
* last offer we've received, so that the peer could use it to send a
* <tt>session-accept</tt>.
*
* @return the last generated list of {@link ContentPacketExtension}s that
* the call peer could use to send a <tt>session-accept</tt>.
*
* @throws OperationFailedException if we fail to configure the media stream
*/
protected List<ContentPacketExtension> generateSessionAccept()
throws OperationFailedException
{
List<ContentPacketExtension> sessAccept
= getTransportManager().wrapupHarvest();
//user answered an incoming call so we go through whatever content
//entries we are initializing and init their corresponding streams
for(ContentPacketExtension ourContent : sessAccept)
{
RtpDescriptionPacketExtension description
= JingleUtils.getRtpDescription(ourContent);
MediaType type = MediaType.parseString(description.getMedia());
//
StreamConnector connector
= getTransportManager().getStreamConnector(type);
//the device this stream would be reading from and writing to.
MediaDevice dev = getDefaultDevice(type);
// stream target
ContentPacketExtension theirContent
= this.remoteContentMap.get(ourContent.getName());
MediaStreamTarget target
= JingleUtils.extractDefaultTarget(theirContent);
//stream direction
MediaDirection direction = JingleUtils.getDirection(
ourContent, !getPeer().isInitiator());
//let's now see what was the format we announced as first and
//configure the stream with it.
MediaFormat format = JingleUtils.payloadTypeToMediaFormat(
description.getPayloadTypes().get(0), getDynamicPayloadTypes());
//extract the extensions that we are advertising:
// check whether we will be exchanging any RTP extensions.
List<RTPExtension> rtpExtensions
= JingleUtils.extractRTPExtensions(
description, this.getRtpExtensionsRegistry());
// create the corresponding stream...
initStream(ourContent.getName(), connector, dev, format, target,
direction, rtpExtensions);
}
return sessAccept;
}
/**
* Creates a <tt>List</tt> containing the {@link ContentPacketExtension}s of
* the streams that this handler is prepared to initiate depending on
* available <tt>MediaDevice</tt>s and local on-hold and video transmission
* preferences.
*
* @return a {@link List} containing the {@link ContentPacketExtension}s of
* streams that this handler is prepared to initiate.
*
* @throws OperationFailedException if we fail to create the descriptions
* for reasons like - problems with device interaction, allocating ports,
* etc.
*/
public List<ContentPacketExtension> createContentList()
throws OperationFailedException
{
//Audio Media Description
List<ContentPacketExtension> mediaDescs
= new ArrayList<ContentPacketExtension>();
for (MediaType mediaType : MediaType.values())
{
MediaDevice dev = getDefaultDevice(mediaType);
if (dev != null)
{
MediaDirection direction = dev.getDirection().and(
getDirectionUserPreference(mediaType));
if(isLocallyOnHold())
direction = direction.and(MediaDirection.SENDONLY);
if(direction != MediaDirection.INACTIVE)
{
ContentPacketExtension content = createContentForOffer(
dev.getSupportedFormats(), direction,
dev.getSupportedExtensions());
//ZRTP
if(getPeer().getCall().isSipZrtpAttribute())
{
ZrtpControl control = getZrtpControls().get(mediaType);
if(control == null)
{
control = JabberActivator.getMediaService()
.createZrtpControl();
getZrtpControls().put(mediaType, control);
}
String helloHash = control.getHelloHash();
if(helloHash != null && helloHash.length() > 0)
{
ZrtpHashPacketExtension hash
= new ZrtpHashPacketExtension();
hash.setValue(helloHash);
//we are currently disabling ZRTP until we find the
//time to fix it
content.addChildExtension(hash);
}
}
mediaDescs.add(content);
}
}
}
//fail if all devices were inactive
if(mediaDescs.isEmpty())
{
ProtocolProviderServiceJabberImpl
.throwOperationFailedException(
"We couldn't find any active Audio/Video devices and "
+ "couldn't create a call",
OperationFailedException.GENERAL_ERROR, null, logger);
}
//now add the transport elements
getTransportManager().startCandidateHarvest(mediaDescs);
//XXX ideally we wouldn't wrapup that quickluy. we need to revisit this
return getTransportManager().wrapupHarvest();
}
/**
* Generates an SDP {@link ContentPacketExtension} for the specified
* {@link MediaFormat} list, direction and RTP extensions taking account
* the local streaming preference for the corresponding media type.
*
* @param supportedFormats the list of <tt>MediaFormats</tt> that we'd
* like to advertise.
* @param direction the <tt>MediaDirection</tt> that we'd like to establish
* the stream in.
* @param supportedExtensions the list of <tt>RTPExtension</tt>s that we'd
* like to advertise in the <tt>MediaDescription</tt>.
*
* @return a newly created {@link ContentPacketExtension} representing
* streams that we'd be able to handle.
*/
private ContentPacketExtension createContentForOffer(
List<MediaFormat> supportedFormats,
MediaDirection direction,
List<RTPExtension> supportedExtensions)
{
return JingleUtils.createDescription(
CreatorEnum.initiator,
supportedFormats.get(0).getMediaType().toString(),
JingleUtils.getSenders(direction, !getPeer().isInitiator()),
supportedFormats,
supportedExtensions,
getDynamicPayloadTypes(),
getRtpExtensionsRegistry());
}
/**
* Handles the specified <tt>answer</tt> by creating and initializing the
* corresponding <tt>MediaStream</tt>s.
*
* @param answer the SDP <tt>SessionDescription</tt>.
*
* @throws OperationFailedException if we fail to handle <tt>answer</tt> for
* reasons like failing to initialize media devices or streams.
* @throws IllegalArgumentException if there's a problem with the syntax or
* the semantics of <tt>answer</tt>. Method is synchronized in order to
* avoid closing mediaHandler when we are currently in process of
* initializing, configuring and starting streams and anybody interested
* in this operation can synchronize to the mediaHandler instance to wait
* processing to stop (method setState in CallPeer).
*/
public void processAnswer(List<ContentPacketExtension> answer)
throws OperationFailedException,
IllegalArgumentException
{
for ( ContentPacketExtension content : answer)
{
RtpDescriptionPacketExtension description
= JingleUtils.getRtpDescription(content);
MediaType mediaType
= MediaType.parseString( description.getMedia() );
//stream target
MediaStreamTarget target
= JingleUtils.extractDefaultTarget(content);
// no target port - try next media description
if(target.getDataAddress().getPort() == 0)
{
closeStream(mediaType);
continue;
}
List<MediaFormat> supportedFormats = JingleUtils.extractFormats(
description, getDynamicPayloadTypes());
MediaDevice dev = getDefaultDevice(mediaType);
if(dev == null)
{
closeStream(mediaType);
continue;
}
MediaDirection devDirection
= (dev == null) ? MediaDirection.INACTIVE : dev.getDirection();
// Take the preference of the user with respect to streaming
// mediaType into account.
devDirection
= devDirection.and(getDirectionUserPreference(mediaType));
if (supportedFormats.isEmpty())
{
//remote party must have messed up our SDP. throw an exception.
ProtocolProviderServiceJabberImpl.throwOperationFailedException(
"Remote party sent an invalid SDP answer.",
OperationFailedException.ILLEGAL_ARGUMENT, null, logger);
}
StreamConnector connector
= getTransportManager().getStreamConnector(mediaType);
//determine the direction that we need to announce.
MediaDirection remoteDirection
= JingleUtils.getDirection(content, getPeer().isInitiator());
MediaDirection direction
= devDirection.getDirectionForAnswer(remoteDirection);
// update the RTP extensions that we will be exchanging.
List<RTPExtension> remoteRTPExtensions
= JingleUtils.extractRTPExtensions(
description, getRtpExtensionsRegistry());
List<RTPExtension> supportedExtensions
= getExtensionsForType(mediaType);
List<RTPExtension> rtpExtensions = intersectRTPExtensions(
remoteRTPExtensions, supportedExtensions);
// create the corresponding stream...
initStream(content.getName(), connector, dev,
supportedFormats.get(0), target, direction, rtpExtensions);
}
}
/**
* Returns the transport manager that is handling our address management.
*
* @return the transport manager that is handling our address management.
*/
@Override
public TransportManagerJabberImpl getTransportManager()
{
return transportManager;
}
/**
* Acts upon a notification received from the remote party indicating that
* they've put us on/off hold.
*
* @param onHold <tt>true</tt> if the remote party has put us on hold
* and <tt>false</tt> if they've just put us off hold.
*/
public void setRemotelyOnHold(boolean onHold)
{
this.remotelyOnHold = onHold;
MediaStream audioStream = getStream(MediaType.AUDIO);
MediaStream videoStream = getStream(MediaType.VIDEO);
if(remotelyOnHold)
{
if(audioStream != null)
{
audioStream.setDirection(audioStream.getDirection()
.and(MediaDirection.RECVONLY));
}
if(videoStream != null)
{
videoStream.setDirection(videoStream.getDirection()
.and(MediaDirection.RECVONLY));
}
}
else
{
//off hold - make sure that we re-enable sending if that's
if(audioStream != null)
{
calculatePostHoldDirection(audioStream);
}
if(videoStream != null)
{
calculatePostHoldDirection(videoStream);
}
}
}
/**
* Determines the direction that a stream, which has been place on hold by
* the remote party, would need to go back to after being re-activated. If
* the stream is not currently on hold (i.e. it is still sending media),
* this method simply returns its current direction.
*
* @param stream the {@link MediaStreamTarget} whose post-hold direction
* we'd like to determine.
*
* @return the {@link MediaDirection} that we need to set on <txt>stream</tt>
* once it is reactivate.
*/
private MediaDirection calculatePostHoldDirection(MediaStream stream)
{
MediaDirection deviceDir = stream.getDirection();
if(deviceDir.allowsSending())
return deviceDir;
//when calculating a direction we need to take into account 1) what
//direction the remote party had asked for before putting us on hold,
//2) what the user preference is for the stream's media type, 3) our
//local hold status, 4) the direction supported by the device this
//stream is reading from.
//1. check what the remote party originally told us (from our persp.)
ContentPacketExtension content = remoteContentMap.get(stream.getName());
MediaDirection remoteDirection = JingleUtils.getDirection(content,
!getPeer().isInitiator());
deviceDir = deviceDir.and(remoteDirection);
//2. check the user preference.
MediaDevice device = stream.getDevice();
deviceDir = deviceDir
.and(getDirectionUserPreference(device.getMediaType()));
//3. check our local hold status.
if(isLocallyOnHold())
deviceDir.and(MediaDirection.SENDONLY);
//4. check the device direction.
deviceDir = deviceDir.and(device.getDirection());
return deviceDir;
}
}
|
Adds to Jingle support for placing calls off and on hold (still: only for Raw UDP)
|
src/net/java/sip/communicator/impl/protocol/jabber/CallPeerMediaHandlerJabberImpl.java
|
Adds to Jingle support for placing calls off and on hold (still: only for Raw UDP)
|
|
Java
|
apache-2.0
|
c88e21f991c43ce90a64b86e7cb9d943cd4813e0
| 0
|
takenit2far/FreeRDP_SSL,lmcro/FreeRDP,MartinHaimberger/FreeRDP,realjiangms/FreeRDP,mfleisz/FreeRDP,akallabeth/FreeRDP,oshogbo/FreeRDP,massuda-marcelo/FreeRDP,vworkspace/FreeRDP,erbth/FreeRDP,RolKau/FreeRDP,ondrejholy/FreeRDP,Testinos/Freerdp,BUGgs/FreeRDP,DavBfr/FreeRDP,eledoux/FreeRDP,mcnestrb/FreeRDP,kingland/FreeRDP,aballier/FreeRDP,realjiangms/FreeRDP,FreeRDP/FreeRDP,mcnestrb/FreeRDP,nfedera/FreeRDP,anjoah/FreeRDP,peterh/FreeRDP,ilammy/FreeRDP,eledoux/FreeRDP,hyacinthes/FreeRDP,everhopingandwaiting/FreeRDP,llyzs/FreeRDP,BUGgs/FreeRDP,cloudbase/FreeRDP-dev,lmcro/FreeRDP,vaginessa/FreeRDP,awakecoding/FreeRDP,BUGgs/FreeRDP,yurashek/FreeRDP,oshogbo/FreeRDP,RolKau/FreeRDP,kingland/FreeRDP,anjoah/FreeRDP,eledoux/FreeRDP,chipitsine/FreeRDP,ssieb/FreeRDP,bsagal/FreeRDP,nanxiongchao/FreeRDP,briggsbog/FreeRDP,peterh/FreeRDP,RangeeGmbH/FreeRDP,bceverly/FreeRDP,dvincent-devolutions/FreeRDP,zhangximin/FreeRDP,peterh/FreeRDP,Distrotech/FreeRDP,anjoah/FreeRDP,tc-anssi/FreeRDP,oshogbo/FreeRDP,zavadovsky/FreeRDP,ivan-83/FreeRDP,tc-anssi/FreeRDP,bmiklautz/FreeRDP,erbth/FreeRDP,Devolutions/FreeRDP,nfedera/FreeRDP,anjoah/FreeRDP,nanxiongchao/FreeRDP,llyzs/FreeRDP,Distrotech/FreeRDP,massuda-marcelo/FreeRDP,briggsbog/FreeRDP,akallabeth/FreeRDP,akallabeth/FreeRDP,bjcollins/FreeRDP,FreeRDP/FreeRDP,bceverly/FreeRDP,infelt/FreeRDP,bsagal/FreeRDP,mcnestrb/FreeRDP,cedrozor/FreeRDP,erbth/FreeRDP,daneshih1125/FreeRDP,clivest/FreeRDP,tc-anssi/FreeRDP,RangeeGmbH/FreeRDP,realjiangms/FreeRDP,vaginessa/FreeRDP,ondrejholy/FreeRDP,realjiangms/FreeRDP,lmcro/FreeRDP,BUGgs/FreeRDP,rjcorrig/FreeRDP,awakecoding/FreeRDP,vaginessa/FreeRDP,yurashek/FreeRDP,realjiangms/FreeRDP,peterh/FreeRDP,RolKau/FreeRDP,cloudbase/FreeRDP-dev,daneshih1125/FreeRDP,zhangximin/FreeRDP,cedrozor/FreeRDP,Devolutions/FreeRDP,akallabeth/FreeRDP,ssieb/FreeRDP,infelt/FreeRDP,bjcollins/FreeRDP,hyacinthes/FreeRDP,lmcro/FreeRDP,takenit2far/FreeRDP_SSL,nanxiongchao/FreeRDP,weinyzhou/FreeRDP,bmiklautz/FreeRDP,weinyzhou/FreeRDP,takenit2far/FreeRDP_SSL,colemickens/FreeRDP,ivan-83/FreeRDP,bsagal/FreeRDP,takenit2far/FreeRDP,chipitsine/FreeRDP,vaginessa/FreeRDP,clivest/FreeRDP,bjcollins/FreeRDP,eledoux/FreeRDP,awakecoding/FreeRDP,bmiklautz/FreeRDP,ondrejholy/FreeRDP,RangeeGmbH/FreeRDP,zavadovsky/FreeRDP,xhaakon/FreeRDP,tinixx/FreeRDP,DavBfr/FreeRDP,MartinHaimberger/FreeRDP,xproax/FreeRDP,Testinos/Freerdp,mcnestrb/FreeRDP,Distrotech/FreeRDP,chipitsine/FreeRDP,mfleisz/FreeRDP,ilammy/FreeRDP,colemickens/FreeRDP,bceverly/FreeRDP,MartinHaimberger/FreeRDP,bmiklautz/FreeRDP,weinyzhou/FreeRDP,everhopingandwaiting/FreeRDP,nfedera/FreeRDP,ondrejholy/FreeRDP,DavBfr/FreeRDP,mfleisz/FreeRDP,rjcorrig/FreeRDP,awakecoding/FreeRDP,rjcorrig/FreeRDP,tinixx/FreeRDP,eledoux/FreeRDP,vworkspace/FreeRDP,nanxiongchao/FreeRDP,everhopingandwaiting/FreeRDP,briggsbog/FreeRDP,vworkspace/FreeRDP,llyzs/FreeRDP,zavadovsky/FreeRDP,vworkspace/FreeRDP,bmiklautz/FreeRDP,mfleisz/FreeRDP,chipitsine/FreeRDP,bceverly/FreeRDP,yurashek/FreeRDP,anjoah/FreeRDP,cloudbase/FreeRDP-dev,erbth/FreeRDP,aballier/FreeRDP,zhangximin/FreeRDP,weinyzhou/FreeRDP,kingland/FreeRDP,tc-anssi/FreeRDP,zavadovsky/FreeRDP,zavadovsky/FreeRDP,ivan-83/FreeRDP,colemickens/FreeRDP,rjcorrig/FreeRDP,hyacinthes/FreeRDP,awakecoding/FreeRDP,akallabeth/FreeRDP,aballier/FreeRDP,everhopingandwaiting/FreeRDP,briggsbog/FreeRDP,oshogbo/FreeRDP,BUGgs/FreeRDP,cloudbase/FreeRDP-dev,xproax/FreeRDP,takenit2far/FreeRDP,BUGgs/FreeRDP,xproax/FreeRDP,clivest/FreeRDP,RolKau/FreeRDP,yurashek/FreeRDP,realjiangms/FreeRDP,RolKau/FreeRDP,colemickens/FreeRDP,ssieb/FreeRDP,ondrejholy/FreeRDP,weinyzhou/FreeRDP,rjcorrig/FreeRDP,tc-anssi/FreeRDP,aballier/FreeRDP,cedrozor/FreeRDP,takenit2far/FreeRDP,everhopingandwaiting/FreeRDP,weinyzhou/FreeRDP,xhaakon/FreeRDP,mcnestrb/FreeRDP,bjcollins/FreeRDP,llyzs/FreeRDP,xproax/FreeRDP,nanxiongchao/FreeRDP,vworkspace/FreeRDP,xhaakon/FreeRDP,tinixx/FreeRDP,dvincent-devolutions/FreeRDP,dvincent-devolutions/FreeRDP,yurashek/FreeRDP,bmiklautz/FreeRDP,ssieb/FreeRDP,lmcro/FreeRDP,clivest/FreeRDP,MartinHaimberger/FreeRDP,zhangximin/FreeRDP,mcnestrb/FreeRDP,RangeeGmbH/FreeRDP,dvincent-devolutions/FreeRDP,bjcollins/FreeRDP,akallabeth/FreeRDP,chipitsine/FreeRDP,takenit2far/FreeRDP,yurashek/FreeRDP,infelt/FreeRDP,nfedera/FreeRDP,mfleisz/FreeRDP,eledoux/FreeRDP,takenit2far/FreeRDP,zavadovsky/FreeRDP,bceverly/FreeRDP,Devolutions/FreeRDP,bmiklautz/FreeRDP,akallabeth/FreeRDP,RangeeGmbH/FreeRDP,erbth/FreeRDP,hyacinthes/FreeRDP,xhaakon/FreeRDP,kingland/FreeRDP,tinixx/FreeRDP,ilammy/FreeRDP,tinixx/FreeRDP,ivan-83/FreeRDP,DavBfr/FreeRDP,clivest/FreeRDP,yurashek/FreeRDP,colemickens/FreeRDP,mfleisz/FreeRDP,zhangximin/FreeRDP,bceverly/FreeRDP,vworkspace/FreeRDP,ivan-83/FreeRDP,FreeRDP/FreeRDP,erbth/FreeRDP,takenit2far/FreeRDP_SSL,ssieb/FreeRDP,ilammy/FreeRDP,briggsbog/FreeRDP,MartinHaimberger/FreeRDP,eledoux/FreeRDP,RolKau/FreeRDP,zavadovsky/FreeRDP,infelt/FreeRDP,tinixx/FreeRDP,zhangximin/FreeRDP,peterh/FreeRDP,bsagal/FreeRDP,nfedera/FreeRDP,everhopingandwaiting/FreeRDP,aballier/FreeRDP,infelt/FreeRDP,takenit2far/FreeRDP_SSL,clivest/FreeRDP,dvincent-devolutions/FreeRDP,ssieb/FreeRDP,akallabeth/FreeRDP,infelt/FreeRDP,bsagal/FreeRDP,aballier/FreeRDP,nanxiongchao/FreeRDP,anjoah/FreeRDP,xhaakon/FreeRDP,RolKau/FreeRDP,llyzs/FreeRDP,lmcro/FreeRDP,Testinos/Freerdp,bjcollins/FreeRDP,weinyzhou/FreeRDP,kingland/FreeRDP,ilammy/FreeRDP,ilammy/FreeRDP,hyacinthes/FreeRDP,mcnestrb/FreeRDP,ivan-83/FreeRDP,Testinos/Freerdp,dvincent-devolutions/FreeRDP,Distrotech/FreeRDP,daneshih1125/FreeRDP,llyzs/FreeRDP,kingland/FreeRDP,peterh/FreeRDP,nanxiongchao/FreeRDP,FreeRDP/FreeRDP,everhopingandwaiting/FreeRDP,realjiangms/FreeRDP,RangeeGmbH/FreeRDP,vaginessa/FreeRDP,bsagal/FreeRDP,cloudbase/FreeRDP-dev,bjcollins/FreeRDP,ondrejholy/FreeRDP,DavBfr/FreeRDP,kingland/FreeRDP,takenit2far/FreeRDP_SSL,chipitsine/FreeRDP,MartinHaimberger/FreeRDP,ivan-83/FreeRDP,DavBfr/FreeRDP,xhaakon/FreeRDP,weinyzhou/FreeRDP,xhaakon/FreeRDP,rjcorrig/FreeRDP,awakecoding/FreeRDP,vworkspace/FreeRDP,mfleisz/FreeRDP,massuda-marcelo/FreeRDP,tinixx/FreeRDP,mcnestrb/FreeRDP,realjiangms/FreeRDP,infelt/FreeRDP,ondrejholy/FreeRDP,DavBfr/FreeRDP,cedrozor/FreeRDP,aballier/FreeRDP,Testinos/Freerdp,briggsbog/FreeRDP,Devolutions/FreeRDP,Distrotech/FreeRDP,Devolutions/FreeRDP,cedrozor/FreeRDP,BUGgs/FreeRDP,awakecoding/FreeRDP,oshogbo/FreeRDP,ilammy/FreeRDP,kingland/FreeRDP,lmcro/FreeRDP,xproax/FreeRDP,rjcorrig/FreeRDP,oshogbo/FreeRDP,bsagal/FreeRDP,erbth/FreeRDP,cedrozor/FreeRDP,Distrotech/FreeRDP,bmiklautz/FreeRDP,anjoah/FreeRDP,oshogbo/FreeRDP,bceverly/FreeRDP,massuda-marcelo/FreeRDP,xproax/FreeRDP,ondrejholy/FreeRDP,everhopingandwaiting/FreeRDP,dvincent-devolutions/FreeRDP,xproax/FreeRDP,daneshih1125/FreeRDP,mfleisz/FreeRDP,nfedera/FreeRDP,massuda-marcelo/FreeRDP,bceverly/FreeRDP,FreeRDP/FreeRDP,ssieb/FreeRDP,FreeRDP/FreeRDP,dvincent-devolutions/FreeRDP,DavBfr/FreeRDP,briggsbog/FreeRDP,nfedera/FreeRDP,zavadovsky/FreeRDP,peterh/FreeRDP,Distrotech/FreeRDP,daneshih1125/FreeRDP,RolKau/FreeRDP,llyzs/FreeRDP,anjoah/FreeRDP,nanxiongchao/FreeRDP,colemickens/FreeRDP,rjcorrig/FreeRDP,colemickens/FreeRDP,cloudbase/FreeRDP-dev,awakecoding/FreeRDP,vworkspace/FreeRDP,FreeRDP/FreeRDP,erbth/FreeRDP,hyacinthes/FreeRDP,nfedera/FreeRDP,cedrozor/FreeRDP,takenit2far/FreeRDP,daneshih1125/FreeRDP,xhaakon/FreeRDP,tinixx/FreeRDP,briggsbog/FreeRDP,xproax/FreeRDP,tc-anssi/FreeRDP,cloudbase/FreeRDP-dev,llyzs/FreeRDP,ilammy/FreeRDP,vaginessa/FreeRDP,massuda-marcelo/FreeRDP,tc-anssi/FreeRDP,ivan-83/FreeRDP,bsagal/FreeRDP,bjcollins/FreeRDP,chipitsine/FreeRDP,infelt/FreeRDP,Distrotech/FreeRDP,zhangximin/FreeRDP,peterh/FreeRDP,massuda-marcelo/FreeRDP,takenit2far/FreeRDP_SSL,Devolutions/FreeRDP,vaginessa/FreeRDP,aballier/FreeRDP,chipitsine/FreeRDP,oshogbo/FreeRDP,FreeRDP/FreeRDP,cedrozor/FreeRDP,BUGgs/FreeRDP,yurashek/FreeRDP,daneshih1125/FreeRDP,vaginessa/FreeRDP,RangeeGmbH/FreeRDP,Devolutions/FreeRDP,eledoux/FreeRDP,colemickens/FreeRDP,clivest/FreeRDP,Testinos/Freerdp,ssieb/FreeRDP,clivest/FreeRDP,Devolutions/FreeRDP,MartinHaimberger/FreeRDP,Testinos/Freerdp,lmcro/FreeRDP,zhangximin/FreeRDP,takenit2far/FreeRDP,RangeeGmbH/FreeRDP,MartinHaimberger/FreeRDP,massuda-marcelo/FreeRDP,tc-anssi/FreeRDP,hyacinthes/FreeRDP,daneshih1125/FreeRDP
|
/*
Android Session Activity
Copyright 2013 Thincast Technologies GmbH, Author: Martin Fleisz
This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package com.freerdp.freerdpcore.presentation;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.inputmethodservice.Keyboard;
import android.inputmethodservice.KeyboardView;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ScaleGestureDetector;
import android.view.View;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;
import android.widget.ZoomControls;
import com.freerdp.freerdpcore.R;
import com.freerdp.freerdpcore.application.GlobalApp;
import com.freerdp.freerdpcore.application.GlobalSettings;
import com.freerdp.freerdpcore.application.SessionState;
import com.freerdp.freerdpcore.domain.BookmarkBase;
import com.freerdp.freerdpcore.domain.ConnectionReference;
import com.freerdp.freerdpcore.domain.ManualBookmark;
import com.freerdp.freerdpcore.services.LibFreeRDP;
import com.freerdp.freerdpcore.utils.ClipboardManagerProxy;
import com.freerdp.freerdpcore.utils.KeyboardMapper;
import com.freerdp.freerdpcore.utils.Mouse;
public class SessionActivity extends ActionBarActivity
implements LibFreeRDP.UIEventListener, KeyboardView.OnKeyboardActionListener, ScrollView2D.ScrollView2DListener,
KeyboardMapper.KeyProcessingListener, SessionView.SessionViewListener, TouchPointerView.TouchPointerListener,
ClipboardManagerProxy.OnClipboardChangedListener
{
private class UIHandler extends Handler {
public static final int REFRESH_SESSIONVIEW = 1;
public static final int DISPLAY_TOAST = 2;
public static final int HIDE_ZOOMCONTROLS = 3;
public static final int SEND_MOVE_EVENT = 4;
public static final int SHOW_DIALOG = 5;
public static final int GRAPHICS_CHANGED = 6;
public static final int SCROLLING_REQUESTED = 7;
UIHandler() {
super();
}
@Override
public void handleMessage(Message msg) {
switch(msg.what)
{
case GRAPHICS_CHANGED:
{
sessionView.onSurfaceChange(session);
scrollView.requestLayout();
break;
}
case REFRESH_SESSIONVIEW:
{
sessionView.invalidateRegion();
break;
}
case DISPLAY_TOAST:
{
Toast errorToast = Toast.makeText(getApplicationContext(), msg.obj.toString(), Toast.LENGTH_LONG);
errorToast.show();
break;
}
case HIDE_ZOOMCONTROLS:
{
zoomControls.hide();
break;
}
case SEND_MOVE_EVENT:
{
LibFreeRDP.sendCursorEvent(session.getInstance(), msg.arg1, msg.arg2, Mouse.getMoveEvent());
break;
}
case SHOW_DIALOG:
{
// create and show the dialog
((Dialog)msg.obj).show();
break;
}
case SCROLLING_REQUESTED:
{
int scrollX = 0;
int scrollY = 0;
float[] pointerPos = touchPointerView.getPointerPosition();
if (pointerPos[0] > (screen_width - touchPointerView.getPointerWidth()))
scrollX = SCROLLING_DISTANCE;
else if (pointerPos[0] < 0)
scrollX = -SCROLLING_DISTANCE;
if (pointerPos[1] > (screen_height - touchPointerView.getPointerHeight()))
scrollY = SCROLLING_DISTANCE;
else if (pointerPos[1] < 0)
scrollY = -SCROLLING_DISTANCE;
scrollView.scrollBy(scrollX, scrollY);
// see if we reached the min/max scroll positions
if (scrollView.getScrollX() == 0 || scrollView.getScrollX() == (sessionView.getWidth() - scrollView.getWidth()))
scrollX = 0;
if (scrollView.getScrollY() == 0 || scrollView.getScrollY() == (sessionView.getHeight() - scrollView.getHeight()))
scrollY = 0;
if (scrollX != 0 || scrollY != 0)
uiHandler.sendEmptyMessageDelayed(SCROLLING_REQUESTED, SCROLLING_TIMEOUT);
else
Log.v(TAG, "Stopping auto-scroll");
break;
}
}
}
}
private class PinchZoomListener extends ScaleGestureDetector.SimpleOnScaleGestureListener
{
private float scaleFactor = 1.0f;
@Override
public boolean onScaleBegin(ScaleGestureDetector detector) {
scrollView.setScrollEnabled(false);
return true;
}
@Override
public boolean onScale(ScaleGestureDetector detector) {
// calc scale factor
scaleFactor *= detector.getScaleFactor();
scaleFactor = Math.max(SessionView.MIN_SCALE_FACTOR, Math.min(scaleFactor, SessionView.MAX_SCALE_FACTOR));
sessionView.setZoom(scaleFactor);
if(!sessionView.isAtMinZoom() && !sessionView.isAtMaxZoom())
{
// transform scroll origin to the new zoom space
float transOriginX = scrollView.getScrollX() * detector.getScaleFactor();
float transOriginY = scrollView.getScrollY() * detector.getScaleFactor();
// transform center point to the zoomed space
float transCenterX = (scrollView.getScrollX() + detector.getFocusX()) * detector.getScaleFactor();
float transCenterY = (scrollView.getScrollY() + detector.getFocusY()) * detector.getScaleFactor();
// scroll by the difference between the distance of the transformed center/origin point and their old distance (focusX/Y)
scrollView.scrollBy((int)((transCenterX - transOriginX) - detector.getFocusX()), (int)((transCenterY - transOriginY) - detector.getFocusY()));
}
return true;
}
@Override
public void onScaleEnd(ScaleGestureDetector de)
{
scrollView.setScrollEnabled(true);
}
}
private class LibFreeRDPBroadcastReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent) {
// still got a valid session?
if (session == null)
return;
// is this event for the current session?
if (session.getInstance() != intent.getExtras().getInt(GlobalApp.EVENT_PARAM, -1))
return;
switch(intent.getExtras().getInt(GlobalApp.EVENT_TYPE, -1))
{
case GlobalApp.FREERDP_EVENT_CONNECTION_SUCCESS:
OnConnectionSuccess(context);
break;
case GlobalApp.FREERDP_EVENT_CONNECTION_FAILURE:
OnConnectionFailure(context);
break;
case GlobalApp.FREERDP_EVENT_DISCONNECTED:
OnDisconnected(context);
break;
}
}
private void OnConnectionSuccess(Context context)
{
Log.v(TAG, "OnConnectionSuccess");
// bind session
bindSession();
if(progressDialog != null)
{
progressDialog.dismiss();
progressDialog = null;
}
// add hostname to history if quick connect was used
Bundle bundle = getIntent().getExtras();
if(bundle != null && bundle.containsKey(PARAM_CONNECTION_REFERENCE))
{
if(ConnectionReference.isHostnameReference(bundle.getString(PARAM_CONNECTION_REFERENCE)))
{
assert session.getBookmark().getType() == BookmarkBase.TYPE_MANUAL;
String item = session.getBookmark().<ManualBookmark>get().getHostname();
if(!GlobalApp.getQuickConnectHistoryGateway().historyItemExists(item))
GlobalApp.getQuickConnectHistoryGateway().addHistoryItem(item);
}
}
}
private void OnConnectionFailure(Context context)
{
Log.v(TAG, "OnConnectionFailure");
// remove pending move events
uiHandler.removeMessages(UIHandler.SEND_MOVE_EVENT);
if(progressDialog != null)
{
progressDialog.dismiss();
progressDialog = null;
}
// post error message on UI thread
if (!connectCancelledByUser)
uiHandler.sendMessage(Message.obtain(null, UIHandler.DISPLAY_TOAST, getResources().getText(R.string.error_connection_failure)));
closeSessionActivity(RESULT_CANCELED);
}
private void OnDisconnected(Context context)
{
Log.v(TAG, "OnDisconnected");
// remove pending move events
uiHandler.removeMessages(UIHandler.SEND_MOVE_EVENT);
if(progressDialog != null)
{
progressDialog.dismiss();
progressDialog = null;
}
session.setUIEventListener(null);
closeSessionActivity(RESULT_OK);
}
}
public static final String PARAM_CONNECTION_REFERENCE = "conRef";
public static final String PARAM_INSTANCE = "instance";
private static final float ZOOMING_STEP = 0.5f;
private static final int ZOOMCONTROLS_AUTOHIDE_TIMEOUT = 4000;
// timeout between subsequent scrolling requests when the touch-pointer is at the edge of the session view
private static final int SCROLLING_TIMEOUT = 50;
private static final int SCROLLING_DISTANCE = 20;
private Bitmap bitmap;
private SessionState session;
private SessionView sessionView;
private TouchPointerView touchPointerView;
private ProgressDialog progressDialog;
private KeyboardView keyboardView;
private KeyboardView modifiersKeyboardView;
private ZoomControls zoomControls;
private KeyboardMapper keyboardMapper;
private Keyboard specialkeysKeyboard;
private Keyboard numpadKeyboard;
private Keyboard cursorKeyboard;
private Keyboard modifiersKeyboard;
private AlertDialog dlgVerifyCertificate;
private AlertDialog dlgUserCredentials;
private View userCredView;
private UIHandler uiHandler;
private int screen_width;
private int screen_height;
private boolean autoScrollTouchPointer = GlobalSettings.getAutoScrollTouchPointer();
private boolean connectCancelledByUser = false;
private boolean sessionRunning = false;
private boolean toggleMouseButtons = false;
private LibFreeRDPBroadcastReceiver libFreeRDPBroadcastReceiver;
private static final String TAG = "FreeRDP.SessionActivity";
private ScrollView2D scrollView;
// keyboard visibility flags
private boolean sysKeyboardVisible = false;
private boolean extKeyboardVisible = false;
// variables for delayed move event sending
private static final int MAX_DISCARDED_MOVE_EVENTS = 3;
private static final int SEND_MOVE_EVENT_TIMEOUT = 150;
private int discardedMoveEvents = 0;
private ClipboardManagerProxy mClipboardManager;
private void createDialogs()
{
// build verify certificate dialog
dlgVerifyCertificate = new AlertDialog.Builder(this)
.setTitle(R.string.dlg_title_verify_certificate)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
callbackDialogResult = true;
synchronized(dialog)
{
dialog.notify();
}
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
callbackDialogResult = false;
connectCancelledByUser = true;
synchronized(dialog)
{
dialog.notify();
}
}
})
.setCancelable(false)
.create();
// build the dialog
userCredView = getLayoutInflater().inflate(R.layout.credentials, null, true);
dlgUserCredentials = new AlertDialog.Builder(this)
.setView(userCredView)
.setTitle(R.string.dlg_title_credentials)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
callbackDialogResult = true;
synchronized(dialog)
{
dialog.notify();
}
}
})
.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
callbackDialogResult = false;
connectCancelledByUser = true;
synchronized(dialog)
{
dialog.notify();
}
}
})
.setCancelable(false)
.create();
}
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// show status bar or make fullscreen?
if(GlobalSettings.getHideStatusBar())
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
this.setContentView(R.layout.session);
Log.v(TAG, "Session.onCreate");
// ATTENTION: We use the onGlobalLayout notification to start our session.
// This is because only then we can know the exact size of our session when using fit screen
// accounting for any status bars etc. that Android might throws on us. A bit weird looking
// but this is the only way ...
final View activityRootView = findViewById(R.id.session_root_view);
activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener()
{
@Override
public void onGlobalLayout() {
screen_width = activityRootView.getWidth();
screen_height = activityRootView.getHeight();
// start session
if(!sessionRunning && getIntent() != null)
{
processIntent(getIntent());
sessionRunning = true;
}
}
});
sessionView = (SessionView) findViewById(R.id.sessionView);
sessionView.setScaleGestureDetector(new ScaleGestureDetector(this, new PinchZoomListener()));
sessionView.setSessionViewListener(this);
sessionView.requestFocus();
touchPointerView = (TouchPointerView) findViewById(R.id.touchPointerView);
touchPointerView.setTouchPointerListener(this);
keyboardMapper = new KeyboardMapper();
keyboardMapper.init(this);
keyboardMapper.reset(this);
modifiersKeyboard = new Keyboard(getApplicationContext(), R.xml.modifiers_keyboard);
specialkeysKeyboard = new Keyboard(getApplicationContext(), R.xml.specialkeys_keyboard);
numpadKeyboard = new Keyboard(getApplicationContext(), R.xml.numpad_keyboard);
cursorKeyboard = new Keyboard(getApplicationContext(), R.xml.cursor_keyboard);
// hide keyboard below the sessionView
keyboardView = (KeyboardView)findViewById(R.id.extended_keyboard);
keyboardView.setKeyboard(specialkeysKeyboard);
keyboardView.setOnKeyboardActionListener(this);
modifiersKeyboardView = (KeyboardView) findViewById(R.id.extended_keyboard_header);
modifiersKeyboardView.setKeyboard(modifiersKeyboard);
modifiersKeyboardView.setOnKeyboardActionListener(this);
scrollView = (ScrollView2D) findViewById(R.id.sessionScrollView);
scrollView.setScrollViewListener(this);
uiHandler = new UIHandler();
libFreeRDPBroadcastReceiver = new LibFreeRDPBroadcastReceiver();
zoomControls = (ZoomControls) findViewById(R.id.zoomControls);
zoomControls.hide();
zoomControls.setOnZoomInClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
resetZoomControlsAutoHideTimeout();
zoomControls.setIsZoomInEnabled(sessionView.zoomIn(ZOOMING_STEP));
zoomControls.setIsZoomOutEnabled(true);
}
});
zoomControls.setOnZoomOutClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
resetZoomControlsAutoHideTimeout();
zoomControls.setIsZoomOutEnabled(sessionView.zoomOut(ZOOMING_STEP));
zoomControls.setIsZoomInEnabled(true);
}
});
toggleMouseButtons = false;
createDialogs();
// register freerdp events broadcast receiver
IntentFilter filter = new IntentFilter();
filter.addAction(GlobalApp.ACTION_EVENT_FREERDP);
registerReceiver(libFreeRDPBroadcastReceiver, filter);
mClipboardManager = ClipboardManagerProxy.getClipboardManager(this);
mClipboardManager.addClipboardChangedListener(this);
ActionBar actionBar = this.getSupportActionBar();
actionBar.show();
}
@Override
protected void onStart() {
super.onStart();
Log.v(TAG, "Session.onStart");
}
@Override
protected void onRestart() {
super.onRestart();
Log.v(TAG, "Session.onRestart");
}
@Override
protected void onResume() {
super.onResume();
Log.v(TAG, "Session.onResume");
}
@Override
protected void onPause() {
super.onPause();
Log.v(TAG, "Session.onPause");
// hide any visible keyboards
showKeyboard(false, false);
}
@Override
protected void onStop() {
super.onStop();
Log.v(TAG, "Session.onStop");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.v(TAG, "Session.onDestroy");
// Cancel running disconnect timers.
GlobalApp.cancelDisconnectTimer();
// Disconnect all remaining sessions.
Collection<SessionState> sessions = GlobalApp.getSessions();
for (SessionState session : sessions)
LibFreeRDP.disconnect(session.getInstance());
// unregister freerdp events broadcast receiver
unregisterReceiver(libFreeRDPBroadcastReceiver);
// remove clipboard listener
mClipboardManager.removeClipboardboardChangedListener(this);
// free session
GlobalApp.freeSession(session.getInstance());
session = null;
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// reload keyboard resources (changed from landscape)
modifiersKeyboard = new Keyboard(getApplicationContext(), R.xml.modifiers_keyboard);
specialkeysKeyboard = new Keyboard(getApplicationContext(), R.xml.specialkeys_keyboard);
numpadKeyboard = new Keyboard(getApplicationContext(), R.xml.numpad_keyboard);
cursorKeyboard = new Keyboard(getApplicationContext(), R.xml.cursor_keyboard);
// apply loaded keyboards
keyboardView.setKeyboard(specialkeysKeyboard);
modifiersKeyboardView.setKeyboard(modifiersKeyboard);
}
private void processIntent(Intent intent)
{
// get either session instance or create one from a bookmark
Bundle bundle = intent.getExtras();
if(bundle.containsKey(PARAM_INSTANCE))
{
int inst = bundle.getInt(PARAM_INSTANCE);
session = GlobalApp.getSession(inst);
bitmap = session.getSurface().getBitmap();
bindSession();
}
else if(bundle.containsKey(PARAM_CONNECTION_REFERENCE))
{
BookmarkBase bookmark = null;
String refStr = bundle.getString(PARAM_CONNECTION_REFERENCE);
if(ConnectionReference.isHostnameReference(refStr))
{
bookmark = new ManualBookmark();
bookmark.<ManualBookmark>get().setHostname(ConnectionReference.getHostname(refStr));
}
else if(ConnectionReference.isBookmarkReference(refStr))
{
if(ConnectionReference.isManualBookmarkReference(refStr))
bookmark = GlobalApp.getManualBookmarkGateway().findById(ConnectionReference.getManualBookmarkId(refStr));
else
assert false;
}
if(bookmark != null)
connect(bookmark);
else
closeSessionActivity(RESULT_CANCELED);
}
else
{
// no session found - exit
closeSessionActivity(RESULT_CANCELED);
}
}
private void connect(BookmarkBase bookmark)
{
session = GlobalApp.createSession(bookmark);
session.setUIEventListener(this);
// set writeable data directory
LibFreeRDP.setDataDirectory(session.getInstance(), getFilesDir().toString());
BookmarkBase.ScreenSettings screenSettings = session.getBookmark().getActiveScreenSettings();
Log.v(TAG, "Screen Resolution: " + screenSettings.getResolutionString());
if (screenSettings.isAutomatic())
{
if((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_LARGE)
{
// large screen device i.e. tablet: simply use screen info
screenSettings.setHeight(screen_height);
screenSettings.setWidth(screen_width);
}
else
{
// small screen device i.e. phone:
// Automatic uses the largest side length of the screen and makes a 16:10 resolution setting out of it
int screenMax = (screen_width > screen_height) ? screen_width : screen_height;
screenSettings.setHeight(screenMax);
screenSettings.setWidth((int)((float)screenMax * 1.6f));
}
}
if (screenSettings.isFitScreen()) {
screenSettings.setHeight(screen_height);
screenSettings.setWidth(screen_width);
}
progressDialog = new ProgressDialog(this);
progressDialog.setTitle(bookmark.getLabel());
progressDialog.setMessage(getResources().getText(R.string.dlg_msg_connecting));
progressDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
connectCancelledByUser = true;
LibFreeRDP.cancelConnection(session.getInstance());
}
});
progressDialog.setCancelable(false);
progressDialog.show();
Thread thread = new Thread(new Runnable() {
public void run() {
session.connect();
}
});
thread.start();
}
// binds the current session to the activity by wiring it up with the sessionView and updating all internal objects accordingly
private void bindSession() {
Log.v("SessionActivity", "bindSession called");
session.setUIEventListener(this);
sessionView.onSurfaceChange(session);
scrollView.requestLayout();
keyboardMapper.reset(this);
}
// displays either the system or the extended keyboard or non of them
private void showKeyboard(boolean showSystemKeyboard, boolean showExtendedKeyboard) {
// no matter what we are doing ... hide the zoom controls
// TODO: this is not working correctly as hiding the keyboard issues a onScrollChange notification showing the control again ...
uiHandler.removeMessages(UIHandler.HIDE_ZOOMCONTROLS);
if(zoomControls.getVisibility() == View.VISIBLE)
zoomControls.hide();
InputMethodManager mgr;
if(showSystemKeyboard)
{
// hide extended keyboard
keyboardView.setVisibility(View.GONE);
// show system keyboard
mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
if(!mgr.isActive(sessionView))
Log.e(TAG, "Failed to show system keyboard: SessionView is not the active view!");
mgr.showSoftInput(sessionView, 0);
// show modifiers keyboard
modifiersKeyboardView.setVisibility(View.VISIBLE);
}
else if(showExtendedKeyboard)
{
// hide system keyboard
mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
mgr.hideSoftInputFromWindow(sessionView.getWindowToken(), 0);
// show extended keyboard
keyboardView.setKeyboard(specialkeysKeyboard);
keyboardView.setVisibility(View.VISIBLE);
modifiersKeyboardView.setVisibility(View.VISIBLE);
}
else
{
// hide both
mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
mgr.hideSoftInputFromWindow(sessionView.getWindowToken(), 0);
keyboardView.setVisibility(View.GONE);
modifiersKeyboardView.setVisibility(View.GONE);
// clear any active key modifiers)
keyboardMapper.clearlAllModifiers();
}
sysKeyboardVisible = showSystemKeyboard;
extKeyboardVisible = showExtendedKeyboard;
}
private void closeSessionActivity(int resultCode) {
// Go back to home activity (and send intent data back to home)
setResult(resultCode, getIntent());
finish();
}
// update the state of our modifier keys
private void updateModifierKeyStates() {
// check if any key is in the keycodes list
List<Keyboard.Key> keys = modifiersKeyboard.getKeys();
for(Iterator<Keyboard.Key> it = keys.iterator(); it.hasNext(); )
{
// if the key is a sticky key - just set it to off
Keyboard.Key curKey = it.next();
if(curKey.sticky)
{
switch(keyboardMapper.getModifierState(curKey.codes[0]))
{
case KeyboardMapper.KEYSTATE_ON:
curKey.on = true;
curKey.pressed = false;
break;
case KeyboardMapper.KEYSTATE_OFF:
curKey.on = false;
curKey.pressed = false;
break;
case KeyboardMapper.KEYSTATE_LOCKED:
curKey.on = true;
curKey.pressed = true;
break;
}
}
}
// refresh image
modifiersKeyboardView.invalidateAllKeys();
}
private void sendDelayedMoveEvent(int x, int y) {
if(uiHandler.hasMessages(UIHandler.SEND_MOVE_EVENT))
{
uiHandler.removeMessages(UIHandler.SEND_MOVE_EVENT);
discardedMoveEvents++;
}
else
discardedMoveEvents = 0;
if(discardedMoveEvents > MAX_DISCARDED_MOVE_EVENTS)
LibFreeRDP.sendCursorEvent(session.getInstance(), x, y, Mouse.getMoveEvent());
else
uiHandler.sendMessageDelayed(Message.obtain(null, UIHandler.SEND_MOVE_EVENT, x, y), SEND_MOVE_EVENT_TIMEOUT);
}
private void cancelDelayedMoveEvent() {
uiHandler.removeMessages(UIHandler.SEND_MOVE_EVENT);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.session_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// refer to http://tools.android.com/tips/non-constant-fields why we can't use switch/case here ..
int itemId = item.getItemId();
if (itemId == R.id.session_touch_pointer)
{
// toggle touch pointer
if(touchPointerView.getVisibility() == View.VISIBLE)
{
touchPointerView.setVisibility(View.INVISIBLE);
sessionView.setTouchPointerPadding(0, 0);
}
else
{
touchPointerView.setVisibility(View.VISIBLE);
sessionView.setTouchPointerPadding(touchPointerView.getPointerWidth(), touchPointerView.getPointerHeight());
}
}
else if (itemId == R.id.session_sys_keyboard)
{
showKeyboard(!sysKeyboardVisible, false);
}
else if (itemId == R.id.session_ext_keyboard)
{
showKeyboard(false, !extKeyboardVisible);
}
else if (itemId == R.id.session_disconnect)
{
showKeyboard(false, false);
LibFreeRDP.disconnect(session.getInstance());
}
return true;
}
@Override
public void onBackPressed() {
// hide keyboards (if any visible) or send alt+f4 to the session
if(sysKeyboardVisible || extKeyboardVisible)
showKeyboard(false, false);
else
keyboardMapper.sendAltF4();
}
// android keyboard input handling
// We always use the unicode value to process input from the android keyboard except if key modifiers
// (like Win, Alt, Ctrl) are activated. In this case we will send the virtual key code to allow key
// combinations (like Win + E to open the explorer).
@Override
public boolean onKeyDown(int keycode, KeyEvent event) {
return keyboardMapper.processAndroidKeyEvent(event);
}
@Override
public boolean onKeyUp(int keycode, KeyEvent event) {
return keyboardMapper.processAndroidKeyEvent(event);
}
// onKeyMultiple is called for input of some special characters like umlauts and some symbol characters
@Override
public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
return keyboardMapper.processAndroidKeyEvent(event);
}
// ****************************************************************************
// KeyboardView.KeyboardActionEventListener
@Override
public void onKey(int primaryCode, int[] keyCodes) {
keyboardMapper.processCustomKeyEvent(primaryCode);
}
@Override
public void onText(CharSequence text) {
}
@Override
public void swipeRight() {
}
@Override
public void swipeLeft() {
}
@Override
public void swipeDown() {
}
@Override
public void swipeUp() {
}
@Override
public void onPress(int primaryCode) {
}
@Override
public void onRelease(int primaryCode) {
}
// ****************************************************************************
// KeyboardMapper.KeyProcessingListener implementation
@Override
public void processVirtualKey(int virtualKeyCode, boolean down) {
LibFreeRDP.sendKeyEvent(session.getInstance(), virtualKeyCode, down);
}
@Override
public void processUnicodeKey(int unicodeKey) {
LibFreeRDP.sendUnicodeKeyEvent(session.getInstance(), unicodeKey);
}
@Override
public void switchKeyboard(int keyboardType) {
switch(keyboardType)
{
case KeyboardMapper.KEYBOARD_TYPE_FUNCTIONKEYS:
keyboardView.setKeyboard(specialkeysKeyboard);
break;
case KeyboardMapper.KEYBOARD_TYPE_NUMPAD:
keyboardView.setKeyboard(numpadKeyboard);
break;
case KeyboardMapper.KEYBOARD_TYPE_CURSOR:
keyboardView.setKeyboard(cursorKeyboard);
break;
default:
break;
}
}
@Override
public void modifiersChanged() {
updateModifierKeyStates();
}
// ****************************************************************************
// LibFreeRDP UI event listener implementation
@Override
public void OnSettingsChanged(int width, int height, int bpp) {
if (bpp > 16)
bitmap = Bitmap.createBitmap(width, height, Config.ARGB_8888);
else
bitmap = Bitmap.createBitmap(width, height, Config.RGB_565);
session.setSurface(new BitmapDrawable(bitmap));
// check this settings and initial settings - if they are not equal the server doesn't support our settings
// FIXME: the additional check (settings.getWidth() != width + 1) is for the RDVH bug fix to avoid accidental notifications
// (refer to android_freerdp.c for more info on this problem)
BookmarkBase.ScreenSettings settings = session.getBookmark().getActiveScreenSettings();
if((settings.getWidth() != width && settings.getWidth() != width + 1) || settings.getHeight() != height || settings.getColors() != bpp)
uiHandler.sendMessage(Message.obtain(null, UIHandler.DISPLAY_TOAST, getResources().getText(R.string.info_capabilities_changed)));
}
@Override
public void OnGraphicsUpdate(int x, int y, int width, int height)
{
LibFreeRDP.updateGraphics(session.getInstance(), bitmap, x, y, width, height);
sessionView.addInvalidRegion(new Rect(x, y, x + width, y + height));
/* since sessionView can only be modified from the UI thread
* any modifications to it need to be scheduled */
uiHandler.sendEmptyMessage(UIHandler.REFRESH_SESSIONVIEW);
}
@Override
public void OnGraphicsResize(int width, int height, int bpp)
{
// replace bitmap
if (bpp > 16)
bitmap = Bitmap.createBitmap(width, height, Config.ARGB_8888);
else
bitmap = Bitmap.createBitmap(width, height, Config.RGB_565);
session.setSurface(new BitmapDrawable(bitmap));
/* since sessionView can only be modified from the UI thread
* any modifications to it need to be scheduled */
uiHandler.sendEmptyMessage(UIHandler.GRAPHICS_CHANGED);
}
private boolean callbackDialogResult;
@Override
public boolean OnAuthenticate(StringBuilder username, StringBuilder domain, StringBuilder password) {
// this is where the return code of our dialog will be stored
callbackDialogResult = false;
// set text fields
((EditText)userCredView.findViewById(R.id.editTextUsername)).setText(username);
((EditText)userCredView.findViewById(R.id.editTextDomain)).setText(domain);
((EditText)userCredView.findViewById(R.id.editTextPassword)).setText(password);
// start dialog in UI thread
uiHandler.sendMessage(Message.obtain(null, UIHandler.SHOW_DIALOG, dlgUserCredentials));
// wait for result
try
{
synchronized(dlgUserCredentials)
{
dlgUserCredentials.wait();
}
}
catch(InterruptedException e)
{
}
// clear buffers
username.setLength(0);
domain.setLength(0);
password.setLength(0);
// read back user credentials
username.append(((EditText)userCredView.findViewById(R.id.editTextUsername)).getText().toString());
domain.append(((EditText)userCredView.findViewById(R.id.editTextDomain)).getText().toString());
password.append(((EditText)userCredView.findViewById(R.id.editTextPassword)).getText().toString());
return callbackDialogResult;
}
@Override
public boolean OnVerifiyCertificate(String subject, String issuer, String fingerprint) {
// see if global settings says accept all
if(GlobalSettings.getAcceptAllCertificates())
return true;
// this is where the return code of our dialog will be stored
callbackDialogResult = false;
// set message
String msg = getResources().getString(R.string.dlg_msg_verify_certificate);
msg = msg + "\n\nSubject: " + subject + "\nIssuer: " + issuer + "\nFingerprint: " + fingerprint;
dlgVerifyCertificate.setMessage(msg);
// start dialog in UI thread
uiHandler.sendMessage(Message.obtain(null, UIHandler.SHOW_DIALOG, dlgVerifyCertificate));
// wait for result
try
{
synchronized(dlgVerifyCertificate)
{
dlgVerifyCertificate.wait();
}
}
catch(InterruptedException e)
{
}
return callbackDialogResult;
}
@Override
public void OnRemoteClipboardChanged(String data)
{
Log.v(TAG, "OnRemoteClipboardChanged: " + data);
mClipboardManager.setClipboardData(data);
}
// ****************************************************************************
// ScrollView2DListener implementation
private void resetZoomControlsAutoHideTimeout() {
uiHandler.removeMessages(UIHandler.HIDE_ZOOMCONTROLS);
uiHandler.sendEmptyMessageDelayed(UIHandler.HIDE_ZOOMCONTROLS, ZOOMCONTROLS_AUTOHIDE_TIMEOUT);
}
@Override
public void onScrollChanged(ScrollView2D scrollView, int x, int y, int oldx, int oldy) {
zoomControls.setIsZoomInEnabled(!sessionView.isAtMaxZoom());
zoomControls.setIsZoomOutEnabled(!sessionView.isAtMinZoom());
if(!GlobalSettings.getHideZoomControls() && zoomControls.getVisibility() != View.VISIBLE)
zoomControls.show();
resetZoomControlsAutoHideTimeout();
}
// ****************************************************************************
// SessionView.SessionViewListener
@Override
public void onSessionViewBeginTouch()
{
scrollView.setScrollEnabled(false);
}
@Override
public void onSessionViewEndTouch()
{
scrollView.setScrollEnabled(true);
}
@Override
public void onSessionViewLeftTouch(int x, int y, boolean down) {
if(!down)
cancelDelayedMoveEvent();
LibFreeRDP.sendCursorEvent(session.getInstance(), x, y, toggleMouseButtons ? Mouse.getRightButtonEvent(down) : Mouse.getLeftButtonEvent(down));
if (!down)
toggleMouseButtons = false;
}
public void onSessionViewRightTouch(int x, int y, boolean down) {
if (!down)
toggleMouseButtons = !toggleMouseButtons;
}
@Override
public void onSessionViewMove(int x, int y) {
sendDelayedMoveEvent(x, y);
}
@Override
public void onSessionViewScroll(boolean down) {
LibFreeRDP.sendCursorEvent(session.getInstance(), 0, 0, Mouse.getScrollEvent(down));
}
// ****************************************************************************
// TouchPointerView.TouchPointerListener
@Override
public void onTouchPointerClose() {
touchPointerView.setVisibility(View.INVISIBLE);
sessionView.setTouchPointerPadding(0, 0);
}
private Point mapScreenCoordToSessionCoord(int x, int y) {
int mappedX = (int)((float)(x + scrollView.getScrollX()) / sessionView.getZoom());
int mappedY = (int)((float)(y + scrollView.getScrollY()) / sessionView.getZoom());
if(mappedX > bitmap.getWidth())
mappedX = bitmap.getWidth();
if(mappedY > bitmap.getHeight())
mappedY = bitmap.getHeight();
return new Point(mappedX, mappedY);
}
@Override
public void onTouchPointerLeftClick(int x, int y, boolean down) {
Point p = mapScreenCoordToSessionCoord(x, y);
LibFreeRDP.sendCursorEvent(session.getInstance(), p.x, p.y, Mouse.getLeftButtonEvent(down));
}
@Override
public void onTouchPointerRightClick(int x, int y, boolean down) {
Point p = mapScreenCoordToSessionCoord(x, y);
LibFreeRDP.sendCursorEvent(session.getInstance(), p.x, p.y, Mouse.getRightButtonEvent(down));
}
@Override
public void onTouchPointerMove(int x, int y) {
Point p = mapScreenCoordToSessionCoord(x, y);
LibFreeRDP.sendCursorEvent(session.getInstance(), p.x, p.y, Mouse.getMoveEvent());
if (autoScrollTouchPointer && !uiHandler.hasMessages(UIHandler.SCROLLING_REQUESTED))
{
Log.v(TAG, "Starting auto-scroll");
uiHandler.sendEmptyMessageDelayed(UIHandler.SCROLLING_REQUESTED, SCROLLING_TIMEOUT);
}
}
@Override
public void onTouchPointerScroll(boolean down) {
LibFreeRDP.sendCursorEvent(session.getInstance(), 0, 0, Mouse.getScrollEvent(down));
}
@Override
public void onTouchPointerToggleKeyboard() {
showKeyboard(!sysKeyboardVisible, false);
}
@Override
public void onTouchPointerToggleExtKeyboard() {
showKeyboard(false, !extKeyboardVisible);
}
@Override
public void onTouchPointerResetScrollZoom() {
sessionView.setZoom(1.0f);
scrollView.scrollTo(0, 0);
}
// ****************************************************************************
// ClipboardManagerProxy.OnClipboardChangedListener
@Override
public void onClipboardChanged(String data) {
Log.v(TAG, "onClipboardChanged: " + data);
LibFreeRDP.sendClipboardData(session.getInstance(), data);
}
}
|
client/Android/FreeRDPCore/src/com/freerdp/freerdpcore/presentation/SessionActivity.java
|
/*
Android Session Activity
Copyright 2013 Thincast Technologies GmbH, Author: Martin Fleisz
This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package com.freerdp.freerdpcore.presentation;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import com.freerdp.freerdpcore.R;
import com.freerdp.freerdpcore.application.GlobalApp;
import com.freerdp.freerdpcore.application.GlobalSettings;
import com.freerdp.freerdpcore.application.SessionState;
import com.freerdp.freerdpcore.domain.BookmarkBase;
import com.freerdp.freerdpcore.domain.ConnectionReference;
import com.freerdp.freerdpcore.domain.ManualBookmark;
import com.freerdp.freerdpcore.services.LibFreeRDP;
import com.freerdp.freerdpcore.utils.KeyboardMapper;
import com.freerdp.freerdpcore.utils.Mouse;
import com.freerdp.freerdpcore.utils.ClipboardManagerProxy;
import android.app.Activity;
import android.app.Dialog;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ScaleGestureDetector;
import android.view.View;
import android.view.WindowManager;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;
import android.widget.ZoomControls;
import android.inputmethodservice.Keyboard;
import android.inputmethodservice.KeyboardView;
public class SessionActivity extends Activity
implements LibFreeRDP.UIEventListener, KeyboardView.OnKeyboardActionListener, ScrollView2D.ScrollView2DListener,
KeyboardMapper.KeyProcessingListener, SessionView.SessionViewListener, TouchPointerView.TouchPointerListener,
ClipboardManagerProxy.OnClipboardChangedListener
{
private class UIHandler extends Handler {
public static final int REFRESH_SESSIONVIEW = 1;
public static final int DISPLAY_TOAST = 2;
public static final int HIDE_ZOOMCONTROLS = 3;
public static final int SEND_MOVE_EVENT = 4;
public static final int SHOW_DIALOG = 5;
public static final int GRAPHICS_CHANGED = 6;
public static final int SCROLLING_REQUESTED = 7;
UIHandler() {
super();
}
@Override
public void handleMessage(Message msg) {
switch(msg.what)
{
case GRAPHICS_CHANGED:
{
sessionView.onSurfaceChange(session);
scrollView.requestLayout();
break;
}
case REFRESH_SESSIONVIEW:
{
sessionView.invalidateRegion();
break;
}
case DISPLAY_TOAST:
{
Toast errorToast = Toast.makeText(getApplicationContext(), msg.obj.toString(), Toast.LENGTH_LONG);
errorToast.show();
break;
}
case HIDE_ZOOMCONTROLS:
{
zoomControls.hide();
break;
}
case SEND_MOVE_EVENT:
{
LibFreeRDP.sendCursorEvent(session.getInstance(), msg.arg1, msg.arg2, Mouse.getMoveEvent());
break;
}
case SHOW_DIALOG:
{
// create and show the dialog
((Dialog)msg.obj).show();
break;
}
case SCROLLING_REQUESTED:
{
int scrollX = 0;
int scrollY = 0;
float[] pointerPos = touchPointerView.getPointerPosition();
if (pointerPos[0] > (screen_width - touchPointerView.getPointerWidth()))
scrollX = SCROLLING_DISTANCE;
else if (pointerPos[0] < 0)
scrollX = -SCROLLING_DISTANCE;
if (pointerPos[1] > (screen_height - touchPointerView.getPointerHeight()))
scrollY = SCROLLING_DISTANCE;
else if (pointerPos[1] < 0)
scrollY = -SCROLLING_DISTANCE;
scrollView.scrollBy(scrollX, scrollY);
// see if we reached the min/max scroll positions
if (scrollView.getScrollX() == 0 || scrollView.getScrollX() == (sessionView.getWidth() - scrollView.getWidth()))
scrollX = 0;
if (scrollView.getScrollY() == 0 || scrollView.getScrollY() == (sessionView.getHeight() - scrollView.getHeight()))
scrollY = 0;
if (scrollX != 0 || scrollY != 0)
uiHandler.sendEmptyMessageDelayed(SCROLLING_REQUESTED, SCROLLING_TIMEOUT);
else
Log.v(TAG, "Stopping auto-scroll");
break;
}
}
}
}
private class PinchZoomListener extends ScaleGestureDetector.SimpleOnScaleGestureListener
{
private float scaleFactor = 1.0f;
@Override
public boolean onScaleBegin(ScaleGestureDetector detector) {
scrollView.setScrollEnabled(false);
return true;
}
@Override
public boolean onScale(ScaleGestureDetector detector) {
// calc scale factor
scaleFactor *= detector.getScaleFactor();
scaleFactor = Math.max(SessionView.MIN_SCALE_FACTOR, Math.min(scaleFactor, SessionView.MAX_SCALE_FACTOR));
sessionView.setZoom(scaleFactor);
if(!sessionView.isAtMinZoom() && !sessionView.isAtMaxZoom())
{
// transform scroll origin to the new zoom space
float transOriginX = scrollView.getScrollX() * detector.getScaleFactor();
float transOriginY = scrollView.getScrollY() * detector.getScaleFactor();
// transform center point to the zoomed space
float transCenterX = (scrollView.getScrollX() + detector.getFocusX()) * detector.getScaleFactor();
float transCenterY = (scrollView.getScrollY() + detector.getFocusY()) * detector.getScaleFactor();
// scroll by the difference between the distance of the transformed center/origin point and their old distance (focusX/Y)
scrollView.scrollBy((int)((transCenterX - transOriginX) - detector.getFocusX()), (int)((transCenterY - transOriginY) - detector.getFocusY()));
}
return true;
}
@Override
public void onScaleEnd(ScaleGestureDetector de)
{
scrollView.setScrollEnabled(true);
}
}
private class LibFreeRDPBroadcastReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent) {
// still got a valid session?
if (session == null)
return;
// is this event for the current session?
if (session.getInstance() != intent.getExtras().getInt(GlobalApp.EVENT_PARAM, -1))
return;
switch(intent.getExtras().getInt(GlobalApp.EVENT_TYPE, -1))
{
case GlobalApp.FREERDP_EVENT_CONNECTION_SUCCESS:
OnConnectionSuccess(context);
break;
case GlobalApp.FREERDP_EVENT_CONNECTION_FAILURE:
OnConnectionFailure(context);
break;
case GlobalApp.FREERDP_EVENT_DISCONNECTED:
OnDisconnected(context);
break;
}
}
private void OnConnectionSuccess(Context context)
{
Log.v(TAG, "OnConnectionSuccess");
// bind session
bindSession();
if(progressDialog != null)
{
progressDialog.dismiss();
progressDialog = null;
}
// add hostname to history if quick connect was used
Bundle bundle = getIntent().getExtras();
if(bundle != null && bundle.containsKey(PARAM_CONNECTION_REFERENCE))
{
if(ConnectionReference.isHostnameReference(bundle.getString(PARAM_CONNECTION_REFERENCE)))
{
assert session.getBookmark().getType() == BookmarkBase.TYPE_MANUAL;
String item = session.getBookmark().<ManualBookmark>get().getHostname();
if(!GlobalApp.getQuickConnectHistoryGateway().historyItemExists(item))
GlobalApp.getQuickConnectHistoryGateway().addHistoryItem(item);
}
}
}
private void OnConnectionFailure(Context context)
{
Log.v(TAG, "OnConnectionFailure");
// remove pending move events
uiHandler.removeMessages(UIHandler.SEND_MOVE_EVENT);
if(progressDialog != null)
{
progressDialog.dismiss();
progressDialog = null;
}
// post error message on UI thread
if (!connectCancelledByUser)
uiHandler.sendMessage(Message.obtain(null, UIHandler.DISPLAY_TOAST, getResources().getText(R.string.error_connection_failure)));
closeSessionActivity(RESULT_CANCELED);
}
private void OnDisconnected(Context context)
{
Log.v(TAG, "OnDisconnected");
// remove pending move events
uiHandler.removeMessages(UIHandler.SEND_MOVE_EVENT);
if(progressDialog != null)
{
progressDialog.dismiss();
progressDialog = null;
}
session.setUIEventListener(null);
closeSessionActivity(RESULT_OK);
}
}
public static final String PARAM_CONNECTION_REFERENCE = "conRef";
public static final String PARAM_INSTANCE = "instance";
private static final float ZOOMING_STEP = 0.5f;
private static final int ZOOMCONTROLS_AUTOHIDE_TIMEOUT = 4000;
// timeout between subsequent scrolling requests when the touch-pointer is at the edge of the session view
private static final int SCROLLING_TIMEOUT = 50;
private static final int SCROLLING_DISTANCE = 20;
private Bitmap bitmap;
private SessionState session;
private SessionView sessionView;
private TouchPointerView touchPointerView;
private ProgressDialog progressDialog;
private KeyboardView keyboardView;
private KeyboardView modifiersKeyboardView;
private ZoomControls zoomControls;
private KeyboardMapper keyboardMapper;
private Keyboard specialkeysKeyboard;
private Keyboard numpadKeyboard;
private Keyboard cursorKeyboard;
private Keyboard modifiersKeyboard;
private AlertDialog dlgVerifyCertificate;
private AlertDialog dlgUserCredentials;
private View userCredView;
private UIHandler uiHandler;
private int screen_width;
private int screen_height;
private boolean autoScrollTouchPointer = GlobalSettings.getAutoScrollTouchPointer();
private boolean connectCancelledByUser = false;
private boolean sessionRunning = false;
private boolean toggleMouseButtons = false;
private LibFreeRDPBroadcastReceiver libFreeRDPBroadcastReceiver;
private static final String TAG = "FreeRDP.SessionActivity";
private ScrollView2D scrollView;
// keyboard visibility flags
private boolean sysKeyboardVisible = false;
private boolean extKeyboardVisible = false;
// variables for delayed move event sending
private static final int MAX_DISCARDED_MOVE_EVENTS = 3;
private static final int SEND_MOVE_EVENT_TIMEOUT = 150;
private int discardedMoveEvents = 0;
private ClipboardManagerProxy mClipboardManager;
private void createDialogs()
{
// build verify certificate dialog
dlgVerifyCertificate = new AlertDialog.Builder(this)
.setTitle(R.string.dlg_title_verify_certificate)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
callbackDialogResult = true;
synchronized(dialog)
{
dialog.notify();
}
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
callbackDialogResult = false;
connectCancelledByUser = true;
synchronized(dialog)
{
dialog.notify();
}
}
})
.setCancelable(false)
.create();
// build the dialog
userCredView = getLayoutInflater().inflate(R.layout.credentials, null, true);
dlgUserCredentials = new AlertDialog.Builder(this)
.setView(userCredView)
.setTitle(R.string.dlg_title_credentials)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
callbackDialogResult = true;
synchronized(dialog)
{
dialog.notify();
}
}
})
.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
callbackDialogResult = false;
connectCancelledByUser = true;
synchronized(dialog)
{
dialog.notify();
}
}
})
.setCancelable(false)
.create();
}
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// show status bar or make fullscreen?
if(GlobalSettings.getHideStatusBar())
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
this.setContentView(R.layout.session);
Log.v(TAG, "Session.onCreate");
// ATTENTION: We use the onGlobalLayout notification to start our session.
// This is because only then we can know the exact size of our session when using fit screen
// accounting for any status bars etc. that Android might throws on us. A bit weird looking
// but this is the only way ...
final View activityRootView = findViewById(R.id.session_root_view);
activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener()
{
@Override
public void onGlobalLayout() {
screen_width = activityRootView.getWidth();
screen_height = activityRootView.getHeight();
// start session
if(!sessionRunning && getIntent() != null)
{
processIntent(getIntent());
sessionRunning = true;
}
}
});
sessionView = (SessionView) findViewById(R.id.sessionView);
sessionView.setScaleGestureDetector(new ScaleGestureDetector(this, new PinchZoomListener()));
sessionView.setSessionViewListener(this);
sessionView.requestFocus();
touchPointerView = (TouchPointerView) findViewById(R.id.touchPointerView);
touchPointerView.setTouchPointerListener(this);
keyboardMapper = new KeyboardMapper();
keyboardMapper.init(this);
keyboardMapper.reset(this);
modifiersKeyboard = new Keyboard(getApplicationContext(), R.xml.modifiers_keyboard);
specialkeysKeyboard = new Keyboard(getApplicationContext(), R.xml.specialkeys_keyboard);
numpadKeyboard = new Keyboard(getApplicationContext(), R.xml.numpad_keyboard);
cursorKeyboard = new Keyboard(getApplicationContext(), R.xml.cursor_keyboard);
// hide keyboard below the sessionView
keyboardView = (KeyboardView)findViewById(R.id.extended_keyboard);
keyboardView.setKeyboard(specialkeysKeyboard);
keyboardView.setOnKeyboardActionListener(this);
modifiersKeyboardView = (KeyboardView) findViewById(R.id.extended_keyboard_header);
modifiersKeyboardView.setKeyboard(modifiersKeyboard);
modifiersKeyboardView.setOnKeyboardActionListener(this);
scrollView = (ScrollView2D) findViewById(R.id.sessionScrollView);
scrollView.setScrollViewListener(this);
uiHandler = new UIHandler();
libFreeRDPBroadcastReceiver = new LibFreeRDPBroadcastReceiver();
zoomControls = (ZoomControls) findViewById(R.id.zoomControls);
zoomControls.hide();
zoomControls.setOnZoomInClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
resetZoomControlsAutoHideTimeout();
zoomControls.setIsZoomInEnabled(sessionView.zoomIn(ZOOMING_STEP));
zoomControls.setIsZoomOutEnabled(true);
}
});
zoomControls.setOnZoomOutClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
resetZoomControlsAutoHideTimeout();
zoomControls.setIsZoomOutEnabled(sessionView.zoomOut(ZOOMING_STEP));
zoomControls.setIsZoomInEnabled(true);
}
});
toggleMouseButtons = false;
createDialogs();
// register freerdp events broadcast receiver
IntentFilter filter = new IntentFilter();
filter.addAction(GlobalApp.ACTION_EVENT_FREERDP);
registerReceiver(libFreeRDPBroadcastReceiver, filter);
mClipboardManager = ClipboardManagerProxy.getClipboardManager(this);
mClipboardManager.addClipboardChangedListener(this);
}
@Override
protected void onStart() {
super.onStart();
Log.v(TAG, "Session.onStart");
}
@Override
protected void onRestart() {
super.onRestart();
Log.v(TAG, "Session.onRestart");
}
@Override
protected void onResume() {
super.onResume();
Log.v(TAG, "Session.onResume");
}
@Override
protected void onPause() {
super.onPause();
Log.v(TAG, "Session.onPause");
// hide any visible keyboards
showKeyboard(false, false);
}
@Override
protected void onStop() {
super.onStop();
Log.v(TAG, "Session.onStop");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.v(TAG, "Session.onDestroy");
// Cancel running disconnect timers.
GlobalApp.cancelDisconnectTimer();
// Disconnect all remaining sessions.
Collection<SessionState> sessions = GlobalApp.getSessions();
for (SessionState session : sessions)
LibFreeRDP.disconnect(session.getInstance());
// unregister freerdp events broadcast receiver
unregisterReceiver(libFreeRDPBroadcastReceiver);
// remove clipboard listener
mClipboardManager.removeClipboardboardChangedListener(this);
// free session
GlobalApp.freeSession(session.getInstance());
session = null;
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// reload keyboard resources (changed from landscape)
modifiersKeyboard = new Keyboard(getApplicationContext(), R.xml.modifiers_keyboard);
specialkeysKeyboard = new Keyboard(getApplicationContext(), R.xml.specialkeys_keyboard);
numpadKeyboard = new Keyboard(getApplicationContext(), R.xml.numpad_keyboard);
cursorKeyboard = new Keyboard(getApplicationContext(), R.xml.cursor_keyboard);
// apply loaded keyboards
keyboardView.setKeyboard(specialkeysKeyboard);
modifiersKeyboardView.setKeyboard(modifiersKeyboard);
}
private void processIntent(Intent intent)
{
// get either session instance or create one from a bookmark
Bundle bundle = intent.getExtras();
if(bundle.containsKey(PARAM_INSTANCE))
{
int inst = bundle.getInt(PARAM_INSTANCE);
session = GlobalApp.getSession(inst);
bitmap = session.getSurface().getBitmap();
bindSession();
}
else if(bundle.containsKey(PARAM_CONNECTION_REFERENCE))
{
BookmarkBase bookmark = null;
String refStr = bundle.getString(PARAM_CONNECTION_REFERENCE);
if(ConnectionReference.isHostnameReference(refStr))
{
bookmark = new ManualBookmark();
bookmark.<ManualBookmark>get().setHostname(ConnectionReference.getHostname(refStr));
}
else if(ConnectionReference.isBookmarkReference(refStr))
{
if(ConnectionReference.isManualBookmarkReference(refStr))
bookmark = GlobalApp.getManualBookmarkGateway().findById(ConnectionReference.getManualBookmarkId(refStr));
else
assert false;
}
if(bookmark != null)
connect(bookmark);
else
closeSessionActivity(RESULT_CANCELED);
}
else
{
// no session found - exit
closeSessionActivity(RESULT_CANCELED);
}
}
private void connect(BookmarkBase bookmark)
{
session = GlobalApp.createSession(bookmark);
session.setUIEventListener(this);
// set writeable data directory
LibFreeRDP.setDataDirectory(session.getInstance(), getFilesDir().toString());
BookmarkBase.ScreenSettings screenSettings = session.getBookmark().getActiveScreenSettings();
Log.v(TAG, "Screen Resolution: " + screenSettings.getResolutionString());
if (screenSettings.isAutomatic())
{
if((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_LARGE)
{
// large screen device i.e. tablet: simply use screen info
screenSettings.setHeight(screen_height);
screenSettings.setWidth(screen_width);
}
else
{
// small screen device i.e. phone:
// Automatic uses the largest side length of the screen and makes a 16:10 resolution setting out of it
int screenMax = (screen_width > screen_height) ? screen_width : screen_height;
screenSettings.setHeight(screenMax);
screenSettings.setWidth((int)((float)screenMax * 1.6f));
}
}
if (screenSettings.isFitScreen()) {
screenSettings.setHeight(screen_height);
screenSettings.setWidth(screen_width);
}
progressDialog = new ProgressDialog(this);
progressDialog.setTitle(bookmark.getLabel());
progressDialog.setMessage(getResources().getText(R.string.dlg_msg_connecting));
progressDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
connectCancelledByUser = true;
LibFreeRDP.cancelConnection(session.getInstance());
}
});
progressDialog.setCancelable(false);
progressDialog.show();
Thread thread = new Thread(new Runnable() {
public void run() {
session.connect();
}
});
thread.start();
}
// binds the current session to the activity by wiring it up with the sessionView and updating all internal objects accordingly
private void bindSession() {
Log.v("SessionActivity", "bindSession called");
session.setUIEventListener(this);
sessionView.onSurfaceChange(session);
scrollView.requestLayout();
keyboardMapper.reset(this);
}
// displays either the system or the extended keyboard or non of them
private void showKeyboard(boolean showSystemKeyboard, boolean showExtendedKeyboard) {
// no matter what we are doing ... hide the zoom controls
// TODO: this is not working correctly as hiding the keyboard issues a onScrollChange notification showing the control again ...
uiHandler.removeMessages(UIHandler.HIDE_ZOOMCONTROLS);
if(zoomControls.getVisibility() == View.VISIBLE)
zoomControls.hide();
InputMethodManager mgr;
if(showSystemKeyboard)
{
// hide extended keyboard
keyboardView.setVisibility(View.GONE);
// show system keyboard
mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
if(!mgr.isActive(sessionView))
Log.e(TAG, "Failed to show system keyboard: SessionView is not the active view!");
mgr.showSoftInput(sessionView, 0);
// show modifiers keyboard
modifiersKeyboardView.setVisibility(View.VISIBLE);
}
else if(showExtendedKeyboard)
{
// hide system keyboard
mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
mgr.hideSoftInputFromWindow(sessionView.getWindowToken(), 0);
// show extended keyboard
keyboardView.setKeyboard(specialkeysKeyboard);
keyboardView.setVisibility(View.VISIBLE);
modifiersKeyboardView.setVisibility(View.VISIBLE);
}
else
{
// hide both
mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
mgr.hideSoftInputFromWindow(sessionView.getWindowToken(), 0);
keyboardView.setVisibility(View.GONE);
modifiersKeyboardView.setVisibility(View.GONE);
// clear any active key modifiers)
keyboardMapper.clearlAllModifiers();
}
sysKeyboardVisible = showSystemKeyboard;
extKeyboardVisible = showExtendedKeyboard;
}
private void closeSessionActivity(int resultCode) {
// Go back to home activity (and send intent data back to home)
setResult(resultCode, getIntent());
finish();
}
// update the state of our modifier keys
private void updateModifierKeyStates() {
// check if any key is in the keycodes list
List<Keyboard.Key> keys = modifiersKeyboard.getKeys();
for(Iterator<Keyboard.Key> it = keys.iterator(); it.hasNext(); )
{
// if the key is a sticky key - just set it to off
Keyboard.Key curKey = it.next();
if(curKey.sticky)
{
switch(keyboardMapper.getModifierState(curKey.codes[0]))
{
case KeyboardMapper.KEYSTATE_ON:
curKey.on = true;
curKey.pressed = false;
break;
case KeyboardMapper.KEYSTATE_OFF:
curKey.on = false;
curKey.pressed = false;
break;
case KeyboardMapper.KEYSTATE_LOCKED:
curKey.on = true;
curKey.pressed = true;
break;
}
}
}
// refresh image
modifiersKeyboardView.invalidateAllKeys();
}
private void sendDelayedMoveEvent(int x, int y) {
if(uiHandler.hasMessages(UIHandler.SEND_MOVE_EVENT))
{
uiHandler.removeMessages(UIHandler.SEND_MOVE_EVENT);
discardedMoveEvents++;
}
else
discardedMoveEvents = 0;
if(discardedMoveEvents > MAX_DISCARDED_MOVE_EVENTS)
LibFreeRDP.sendCursorEvent(session.getInstance(), x, y, Mouse.getMoveEvent());
else
uiHandler.sendMessageDelayed(Message.obtain(null, UIHandler.SEND_MOVE_EVENT, x, y), SEND_MOVE_EVENT_TIMEOUT);
}
private void cancelDelayedMoveEvent() {
uiHandler.removeMessages(UIHandler.SEND_MOVE_EVENT);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.session_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// refer to http://tools.android.com/tips/non-constant-fields why we can't use switch/case here ..
int itemId = item.getItemId();
if (itemId == R.id.session_touch_pointer)
{
// toggle touch pointer
if(touchPointerView.getVisibility() == View.VISIBLE)
{
touchPointerView.setVisibility(View.INVISIBLE);
sessionView.setTouchPointerPadding(0, 0);
}
else
{
touchPointerView.setVisibility(View.VISIBLE);
sessionView.setTouchPointerPadding(touchPointerView.getPointerWidth(), touchPointerView.getPointerHeight());
}
}
else if (itemId == R.id.session_sys_keyboard)
{
showKeyboard(!sysKeyboardVisible, false);
}
else if (itemId == R.id.session_ext_keyboard)
{
showKeyboard(false, !extKeyboardVisible);
}
else if (itemId == R.id.session_disconnect)
{
showKeyboard(false, false);
LibFreeRDP.disconnect(session.getInstance());
}
return true;
}
@Override
public void onBackPressed() {
// hide keyboards (if any visible) or send alt+f4 to the session
if(sysKeyboardVisible || extKeyboardVisible)
showKeyboard(false, false);
else
keyboardMapper.sendAltF4();
}
// android keyboard input handling
// We always use the unicode value to process input from the android keyboard except if key modifiers
// (like Win, Alt, Ctrl) are activated. In this case we will send the virtual key code to allow key
// combinations (like Win + E to open the explorer).
@Override
public boolean onKeyDown(int keycode, KeyEvent event) {
return keyboardMapper.processAndroidKeyEvent(event);
}
@Override
public boolean onKeyUp(int keycode, KeyEvent event) {
return keyboardMapper.processAndroidKeyEvent(event);
}
// onKeyMultiple is called for input of some special characters like umlauts and some symbol characters
@Override
public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
return keyboardMapper.processAndroidKeyEvent(event);
}
// ****************************************************************************
// KeyboardView.KeyboardActionEventListener
@Override
public void onKey(int primaryCode, int[] keyCodes) {
keyboardMapper.processCustomKeyEvent(primaryCode);
}
@Override
public void onText(CharSequence text) {
}
@Override
public void swipeRight() {
}
@Override
public void swipeLeft() {
}
@Override
public void swipeDown() {
}
@Override
public void swipeUp() {
}
@Override
public void onPress(int primaryCode) {
}
@Override
public void onRelease(int primaryCode) {
}
// ****************************************************************************
// KeyboardMapper.KeyProcessingListener implementation
@Override
public void processVirtualKey(int virtualKeyCode, boolean down) {
LibFreeRDP.sendKeyEvent(session.getInstance(), virtualKeyCode, down);
}
@Override
public void processUnicodeKey(int unicodeKey) {
LibFreeRDP.sendUnicodeKeyEvent(session.getInstance(), unicodeKey);
}
@Override
public void switchKeyboard(int keyboardType) {
switch(keyboardType)
{
case KeyboardMapper.KEYBOARD_TYPE_FUNCTIONKEYS:
keyboardView.setKeyboard(specialkeysKeyboard);
break;
case KeyboardMapper.KEYBOARD_TYPE_NUMPAD:
keyboardView.setKeyboard(numpadKeyboard);
break;
case KeyboardMapper.KEYBOARD_TYPE_CURSOR:
keyboardView.setKeyboard(cursorKeyboard);
break;
default:
break;
}
}
@Override
public void modifiersChanged() {
updateModifierKeyStates();
}
// ****************************************************************************
// LibFreeRDP UI event listener implementation
@Override
public void OnSettingsChanged(int width, int height, int bpp) {
if (bpp > 16)
bitmap = Bitmap.createBitmap(width, height, Config.ARGB_8888);
else
bitmap = Bitmap.createBitmap(width, height, Config.RGB_565);
session.setSurface(new BitmapDrawable(bitmap));
// check this settings and initial settings - if they are not equal the server doesn't support our settings
// FIXME: the additional check (settings.getWidth() != width + 1) is for the RDVH bug fix to avoid accidental notifications
// (refer to android_freerdp.c for more info on this problem)
BookmarkBase.ScreenSettings settings = session.getBookmark().getActiveScreenSettings();
if((settings.getWidth() != width && settings.getWidth() != width + 1) || settings.getHeight() != height || settings.getColors() != bpp)
uiHandler.sendMessage(Message.obtain(null, UIHandler.DISPLAY_TOAST, getResources().getText(R.string.info_capabilities_changed)));
}
@Override
public void OnGraphicsUpdate(int x, int y, int width, int height)
{
LibFreeRDP.updateGraphics(session.getInstance(), bitmap, x, y, width, height);
sessionView.addInvalidRegion(new Rect(x, y, x + width, y + height));
/* since sessionView can only be modified from the UI thread
* any modifications to it need to be scheduled */
uiHandler.sendEmptyMessage(UIHandler.REFRESH_SESSIONVIEW);
}
@Override
public void OnGraphicsResize(int width, int height, int bpp)
{
// replace bitmap
if (bpp > 16)
bitmap = Bitmap.createBitmap(width, height, Config.ARGB_8888);
else
bitmap = Bitmap.createBitmap(width, height, Config.RGB_565);
session.setSurface(new BitmapDrawable(bitmap));
/* since sessionView can only be modified from the UI thread
* any modifications to it need to be scheduled */
uiHandler.sendEmptyMessage(UIHandler.GRAPHICS_CHANGED);
}
private boolean callbackDialogResult;
@Override
public boolean OnAuthenticate(StringBuilder username, StringBuilder domain, StringBuilder password) {
// this is where the return code of our dialog will be stored
callbackDialogResult = false;
// set text fields
((EditText)userCredView.findViewById(R.id.editTextUsername)).setText(username);
((EditText)userCredView.findViewById(R.id.editTextDomain)).setText(domain);
((EditText)userCredView.findViewById(R.id.editTextPassword)).setText(password);
// start dialog in UI thread
uiHandler.sendMessage(Message.obtain(null, UIHandler.SHOW_DIALOG, dlgUserCredentials));
// wait for result
try
{
synchronized(dlgUserCredentials)
{
dlgUserCredentials.wait();
}
}
catch(InterruptedException e)
{
}
// clear buffers
username.setLength(0);
domain.setLength(0);
password.setLength(0);
// read back user credentials
username.append(((EditText)userCredView.findViewById(R.id.editTextUsername)).getText().toString());
domain.append(((EditText)userCredView.findViewById(R.id.editTextDomain)).getText().toString());
password.append(((EditText)userCredView.findViewById(R.id.editTextPassword)).getText().toString());
return callbackDialogResult;
}
@Override
public boolean OnVerifiyCertificate(String subject, String issuer, String fingerprint) {
// see if global settings says accept all
if(GlobalSettings.getAcceptAllCertificates())
return true;
// this is where the return code of our dialog will be stored
callbackDialogResult = false;
// set message
String msg = getResources().getString(R.string.dlg_msg_verify_certificate);
msg = msg + "\n\nSubject: " + subject + "\nIssuer: " + issuer + "\nFingerprint: " + fingerprint;
dlgVerifyCertificate.setMessage(msg);
// start dialog in UI thread
uiHandler.sendMessage(Message.obtain(null, UIHandler.SHOW_DIALOG, dlgVerifyCertificate));
// wait for result
try
{
synchronized(dlgVerifyCertificate)
{
dlgVerifyCertificate.wait();
}
}
catch(InterruptedException e)
{
}
return callbackDialogResult;
}
@Override
public void OnRemoteClipboardChanged(String data)
{
Log.v(TAG, "OnRemoteClipboardChanged: " + data);
mClipboardManager.setClipboardData(data);
}
// ****************************************************************************
// ScrollView2DListener implementation
private void resetZoomControlsAutoHideTimeout() {
uiHandler.removeMessages(UIHandler.HIDE_ZOOMCONTROLS);
uiHandler.sendEmptyMessageDelayed(UIHandler.HIDE_ZOOMCONTROLS, ZOOMCONTROLS_AUTOHIDE_TIMEOUT);
}
@Override
public void onScrollChanged(ScrollView2D scrollView, int x, int y, int oldx, int oldy) {
zoomControls.setIsZoomInEnabled(!sessionView.isAtMaxZoom());
zoomControls.setIsZoomOutEnabled(!sessionView.isAtMinZoom());
if(!GlobalSettings.getHideZoomControls() && zoomControls.getVisibility() != View.VISIBLE)
zoomControls.show();
resetZoomControlsAutoHideTimeout();
}
// ****************************************************************************
// SessionView.SessionViewListener
@Override
public void onSessionViewBeginTouch()
{
scrollView.setScrollEnabled(false);
}
@Override
public void onSessionViewEndTouch()
{
scrollView.setScrollEnabled(true);
}
@Override
public void onSessionViewLeftTouch(int x, int y, boolean down) {
if(!down)
cancelDelayedMoveEvent();
LibFreeRDP.sendCursorEvent(session.getInstance(), x, y, toggleMouseButtons ? Mouse.getRightButtonEvent(down) : Mouse.getLeftButtonEvent(down));
if (!down)
toggleMouseButtons = false;
}
public void onSessionViewRightTouch(int x, int y, boolean down) {
if (!down)
toggleMouseButtons = !toggleMouseButtons;
}
@Override
public void onSessionViewMove(int x, int y) {
sendDelayedMoveEvent(x, y);
}
@Override
public void onSessionViewScroll(boolean down) {
LibFreeRDP.sendCursorEvent(session.getInstance(), 0, 0, Mouse.getScrollEvent(down));
}
// ****************************************************************************
// TouchPointerView.TouchPointerListener
@Override
public void onTouchPointerClose() {
touchPointerView.setVisibility(View.INVISIBLE);
sessionView.setTouchPointerPadding(0, 0);
}
private Point mapScreenCoordToSessionCoord(int x, int y) {
int mappedX = (int)((float)(x + scrollView.getScrollX()) / sessionView.getZoom());
int mappedY = (int)((float)(y + scrollView.getScrollY()) / sessionView.getZoom());
if(mappedX > bitmap.getWidth())
mappedX = bitmap.getWidth();
if(mappedY > bitmap.getHeight())
mappedY = bitmap.getHeight();
return new Point(mappedX, mappedY);
}
@Override
public void onTouchPointerLeftClick(int x, int y, boolean down) {
Point p = mapScreenCoordToSessionCoord(x, y);
LibFreeRDP.sendCursorEvent(session.getInstance(), p.x, p.y, Mouse.getLeftButtonEvent(down));
}
@Override
public void onTouchPointerRightClick(int x, int y, boolean down) {
Point p = mapScreenCoordToSessionCoord(x, y);
LibFreeRDP.sendCursorEvent(session.getInstance(), p.x, p.y, Mouse.getRightButtonEvent(down));
}
@Override
public void onTouchPointerMove(int x, int y) {
Point p = mapScreenCoordToSessionCoord(x, y);
LibFreeRDP.sendCursorEvent(session.getInstance(), p.x, p.y, Mouse.getMoveEvent());
if (autoScrollTouchPointer && !uiHandler.hasMessages(UIHandler.SCROLLING_REQUESTED))
{
Log.v(TAG, "Starting auto-scroll");
uiHandler.sendEmptyMessageDelayed(UIHandler.SCROLLING_REQUESTED, SCROLLING_TIMEOUT);
}
}
@Override
public void onTouchPointerScroll(boolean down) {
LibFreeRDP.sendCursorEvent(session.getInstance(), 0, 0, Mouse.getScrollEvent(down));
}
@Override
public void onTouchPointerToggleKeyboard() {
showKeyboard(!sysKeyboardVisible, false);
}
@Override
public void onTouchPointerToggleExtKeyboard() {
showKeyboard(false, !extKeyboardVisible);
}
@Override
public void onTouchPointerResetScrollZoom() {
sessionView.setZoom(1.0f);
scrollView.scrollTo(0, 0);
}
// ****************************************************************************
// ClipboardManagerProxy.OnClipboardChangedListener
@Override
public void onClipboardChanged(String data) {
Log.v(TAG, "onClipboardChanged: " + data);
LibFreeRDP.sendClipboardData(session.getInstance(), data);
}
}
|
Now using compatibility menu.
|
client/Android/FreeRDPCore/src/com/freerdp/freerdpcore/presentation/SessionActivity.java
|
Now using compatibility menu.
|
|
Java
|
apache-2.0
|
527c0e1735fc7e6b98a4f621ae9a6bda56f125b1
| 0
|
bpvelloso/freenasmonitor,Sonelli/juicessh-performancemonitor,mseabold/juicessh-performancemonitor,youvegotmoxie/juicessh-performancemonitor,bobpattersonjr/juicessh-performancemonitor,TRex22/juicessh-performancemonitor,The1andONLYdave/juicessh-performancemonitor
|
package com.sonelli.juicessh.performancemonitor.activities;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.sonelli.juicessh.performancemonitor.R;
import com.sonelli.juicessh.performancemonitor.adapters.ConnectionSpinnerAdapter;
import com.sonelli.juicessh.performancemonitor.controllers.BaseController;
import com.sonelli.juicessh.performancemonitor.controllers.CpuUsageController;
import com.sonelli.juicessh.performancemonitor.controllers.DiskUsageController;
import com.sonelli.juicessh.performancemonitor.controllers.FreeRamController;
import com.sonelli.juicessh.performancemonitor.controllers.LoadAverageController;
import com.sonelli.juicessh.performancemonitor.controllers.NetworkUsageController;
import com.sonelli.juicessh.performancemonitor.loaders.ConnectionListLoader;
import com.sonelli.juicessh.performancemonitor.views.AutoResizeTextView;
import com.sonelli.juicessh.pluginlibrary.PluginClient;
import com.sonelli.juicessh.pluginlibrary.PluginContract;
import com.sonelli.juicessh.pluginlibrary.exceptions.ServiceNotConnectedException;
import com.sonelli.juicessh.pluginlibrary.listeners.OnClientStartedListener;
import com.sonelli.juicessh.pluginlibrary.listeners.OnSessionFinishedListener;
import com.sonelli.juicessh.pluginlibrary.listeners.OnSessionStartedListener;
import java.util.UUID;
public class MainActivity extends ActionBarActivity implements ActionBar.OnNavigationListener, OnSessionStartedListener, OnSessionFinishedListener {
public static final String TAG = "MainActivity";
private boolean isClientStarted = false;
private final PluginClient client = new PluginClient();
private final static int JUICESSH_REQUEST_CODE = 2585;
private Button connectButton;
private Button disconnectButton;
private ConnectionSpinnerAdapter spinnerAdapter;
// Controllers
private BaseController loadAverageController;
private BaseController freeRamController;
private BaseController cpuUsageController;
private BaseController diskUsageController;
private BaseController networkUsageController;
// Text displays
private AutoResizeTextView loadAverageTextView;
private AutoResizeTextView freeRamTextView;
private AutoResizeTextView cpuUsageTextView;
private AutoResizeTextView networkUsageTextView;
private AutoResizeTextView diskUsageTextView;
// State
private volatile int sessionId;
private volatile String sessionKey;
private volatile boolean isConnected = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create an adapter for populating the actionbar spinner with connections.
// We're going to pass in TYPE_SSH to disable all spinner items not of this type.
// This is because sending of commands required to poll performance data is only
// possible on SSH connections.
this.spinnerAdapter = new ConnectionSpinnerAdapter(this, PluginContract.Connections.TYPE_SSH);
getSupportActionBar().setNavigationMode(android.app.ActionBar.NAVIGATION_MODE_LIST);
getSupportActionBar().setListNavigationCallbacks(spinnerAdapter, this);
this.loadAverageTextView = (AutoResizeTextView) findViewById(R.id.load_average);
this.freeRamTextView = (AutoResizeTextView) findViewById(R.id.free_memory);
this.cpuUsageTextView = (AutoResizeTextView) findViewById(R.id.cpu_usage);
this.networkUsageTextView = (AutoResizeTextView) findViewById(R.id.network_usage);
this.diskUsageTextView = (AutoResizeTextView) findViewById(R.id.disk_usage);
this.connectButton = (Button) findViewById(R.id.connect_button);
connectButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
final UUID id = spinnerAdapter.getConnectionId(getSupportActionBar().getSelectedNavigationIndex());
if(id != null){
if(isClientStarted){
try {
client.connect(MainActivity.this, id, MainActivity.this, JUICESSH_REQUEST_CODE);
} catch (ServiceNotConnectedException e){
Toast.makeText(MainActivity.this, "Could not connect to JuiceSSH Plugin Service", Toast.LENGTH_SHORT).show();
}
}
}
}
});
this.disconnectButton = (Button) findViewById(R.id.disconnect_button);
this.disconnectButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(sessionId > -1 && sessionKey != null){
if(isClientStarted){
disconnectButton.setText(R.string.disconnecting);
disconnectButton.setEnabled(false);
new Thread(new Runnable() {
@Override
public void run() {
try {
client.disconnect(sessionId, sessionKey);
} catch (ServiceNotConnectedException e){
Toast.makeText(MainActivity.this, "Could not connect to JuiceSSH Plugin Service", Toast.LENGTH_SHORT).show();
}
disconnectButton.post(new Runnable() {
@Override
public void run() {
disconnectButton.setEnabled(true);
disconnectButton.setText(R.string.disconnect);
}
});
}
}).start();
}
}
}
});
}
@Override
protected void onResume() {
super.onResume();
if(loadAverageTextView != null){
loadAverageTextView.resizeText();
}
// Use a Loader to load the connection list into the adapter from the JuiceSSH content provider
// This keeps DB activity async and off the UI thread to prevent the plugin lagging
getSupportLoaderManager().initLoader(0, null, new ConnectionListLoader(this, spinnerAdapter));
if(this.isConnected){
connectButton.setVisibility(View.GONE);
disconnectButton.setVisibility(View.VISIBLE);
} else {
connectButton.setVisibility(View.VISIBLE);
disconnectButton.setVisibility(View.GONE);
}
}
@Override
protected void onStart() {
super.onStart();
client.start(this, new OnClientStartedListener() {
@Override
public void onClientStarted() {
isClientStarted = true;
connectButton.setEnabled(true);
}
@Override
public void onClientStopped() {
isClientStarted = false;
connectButton.setEnabled(false);
}
});
}
@Override
protected void onStop() {
super.onStop();
if(isClientStarted){
client.stop(this);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// This is important if you want to be able to interact with JuiceSSH sessions that you
// have started otherwise the plugin won't have access.
if(requestCode == JUICESSH_REQUEST_CODE){
client.gotActivityResult(requestCode, resultCode, data);
}
}
@Override
public void onSessionStarted(final int sessionId, final String sessionKey) {
MainActivity.this.sessionId = sessionId;
MainActivity.this.sessionKey = sessionKey;
MainActivity.this.isConnected = true;
connectButton.setVisibility(View.GONE);
connectButton.setEnabled(false);
disconnectButton.setVisibility(View.VISIBLE);
disconnectButton.setEnabled(true);
// Register a listener for session finish events so that we know when the session has been disconnected
try {
client.addSessionFinishedListener(sessionId, sessionKey, this);
} catch (ServiceNotConnectedException e){}
this.loadAverageController = new LoadAverageController(this)
.setSessionId(sessionId)
.setSessionKey(sessionKey)
.setPluginClient(client)
.setTextview(loadAverageTextView)
.start();
this.freeRamController = new FreeRamController(this)
.setSessionId(sessionId)
.setSessionKey(sessionKey)
.setPluginClient(client)
.setTextview(freeRamTextView)
.start();
this.cpuUsageController = new CpuUsageController(this)
.setSessionId(sessionId)
.setSessionKey(sessionKey)
.setPluginClient(client)
.setTextview(cpuUsageTextView)
.start();
this.diskUsageController = new DiskUsageController(this)
.setSessionId(sessionId)
.setSessionKey(sessionKey)
.setPluginClient(client)
.setTextview(diskUsageTextView)
.start();
this.networkUsageController = new NetworkUsageController(this)
.setSessionId(sessionId)
.setSessionKey(sessionKey)
.setPluginClient(client)
.setTextview(networkUsageTextView)
.start();
}
@Override
public void onSessionCancelled() {
// The user cancelled our JuiceSSH connection before it finished
// connecting or failed authentication.
}
@Override
public void onSessionFinished() {
MainActivity.this.sessionId = -1;
MainActivity.this.sessionKey = null;
MainActivity.this.isConnected = false;
if(loadAverageController != null){
loadAverageController.stop();
}
if(freeRamController != null){
freeRamController.stop();
}
if(cpuUsageController != null){
cpuUsageController.stop();
}
if(diskUsageController != null){
diskUsageController.stop();
}
if(networkUsageController != null){
networkUsageController.stop();
}
loadAverageTextView.setText("--");
freeRamTextView.setText("--");
cpuUsageTextView.setText("--");
networkUsageTextView.setText("--");
diskUsageTextView.setText("--");
disconnectButton.setVisibility(View.GONE);
disconnectButton.setEnabled(false);
connectButton.setVisibility(View.VISIBLE);
connectButton.setEnabled(true);
}
@Override
public boolean onNavigationItemSelected(int position, long id) {
return false;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case R.id.fork_on_github:
Intent urlIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(getString(R.string.app_url)));
urlIntent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
startActivity(Intent.createChooser(urlIntent, getString(R.string.open_address)));
return true;
case R.id.rate_plugin:
String packageName = getResources().getString(R.string.app_package);
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + packageName));
intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
try {
startActivity(intent);
} catch (ActivityNotFoundException e){
Toast.makeText(this, getString(R.string.google_play_not_installed), Toast.LENGTH_SHORT).show();
}
return true;
case R.id.about:
return true;
}
return false;
}
}
|
Plugin/src/main/java/com/sonelli/juicessh/performancemonitor/activities/MainActivity.java
|
package com.sonelli.juicessh.performancemonitor.activities;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.sonelli.juicessh.performancemonitor.R;
import com.sonelli.juicessh.performancemonitor.adapters.ConnectionSpinnerAdapter;
import com.sonelli.juicessh.performancemonitor.controllers.BaseController;
import com.sonelli.juicessh.performancemonitor.controllers.CpuUsageController;
import com.sonelli.juicessh.performancemonitor.controllers.DiskUsageController;
import com.sonelli.juicessh.performancemonitor.controllers.FreeRamController;
import com.sonelli.juicessh.performancemonitor.controllers.LoadAverageController;
import com.sonelli.juicessh.performancemonitor.controllers.NetworkUsageController;
import com.sonelli.juicessh.performancemonitor.loaders.ConnectionListLoader;
import com.sonelli.juicessh.performancemonitor.views.AutoResizeTextView;
import com.sonelli.juicessh.pluginlibrary.PluginClient;
import com.sonelli.juicessh.pluginlibrary.PluginContract;
import com.sonelli.juicessh.pluginlibrary.exceptions.ServiceNotConnectedException;
import com.sonelli.juicessh.pluginlibrary.listeners.OnClientStartedListener;
import com.sonelli.juicessh.pluginlibrary.listeners.OnSessionFinishedListener;
import com.sonelli.juicessh.pluginlibrary.listeners.OnSessionStartedListener;
import java.util.UUID;
public class MainActivity extends ActionBarActivity implements ActionBar.OnNavigationListener, OnSessionStartedListener, OnSessionFinishedListener {
public static final String TAG = "MainActivity";
private boolean isClientStarted = false;
private final PluginClient client = new PluginClient();
private Button connectButton;
private Button disconnectButton;
private ConnectionSpinnerAdapter spinnerAdapter;
// Controllers
private BaseController loadAverageController;
private BaseController freeRamController;
private BaseController cpuUsageController;
private BaseController diskUsageController;
private BaseController networkUsageController;
// Text displays
private AutoResizeTextView loadAverageTextView;
private AutoResizeTextView freeRamTextView;
private AutoResizeTextView cpuUsageTextView;
private AutoResizeTextView networkUsageTextView;
private AutoResizeTextView diskUsageTextView;
// State
private volatile int sessionId;
private volatile String sessionKey;
private volatile boolean isConnected = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create an adapter for populating the actionbar spinner with connections.
// We're going to pass in TYPE_SSH to disable all spinner items not of this type.
// This is because sending of commands required to poll performance data is only
// possible on SSH connections.
this.spinnerAdapter = new ConnectionSpinnerAdapter(this, PluginContract.Connections.TYPE_SSH);
getSupportActionBar().setNavigationMode(android.app.ActionBar.NAVIGATION_MODE_LIST);
getSupportActionBar().setListNavigationCallbacks(spinnerAdapter, this);
this.loadAverageTextView = (AutoResizeTextView) findViewById(R.id.load_average);
this.freeRamTextView = (AutoResizeTextView) findViewById(R.id.free_memory);
this.cpuUsageTextView = (AutoResizeTextView) findViewById(R.id.cpu_usage);
this.networkUsageTextView = (AutoResizeTextView) findViewById(R.id.network_usage);
this.diskUsageTextView = (AutoResizeTextView) findViewById(R.id.disk_usage);
this.connectButton = (Button) findViewById(R.id.connect_button);
connectButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
final UUID id = spinnerAdapter.getConnectionId(getSupportActionBar().getSelectedNavigationIndex());
if(id != null){
if(isClientStarted){
try {
client.connect(MainActivity.this, id, true, MainActivity.this);
} catch (ServiceNotConnectedException e){
Toast.makeText(MainActivity.this, "Could not connect to JuiceSSH Plugin Service", Toast.LENGTH_SHORT).show();
}
}
}
}
});
this.disconnectButton = (Button) findViewById(R.id.disconnect_button);
this.disconnectButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(sessionId > -1 && sessionKey != null){
if(isClientStarted){
disconnectButton.setText(R.string.disconnecting);
disconnectButton.setEnabled(false);
new Thread(new Runnable() {
@Override
public void run() {
try {
client.disconnect(sessionId, sessionKey);
} catch (ServiceNotConnectedException e){
Toast.makeText(MainActivity.this, "Could not connect to JuiceSSH Plugin Service", Toast.LENGTH_SHORT).show();
}
disconnectButton.post(new Runnable() {
@Override
public void run() {
disconnectButton.setEnabled(true);
disconnectButton.setText(R.string.disconnect);
}
});
}
}).start();
}
}
}
});
}
@Override
protected void onResume() {
super.onResume();
if(loadAverageTextView != null){
loadAverageTextView.resizeText();
}
// Use a Loader to load the connection list into the adapter from the JuiceSSH content provider
// This keeps DB activity async and off the UI thread to prevent the plugin lagging
getSupportLoaderManager().initLoader(0, null, new ConnectionListLoader(this, spinnerAdapter));
if(this.isConnected){
connectButton.setVisibility(View.GONE);
disconnectButton.setVisibility(View.VISIBLE);
} else {
connectButton.setVisibility(View.VISIBLE);
disconnectButton.setVisibility(View.GONE);
}
}
@Override
protected void onStart() {
super.onStart();
client.start(this, new OnClientStartedListener() {
@Override
public void onClientStarted() {
isClientStarted = true;
connectButton.setEnabled(true);
}
@Override
public void onClientStopped() {
isClientStarted = false;
connectButton.setEnabled(false);
}
});
}
@Override
protected void onStop() {
super.onStop();
if(isClientStarted){
client.stop(this);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// This is important if you want to be able to interact with JuiceSSH sessions that you
// have started otherwise the plugin won't have access.
if(requestCode == PluginClient.JUICESSH_REQUEST){
client.gotActivityResult(resultCode, data);
}
}
@Override
public void onSessionStarted(final int sessionId, final String sessionKey) {
MainActivity.this.sessionId = sessionId;
MainActivity.this.sessionKey = sessionKey;
MainActivity.this.isConnected = true;
connectButton.setVisibility(View.GONE);
connectButton.setEnabled(false);
disconnectButton.setVisibility(View.VISIBLE);
disconnectButton.setEnabled(true);
// Register a listener for session finish events so that we know when the session has been disconnected
try {
client.addSessionFinishedListener(sessionId, sessionKey, this);
} catch (ServiceNotConnectedException e){}
this.loadAverageController = new LoadAverageController(this)
.setSessionId(sessionId)
.setSessionKey(sessionKey)
.setPluginClient(client)
.setTextview(loadAverageTextView)
.start();
this.freeRamController = new FreeRamController(this)
.setSessionId(sessionId)
.setSessionKey(sessionKey)
.setPluginClient(client)
.setTextview(freeRamTextView)
.start();
this.cpuUsageController = new CpuUsageController(this)
.setSessionId(sessionId)
.setSessionKey(sessionKey)
.setPluginClient(client)
.setTextview(cpuUsageTextView)
.start();
this.diskUsageController = new DiskUsageController(this)
.setSessionId(sessionId)
.setSessionKey(sessionKey)
.setPluginClient(client)
.setTextview(diskUsageTextView)
.start();
this.networkUsageController = new NetworkUsageController(this)
.setSessionId(sessionId)
.setSessionKey(sessionKey)
.setPluginClient(client)
.setTextview(networkUsageTextView)
.start();
}
@Override
public void onSessionCancelled() {
// The user cancelled our JuiceSSH connection before it finished
// connecting or failed authentication.
}
@Override
public void onSessionFinished() {
MainActivity.this.sessionId = -1;
MainActivity.this.sessionKey = null;
MainActivity.this.isConnected = false;
if(loadAverageController != null){
loadAverageController.stop();
}
if(freeRamController != null){
freeRamController.stop();
}
if(cpuUsageController != null){
cpuUsageController.stop();
}
if(diskUsageController != null){
diskUsageController.stop();
}
if(networkUsageController != null){
networkUsageController.stop();
}
loadAverageTextView.setText("--");
freeRamTextView.setText("--");
cpuUsageTextView.setText("--");
networkUsageTextView.setText("--");
diskUsageTextView.setText("--");
disconnectButton.setVisibility(View.GONE);
disconnectButton.setEnabled(false);
connectButton.setVisibility(View.VISIBLE);
connectButton.setEnabled(true);
}
@Override
public boolean onNavigationItemSelected(int position, long id) {
return false;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case R.id.fork_on_github:
Intent urlIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(getString(R.string.app_url)));
urlIntent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
startActivity(Intent.createChooser(urlIntent, getString(R.string.open_address)));
return true;
case R.id.rate_plugin:
String packageName = getResources().getString(R.string.app_package);
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + packageName));
intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
try {
startActivity(intent);
} catch (ActivityNotFoundException e){
Toast.makeText(this, getString(R.string.google_play_not_installed), Toast.LENGTH_SHORT).show();
}
return true;
case R.id.about:
return true;
}
return false;
}
}
|
Updated to PluginClient v1.0.1
|
Plugin/src/main/java/com/sonelli/juicessh/performancemonitor/activities/MainActivity.java
|
Updated to PluginClient v1.0.1
|
|
Java
|
apache-2.0
|
bfd39299f6635b2639b954f92b2388a30c99977f
| 0
|
rabl-dev/cwac-cam2,idish/cwac-cam2-instant-camera,commonsguy/cwac-cam2
|
/***
Copyright (c) 2015 CommonsWare, LLC
Licensed under the Apache License, Version 2.0 (the "License"); you may
not use this file except in compliance with the License. You may obtain
a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.commonsware.cwac.cam2;
import android.content.Context;
import android.graphics.SurfaceTexture;
import android.os.Build;
import android.util.Log;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import de.greenrobot.event.EventBus;
/**
* Base class for camera engines, which abstract out camera
* functionality for different APIs (e.g., android.hardware.Camera,
* android.hardware.camera2.*).
*/
abstract public class CameraEngine {
private static final int CORE_POOL_SIZE=1;
private static final int MAX_POOL_SIZE=Runtime.getRuntime().availableProcessors();
private static final int KEEP_ALIVE_SECONDS=60;
private static volatile CameraEngine singleton=null;
private EventBus bus=EventBus.getDefault();
private boolean isDebug=false;
private LinkedBlockingQueue<Runnable> queue=new LinkedBlockingQueue<Runnable>();
private ThreadPoolExecutor pool;
private File savePreviewFile=null;
protected List<FlashMode> preferredFlashModes;
protected ArrayList<FlashMode> eligibleFlashModes=
new ArrayList<FlashMode>();
private static class CrashableEvent {
/**
* The exception that was raised when trying to process
* the request, or null if no such exception was raised.
*/
public final Exception exception;
public CrashableEvent() {
this(null);
}
public CrashableEvent(Exception e) {
if (e!=null) {
Log.e("CWAC-Cam2", "Exception in camera processing", e);
}
this.exception=e;
}
}
/**
* Event raised when camera descriptors are ready for use.
* Subscribe to this event if you use loadCameraDescriptors()
* to get the results. May include an exception if there was
* an exception accessing the camera.
*
* Note that the descriptors will be in a ranked order based
* on your requested CameraSelectionCriteria, with the best
* match as the 0th element of the list.
*/
public static class CameraDescriptorsEvent extends CrashableEvent {
/**
* The camera descriptors loaded in response to a call
* to loadCameraDescriptors()
*/
public final List<CameraDescriptor> descriptors;
public CameraDescriptorsEvent(List<CameraDescriptor> descriptors) {
this.descriptors=descriptors;
}
public CameraDescriptorsEvent(Exception exception) {
super(exception);
this.descriptors=null;
}
}
/**
* Event raised when the camera has been opened.
* Subscribe to this event if you use open()
* to to find out when the open has succeeded.
* May include an exception if there was
* an exception accessing the camera.
*/
public static class OpenedEvent extends CrashableEvent {
public OpenedEvent() {
super();
}
public OpenedEvent(Exception exception) {
super(exception);
}
}
/**
* Event raised when the camera has been closed.
* Subscribe to this event if you use close()
* to to find out when the close has completed.
* May include an exception if there was
* an exception closing the camera.
*/
public static class ClosedEvent extends CrashableEvent {
public ClosedEvent() {
super();
}
public ClosedEvent(Exception exception) {
super(exception);
}
}
public static class OrientationChangedEvent {
}
/**
* Event raised when picture is taken, as a result of a
* takePicture() call. May include an exception if there was
* an exception accessing the camera.
*/
public static class PictureTakenEvent extends CrashableEvent {
private ImageContext imageContext;
private PictureTransaction xact;
public PictureTakenEvent(PictureTransaction xact,
ImageContext imageContext) {
super();
this.xact=xact;
this.imageContext=imageContext;
}
public PictureTakenEvent(Exception exception) {
super(exception);
}
public ImageContext getImageContext() {
return(imageContext);
}
public PictureTransaction getPictureTransaction() {
return(xact);
}
}
/**
* Event raised when picture is taken, as a result of a
* takePicture() call. May include an exception if there was
* an exception accessing the camera.
*/
public static class VideoTakenEvent extends CrashableEvent {
private VideoTransaction xact;
public VideoTakenEvent(VideoTransaction xact) {
super();
this.xact=xact;
}
public VideoTakenEvent(Exception exception) {
super(exception);
}
public VideoTransaction getVideoTransaction() {
return(xact);
}
}
/**
* Base class for all ¯\_(ツ)_/¯ errors triggered by camera2
* API operations that we really should surface to callers,
* but either are not tied to specific requests or happen
* asynchronously with respect to the request. Usually, these
* are bad. However, they frequently do not have useful
* error information associated with them, because, well,
* that would have been useful.
*/
public static class CameraTwoGenericEvent {
}
/**
* Event raised if there is a problem starting up the
* CameraTwoEngine preview. The error field is the value passed
* into onError() of a CameraDevice.StateCallback object and
* probably means something to somebody.
*/
public static class CameraTwoPreviewErrorEvent
extends CameraTwoGenericEvent {
public final int error;
CameraTwoPreviewErrorEvent(int error) {
this.error=error;
}
}
/**
* Event raised if there is a different sort of problem
* starting up the CameraTwoEngine preview. This will be
* triggered by a CameraCaptureSession.StateCallback,
* and there is no error information of note.
*/
public static class CameraTwoPreviewFailureEvent
extends CameraTwoGenericEvent {
}
/**
* Create a CameraSession.Builder to build a CameraSession
* for a given CameraDescriptor. On the Builder is where you
* indicate your desired preview size, picture size, and
* so forth.
*
* @param ctxt an Android Context for accessing system stuff
* @param descriptor the CameraDescriptor for which we want
* a session
* @return a Builder to build that session
*/
abstract public CameraSession.Builder buildSession(Context ctxt,
CameraDescriptor descriptor);
/**
* Loads a roster of the available cameras for this engine,
* ranked based on the supplied criteria. Subscribe
* to the CameraDescriptorsEvent to get the results of this
* call asynchronously.
*
* @param criteria preferred camera capabilities, or
* null for a default ranking
*/
abstract public void loadCameraDescriptors(CameraSelectionCriteria criteria);
/**
* Open the requested camera and show a preview on the supplied
* surface. Subscribe to the OpenEvent to find out when this
* work is completed.
*
* @param session the session for the camera of interest
* @param texture the preview surface
*/
abstract public void open(CameraSession session,
SurfaceTexture texture);
/**
* Close the open camera. Subscribe to the ClosedEvent to
* find out when this work is completed. Note that this
* method may be synchronous or asynchronous.
*
* @param session the session for the camera of interest
*/
abstract public void close(CameraSession session);
/**
* Take a picture, on the supplied camera, using the picture
* configuration from the supplied transaction. Posts a
* PictureTakenEvent when the request is completed, successfully
* or unsuccessfully.
*
* @param session the session for the camera of interest
* @param xact the configuration of the picture to take
*/
abstract public void takePicture(CameraSession session,
PictureTransaction xact);
abstract public void recordVideo(CameraSession session,
VideoTransaction xact) throws Exception;
abstract public void stopVideoRecording(CameraSession session) throws Exception;
abstract public void handleOrientationChange(CameraSession session,
OrientationChangedEvent event);
/**
* @return true if the engine supports changing flash modes
* on the fly, false otherwise
*/
abstract public boolean supportsDynamicFlashModes();
/**
* Builds a CameraEngine instance based on the device's
* API level.
*
* @param ctxt any Context will do
* @param forceClassic if true, always use ClassicCameraEngine
* @return a new CameraEngine instance
*/
synchronized public static CameraEngine buildInstance(Context ctxt,
boolean forceClassic) {
if (singleton==null) {
if (!forceClassic &&
Build.VERSION.SDK_INT>=Build.VERSION_CODES.LOLLIPOP
&& !isProblematicDeviceOnNewCameraApi()) {
singleton=new CameraTwoEngine(ctxt);
}
else {
singleton=new ClassicCameraEngine(ctxt);
}
}
return(singleton);
}
/**
* Sets the event bus to use, where the default is the
* default event bus supplied by the EventBus class.
*
* @param bus the bus to use for events
*/
public void setBus(EventBus bus) {
this.bus=bus;
}
/**
* @return the bus to use for events
*/
public EventBus getBus() {
return(bus);
}
/**
* Sets whether or not exceptions should be logged, in addition
* to being included in relevant events. The default is false.
*
* @param isDebug true if exceptions should be logged, false otherwise
*/
public void setDebug(boolean isDebug) {
this.isDebug=isDebug;
}
/**
* @return true if exceptions should be logged, false otherwise
*/
public boolean isDebug() {
return(isDebug);
}
public void setDebugSavePreviewFile(File savePreviewFile) {
this.savePreviewFile=savePreviewFile;
}
public File savePreviewFile() {
return(savePreviewFile);
}
public ThreadPoolExecutor getThreadPool() {
if (pool==null) {
pool=new ThreadPoolExecutor(CORE_POOL_SIZE, MAX_POOL_SIZE,
KEEP_ALIVE_SECONDS, TimeUnit.SECONDS, queue);
}
return(pool);
}
public void setThreadPool(ThreadPoolExecutor pool) {
this.pool=pool;
}
void setPreferredFlashModes(List<FlashMode> flashModes) {
preferredFlashModes=flashModes;
}
boolean hasMoreThanOneEligibleFlashMode() {
return(eligibleFlashModes.size()>1);
}
private static boolean isProblematicDeviceOnNewCameraApi() {
if ("Huawei".equals(Build.MANUFACTURER) &&
"angler".equals(Build.PRODUCT)) {
return(true);
}
if ("LGE".equals(Build.MANUFACTURER) &&
"occam".equals(Build.PRODUCT)) {
return(true);
}
if ("Amazon".equals(Build.MANUFACTURER) &&
"full_ford".equals(Build.PRODUCT)) {
return(true);
}
if ("Amazon".equals(Build.MANUFACTURER) &&
"full_thebes".equals(Build.PRODUCT)) {
return(true);
}
if ("HTC".equals(Build.MANUFACTURER) &&
"m7_google".equals(Build.PRODUCT)) {
return(true);
}
if ("HTC".equals(Build.MANUFACTURER) &&
"hiaeuhl_00709".equals(Build.PRODUCT)) {
return(true);
}
if ("Wileyfox".equals(Build.MANUFACTURER) &&
"Swift".equals(Build.PRODUCT)) {
return(true);
}
if ("Sony".equals(Build.MANUFACTURER) &&
"C6603".equals(Build.PRODUCT)) {
return(true);
}
if ("Sony".equals(Build.MANUFACTURER) &&
"C6802".equals(Build.PRODUCT)) {
return(true);
}
if ("samsung".equals(Build.MANUFACTURER) &&
"zerofltexx".equals(Build.PRODUCT)) {
return(true);
}
return(false);
}
}
|
cam2/src/main/java/com/commonsware/cwac/cam2/CameraEngine.java
|
/***
Copyright (c) 2015 CommonsWare, LLC
Licensed under the Apache License, Version 2.0 (the "License"); you may
not use this file except in compliance with the License. You may obtain
a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.commonsware.cwac.cam2;
import android.content.Context;
import android.graphics.SurfaceTexture;
import android.os.Build;
import android.util.Log;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import de.greenrobot.event.EventBus;
/**
* Base class for camera engines, which abstract out camera
* functionality for different APIs (e.g., android.hardware.Camera,
* android.hardware.camera2.*).
*/
abstract public class CameraEngine {
private static final int CORE_POOL_SIZE=1;
private static final int MAX_POOL_SIZE=Runtime.getRuntime().availableProcessors();
private static final int KEEP_ALIVE_SECONDS=60;
private static volatile CameraEngine singleton=null;
private EventBus bus=EventBus.getDefault();
private boolean isDebug=false;
private LinkedBlockingQueue<Runnable> queue=new LinkedBlockingQueue<Runnable>();
private ThreadPoolExecutor pool;
private File savePreviewFile=null;
protected List<FlashMode> preferredFlashModes;
protected ArrayList<FlashMode> eligibleFlashModes=
new ArrayList<FlashMode>();
private static class CrashableEvent {
/**
* The exception that was raised when trying to process
* the request, or null if no such exception was raised.
*/
public final Exception exception;
public CrashableEvent() {
this(null);
}
public CrashableEvent(Exception e) {
if (e!=null) {
Log.e("CWAC-Cam2", "Exception in camera processing", e);
}
this.exception=e;
}
}
/**
* Event raised when camera descriptors are ready for use.
* Subscribe to this event if you use loadCameraDescriptors()
* to get the results. May include an exception if there was
* an exception accessing the camera.
*
* Note that the descriptors will be in a ranked order based
* on your requested CameraSelectionCriteria, with the best
* match as the 0th element of the list.
*/
public static class CameraDescriptorsEvent extends CrashableEvent {
/**
* The camera descriptors loaded in response to a call
* to loadCameraDescriptors()
*/
public final List<CameraDescriptor> descriptors;
public CameraDescriptorsEvent(List<CameraDescriptor> descriptors) {
this.descriptors=descriptors;
}
public CameraDescriptorsEvent(Exception exception) {
super(exception);
this.descriptors=null;
}
}
/**
* Event raised when the camera has been opened.
* Subscribe to this event if you use open()
* to to find out when the open has succeeded.
* May include an exception if there was
* an exception accessing the camera.
*/
public static class OpenedEvent extends CrashableEvent {
public OpenedEvent() {
super();
}
public OpenedEvent(Exception exception) {
super(exception);
}
}
/**
* Event raised when the camera has been closed.
* Subscribe to this event if you use close()
* to to find out when the close has completed.
* May include an exception if there was
* an exception closing the camera.
*/
public static class ClosedEvent extends CrashableEvent {
public ClosedEvent() {
super();
}
public ClosedEvent(Exception exception) {
super(exception);
}
}
public static class OrientationChangedEvent {
}
/**
* Event raised when picture is taken, as a result of a
* takePicture() call. May include an exception if there was
* an exception accessing the camera.
*/
public static class PictureTakenEvent extends CrashableEvent {
private ImageContext imageContext;
private PictureTransaction xact;
public PictureTakenEvent(PictureTransaction xact,
ImageContext imageContext) {
super();
this.xact=xact;
this.imageContext=imageContext;
}
public PictureTakenEvent(Exception exception) {
super(exception);
}
public ImageContext getImageContext() {
return(imageContext);
}
public PictureTransaction getPictureTransaction() {
return(xact);
}
}
/**
* Event raised when picture is taken, as a result of a
* takePicture() call. May include an exception if there was
* an exception accessing the camera.
*/
public static class VideoTakenEvent extends CrashableEvent {
private VideoTransaction xact;
public VideoTakenEvent(VideoTransaction xact) {
super();
this.xact=xact;
}
public VideoTakenEvent(Exception exception) {
super(exception);
}
public VideoTransaction getVideoTransaction() {
return(xact);
}
}
/**
* Base class for all ¯\_(ツ)_/¯ errors triggered by camera2
* API operations that we really should surface to callers,
* but either are not tied to specific requests or happen
* asynchronously with respect to the request. Usually, these
* are bad. However, they frequently do not have useful
* error information associated with them, because, well,
* that would have been useful.
*/
public static class CameraTwoGenericEvent {
}
/**
* Event raised if there is a problem starting up the
* CameraTwoEngine preview. The error field is the value passed
* into onError() of a CameraDevice.StateCallback object and
* probably means something to somebody.
*/
public static class CameraTwoPreviewErrorEvent
extends CameraTwoGenericEvent {
public final int error;
CameraTwoPreviewErrorEvent(int error) {
this.error=error;
}
}
/**
* Event raised if there is a different sort of problem
* starting up the CameraTwoEngine preview. This will be
* triggered by a CameraCaptureSession.StateCallback,
* and there is no error information of note.
*/
public static class CameraTwoPreviewFailureEvent
extends CameraTwoGenericEvent {
}
/**
* Create a CameraSession.Builder to build a CameraSession
* for a given CameraDescriptor. On the Builder is where you
* indicate your desired preview size, picture size, and
* so forth.
*
* @param ctxt an Android Context for accessing system stuff
* @param descriptor the CameraDescriptor for which we want
* a session
* @return a Builder to build that session
*/
abstract public CameraSession.Builder buildSession(Context ctxt,
CameraDescriptor descriptor);
/**
* Loads a roster of the available cameras for this engine,
* ranked based on the supplied criteria. Subscribe
* to the CameraDescriptorsEvent to get the results of this
* call asynchronously.
*
* @param criteria preferred camera capabilities, or
* null for a default ranking
*/
abstract public void loadCameraDescriptors(CameraSelectionCriteria criteria);
/**
* Open the requested camera and show a preview on the supplied
* surface. Subscribe to the OpenEvent to find out when this
* work is completed.
*
* @param session the session for the camera of interest
* @param texture the preview surface
*/
abstract public void open(CameraSession session,
SurfaceTexture texture);
/**
* Close the open camera. Subscribe to the ClosedEvent to
* find out when this work is completed. Note that this
* method may be synchronous or asynchronous.
*
* @param session the session for the camera of interest
*/
abstract public void close(CameraSession session);
/**
* Take a picture, on the supplied camera, using the picture
* configuration from the supplied transaction. Posts a
* PictureTakenEvent when the request is completed, successfully
* or unsuccessfully.
*
* @param session the session for the camera of interest
* @param xact the configuration of the picture to take
*/
abstract public void takePicture(CameraSession session,
PictureTransaction xact);
abstract public void recordVideo(CameraSession session,
VideoTransaction xact) throws Exception;
abstract public void stopVideoRecording(CameraSession session) throws Exception;
abstract public void handleOrientationChange(CameraSession session,
OrientationChangedEvent event);
/**
* @return true if the engine supports changing flash modes
* on the fly, false otherwise
*/
abstract public boolean supportsDynamicFlashModes();
/**
* Builds a CameraEngine instance based on the device's
* API level.
*
* @param ctxt any Context will do
* @param forceClassic if true, always use ClassicCameraEngine
* @return a new CameraEngine instance
*/
synchronized public static CameraEngine buildInstance(Context ctxt,
boolean forceClassic) {
if (singleton==null) {
if (!forceClassic &&
Build.VERSION.SDK_INT>=Build.VERSION_CODES.LOLLIPOP
&& !isProblematicDeviceOnNewCameraApi()) {
singleton=new CameraTwoEngine(ctxt);
}
else {
singleton=new ClassicCameraEngine(ctxt);
}
}
return(singleton);
}
/**
* Sets the event bus to use, where the default is the
* default event bus supplied by the EventBus class.
*
* @param bus the bus to use for events
*/
public void setBus(EventBus bus) {
this.bus=bus;
}
/**
* @return the bus to use for events
*/
public EventBus getBus() {
return(bus);
}
/**
* Sets whether or not exceptions should be logged, in addition
* to being included in relevant events. The default is false.
*
* @param isDebug true if exceptions should be logged, false otherwise
*/
public void setDebug(boolean isDebug) {
this.isDebug=isDebug;
}
/**
* @return true if exceptions should be logged, false otherwise
*/
public boolean isDebug() {
return(isDebug);
}
public void setDebugSavePreviewFile(File savePreviewFile) {
this.savePreviewFile=savePreviewFile;
}
public File savePreviewFile() {
return(savePreviewFile);
}
public ThreadPoolExecutor getThreadPool() {
if (pool==null) {
pool=new ThreadPoolExecutor(CORE_POOL_SIZE, MAX_POOL_SIZE,
KEEP_ALIVE_SECONDS, TimeUnit.SECONDS, queue);
}
return(pool);
}
public void setThreadPool(ThreadPoolExecutor pool) {
this.pool=pool;
}
void setPreferredFlashModes(List<FlashMode> flashModes) {
preferredFlashModes=flashModes;
}
boolean hasMoreThanOneEligibleFlashMode() {
return(eligibleFlashModes.size()>1);
}
private static boolean isProblematicDeviceOnNewCameraApi() {
if ("Huawei".equals(Build.MANUFACTURER) &&
"angler".equals(Build.PRODUCT)) {
return(true);
}
if ("LGE".equals(Build.MANUFACTURER) &&
"occam".equals(Build.PRODUCT)) {
return(true);
}
if ("Amazon".equals(Build.MANUFACTURER) &&
"full_ford".equals(Build.PRODUCT)) {
return(true);
}
if ("Amazon".equals(Build.MANUFACTURER) &&
"full_thebes".equals(Build.PRODUCT)) {
return(true);
}
if ("HTC".equals(Build.MANUFACTURER) &&
"m7_google".equals(Build.PRODUCT)) {
return(true);
}
if ("HTC".equals(Build.MANUFACTURER) &&
"hiaeuhl_00709".equals(Build.PRODUCT)) {
return(true);
}
if ("Wileyfox".equals(Build.MANUFACTURER) &&
"Swift".equals(Build.PRODUCT)) {
return(true);
}
if ("Sony".equals(Build.MANUFACTURER) &&
"C6603".equals(Build.PRODUCT)) {
return(true);
}
if ("Sony".equals(Build.MANUFACTURER) &&
"C6802".equals(Build.PRODUCT)) {
return(true);
}
return(false);
}
}
|
added SM-G920F workaround per issue #143
|
cam2/src/main/java/com/commonsware/cwac/cam2/CameraEngine.java
|
added SM-G920F workaround per issue #143
|
|
Java
|
apache-2.0
|
607e41860c533d7f198150b6572c6cb19246d0d3
| 0
|
caot/intellij-community,MER-GROUP/intellij-community,youdonghai/intellij-community,clumsy/intellij-community,slisson/intellij-community,dslomov/intellij-community,pwoodworth/intellij-community,petteyg/intellij-community,MER-GROUP/intellij-community,clumsy/intellij-community,alphafoobar/intellij-community,Distrotech/intellij-community,xfournet/intellij-community,allotria/intellij-community,dslomov/intellij-community,ryano144/intellij-community,petteyg/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,holmes/intellij-community,samthor/intellij-community,robovm/robovm-studio,ibinti/intellij-community,fnouama/intellij-community,vladmm/intellij-community,ivan-fedorov/intellij-community,izonder/intellij-community,alphafoobar/intellij-community,slisson/intellij-community,xfournet/intellij-community,ahb0327/intellij-community,xfournet/intellij-community,muntasirsyed/intellij-community,robovm/robovm-studio,da1z/intellij-community,MichaelNedzelsky/intellij-community,nicolargo/intellij-community,ol-loginov/intellij-community,ol-loginov/intellij-community,fitermay/intellij-community,TangHao1987/intellij-community,SerCeMan/intellij-community,vvv1559/intellij-community,semonte/intellij-community,signed/intellij-community,allotria/intellij-community,salguarnieri/intellij-community,FHannes/intellij-community,semonte/intellij-community,jagguli/intellij-community,TangHao1987/intellij-community,petteyg/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,dslomov/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,xfournet/intellij-community,robovm/robovm-studio,dslomov/intellij-community,muntasirsyed/intellij-community,ahb0327/intellij-community,vladmm/intellij-community,ftomassetti/intellij-community,amith01994/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,TangHao1987/intellij-community,ol-loginov/intellij-community,blademainer/intellij-community,mglukhikh/intellij-community,akosyakov/intellij-community,MER-GROUP/intellij-community,ivan-fedorov/intellij-community,jagguli/intellij-community,jagguli/intellij-community,izonder/intellij-community,michaelgallacher/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,izonder/intellij-community,ThiagoGarciaAlves/intellij-community,gnuhub/intellij-community,petteyg/intellij-community,ol-loginov/intellij-community,ryano144/intellij-community,clumsy/intellij-community,ol-loginov/intellij-community,Distrotech/intellij-community,xfournet/intellij-community,fitermay/intellij-community,caot/intellij-community,holmes/intellij-community,semonte/intellij-community,fengbaicanhe/intellij-community,gnuhub/intellij-community,akosyakov/intellij-community,MichaelNedzelsky/intellij-community,petteyg/intellij-community,caot/intellij-community,amith01994/intellij-community,ibinti/intellij-community,ivan-fedorov/intellij-community,youdonghai/intellij-community,orekyuu/intellij-community,mglukhikh/intellij-community,alphafoobar/intellij-community,vvv1559/intellij-community,allotria/intellij-community,holmes/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,adedayo/intellij-community,robovm/robovm-studio,amith01994/intellij-community,ThiagoGarciaAlves/intellij-community,petteyg/intellij-community,vvv1559/intellij-community,pwoodworth/intellij-community,holmes/intellij-community,youdonghai/intellij-community,kdwink/intellij-community,pwoodworth/intellij-community,petteyg/intellij-community,clumsy/intellij-community,lucafavatella/intellij-community,blademainer/intellij-community,nicolargo/intellij-community,ftomassetti/intellij-community,xfournet/intellij-community,fengbaicanhe/intellij-community,semonte/intellij-community,slisson/intellij-community,pwoodworth/intellij-community,SerCeMan/intellij-community,ol-loginov/intellij-community,kdwink/intellij-community,robovm/robovm-studio,xfournet/intellij-community,diorcety/intellij-community,vvv1559/intellij-community,jagguli/intellij-community,lucafavatella/intellij-community,kool79/intellij-community,semonte/intellij-community,hurricup/intellij-community,Distrotech/intellij-community,signed/intellij-community,wreckJ/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,amith01994/intellij-community,fengbaicanhe/intellij-community,supersven/intellij-community,supersven/intellij-community,fitermay/intellij-community,MichaelNedzelsky/intellij-community,robovm/robovm-studio,vvv1559/intellij-community,ibinti/intellij-community,signed/intellij-community,asedunov/intellij-community,alphafoobar/intellij-community,slisson/intellij-community,adedayo/intellij-community,apixandru/intellij-community,signed/intellij-community,apixandru/intellij-community,pwoodworth/intellij-community,da1z/intellij-community,nicolargo/intellij-community,retomerz/intellij-community,mglukhikh/intellij-community,vladmm/intellij-community,amith01994/intellij-community,pwoodworth/intellij-community,tmpgit/intellij-community,tmpgit/intellij-community,ftomassetti/intellij-community,jagguli/intellij-community,michaelgallacher/intellij-community,xfournet/intellij-community,Distrotech/intellij-community,youdonghai/intellij-community,fengbaicanhe/intellij-community,idea4bsd/idea4bsd,semonte/intellij-community,ivan-fedorov/intellij-community,petteyg/intellij-community,Distrotech/intellij-community,apixandru/intellij-community,asedunov/intellij-community,salguarnieri/intellij-community,kdwink/intellij-community,holmes/intellij-community,salguarnieri/intellij-community,kdwink/intellij-community,Lekanich/intellij-community,apixandru/intellij-community,fnouama/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,adedayo/intellij-community,adedayo/intellij-community,blademainer/intellij-community,samthor/intellij-community,vvv1559/intellij-community,Lekanich/intellij-community,pwoodworth/intellij-community,izonder/intellij-community,orekyuu/intellij-community,wreckJ/intellij-community,mglukhikh/intellij-community,blademainer/intellij-community,michaelgallacher/intellij-community,salguarnieri/intellij-community,da1z/intellij-community,retomerz/intellij-community,orekyuu/intellij-community,da1z/intellij-community,ahb0327/intellij-community,MichaelNedzelsky/intellij-community,supersven/intellij-community,xfournet/intellij-community,blademainer/intellij-community,signed/intellij-community,muntasirsyed/intellij-community,jagguli/intellij-community,kool79/intellij-community,holmes/intellij-community,nicolargo/intellij-community,MER-GROUP/intellij-community,vladmm/intellij-community,vladmm/intellij-community,asedunov/intellij-community,muntasirsyed/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,izonder/intellij-community,ryano144/intellij-community,idea4bsd/idea4bsd,akosyakov/intellij-community,idea4bsd/idea4bsd,ivan-fedorov/intellij-community,suncycheng/intellij-community,Distrotech/intellij-community,fengbaicanhe/intellij-community,wreckJ/intellij-community,holmes/intellij-community,idea4bsd/idea4bsd,supersven/intellij-community,dslomov/intellij-community,asedunov/intellij-community,clumsy/intellij-community,ThiagoGarciaAlves/intellij-community,tmpgit/intellij-community,orekyuu/intellij-community,Lekanich/intellij-community,diorcety/intellij-community,diorcety/intellij-community,lucafavatella/intellij-community,alphafoobar/intellij-community,salguarnieri/intellij-community,ftomassetti/intellij-community,asedunov/intellij-community,tmpgit/intellij-community,supersven/intellij-community,ivan-fedorov/intellij-community,akosyakov/intellij-community,jagguli/intellij-community,samthor/intellij-community,retomerz/intellij-community,holmes/intellij-community,ol-loginov/intellij-community,nicolargo/intellij-community,diorcety/intellij-community,signed/intellij-community,ftomassetti/intellij-community,samthor/intellij-community,kool79/intellij-community,fengbaicanhe/intellij-community,idea4bsd/idea4bsd,diorcety/intellij-community,ThiagoGarciaAlves/intellij-community,retomerz/intellij-community,petteyg/intellij-community,clumsy/intellij-community,wreckJ/intellij-community,apixandru/intellij-community,Distrotech/intellij-community,ibinti/intellij-community,fnouama/intellij-community,vladmm/intellij-community,diorcety/intellij-community,diorcety/intellij-community,da1z/intellij-community,apixandru/intellij-community,supersven/intellij-community,caot/intellij-community,dslomov/intellij-community,hurricup/intellij-community,da1z/intellij-community,alphafoobar/intellij-community,samthor/intellij-community,ftomassetti/intellij-community,TangHao1987/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,supersven/intellij-community,slisson/intellij-community,jagguli/intellij-community,ol-loginov/intellij-community,petteyg/intellij-community,retomerz/intellij-community,SerCeMan/intellij-community,ol-loginov/intellij-community,gnuhub/intellij-community,ibinti/intellij-community,michaelgallacher/intellij-community,Distrotech/intellij-community,vvv1559/intellij-community,kdwink/intellij-community,semonte/intellij-community,Lekanich/intellij-community,ol-loginov/intellij-community,SerCeMan/intellij-community,amith01994/intellij-community,jagguli/intellij-community,retomerz/intellij-community,ryano144/intellij-community,allotria/intellij-community,alphafoobar/intellij-community,nicolargo/intellij-community,muntasirsyed/intellij-community,mglukhikh/intellij-community,clumsy/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,caot/intellij-community,salguarnieri/intellij-community,apixandru/intellij-community,fnouama/intellij-community,ftomassetti/intellij-community,SerCeMan/intellij-community,izonder/intellij-community,semonte/intellij-community,akosyakov/intellij-community,MichaelNedzelsky/intellij-community,fitermay/intellij-community,fitermay/intellij-community,hurricup/intellij-community,mglukhikh/intellij-community,salguarnieri/intellij-community,adedayo/intellij-community,MER-GROUP/intellij-community,amith01994/intellij-community,ThiagoGarciaAlves/intellij-community,fnouama/intellij-community,suncycheng/intellij-community,amith01994/intellij-community,samthor/intellij-community,adedayo/intellij-community,dslomov/intellij-community,dslomov/intellij-community,fitermay/intellij-community,hurricup/intellij-community,FHannes/intellij-community,fengbaicanhe/intellij-community,gnuhub/intellij-community,TangHao1987/intellij-community,fengbaicanhe/intellij-community,vladmm/intellij-community,fnouama/intellij-community,kdwink/intellij-community,robovm/robovm-studio,mglukhikh/intellij-community,hurricup/intellij-community,ibinti/intellij-community,lucafavatella/intellij-community,blademainer/intellij-community,lucafavatella/intellij-community,nicolargo/intellij-community,pwoodworth/intellij-community,akosyakov/intellij-community,amith01994/intellij-community,ibinti/intellij-community,fitermay/intellij-community,fnouama/intellij-community,tmpgit/intellij-community,robovm/robovm-studio,asedunov/intellij-community,clumsy/intellij-community,ibinti/intellij-community,asedunov/intellij-community,alphafoobar/intellij-community,ibinti/intellij-community,caot/intellij-community,hurricup/intellij-community,ftomassetti/intellij-community,fengbaicanhe/intellij-community,ThiagoGarciaAlves/intellij-community,caot/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,akosyakov/intellij-community,ryano144/intellij-community,FHannes/intellij-community,robovm/robovm-studio,da1z/intellij-community,diorcety/intellij-community,caot/intellij-community,SerCeMan/intellij-community,kool79/intellij-community,lucafavatella/intellij-community,pwoodworth/intellij-community,suncycheng/intellij-community,vladmm/intellij-community,izonder/intellij-community,ahb0327/intellij-community,asedunov/intellij-community,salguarnieri/intellij-community,pwoodworth/intellij-community,da1z/intellij-community,tmpgit/intellij-community,youdonghai/intellij-community,michaelgallacher/intellij-community,akosyakov/intellij-community,fnouama/intellij-community,idea4bsd/idea4bsd,pwoodworth/intellij-community,petteyg/intellij-community,ol-loginov/intellij-community,TangHao1987/intellij-community,hurricup/intellij-community,Distrotech/intellij-community,MichaelNedzelsky/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,alphafoobar/intellij-community,muntasirsyed/intellij-community,robovm/robovm-studio,idea4bsd/idea4bsd,fitermay/intellij-community,kdwink/intellij-community,adedayo/intellij-community,diorcety/intellij-community,nicolargo/intellij-community,blademainer/intellij-community,signed/intellij-community,caot/intellij-community,FHannes/intellij-community,semonte/intellij-community,gnuhub/intellij-community,slisson/intellij-community,apixandru/intellij-community,signed/intellij-community,FHannes/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,ftomassetti/intellij-community,slisson/intellij-community,holmes/intellij-community,asedunov/intellij-community,muntasirsyed/intellij-community,orekyuu/intellij-community,MER-GROUP/intellij-community,lucafavatella/intellij-community,MER-GROUP/intellij-community,ahb0327/intellij-community,blademainer/intellij-community,ivan-fedorov/intellij-community,samthor/intellij-community,wreckJ/intellij-community,idea4bsd/idea4bsd,ivan-fedorov/intellij-community,vvv1559/intellij-community,michaelgallacher/intellij-community,Distrotech/intellij-community,kdwink/intellij-community,semonte/intellij-community,allotria/intellij-community,wreckJ/intellij-community,izonder/intellij-community,gnuhub/intellij-community,pwoodworth/intellij-community,fengbaicanhe/intellij-community,lucafavatella/intellij-community,Lekanich/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,Lekanich/intellij-community,akosyakov/intellij-community,FHannes/intellij-community,izonder/intellij-community,ryano144/intellij-community,holmes/intellij-community,akosyakov/intellij-community,wreckJ/intellij-community,amith01994/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,clumsy/intellij-community,TangHao1987/intellij-community,supersven/intellij-community,hurricup/intellij-community,ftomassetti/intellij-community,tmpgit/intellij-community,michaelgallacher/intellij-community,hurricup/intellij-community,orekyuu/intellij-community,caot/intellij-community,SerCeMan/intellij-community,nicolargo/intellij-community,MER-GROUP/intellij-community,allotria/intellij-community,suncycheng/intellij-community,adedayo/intellij-community,retomerz/intellij-community,wreckJ/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,samthor/intellij-community,allotria/intellij-community,vladmm/intellij-community,ftomassetti/intellij-community,allotria/intellij-community,orekyuu/intellij-community,adedayo/intellij-community,ibinti/intellij-community,gnuhub/intellij-community,dslomov/intellij-community,FHannes/intellij-community,ivan-fedorov/intellij-community,retomerz/intellij-community,ryano144/intellij-community,signed/intellij-community,diorcety/intellij-community,salguarnieri/intellij-community,Lekanich/intellij-community,SerCeMan/intellij-community,michaelgallacher/intellij-community,michaelgallacher/intellij-community,samthor/intellij-community,amith01994/intellij-community,kdwink/intellij-community,fitermay/intellij-community,FHannes/intellij-community,allotria/intellij-community,muntasirsyed/intellij-community,fitermay/intellij-community,dslomov/intellij-community,TangHao1987/intellij-community,jagguli/intellij-community,MER-GROUP/intellij-community,vladmm/intellij-community,salguarnieri/intellij-community,samthor/intellij-community,ivan-fedorov/intellij-community,izonder/intellij-community,fnouama/intellij-community,hurricup/intellij-community,slisson/intellij-community,retomerz/intellij-community,xfournet/intellij-community,Distrotech/intellij-community,robovm/robovm-studio,da1z/intellij-community,kool79/intellij-community,wreckJ/intellij-community,TangHao1987/intellij-community,orekyuu/intellij-community,MichaelNedzelsky/intellij-community,kdwink/intellij-community,da1z/intellij-community,lucafavatella/intellij-community,caot/intellij-community,fengbaicanhe/intellij-community,ThiagoGarciaAlves/intellij-community,akosyakov/intellij-community,asedunov/intellij-community,semonte/intellij-community,alphafoobar/intellij-community,tmpgit/intellij-community,kool79/intellij-community,kool79/intellij-community,fnouama/intellij-community,gnuhub/intellij-community,gnuhub/intellij-community,salguarnieri/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,FHannes/intellij-community,ahb0327/intellij-community,semonte/intellij-community,ryano144/intellij-community,MichaelNedzelsky/intellij-community,suncycheng/intellij-community,orekyuu/intellij-community,ftomassetti/intellij-community,ryano144/intellij-community,muntasirsyed/intellij-community,signed/intellij-community,semonte/intellij-community,youdonghai/intellij-community,izonder/intellij-community,diorcety/intellij-community,kool79/intellij-community,Lekanich/intellij-community,wreckJ/intellij-community,nicolargo/intellij-community,caot/intellij-community,vvv1559/intellij-community,SerCeMan/intellij-community,clumsy/intellij-community,adedayo/intellij-community,FHannes/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,clumsy/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,wreckJ/intellij-community,muntasirsyed/intellij-community,supersven/intellij-community,kdwink/intellij-community,MER-GROUP/intellij-community,blademainer/intellij-community,mglukhikh/intellij-community,TangHao1987/intellij-community,slisson/intellij-community,allotria/intellij-community,MER-GROUP/intellij-community,Lekanich/intellij-community,gnuhub/intellij-community,supersven/intellij-community,jagguli/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,tmpgit/intellij-community,retomerz/intellij-community,adedayo/intellij-community,da1z/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,samthor/intellij-community,vvv1559/intellij-community,slisson/intellij-community,MichaelNedzelsky/intellij-community,blademainer/intellij-community,nicolargo/intellij-community,kool79/intellij-community,petteyg/intellij-community,vladmm/intellij-community,kool79/intellij-community,muntasirsyed/intellij-community,alphafoobar/intellij-community,adedayo/intellij-community,slisson/intellij-community,wreckJ/intellij-community,salguarnieri/intellij-community,kdwink/intellij-community,MichaelNedzelsky/intellij-community,ThiagoGarciaAlves/intellij-community,ahb0327/intellij-community,michaelgallacher/intellij-community,michaelgallacher/intellij-community,asedunov/intellij-community,Lekanich/intellij-community,orekyuu/intellij-community,suncycheng/intellij-community,ahb0327/intellij-community,ryano144/intellij-community,retomerz/intellij-community,nicolargo/intellij-community,diorcety/intellij-community,Distrotech/intellij-community,SerCeMan/intellij-community,apixandru/intellij-community,akosyakov/intellij-community,mglukhikh/intellij-community,tmpgit/intellij-community,signed/intellij-community,blademainer/intellij-community,dslomov/intellij-community,ahb0327/intellij-community,vvv1559/intellij-community,tmpgit/intellij-community,fengbaicanhe/intellij-community,Lekanich/intellij-community,fitermay/intellij-community,youdonghai/intellij-community,dslomov/intellij-community,SerCeMan/intellij-community,MichaelNedzelsky/intellij-community,kool79/intellij-community,Lekanich/intellij-community,TangHao1987/intellij-community,izonder/intellij-community,alphafoobar/intellij-community,tmpgit/intellij-community,kool79/intellij-community,holmes/intellij-community,SerCeMan/intellij-community,vvv1559/intellij-community,retomerz/intellij-community,MichaelNedzelsky/intellij-community,signed/intellij-community,slisson/intellij-community,ahb0327/intellij-community,ryano144/intellij-community,supersven/intellij-community,retomerz/intellij-community,allotria/intellij-community,samthor/intellij-community,lucafavatella/intellij-community,supersven/intellij-community,fnouama/intellij-community,da1z/intellij-community,jagguli/intellij-community,fnouama/intellij-community,ivan-fedorov/intellij-community,ol-loginov/intellij-community,clumsy/intellij-community,gnuhub/intellij-community,xfournet/intellij-community,ivan-fedorov/intellij-community,ahb0327/intellij-community,orekyuu/intellij-community,lucafavatella/intellij-community,amith01994/intellij-community,TangHao1987/intellij-community,orekyuu/intellij-community,muntasirsyed/intellij-community,MER-GROUP/intellij-community,holmes/intellij-community,blademainer/intellij-community,robovm/robovm-studio,ahb0327/intellij-community,gnuhub/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,vladmm/intellij-community,ryano144/intellij-community
|
/*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.plugins.groovy.lang.psi.impl;
import com.intellij.codeInsight.javadoc.JavaDocInfoGenerator;
import com.intellij.lang.ASTNode;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Key;
import com.intellij.psi.*;
import com.intellij.psi.impl.source.tree.AstBufferUtil;
import com.intellij.psi.impl.source.tree.Factory;
import com.intellij.psi.infos.CandidateInfo;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.tree.TokenSet;
import com.intellij.psi.util.MethodSignature;
import com.intellij.psi.util.MethodSignatureUtil;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.reference.SoftReference;
import com.intellij.util.ArrayUtil;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.ReflectionUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.plugins.groovy.codeInspection.utils.ControlFlowUtils;
import org.jetbrains.plugins.groovy.lang.lexer.GroovyTokenTypes;
import org.jetbrains.plugins.groovy.lang.lexer.TokenSets;
import org.jetbrains.plugins.groovy.lang.psi.*;
import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult;
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.GrCondition;
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.GrListOrMap;
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifier;
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifierList;
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation.GrAnnotation;
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation.GrAnnotationNameValuePair;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrConstructorInvocation;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrStatement;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariableDeclaration;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentLabel;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentList;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrNamedArgument;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrCodeBlock;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrOpenBlock;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.*;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrLiteral;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrString;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrStringInjection;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrIndexProperty;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrMethodCallExpression;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameter;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrReferenceList;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrGdkMethod;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMember;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrReflectedMethod;
import org.jetbrains.plugins.groovy.lang.psi.api.types.GrTypeElement;
import org.jetbrains.plugins.groovy.lang.psi.api.util.GrNamedArgumentsOwner;
import org.jetbrains.plugins.groovy.lang.psi.api.util.GrStatementOwner;
import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil;
import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.literals.GrLiteralImpl;
import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GrSyntheticCodeBlock;
import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GrSyntheticExpression;
import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GrSyntheticReferenceList;
import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GrSyntheticTypeElement;
import org.jetbrains.plugins.groovy.lang.psi.util.GdkMethodUtil;
import org.jetbrains.plugins.groovy.lang.psi.util.GrStringUtil;
import org.jetbrains.plugins.groovy.lang.psi.util.GroovyCommonClassNames;
import org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil;
import org.jetbrains.plugins.groovy.refactoring.introduce.StringPartInfo;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class PsiImplUtil {
private static final Logger LOG = Logger.getInstance("org.jetbrains.plugins.groovy.lang.psi.impl.PsiImplUtil");
private static final String MAIN_METHOD = "main";
public static final Key<SoftReference<PsiCodeBlock>> PSI_CODE_BLOCK = Key.create("Psi_code_block");
public static final Key<SoftReference<PsiTypeElement>> PSI_TYPE_ELEMENT = Key.create("psi.type.element");
public static final Key<SoftReference<PsiExpression>> PSI_EXPRESSION = Key.create("psi.expression");
private static final Key<SoftReference<PsiReferenceList>> PSI_REFERENCE_LIST = Key.create("psi.reference.list");
private PsiImplUtil() {
}
/**
* @return leading regex or null if it does not exist
*/
@Nullable
private static GrLiteral getRegexAtTheBeginning(PsiElement expr) {
PsiElement fchild = expr;
while (fchild != null) {
if (fchild instanceof GrLiteral && GrStringUtil.isRegex((GrLiteral)fchild)) return (GrLiteral)fchild;
fchild = fchild.getFirstChild();
}
return null;
}
private static boolean isAfterIdentifier(PsiElement el) {
final PsiElement prev = PsiUtil.getPreviousNonWhitespaceToken(el);
return prev != null && prev.getNode().getElementType() == GroovyTokenTypes.mIDENT;
}
@Nullable
public static GrExpression replaceExpression(GrExpression oldExpr, GrExpression newExpr, boolean removeUnnecessaryParentheses) {
PsiElement oldParent = oldExpr.getParent();
if (oldParent == null) throw new PsiInvalidElementAccessException(oldExpr);
if (!(oldExpr instanceof GrApplicationStatement)) {
newExpr = ApplicationStatementUtil.convertToMethodCallExpression(newExpr);
}
// Remove unnecessary parentheses
if (removeUnnecessaryParentheses &&
oldParent instanceof GrParenthesizedExpression &&
!(oldParent.getParent() instanceof GrArgumentLabel)) {
return ((GrExpression)oldParent).replaceWithExpression(newExpr, removeUnnecessaryParentheses);
}
//regexes cannot be after identifier , try to replace it with simple string
if (getRegexAtTheBeginning(newExpr) != null && isAfterIdentifier(oldExpr)) {
final PsiElement copy = newExpr.copy();
final GrLiteral regex = getRegexAtTheBeginning(copy);
LOG.assertTrue(regex != null);
final GrLiteral stringLiteral = GrStringUtil.createStringFromRegex(regex);
if (regex == copy) {
return oldExpr.replaceWithExpression(stringLiteral, removeUnnecessaryParentheses);
}
else {
regex.replace(stringLiteral);
return oldExpr.replaceWithExpression((GrExpression)copy, removeUnnecessaryParentheses);
}
}
GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(oldExpr.getProject());
if (oldParent instanceof GrStringInjection) {
if (newExpr instanceof GrString || newExpr instanceof GrLiteral && ((GrLiteral)newExpr).getValue() instanceof String) {
return GrStringUtil.replaceStringInjectionByLiteral((GrStringInjection)oldParent, (GrLiteral)newExpr);
}
else {
GrClosableBlock block = factory.createClosureFromText("{foo}");
oldParent.getNode().replaceChild(oldExpr.getNode(), block.getNode());
GrStatement[] statements = block.getStatements();
return ((GrExpression)statements[0]).replaceWithExpression(newExpr, removeUnnecessaryParentheses);
}
}
if (PsiTreeUtil.getParentOfType(oldExpr, GrStringInjection.class, false, GrCodeBlock.class) != null) {
final GrStringInjection stringInjection = PsiTreeUtil.getParentOfType(oldExpr, GrStringInjection.class);
GrStringUtil.wrapInjection(stringInjection);
assert stringInjection != null;
final PsiElement replaced = oldExpr.replaceWithExpression(newExpr, removeUnnecessaryParentheses);
return (GrExpression)replaced;
}
//check priorities
if (oldParent instanceof GrExpression && !(oldParent instanceof GrParenthesizedExpression)) {
GrExpression addedParenth = addParenthesesIfNeeded(newExpr, oldExpr, (GrExpression)oldParent);
if (newExpr != addedParenth) {
return oldExpr.replaceWithExpression(addedParenth, removeUnnecessaryParentheses);
}
}
//if replace closure argument with expression
//we should add the expression in arg list
if (oldExpr instanceof GrClosableBlock &&
!(newExpr instanceof GrClosableBlock) &&
oldParent instanceof GrMethodCallExpression &&
ArrayUtil.contains(oldExpr, ((GrMethodCallExpression)oldParent).getClosureArguments())) {
return ((GrMethodCallExpression)oldParent).replaceClosureArgument((GrClosableBlock)oldExpr, newExpr);
}
newExpr = (GrExpression)oldExpr.replace(newExpr);
//if newExpr is the first grand child of command argument list we should replace command arg list with parenthesised arg list.
// In other case the code will be broken. So we try to find wrapping command arg list counting levels. After arg list replace we go inside it
// to find target parenthesised expression.
if (newExpr instanceof GrParenthesizedExpression && isFirstChild(newExpr)) {
int parentCount = 0;
PsiElement element = oldParent;
while (element != null && !(element instanceof GrCommandArgumentList)) {
if (element instanceof GrCodeBlock || element instanceof GrParenthesizedExpression) break;
if (element instanceof PsiFile) break;
final PsiElement parent = element.getParent();
if (parent == null) break;
if (!isFirstChild(element)) break;
element = parent;
parentCount++;
}
if (element instanceof GrCommandArgumentList) {
final GrCommandArgumentList commandArgList = (GrCommandArgumentList)element;
final PsiElement parent = commandArgList.getParent();
LOG.assertTrue(parent instanceof GrApplicationStatement);
final GrMethodCall methodCall = factory.createMethodCallByAppCall((GrApplicationStatement)parent);
final GrMethodCall newCall = (GrMethodCall)parent.replace(methodCall);
PsiElement result = newCall.getArgumentList().getAllArguments()[0];
for (int i = 0; i < parentCount; i++) {
result = PsiUtil.skipWhitespacesAndComments(result.getFirstChild(), true);
}
LOG.assertTrue(result instanceof GrParenthesizedExpression);
return (GrExpression)result;
}
}
return newExpr;
}
private static boolean isFirstChild(PsiElement element) {
return PsiUtil.skipWhitespacesAndComments(element.getParent().getFirstChild(), true) == element;
}
/**
* @return replaced expression or null if expression is not replaced
*/
@Nullable
private static GrExpression addParenthesesIfNeeded(GrExpression newExpr, GrExpression oldExpr, GrExpression oldParent) {
GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(oldExpr.getProject());
int parentPriorityLevel = getExprPriorityLevel(oldParent);
int newPriorityLevel = getExprPriorityLevel(newExpr);
if (parentPriorityLevel > newPriorityLevel) {
newExpr = factory.createParenthesizedExpr(newExpr);
}
else if (parentPriorityLevel == newPriorityLevel && parentPriorityLevel != 0) {
if (oldParent instanceof GrBinaryExpression) {
GrBinaryExpression binaryExpression = (GrBinaryExpression)oldParent;
if (isNotAssociative(binaryExpression) && oldExpr.equals(binaryExpression.getRightOperand())) {
newExpr = factory.createParenthesizedExpr(newExpr);
}
}
}
return newExpr;
}
private static boolean isNotAssociative(GrBinaryExpression binaryExpression) {
final IElementType opToken = binaryExpression.getOperationTokenType();
return !TokenSets.ASSOCIATIVE_BINARY_OP_SET.contains(opToken);
}
@Nullable
public static GrExpression getRuntimeQualifier(@NotNull GrReferenceExpression refExpr) {
GrExpression qualifier = refExpr.getQualifierExpression();
if (qualifier != null) return qualifier;
for (GrClosableBlock closure = PsiTreeUtil.getParentOfType(refExpr, GrClosableBlock.class);
closure != null;
closure = PsiTreeUtil.getParentOfType(closure, GrClosableBlock.class)) {
PsiElement parent = closure.getParent();
if (parent instanceof GrArgumentList) parent = parent.getParent();
if (!(parent instanceof GrMethodCall)) continue;
GrExpression funExpr = ((GrMethodCall)parent).getInvokedExpression();
if (!(funExpr instanceof GrReferenceExpression)) return funExpr;
final PsiElement resolved = ((GrReferenceExpression)funExpr).resolve();
if (!(resolved instanceof PsiMethod)) return funExpr;
if (resolved instanceof GrGdkMethod &&
isFromDGM((GrGdkMethod)resolved) &&
!GdkMethodUtil.isWithName(((GrGdkMethod)resolved).getStaticMethod().getName())) {
continue;
}
qualifier = ((GrReferenceExpression)funExpr).getQualifierExpression();
if (qualifier != null) return qualifier;
}
return null;
}
private static boolean isFromDGM(GrGdkMethod resolved) {
final PsiClass containingClass = resolved.getStaticMethod().getContainingClass();
return containingClass != null && GroovyCommonClassNames.DEFAULT_GROOVY_METHODS.equals(containingClass.getQualifiedName());
}
public static void removeVariable(GrVariable variable) {
final GrVariableDeclaration varDecl = (GrVariableDeclaration) variable.getParent();
final List<GrVariable> variables = Arrays.asList(varDecl.getVariables());
if (!variables.contains(variable)) {
throw new IllegalArgumentException();
}
final PsiElement parent = varDecl.getParent();
final ASTNode owner = parent.getNode();
if (variables.size() == 1 && owner != null) {
PsiElement next = varDecl.getNextSibling();
// remove redundant semicolons
//noinspection ConstantConditions
while (next != null && next.getNode() != null && next.getNode().getElementType() == GroovyTokenTypes.mSEMI) {
PsiElement tmpNext = next.getNextSibling();
//noinspection ConstantConditions
next.delete();
next = tmpNext;
}
removeNewLineAfter(varDecl);
varDecl.delete();
return;
}
variable.delete();
}
@Nullable
public static PsiElement realPrevious(PsiElement previousLeaf) {
while (previousLeaf != null &&
(previousLeaf instanceof PsiWhiteSpace ||
previousLeaf instanceof PsiComment ||
previousLeaf instanceof PsiErrorElement)) {
previousLeaf = previousLeaf.getPrevSibling();
}
return previousLeaf;
}
private static int getExprPriorityLevel(GrExpression expr) {
int priority;
//if (expr instanceof GrNewExpression) priority = 1;
if (expr instanceof GrUnaryExpression) priority = ((GrUnaryExpression)expr).isPostfix() ? 5 : 6;
else if (expr instanceof GrTypeCastExpression) priority = 6;
else if (expr instanceof GrBinaryExpression) {
final IElementType opToken = ((GrBinaryExpression)expr).getOperationTokenType();
if (opToken == GroovyTokenTypes.mSTAR_STAR) priority = 7;
else if (opToken == GroovyTokenTypes.mSTAR || opToken == GroovyTokenTypes.mDIV) priority = 8;
else if (opToken == GroovyTokenTypes.mPLUS || opToken == GroovyTokenTypes.mMINUS) priority = 9;
else if (TokenSets.SHIFT_SIGNS.contains(opToken)) priority = 10;
else if (opToken == GroovyTokenTypes.mRANGE_EXCLUSIVE || opToken == GroovyTokenTypes.mRANGE_INCLUSIVE) priority = 11;
else if (TokenSets.RELATIONS.contains(opToken)) priority = 12;
else if (opToken == GroovyTokenTypes.mEQUAL || opToken == GroovyTokenTypes.mNOT_EQUAL || opToken == GroovyTokenTypes.mCOMPARE_TO) priority = 13;
else if (opToken == GroovyTokenTypes.mREGEX_FIND || opToken == GroovyTokenTypes.mREGEX_MATCH) priority = 14;
else if (opToken == GroovyTokenTypes.mBAND) priority = 15;
else if (opToken == GroovyTokenTypes.mBXOR) priority = 16;
else if (opToken == GroovyTokenTypes.mBOR) priority = 17;
else if (opToken == GroovyTokenTypes.mLAND) priority = 18;
else if (opToken == GroovyTokenTypes.mLOR) priority = 19;
else {
assert false :"unknown operation:"+opToken;
priority = 0;
}
}
else if (expr instanceof GrConditionalExpression) priority = 20;
else if (expr instanceof GrSafeCastExpression) priority = 21;
else if (expr instanceof GrAssignmentExpression) priority = 22;
else if (expr instanceof GrApplicationStatement) priority = 23;
else priority = 0;
return -priority;
}
public static void setName(String name, PsiElement nameElement) {
final PsiElement newNameElement = GroovyPsiElementFactory.getInstance(nameElement.getProject()).createReferenceNameFromText(name);
nameElement.replace(newNameElement);
}
public static boolean isExtendsSignature(MethodSignature superSignatureCandidate, MethodSignature subSignature) {
return MethodSignatureUtil.isSubsignature(superSignatureCandidate, subSignature);
}
@Nullable
public static PsiMethod extractUniqueElement(@NotNull GroovyResolveResult[] results) {
if (results.length != 1) return null;
final PsiElement element = results[0].getElement();
return element instanceof PsiMethod ? (PsiMethod) element : null;
}
@NotNull
public static GroovyResolveResult extractUniqueResult(@NotNull GroovyResolveResult[] results) {
if (results.length != 1) return GroovyResolveResult.EMPTY_RESULT;
return results[0];
}
public static PsiMethod[] mapToMethods(@Nullable List<CandidateInfo> list) {
if (list == null) return PsiMethod.EMPTY_ARRAY;
PsiMethod[] result = new PsiMethod[list.size()];
for (int i = 0; i < list.size(); i++) {
result[i] = (PsiMethod) list.get(i).getElement();
}
return result;
}
@NotNull
public static String getName(@NotNull GrNamedElement namedElement) {
PsiElement nameElement = namedElement.getNameIdentifierGroovy();
ASTNode node = nameElement.getNode();
LOG.assertTrue(node != null);
if (node.getElementType() == GroovyTokenTypes.mIDENT) {
return nameElement.getText();
}
if (node.getElementType() == GroovyTokenTypes.mSTRING_LITERAL || node.getElementType() == GroovyTokenTypes.mGSTRING_LITERAL) {
final Object value = GrLiteralImpl.getLiteralValue(nameElement);
if (value instanceof String) {
return (String)value;
}
else {
return GrStringUtil.removeQuotes(nameElement.getText());
}
}
throw new IncorrectOperationException("incorrect name element: " + node.getElementType() + ", named element: " + namedElement);
}
public static void removeNewLineAfter(@NotNull GrStatement statement) {
ASTNode parentNode = statement.getParent().getNode();
ASTNode next = statement.getNode().getTreeNext();
if (parentNode != null && next != null && GroovyTokenTypes.mNLS == next.getElementType()) {
parentNode.removeChild(next);
}
}
public static boolean isMainMethod(GrMethod method) {
if (!method.getName().equals(MAIN_METHOD)) return false;
else if (!method.hasModifierProperty(PsiModifier.STATIC))return false;
final GrParameter[] parameters = method.getParameters();
if (parameters.length == 0) return false;
if (parameters.length == 1 && parameters[0].getTypeElementGroovy() == null) return true;
int args_count = 0;
int optional_count = 0;
for (GrParameter p : parameters) {
final GrTypeElement declaredType = p.getTypeElementGroovy();
if ((declaredType == null || declaredType.getType().equalsToText(CommonClassNames.JAVA_LANG_STRING + "[]")) &&
p.getInitializerGroovy() == null) {
args_count++;
}
if (p.getInitializerGroovy() != null) optional_count++;
}
return optional_count == parameters.length - 1 && args_count == 1;
}
public static void deleteStatementTail(PsiElement container, @NotNull PsiElement statement) {
PsiElement next = statement.getNextSibling();
while (next != null) {
final ASTNode node = next.getNode();
final IElementType type = node.getElementType();
if (type == GroovyTokenTypes.mSEMI || type == TokenType.WHITE_SPACE && !next.getText().contains("\n")) {
final PsiElement nnext = next.getNextSibling();
container.deleteChildRange(next, next);
next = nnext;
}
else if (type == GroovyTokenTypes.mNLS || type == TokenType.WHITE_SPACE && next.getText().contains("\n")) {
final String text = next.getText();
final int first = text.indexOf("\n");
final int second = text.indexOf("\n", first + 1);
if (second < 0) {
container.deleteChildRange(next, next);
return;
}
final String substring = text.substring(second);
container.getNode()
.replaceChild(node, Factory.createSingleLeafElement(type, substring, 0, substring.length(), null, container.getManager()));
return;
}
else {
break;
}
}
}
public static <T extends PsiElement> void setQualifier(@NotNull GrQualifiedReference<T> ref, @Nullable T newQualifier) {
final T oldQualifier = ref.getQualifier();
final ASTNode node = ref.getNode();
final PsiElement refNameElement = ref.getReferenceNameElement();
if (newQualifier == null) {
if (oldQualifier != null && refNameElement != null) {
ref.deleteChildRange(ref.getFirstChild(), refNameElement.getPrevSibling());
}
} else {
if (oldQualifier == null) {
if (refNameElement != null) {
node.addLeaf(GroovyTokenTypes.mDOT, ".", refNameElement.getNode());
ref.addBefore(newQualifier, refNameElement.getPrevSibling());
}
}
else {
oldQualifier.replace(newQualifier);
}
}
}
public static boolean isSimpleArrayAccess(PsiType exprType, PsiType[] argTypes, PsiElement context, boolean isLValue) {
return exprType instanceof PsiArrayType &&
(isLValue && argTypes.length == 2 || !isLValue && argTypes.length == 1) &&
TypesUtil.isAssignableByMethodCallConversion(PsiType.INT, argTypes[0], context);
}
public static String getTextSkipWhiteSpaceAndComments(ASTNode node) {
return AstBufferUtil.getTextSkippingWhitespaceComments(node);
}
public static PsiCodeBlock getOrCreatePsiCodeBlock(GrOpenBlock block) {
if (block == null) return null;
final SoftReference<PsiCodeBlock> ref = block.getUserData(PSI_CODE_BLOCK);
final PsiCodeBlock body = SoftReference.dereference(ref);
if (body != null) return body;
final GrSyntheticCodeBlock newBody = new GrSyntheticCodeBlock(block);
block.putUserData(PSI_CODE_BLOCK, new SoftReference<PsiCodeBlock>(newBody));
return newBody;
}
public static PsiTypeElement getOrCreateTypeElement(GrTypeElement typeElement) {
if (typeElement == null) return null;
final SoftReference<PsiTypeElement> ref = typeElement.getUserData(PSI_TYPE_ELEMENT);
final PsiTypeElement element = SoftReference.dereference(ref);
if (element != null) return element;
final GrSyntheticTypeElement newTypeElement = new GrSyntheticTypeElement(typeElement);
typeElement.putUserData(PSI_TYPE_ELEMENT, new SoftReference<PsiTypeElement>(newTypeElement));
return newTypeElement;
}
public static PsiExpression getOrCreatePisExpression(GrExpression expr) {
if (expr == null) return null;
final SoftReference<PsiExpression> ref = expr.getUserData(PSI_EXPRESSION);
final PsiExpression element = SoftReference.dereference(ref);
if (element != null) return element;
final GrSyntheticExpression newExpr = new GrSyntheticExpression(expr);
expr.putUserData(PSI_EXPRESSION, new SoftReference<PsiExpression>(newExpr));
return newExpr;
}
public static PsiReferenceList getOrCreatePsiReferenceList(GrReferenceList list, PsiReferenceList.Role role) {
if (list == null) return null;
final SoftReference<PsiReferenceList> ref = list.getUserData(PSI_REFERENCE_LIST);
final PsiReferenceList element = SoftReference.dereference(ref);
if (element != null) return element;
final GrSyntheticReferenceList newList = new GrSyntheticReferenceList(list, role);
list.putUserData(PSI_REFERENCE_LIST, new SoftReference<PsiReferenceList>(newList));
return newList;
}
public static <T extends GrCondition> T replaceBody(T newBody, GrStatement body, ASTNode node, Project project) {
if (body == null || newBody == null) {
throw new IncorrectOperationException();
}
ASTNode oldBodyNode = body.getNode();
if (oldBodyNode.getTreePrev() != null && GroovyTokenTypes.mNLS.equals(oldBodyNode.getTreePrev().getElementType())) {
ASTNode whiteNode = GroovyPsiElementFactory.getInstance(project).createWhiteSpace().getNode();
node.replaceChild(oldBodyNode.getTreePrev(), whiteNode);
}
node.replaceChild(oldBodyNode, newBody.getNode());
return newBody;
}
public static boolean isVarArgs(GrParameter[] parameters) {
return parameters.length > 0 && parameters[parameters.length - 1].isVarArgs();
}
@Nullable
public static PsiAnnotation getAnnotation(@NotNull PsiModifierListOwner field, @NotNull String annotationName) {
final PsiModifierList modifierList = field.getModifierList();
if (modifierList == null) return null;
return modifierList.findAnnotation(annotationName);
}
@Nullable
public static GrConstructorInvocation getChainingConstructorInvocation(GrMethod constructor) {
if (constructor instanceof GrReflectedMethod && ((GrReflectedMethod)constructor).getSkippedParameters().length > 0) return null;
LOG.assertTrue(constructor.isConstructor());
GrOpenBlock body = constructor.getBlock();
if (body == null) return null;
GrStatement[] statements = body.getStatements();
if (statements.length > 0 && statements[0] instanceof GrConstructorInvocation) {
return (GrConstructorInvocation) statements[0];
}
return null;
}
public static GrMethod[] getMethodOrReflectedMethods(GrMethod method) {
final GrReflectedMethod[] reflectedMethods = method.getReflectedMethods();
return reflectedMethods.length > 0 ? reflectedMethods : new GrMethod[]{method};
}
@Nullable
public static PsiType inferExpectedTypeForDiamond(GrExpression diamondNew) {
PsiElement skipped = PsiUtil.skipParentheses(diamondNew, true);
assert skipped != null;
PsiElement pparent = skipped.getParent();
if (pparent instanceof GrAssignmentExpression &&
PsiTreeUtil.isAncestor(((GrAssignmentExpression)pparent).getRValue(), diamondNew, false)) {
GrExpression lValue = ((GrAssignmentExpression)pparent).getLValue();
if (PsiUtil.mightBeLValue(lValue)) {
return lValue.getNominalType();
}
}
else if (pparent instanceof GrVariable && ((GrVariable)pparent).getInitializerGroovy() == diamondNew) {
return ((GrVariable)pparent).getDeclaredType();
}
else if (pparent instanceof GrListOrMap) {
PsiElement ppparent = PsiUtil.skipParentheses(pparent.getParent(), true);
if (ppparent instanceof GrAssignmentExpression &&
PsiTreeUtil.isAncestor(((GrAssignmentExpression)ppparent).getRValue(), pparent, false)) {
PsiElement lValue = PsiUtil.skipParentheses(((GrAssignmentExpression)ppparent).getLValue(), false);
if (lValue instanceof GrTupleExpression) {
GrExpression[] initializers = ((GrListOrMap)pparent).getInitializers();
int index = ArrayUtil.find(initializers, diamondNew);
GrExpression[] expressions = ((GrTupleExpression)lValue).getExpressions();
if (index < expressions.length) {
return expressions[index].getNominalType();
}
}
}
}
return null;
}
@Nullable
public static PsiType normalizeWildcardTypeByPosition(@NotNull PsiType type, @NotNull GrExpression expression) {
GrExpression toplevel = expression;
while (toplevel.getParent() instanceof GrIndexProperty &&
((GrIndexProperty)toplevel.getParent()).getInvokedExpression() == toplevel) {
toplevel = (GrExpression)toplevel.getParent();
}
final PsiType normalized = doNormalizeWildcardByPosition(type, expression, toplevel);
if (normalized instanceof PsiClassType && !PsiUtil.isAccessedForWriting(toplevel)) {
return com.intellij.psi.util.PsiUtil.captureToplevelWildcards(normalized, expression);
}
return normalized;
}
@Nullable
private static PsiType doNormalizeWildcardByPosition(final PsiType type, final GrExpression expression, final GrExpression toplevel) {
if (type instanceof PsiCapturedWildcardType) {
return doNormalizeWildcardByPosition(((PsiCapturedWildcardType)type).getWildcard(), expression, toplevel);
}
if (type instanceof PsiWildcardType) {
final PsiWildcardType wildcardType = (PsiWildcardType)type;
if (PsiUtil.isAccessedForWriting(toplevel)) {
return wildcardType.isSuper() ? wildcardType.getBound() : PsiCapturedWildcardType.create(wildcardType, expression);
}
else {
if (wildcardType.isExtends()) {
return wildcardType.getBound();
}
else {
return TypesUtil.getJavaLangObject(expression);
}
}
}
else if (type instanceof PsiArrayType) {
final PsiType componentType = ((PsiArrayType)type).getComponentType();
final PsiType normalizedComponentType = doNormalizeWildcardByPosition(componentType, expression, toplevel);
if (normalizedComponentType != componentType) {
assert normalizedComponentType != null;
return normalizedComponentType.createArrayType();
}
}
return type;
}
public static boolean hasElementType(@Nullable PsiElement next, @NotNull final IElementType type) {
if (next == null) return false;
final ASTNode astNode = next.getNode();
return astNode != null && astNode.getElementType() == type;
}
public static boolean hasElementType(@Nullable PsiElement next, final TokenSet set) {
if (next == null) return false;
final ASTNode astNode = next.getNode();
return astNode != null && set.contains(astNode.getElementType());
}
public static boolean hasNamedArguments(@Nullable GrNamedArgumentsOwner list) {
if (list == null) return false;
for (PsiElement child = list.getFirstChild(); child != null; child = child.getNextSibling()) {
if (child instanceof GrNamedArgument) return true;
}
return false;
}
public static boolean hasExpressionArguments(@Nullable GrArgumentList list) {
if (list == null) return false;
for (PsiElement child = list.getFirstChild(); child != null; child = child.getNextSibling()) {
if (child instanceof GrExpression) return true;
}
return false;
}
public static boolean hasClosureArguments(@Nullable GrCall call) {
if (call == null) return false;
for (PsiElement child = call.getFirstChild(); child != null; child = child.getNextSibling()) {
if (child instanceof GrClosableBlock) return true;
}
return false;
}
public static PsiElement findTailingSemicolon(@NotNull GrStatement statement) {
final PsiElement nextNonSpace = PsiUtil.skipWhitespaces(statement.getNextSibling(), true);
if (nextNonSpace != null && nextNonSpace.getNode().getElementType() == GroovyTokenTypes.mSEMI) {
return nextNonSpace;
}
return null;
}
@Nullable
public static PsiType inferReturnType(PsiElement position) {
final GrControlFlowOwner flowOwner = ControlFlowUtils.findControlFlowOwner(position);
if (flowOwner == null) return null;
final PsiElement parent = flowOwner.getContext();
if (flowOwner instanceof GrOpenBlock && parent instanceof GrMethod) {
final GrMethod method = (GrMethod)parent;
if (method.isConstructor()) return null;
return method.getReturnType();
}
return null;
}
public static GrStatement[] getStatements(final GrStatementOwner statementOwner) {
List<GrStatement> result = new ArrayList<GrStatement>();
for (PsiElement cur = statementOwner.getFirstChild(); cur != null; cur = cur.getNextSibling()) {
if (cur instanceof GrStatement) {
result.add((GrStatement)cur);
}
}
return result.toArray(new GrStatement[result.size()]);
}
public static GrNamedArgument findNamedArgument(final GrNamedArgumentsOwner namedArgumentOwner,
String label) {
for (PsiElement cur = namedArgumentOwner.getFirstChild(); cur != null; cur = cur.getNextSibling()) {
if (cur instanceof GrNamedArgument) {
if (label.equals(((GrNamedArgument)cur).getLabelName())) {
return (GrNamedArgument)cur;
}
}
}
return null;
}
public static boolean hasImmutableAnnotation(PsiModifierList modifierList) {
return modifierList.findAnnotation(GroovyCommonClassNames.GROOVY_LANG_IMMUTABLE) != null ||
modifierList.findAnnotation(GroovyCommonClassNames.GROOVY_TRANSFORM_IMMUTABLE) != null;
}
public static boolean isWhiteSpaceOrNls(@Nullable PsiElement sibling) {
return sibling != null && isWhiteSpaceOrNls(sibling.getNode());
}
public static boolean isWhiteSpaceOrNls(@Nullable ASTNode node) {
return node != null && TokenSets.WHITE_SPACES_SET.contains(node.getElementType());
}
public static void insertPlaceHolderToModifierListAtEndIfNeeded(GrModifierList modifierList) {
PsiElement newLineAfterModifierList = findNewLineAfterElement(modifierList);
if (newLineAfterModifierList != null) {
modifierList.setModifierProperty(GrModifier.DEF, false);
if (modifierList.getModifiers().length > 0) {
modifierList.getNode().addLeaf(GroovyTokenTypes.mNLS, newLineAfterModifierList.getText(), null);
}
modifierList.getNode().addLeaf(GroovyTokenTypes.kDEF, "def", null);
final PsiElement newLineUpdated = findNewLineAfterElement(modifierList);
if (newLineUpdated != null) newLineUpdated.delete();
if (!isWhiteSpaceOrNls(modifierList.getNextSibling())) {
modifierList.getParent().getNode().addLeaf(TokenType.WHITE_SPACE, " ", modifierList.getNextSibling().getNode());
}
}
else if (modifierList.getModifiers().length == 0) {
modifierList.setModifierProperty(GrModifier.DEF, true);
}
}
@Nullable
private static PsiElement findNewLineAfterElement(PsiElement element) {
PsiElement sibling = element.getNextSibling();
while (sibling != null && isWhiteSpaceOrNls(sibling)) {
if (PsiUtil.isNewLine(sibling)) {
return sibling;
}
sibling = sibling.getNextSibling();
}
return null;
}
@Nullable
public static GrAnnotation getAnnotation(@NotNull GrAnnotationNameValuePair pair) {
PsiElement pParent = pair.getParent().getParent();
if (pParent instanceof GrAnnotation) return (GrAnnotation)pParent;
PsiElement ppParent = pParent.getParent();
return ppParent instanceof GrAnnotation ? (GrAnnotation)ppParent : null;
}
@Nullable
public static <T extends PsiElement> T findElementInRange(final PsiFile file,
int startOffset,
int endOffset,
final Class<T> klass) {
PsiElement element1 = file.getViewProvider().findElementAt(startOffset, file.getLanguage());
PsiElement element2 = file.getViewProvider().findElementAt(endOffset - 1, file.getLanguage());
if (element1 == null || element2 == null) return null;
if (isWhiteSpaceOrNls(element1)) {
startOffset = element1.getTextRange().getEndOffset();
element1 = file.getViewProvider().findElementAt(startOffset, file.getLanguage());
}
if (isWhiteSpaceOrNls(element2)) {
endOffset = element2.getTextRange().getStartOffset();
element2 = file.getViewProvider().findElementAt(endOffset - 1, file.getLanguage());
}
if (element2 == null || element1 == null) return null;
final PsiElement commonParent = PsiTreeUtil.findCommonParent(element1, element2);
assert commonParent != null;
final T element = ReflectionUtil.isAssignable(klass, commonParent.getClass()) ? (T) commonParent : PsiTreeUtil.getParentOfType(commonParent, klass);
if (element == null) {
return null;
}
if (!checkRanges(element, startOffset, endOffset)) {
return null;
}
return element;
}
private static boolean checkRanges(@NotNull PsiElement element, int startOffset, int endOffset) {
if (element instanceof GrLiteral && StringPartInfo.isWholeLiteralContentSelected((GrLiteral)element, startOffset, endOffset)) {
return true;
}
if (element.getTextRange().getStartOffset() == startOffset) {
return true;
}
return false;
}
public static void appendTypeString(StringBuilder buffer, final PsiType type, PsiElement context) {
if (type != null) {
JavaDocInfoGenerator.generateType(buffer, type, context);
}
else {
buffer.append(GrModifier.DEF);
}
}
public static boolean isSpreadAssignment(@Nullable GrExpression lValue) {
if (lValue instanceof GrReferenceExpression) {
GrReferenceExpression expression = (GrReferenceExpression)lValue;
final PsiElement dot = expression.getDotToken();
//noinspection ConstantConditions
if (dot != null && dot.getNode().getElementType() == GroovyTokenTypes.mSPREAD_DOT) {
return true;
}
else {
final GrExpression qualifier = expression.getQualifierExpression();
if (qualifier != null) return isSpreadAssignment(qualifier);
}
}
return false;
}
public static void replaceExpression(@NotNull String newExpression, @NotNull GrExpression expression) throws IncorrectOperationException {
final GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(expression.getProject());
final GrExpression newCall = factory.createExpressionFromText(newExpression);
expression.replaceWithExpression(newCall, true);
}
public static GrStatement replaceStatement(@NonNls @NotNull String newStatement, @NonNls @NotNull GrStatement statement)
throws IncorrectOperationException {
final GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(statement.getProject());
final GrStatement newCall = (GrStatement)factory.createTopElementFromText(newStatement);
return statement.replaceWithStatement(newCall);
}
public static boolean seemsToBeQualifiedClassName(@Nullable GrExpression expr) {
if (expr == null) return false;
while (expr instanceof GrReferenceExpression) {
final PsiElement nameElement = ((GrReferenceExpression)expr).getReferenceNameElement();
if (((GrReferenceExpression)expr).getTypeArguments().length > 0) return false;
if (nameElement == null || nameElement.getNode().getElementType() != GroovyTokenTypes.mIDENT) return false;
IElementType dotType = ((GrReferenceExpression)expr).getDotTokenType();
if (dotType != null && dotType != GroovyTokenTypes.mDOT) return false;
expr = ((GrReferenceExpression)expr).getQualifierExpression();
}
return expr == null;
}
@Nullable
public static PsiType getQualifierType(@NotNull GrReferenceExpression ref) {
final GrExpression rtQualifier = getRuntimeQualifier(ref);
if (rtQualifier != null) {
return rtQualifier.getType();
}
PsiClass containingClass = null;
final GrMember member = PsiTreeUtil.getParentOfType(ref, GrMember.class);
if (member == null) {
final PsiFile file = ref.getContainingFile();
if (file instanceof GroovyFileBase && ((GroovyFileBase)file).isScript()) {
containingClass = ((GroovyFileBase)file).getScriptClass();
}
else {
return null;
}
}
else if (member instanceof GrMethod) {
if (!member.hasModifierProperty(PsiModifier.STATIC)) {
containingClass = member.getContainingClass();
}
}
if (containingClass != null) {
final PsiClassType categoryType = GdkMethodUtil.getCategoryType(containingClass);
if (categoryType != null) {
return categoryType;
}
return JavaPsiFacade.getElementFactory(ref.getProject()).createType(containingClass);
}
return null;
}
@NotNull
public static GroovyResolveResult reflectedToBase(GroovyResolveResult result, GrMethod baseMethod, GrReflectedMethod reflectedMethod) {
PsiSubstitutor substitutor = result.getSubstitutor();
PsiTypeParameter[] reflectedParameters = reflectedMethod.getTypeParameters();
PsiTypeParameter[] baseParameters = baseMethod.getTypeParameters();
assert baseParameters.length == reflectedParameters.length;
for (int i = 0; i < baseParameters.length; i++) {
substitutor = substitutor.put(baseParameters[i], result.getSubstitutor().substitute(reflectedParameters[i]));
}
return new GroovyResolveResultImpl(baseMethod, result.getCurrentFileResolveContext(), result.getSpreadState(),
substitutor, result.isAccessible(), result.isStaticsOK(),
result.isInvokedOnProperty(), result.isValidResult());
}
}
|
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/PsiImplUtil.java
|
/*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.plugins.groovy.lang.psi.impl;
import com.intellij.codeInsight.javadoc.JavaDocInfoGenerator;
import com.intellij.lang.ASTNode;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Key;
import com.intellij.psi.*;
import com.intellij.psi.impl.source.tree.AstBufferUtil;
import com.intellij.psi.impl.source.tree.Factory;
import com.intellij.psi.infos.CandidateInfo;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.tree.TokenSet;
import com.intellij.psi.util.MethodSignature;
import com.intellij.psi.util.MethodSignatureUtil;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.reference.SoftReference;
import com.intellij.util.ArrayUtil;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.ReflectionUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.plugins.groovy.codeInspection.utils.ControlFlowUtils;
import org.jetbrains.plugins.groovy.lang.lexer.GroovyTokenTypes;
import org.jetbrains.plugins.groovy.lang.lexer.TokenSets;
import org.jetbrains.plugins.groovy.lang.psi.*;
import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult;
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.GrCondition;
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.GrListOrMap;
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifier;
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifierList;
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation.GrAnnotation;
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation.GrAnnotationNameValuePair;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrConstructorInvocation;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrStatement;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariableDeclaration;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentLabel;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentList;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrNamedArgument;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrCodeBlock;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrOpenBlock;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.*;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrLiteral;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrString;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrStringInjection;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrIndexProperty;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrMethodCallExpression;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameter;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrReferenceList;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrGdkMethod;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMember;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrReflectedMethod;
import org.jetbrains.plugins.groovy.lang.psi.api.types.GrTypeElement;
import org.jetbrains.plugins.groovy.lang.psi.api.util.GrNamedArgumentsOwner;
import org.jetbrains.plugins.groovy.lang.psi.api.util.GrStatementOwner;
import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil;
import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.literals.GrLiteralImpl;
import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GrSyntheticCodeBlock;
import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GrSyntheticExpression;
import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GrSyntheticReferenceList;
import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GrSyntheticTypeElement;
import org.jetbrains.plugins.groovy.lang.psi.util.GdkMethodUtil;
import org.jetbrains.plugins.groovy.lang.psi.util.GrStringUtil;
import org.jetbrains.plugins.groovy.lang.psi.util.GroovyCommonClassNames;
import org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil;
import org.jetbrains.plugins.groovy.refactoring.introduce.StringPartInfo;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class PsiImplUtil {
private static final Logger LOG = Logger.getInstance("org.jetbrains.plugins.groovy.lang.psi.impl.PsiImplUtil");
private static final String MAIN_METHOD = "main";
public static final Key<SoftReference<PsiCodeBlock>> PSI_CODE_BLOCK = Key.create("Psi_code_block");
public static final Key<SoftReference<PsiTypeElement>> PSI_TYPE_ELEMENT = Key.create("psi.type.element");
public static final Key<SoftReference<PsiExpression>> PSI_EXPRESSION = Key.create("psi.expression");
private static final Key<SoftReference<PsiReferenceList>> PSI_REFERENCE_LIST = Key.create("psi.reference.list");
private PsiImplUtil() {
}
/**
* @return leading regex or null if it does not exist
*/
@Nullable
private static GrLiteral getRegexAtTheBeginning(PsiElement expr) {
PsiElement fchild = expr;
while (fchild != null) {
if (fchild instanceof GrLiteral && GrStringUtil.isRegex((GrLiteral)fchild)) return (GrLiteral)fchild;
fchild = fchild.getFirstChild();
}
return null;
}
private static boolean isAfterIdentifier(PsiElement el) {
final PsiElement prev = PsiUtil.getPreviousNonWhitespaceToken(el);
return prev != null && prev.getNode().getElementType() == GroovyTokenTypes.mIDENT;
}
@Nullable
public static GrExpression replaceExpression(GrExpression oldExpr, GrExpression newExpr, boolean removeUnnecessaryParentheses) {
PsiElement oldParent = oldExpr.getParent();
if (oldParent == null) throw new PsiInvalidElementAccessException(oldExpr);
if (!(oldExpr instanceof GrApplicationStatement)) {
newExpr = ApplicationStatementUtil.convertToMethodCallExpression(newExpr);
}
// Remove unnecessary parentheses
if (removeUnnecessaryParentheses &&
oldParent instanceof GrParenthesizedExpression &&
!(oldParent.getParent() instanceof GrArgumentLabel)) {
return ((GrExpression)oldParent).replaceWithExpression(newExpr, removeUnnecessaryParentheses);
}
//regexes cannot be after identifier , try to replace it with simple string
if (getRegexAtTheBeginning(newExpr) != null && isAfterIdentifier(oldExpr)) {
final PsiElement copy = newExpr.copy();
final GrLiteral regex = getRegexAtTheBeginning(copy);
LOG.assertTrue(regex != null);
final GrLiteral stringLiteral = GrStringUtil.createStringFromRegex(regex);
if (regex == copy) {
return oldExpr.replaceWithExpression(stringLiteral, removeUnnecessaryParentheses);
}
else {
regex.replace(stringLiteral);
return oldExpr.replaceWithExpression((GrExpression)copy, removeUnnecessaryParentheses);
}
}
GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(oldExpr.getProject());
if (oldParent instanceof GrStringInjection) {
if (newExpr instanceof GrString || newExpr instanceof GrLiteral && ((GrLiteral)newExpr).getValue() instanceof String) {
return GrStringUtil.replaceStringInjectionByLiteral((GrStringInjection)oldParent, (GrLiteral)newExpr);
}
else {
GrClosableBlock block = factory.createClosureFromText("{foo}");
oldParent.getNode().replaceChild(oldExpr.getNode(), block.getNode());
GrStatement[] statements = block.getStatements();
return ((GrExpression)statements[0]).replaceWithExpression(newExpr, removeUnnecessaryParentheses);
}
}
if (PsiTreeUtil.getParentOfType(oldExpr, GrStringInjection.class, false, GrCodeBlock.class) != null) {
final GrStringInjection stringInjection = PsiTreeUtil.getParentOfType(oldExpr, GrStringInjection.class);
GrStringUtil.wrapInjection(stringInjection);
assert stringInjection != null;
final PsiElement replaced = oldExpr.replaceWithExpression(newExpr, removeUnnecessaryParentheses);
return (GrExpression)replaced;
}
//check priorities
if (oldParent instanceof GrExpression && !(oldParent instanceof GrParenthesizedExpression)) {
GrExpression addedParenth = addParenthesesIfNeeded(newExpr, oldExpr, (GrExpression)oldParent);
if (newExpr != addedParenth) {
return oldExpr.replaceWithExpression(addedParenth, removeUnnecessaryParentheses);
}
}
//if replace closure argument with expression
//we should add the expression in arg list
if (oldExpr instanceof GrClosableBlock &&
!(newExpr instanceof GrClosableBlock) &&
oldParent instanceof GrMethodCallExpression &&
ArrayUtil.contains(oldExpr, ((GrMethodCallExpression)oldParent).getClosureArguments())) {
return ((GrMethodCallExpression)oldParent).replaceClosureArgument((GrClosableBlock)oldExpr, newExpr);
}
newExpr = (GrExpression)oldExpr.replace(newExpr);
//if newExpr is the first grand child of command argument list we should replace command arg list with parenthesised arg list.
// In other case the code will be broken. So we try to find wrapping command arg list counting levels. After arg list replace we go inside it
// to find target parenthesised expression.
if (newExpr instanceof GrParenthesizedExpression && isFirstChild(newExpr)) {
int parentCount = 0;
PsiElement element = oldParent;
while (element != null && !(element instanceof GrCommandArgumentList)) {
if (element instanceof GrCodeBlock || element instanceof GrParenthesizedExpression) break;
if (element instanceof PsiFile) break;
final PsiElement parent = element.getParent();
if (parent == null) break;
if (!isFirstChild(element)) break;
element = parent;
parentCount++;
}
if (element instanceof GrCommandArgumentList) {
final GrCommandArgumentList commandArgList = (GrCommandArgumentList)element;
final PsiElement parent = commandArgList.getParent();
LOG.assertTrue(parent instanceof GrApplicationStatement);
final GrMethodCall methodCall = factory.createMethodCallByAppCall((GrApplicationStatement)parent);
final GrMethodCall newCall = (GrMethodCall)parent.replace(methodCall);
PsiElement result = newCall.getArgumentList().getAllArguments()[0];
for (int i = 0; i < parentCount; i++) {
result = PsiUtil.skipWhitespacesAndComments(result.getFirstChild(), true);
}
LOG.assertTrue(result instanceof GrParenthesizedExpression);
return (GrExpression)result;
}
}
return newExpr;
}
private static boolean isFirstChild(PsiElement element) {
return PsiUtil.skipWhitespacesAndComments(element.getParent().getFirstChild(), true) == element;
}
/**
* @return replaced expression or null if expression is not replaced
*/
@Nullable
private static GrExpression addParenthesesIfNeeded(GrExpression newExpr, GrExpression oldExpr, GrExpression oldParent) {
GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(oldExpr.getProject());
int parentPriorityLevel = getExprPriorityLevel(oldParent);
int newPriorityLevel = getExprPriorityLevel(newExpr);
if (parentPriorityLevel > newPriorityLevel) {
newExpr = factory.createParenthesizedExpr(newExpr);
}
else if (parentPriorityLevel == newPriorityLevel && parentPriorityLevel != 0) {
if (oldParent instanceof GrBinaryExpression) {
GrBinaryExpression binaryExpression = (GrBinaryExpression)oldParent;
if (isNotAssociative(binaryExpression) && oldExpr.equals(binaryExpression.getRightOperand())) {
newExpr = factory.createParenthesizedExpr(newExpr);
}
}
}
return newExpr;
}
private static boolean isNotAssociative(GrBinaryExpression binaryExpression) {
final IElementType opToken = binaryExpression.getOperationTokenType();
return !TokenSets.ASSOCIATIVE_BINARY_OP_SET.contains(opToken);
}
@Nullable
public static GrExpression getRuntimeQualifier(@NotNull GrReferenceExpression refExpr) {
GrExpression qualifier = refExpr.getQualifierExpression();
if (qualifier != null) return qualifier;
for (GrClosableBlock closure = PsiTreeUtil.getParentOfType(refExpr, GrClosableBlock.class);
closure != null;
closure = PsiTreeUtil.getParentOfType(closure, GrClosableBlock.class)) {
PsiElement parent = closure.getParent();
if (parent instanceof GrArgumentList) parent = parent.getParent();
if (!(parent instanceof GrMethodCall)) continue;
GrExpression funExpr = ((GrMethodCall)parent).getInvokedExpression();
if (!(funExpr instanceof GrReferenceExpression)) return funExpr;
final PsiElement resolved = ((GrReferenceExpression)funExpr).resolve();
if (!(resolved instanceof PsiMethod)) return funExpr;
if (resolved instanceof GrGdkMethod &&
isFromDGM((GrGdkMethod)resolved) &&
!GdkMethodUtil.isWithName(((GrGdkMethod)resolved).getStaticMethod().getName())) {
continue;
}
qualifier = ((GrReferenceExpression)funExpr).getQualifierExpression();
if (qualifier != null) return qualifier;
}
return null;
}
private static boolean isFromDGM(GrGdkMethod resolved) {
final PsiClass containingClass = resolved.getStaticMethod().getContainingClass();
return containingClass != null && GroovyCommonClassNames.DEFAULT_GROOVY_METHODS.equals(containingClass.getQualifiedName());
}
public static void removeVariable(GrVariable variable) {
final GrVariableDeclaration varDecl = (GrVariableDeclaration) variable.getParent();
final List<GrVariable> variables = Arrays.asList(varDecl.getVariables());
if (!variables.contains(variable)) {
throw new IllegalArgumentException();
}
final PsiElement parent = varDecl.getParent();
final ASTNode owner = parent.getNode();
if (variables.size() == 1 && owner != null) {
PsiElement next = varDecl.getNextSibling();
// remove redundant semicolons
//noinspection ConstantConditions
while (next != null && next.getNode() != null && next.getNode().getElementType() == GroovyTokenTypes.mSEMI) {
PsiElement tmpNext = next.getNextSibling();
//noinspection ConstantConditions
next.delete();
next = tmpNext;
}
removeNewLineAfter(varDecl);
varDecl.delete();
return;
}
variable.delete();
}
@Nullable
public static PsiElement realPrevious(PsiElement previousLeaf) {
while (previousLeaf != null &&
(previousLeaf instanceof PsiWhiteSpace ||
previousLeaf instanceof PsiComment ||
previousLeaf instanceof PsiErrorElement)) {
previousLeaf = previousLeaf.getPrevSibling();
}
return previousLeaf;
}
private static int getExprPriorityLevel(GrExpression expr) {
int priority;
//if (expr instanceof GrNewExpression) priority = 1;
if (expr instanceof GrUnaryExpression) priority = ((GrUnaryExpression)expr).isPostfix() ? 5 : 6;
else if (expr instanceof GrTypeCastExpression) priority = 6;
else if (expr instanceof GrBinaryExpression) {
final IElementType opToken = ((GrBinaryExpression)expr).getOperationTokenType();
if (opToken == GroovyTokenTypes.mSTAR_STAR) priority = 7;
else if (opToken == GroovyTokenTypes.mSTAR || opToken == GroovyTokenTypes.mDIV) priority = 8;
else if (opToken == GroovyTokenTypes.mPLUS || opToken == GroovyTokenTypes.mMINUS) priority = 9;
else if (TokenSets.SHIFT_SIGNS.contains(opToken)) priority = 10;
else if (opToken == GroovyTokenTypes.mRANGE_EXCLUSIVE || opToken == GroovyTokenTypes.mRANGE_INCLUSIVE) priority = 11;
else if (TokenSets.RELATIONS.contains(opToken)) priority = 12;
else if (opToken == GroovyTokenTypes.mEQUAL || opToken == GroovyTokenTypes.mNOT_EQUAL || opToken == GroovyTokenTypes.mCOMPARE_TO) priority = 13;
else if (opToken == GroovyTokenTypes.mREGEX_FIND || opToken == GroovyTokenTypes.mREGEX_MATCH) priority = 14;
else if (opToken == GroovyTokenTypes.mBAND) priority = 15;
else if (opToken == GroovyTokenTypes.mBXOR) priority = 16;
else if (opToken == GroovyTokenTypes.mBOR) priority = 17;
else if (opToken == GroovyTokenTypes.mLAND) priority = 18;
else if (opToken == GroovyTokenTypes.mLOR) priority = 19;
else {
assert false :"unknown operation:"+opToken;
priority = 0;
}
}
else if (expr instanceof GrConditionalExpression) priority = 20;
else if (expr instanceof GrSafeCastExpression) priority = 21;
else if (expr instanceof GrAssignmentExpression) priority = 22;
else if (expr instanceof GrApplicationStatement) priority = 23;
else priority = 0;
return -priority;
}
public static void setName(String name, PsiElement nameElement) {
final PsiElement newNameElement = GroovyPsiElementFactory.getInstance(nameElement.getProject()).createReferenceNameFromText(name);
nameElement.replace(newNameElement);
}
public static boolean isExtendsSignature(MethodSignature superSignatureCandidate, MethodSignature subSignature) {
return MethodSignatureUtil.isSubsignature(superSignatureCandidate, subSignature);
}
@Nullable
public static PsiMethod extractUniqueElement(@NotNull GroovyResolveResult[] results) {
if (results.length != 1) return null;
final PsiElement element = results[0].getElement();
return element instanceof PsiMethod ? (PsiMethod) element : null;
}
@NotNull
public static GroovyResolveResult extractUniqueResult(@NotNull GroovyResolveResult[] results) {
if (results.length != 1) return GroovyResolveResult.EMPTY_RESULT;
return results[0];
}
public static PsiMethod[] mapToMethods(@Nullable List<CandidateInfo> list) {
if (list == null) return PsiMethod.EMPTY_ARRAY;
PsiMethod[] result = new PsiMethod[list.size()];
for (int i = 0; i < list.size(); i++) {
result[i] = (PsiMethod) list.get(i).getElement();
}
return result;
}
@NotNull
public static String getName(@NotNull GrNamedElement namedElement) {
PsiElement nameElement = namedElement.getNameIdentifierGroovy();
ASTNode node = nameElement.getNode();
LOG.assertTrue(node != null);
if (node.getElementType() == GroovyTokenTypes.mIDENT) {
return nameElement.getText();
}
if (node.getElementType() == GroovyTokenTypes.mSTRING_LITERAL || node.getElementType() == GroovyTokenTypes.mGSTRING_LITERAL) {
final Object value = GrLiteralImpl.getLiteralValue(nameElement);
if (value instanceof String) {
return (String)value;
}
else {
return GrStringUtil.removeQuotes(nameElement.getText());
}
}
throw new IncorrectOperationException("incorrect name element: " + node.getElementType() + ", named element: " + namedElement);
}
public static void removeNewLineAfter(@NotNull GrStatement statement) {
ASTNode parentNode = statement.getParent().getNode();
ASTNode next = statement.getNode().getTreeNext();
if (parentNode != null && next != null && GroovyTokenTypes.mNLS == next.getElementType()) {
parentNode.removeChild(next);
}
}
public static boolean isMainMethod(GrMethod method) {
if (!method.getName().equals(MAIN_METHOD)) return false;
else if (!method.hasModifierProperty(PsiModifier.STATIC))return false;
final GrParameter[] parameters = method.getParameters();
if (parameters.length == 0) return false;
if (parameters.length == 1 && parameters[0].getTypeElementGroovy() == null) return true;
int args_count = 0;
int optional_count = 0;
for (GrParameter p : parameters) {
final GrTypeElement declaredType = p.getTypeElementGroovy();
if ((declaredType == null || declaredType.getType().equalsToText(CommonClassNames.JAVA_LANG_STRING + "[]")) &&
p.getInitializerGroovy() == null) {
args_count++;
}
if (p.getInitializerGroovy() != null) optional_count++;
}
return optional_count == parameters.length - 1 && args_count == 1;
}
public static void deleteStatementTail(PsiElement container, @NotNull PsiElement statement) {
PsiElement next = statement.getNextSibling();
while (next != null) {
final ASTNode node = next.getNode();
final IElementType type = node.getElementType();
if (type == GroovyTokenTypes.mSEMI || type == TokenType.WHITE_SPACE && !next.getText().contains("\n")) {
final PsiElement nnext = next.getNextSibling();
container.deleteChildRange(next, next);
next = nnext;
}
else if (type == GroovyTokenTypes.mNLS || type == TokenType.WHITE_SPACE && next.getText().contains("\n")) {
final String text = next.getText();
final int first = text.indexOf("\n");
final int second = text.indexOf("\n", first + 1);
if (second < 0) {
container.deleteChildRange(next, next);
return;
}
final String substring = text.substring(second);
container.getNode()
.replaceChild(node, Factory.createSingleLeafElement(type, substring, 0, substring.length(), null, container.getManager()));
return;
}
else {
break;
}
}
}
public static <T extends PsiElement> void setQualifier(@NotNull GrQualifiedReference<T> ref, @Nullable T newQualifier) {
final T oldQualifier = ref.getQualifier();
final ASTNode node = ref.getNode();
final PsiElement refNameElement = ref.getReferenceNameElement();
if (newQualifier == null) {
if (oldQualifier != null && refNameElement != null) {
ref.deleteChildRange(ref.getFirstChild(), refNameElement.getPrevSibling());
}
} else {
if (oldQualifier == null) {
if (refNameElement != null) {
node.addLeaf(GroovyTokenTypes.mDOT, ".", refNameElement.getNode());
ref.addBefore(newQualifier, refNameElement.getPrevSibling());
}
}
else {
oldQualifier.replace(newQualifier);
}
}
}
public static boolean isSimpleArrayAccess(PsiType exprType, PsiType[] argTypes, PsiElement context, boolean isLValue) {
return exprType instanceof PsiArrayType &&
(isLValue && argTypes.length == 2 || !isLValue && argTypes.length == 1) &&
TypesUtil.isAssignableByMethodCallConversion(PsiType.INT, argTypes[0], context);
}
public static String getTextSkipWhiteSpaceAndComments(ASTNode node) {
return AstBufferUtil.getTextSkippingWhitespaceComments(node);
}
public static PsiCodeBlock getOrCreatePsiCodeBlock(GrOpenBlock block) {
if (block == null) return null;
final SoftReference<PsiCodeBlock> ref = block.getUserData(PSI_CODE_BLOCK);
final PsiCodeBlock body = SoftReference.dereference(ref);
if (body != null) return body;
final GrSyntheticCodeBlock newBody = new GrSyntheticCodeBlock(block);
block.putUserData(PSI_CODE_BLOCK, new SoftReference<PsiCodeBlock>(newBody));
return newBody;
}
public static PsiTypeElement getOrCreateTypeElement(GrTypeElement typeElement) {
if (typeElement == null) return null;
final SoftReference<PsiTypeElement> ref = typeElement.getUserData(PSI_TYPE_ELEMENT);
final PsiTypeElement element = SoftReference.dereference(ref);
if (element != null) return element;
final GrSyntheticTypeElement newTypeElement = new GrSyntheticTypeElement(typeElement);
typeElement.putUserData(PSI_TYPE_ELEMENT, new SoftReference<PsiTypeElement>(newTypeElement));
return newTypeElement;
}
public static PsiExpression getOrCreatePisExpression(GrExpression expr) {
if (expr == null) return null;
final SoftReference<PsiExpression> ref = expr.getUserData(PSI_EXPRESSION);
final PsiExpression element = SoftReference.dereference(ref);
if (element != null) return element;
final GrSyntheticExpression newExpr = new GrSyntheticExpression(expr);
expr.putUserData(PSI_EXPRESSION, new SoftReference<PsiExpression>(newExpr));
return newExpr;
}
public static PsiReferenceList getOrCreatePsiReferenceList(GrReferenceList list, PsiReferenceList.Role role) {
if (list == null) return null;
final SoftReference<PsiReferenceList> ref = list.getUserData(PSI_REFERENCE_LIST);
final PsiReferenceList element = SoftReference.dereference(ref);
if (element != null) return element;
final GrSyntheticReferenceList newList = new GrSyntheticReferenceList(list, role);
list.putUserData(PSI_REFERENCE_LIST, new SoftReference<PsiReferenceList>(newList));
return newList;
}
public static <T extends GrCondition> T replaceBody(T newBody, GrStatement body, ASTNode node, Project project) {
if (body == null || newBody == null) {
throw new IncorrectOperationException();
}
ASTNode oldBodyNode = body.getNode();
if (oldBodyNode.getTreePrev() != null && GroovyTokenTypes.mNLS.equals(oldBodyNode.getTreePrev().getElementType())) {
ASTNode whiteNode = GroovyPsiElementFactory.getInstance(project).createWhiteSpace().getNode();
node.replaceChild(oldBodyNode.getTreePrev(), whiteNode);
}
node.replaceChild(oldBodyNode, newBody.getNode());
return newBody;
}
public static boolean isVarArgs(GrParameter[] parameters) {
return parameters.length > 0 && parameters[parameters.length - 1].isVarArgs();
}
@Nullable
public static PsiAnnotation getAnnotation(@NotNull PsiModifierListOwner field, @NotNull String annotationName) {
final PsiModifierList modifierList = field.getModifierList();
if (modifierList == null) return null;
return modifierList.findAnnotation(annotationName);
}
@Nullable
public static GrConstructorInvocation getChainingConstructorInvocation(GrMethod constructor) {
if (constructor instanceof GrReflectedMethod && ((GrReflectedMethod)constructor).getSkippedParameters().length > 0) return null;
LOG.assertTrue(constructor.isConstructor());
GrOpenBlock body = constructor.getBlock();
if (body == null) return null;
GrStatement[] statements = body.getStatements();
if (statements.length > 0 && statements[0] instanceof GrConstructorInvocation) {
return (GrConstructorInvocation) statements[0];
}
return null;
}
public static GrMethod[] getMethodOrReflectedMethods(GrMethod method) {
final GrReflectedMethod[] reflectedMethods = method.getReflectedMethods();
return reflectedMethods.length > 0 ? reflectedMethods : new GrMethod[]{method};
}
@Nullable
public static PsiType inferExpectedTypeForDiamond(GrExpression diamondNew) {
PsiElement skipped = PsiUtil.skipParentheses(diamondNew, true);
assert skipped != null;
PsiElement pparent = skipped.getParent();
if (pparent instanceof GrAssignmentExpression &&
PsiTreeUtil.isAncestor(((GrAssignmentExpression)pparent).getRValue(), diamondNew, false)) {
GrExpression lValue = ((GrAssignmentExpression)pparent).getLValue();
if (PsiUtil.mightBeLValue(lValue)) {
return lValue.getNominalType();
}
}
else if (pparent instanceof GrVariable && ((GrVariable)pparent).getInitializerGroovy() == diamondNew) {
return ((GrVariable)pparent).getDeclaredType();
}
else if (pparent instanceof GrListOrMap) {
PsiElement ppparent = PsiUtil.skipParentheses(pparent.getParent(), true);
if (ppparent instanceof GrAssignmentExpression &&
PsiTreeUtil.isAncestor(((GrAssignmentExpression)ppparent).getRValue(), pparent, false)) {
PsiElement lValue = PsiUtil.skipParentheses(((GrAssignmentExpression)ppparent).getLValue(), false);
if (lValue instanceof GrTupleExpression) {
GrExpression[] initializers = ((GrListOrMap)pparent).getInitializers();
int index = ArrayUtil.find(initializers, diamondNew);
GrExpression[] expressions = ((GrTupleExpression)lValue).getExpressions();
if (index < expressions.length) {
return expressions[index].getNominalType();
}
}
}
}
return null;
}
@Nullable
public static PsiType normalizeWildcardTypeByPosition(@NotNull PsiType type, @NotNull GrExpression expression) {
GrExpression toplevel = expression;
while (toplevel.getParent() instanceof GrIndexProperty &&
((GrIndexProperty)toplevel.getParent()).getInvokedExpression() == toplevel) {
toplevel = (GrExpression)toplevel.getParent();
}
final PsiType normalized = doNormalizeWildcardByPosition(type, expression, toplevel);
if (normalized instanceof PsiClassType && !PsiUtil.isAccessedForWriting(toplevel)) {
return com.intellij.psi.util.PsiUtil.captureToplevelWildcards(normalized, expression);
}
return normalized;
}
@Nullable
private static PsiType doNormalizeWildcardByPosition(final PsiType type, final GrExpression expression, final GrExpression toplevel) {
if (type instanceof PsiCapturedWildcardType) {
return doNormalizeWildcardByPosition(((PsiCapturedWildcardType)type).getWildcard(), expression, toplevel);
}
if (type instanceof PsiWildcardType) {
final PsiWildcardType wildcardType = (PsiWildcardType)type;
if (PsiUtil.isAccessedForWriting(toplevel)) {
return wildcardType.isSuper() ? wildcardType.getBound() : PsiCapturedWildcardType.create(wildcardType, expression);
}
else {
if (wildcardType.isExtends()) {
return wildcardType.getBound();
}
else {
return TypesUtil.getJavaLangObject(expression);
}
}
}
else if (type instanceof PsiArrayType) {
final PsiType componentType = ((PsiArrayType)type).getComponentType();
final PsiType normalizedComponentType = doNormalizeWildcardByPosition(componentType, expression, toplevel);
if (normalizedComponentType != componentType) {
assert normalizedComponentType != null;
return normalizedComponentType.createArrayType();
}
}
return type;
}
public static boolean hasElementType(@Nullable PsiElement next, @NotNull final IElementType type) {
if (next == null) return false;
final ASTNode astNode = next.getNode();
return astNode != null && astNode.getElementType() == type;
}
public static boolean hasElementType(@Nullable PsiElement next, final TokenSet set) {
if (next == null) return false;
final ASTNode astNode = next.getNode();
return astNode != null && set.contains(astNode.getElementType());
}
public static boolean hasNamedArguments(@Nullable GrNamedArgumentsOwner list) {
if (list == null) return false;
for (PsiElement child = list.getFirstChild(); child != null; child = child.getNextSibling()) {
if (child instanceof GrNamedArgument) return true;
}
return false;
}
public static boolean hasExpressionArguments(@Nullable GrArgumentList list) {
if (list == null) return false;
for (PsiElement child = list.getFirstChild(); child != null; child = child.getNextSibling()) {
if (child instanceof GrExpression) return true;
}
return false;
}
public static boolean hasClosureArguments(@Nullable GrCall call) {
if (call == null) return false;
for (PsiElement child = call.getFirstChild(); child != null; child = child.getNextSibling()) {
if (child instanceof GrClosableBlock) return true;
}
return false;
}
public static PsiElement findTailingSemicolon(@NotNull GrStatement statement) {
final PsiElement nextNonSpace = PsiUtil.skipWhitespaces(statement.getNextSibling(), true);
if (nextNonSpace != null && nextNonSpace.getNode().getElementType() == GroovyTokenTypes.mSEMI) {
return nextNonSpace;
}
return null;
}
@Nullable
public static PsiType inferReturnType(PsiElement position) {
final GrControlFlowOwner flowOwner = ControlFlowUtils.findControlFlowOwner(position);
if (flowOwner == null) return null;
final PsiElement parent = flowOwner.getContext();
if (flowOwner instanceof GrOpenBlock && parent instanceof GrMethod) {
final GrMethod method = (GrMethod)parent;
if (method.isConstructor()) return null;
return method.getReturnType();
}
return null;
}
public static GrStatement[] getStatements(final GrStatementOwner statementOwner) {
List<GrStatement> result = new ArrayList<GrStatement>();
for (PsiElement cur = statementOwner.getFirstChild(); cur != null; cur = cur.getNextSibling()) {
if (cur instanceof GrStatement) {
result.add((GrStatement)cur);
}
}
return result.toArray(new GrStatement[result.size()]);
}
public static GrNamedArgument findNamedArgument(final GrNamedArgumentsOwner namedArgumentOwner,
String label) {
for (PsiElement cur = namedArgumentOwner.getFirstChild(); cur != null; cur = cur.getNextSibling()) {
if (cur instanceof GrNamedArgument) {
if (label.equals(((GrNamedArgument)cur).getLabelName())) {
return (GrNamedArgument)cur;
}
}
}
return null;
}
public static boolean hasImmutableAnnotation(PsiModifierList modifierList) {
return modifierList.findAnnotation(GroovyCommonClassNames.GROOVY_LANG_IMMUTABLE) != null ||
modifierList.findAnnotation(GroovyCommonClassNames.GROOVY_TRANSFORM_IMMUTABLE) != null;
}
public static boolean isWhiteSpaceOrNls(@Nullable PsiElement sibling) {
return sibling != null && isWhiteSpaceOrNls(sibling.getNode());
}
public static boolean isWhiteSpaceOrNls(@Nullable ASTNode node) {
return node != null && TokenSets.WHITE_SPACES_SET.contains(node.getElementType());
}
public static void insertPlaceHolderToModifierListAtEndIfNeeded(GrModifierList modifierList) {
PsiElement newLineAfterModifierList = findNewLineAfterElement(modifierList);
if (newLineAfterModifierList != null) {
modifierList.setModifierProperty(GrModifier.DEF, false);
if (modifierList.getModifiers().length > 0) {
modifierList.getNode().addLeaf(GroovyTokenTypes.mNLS, newLineAfterModifierList.getText(), null);
}
modifierList.getNode().addLeaf(GroovyTokenTypes.kDEF, "def", null);
final PsiElement newLineUpdated = findNewLineAfterElement(modifierList);
if (newLineUpdated != null) newLineUpdated.delete();
if (!isWhiteSpaceOrNls(modifierList.getNextSibling())) {
modifierList.getParent().getNode().addLeaf(TokenType.WHITE_SPACE, " ", modifierList.getNextSibling().getNode());
}
}
else if (modifierList.getModifiers().length == 0) {
modifierList.setModifierProperty(GrModifier.DEF, true);
}
}
@Nullable
private static PsiElement findNewLineAfterElement(PsiElement element) {
PsiElement sibling = element.getNextSibling();
while (sibling != null && isWhiteSpaceOrNls(sibling)) {
if (PsiUtil.isNewLine(sibling)) {
return sibling;
}
sibling = sibling.getNextSibling();
}
return null;
}
@Nullable
public static GrAnnotation getAnnotation(@NotNull GrAnnotationNameValuePair pair) {
PsiElement pParent = pair.getParent().getParent();
if (pParent instanceof GrAnnotation) return (GrAnnotation)pParent;
PsiElement ppParent = pParent.getParent();
return ppParent instanceof GrAnnotation ? (GrAnnotation)ppParent : null;
}
@Nullable
public static <T extends PsiElement> T findElementInRange(final PsiFile file,
int startOffset,
int endOffset,
final Class<T> klass) {
PsiElement element1 = file.getViewProvider().findElementAt(startOffset, file.getLanguage());
PsiElement element2 = file.getViewProvider().findElementAt(endOffset - 1, file.getLanguage());
if (element1 == null || element2 == null) return null;
if (isWhiteSpaceOrNls(element1)) {
startOffset = element1.getTextRange().getEndOffset();
element1 = file.getViewProvider().findElementAt(startOffset, file.getLanguage());
}
if (isWhiteSpaceOrNls(element2)) {
endOffset = element2.getTextRange().getStartOffset();
element2 = file.getViewProvider().findElementAt(endOffset - 1, file.getLanguage());
}
if (element2 == null || element1 == null) return null;
final PsiElement commonParent = PsiTreeUtil.findCommonParent(element1, element2);
assert commonParent != null;
final T element = ReflectionUtil.isAssignable(klass, commonParent.getClass()) ? (T) commonParent : PsiTreeUtil.getParentOfType(commonParent, klass);
if (element == null) {
return null;
}
if (!checkRanges(element, startOffset, endOffset)) {
return null;
}
return element;
}
private static boolean checkRanges(@NotNull PsiElement element, int startOffset, int endOffset) {
if (element instanceof GrLiteral && StringPartInfo.isWholeLiteralContentSelected((GrLiteral)element, startOffset, endOffset)) {
return true;
}
if (element.getTextRange().getStartOffset() == startOffset) {
return true;
}
return false;
}
public static void appendTypeString(StringBuilder buffer, final PsiType type, PsiElement context) {
if (type != null) {
JavaDocInfoGenerator.generateType(buffer, type, context);
}
else {
buffer.append(GrModifier.DEF);
}
}
public static boolean isSpreadAssignment(@Nullable GrExpression lValue) {
if (lValue instanceof GrReferenceExpression) {
GrReferenceExpression expression = (GrReferenceExpression)lValue;
final PsiElement dot = expression.getDotToken();
//noinspection ConstantConditions
if (dot != null && dot.getNode().getElementType() == GroovyTokenTypes.mSPREAD_DOT) {
return true;
}
else {
final GrExpression qualifier = expression.getQualifierExpression();
if (qualifier != null) return isSpreadAssignment(qualifier);
}
}
return false;
}
public static void replaceExpression(@NotNull String newExpression, @NotNull GrExpression expression) throws IncorrectOperationException {
final GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(expression.getProject());
final GrExpression newCall = factory.createExpressionFromText(newExpression);
expression.replaceWithExpression(newCall, true);
}
public static GrStatement replaceStatement(@NonNls @NotNull String newStatement, @NonNls @NotNull GrStatement statement)
throws IncorrectOperationException {
final GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(statement.getProject());
final GrStatement newCall = (GrStatement)factory.createTopElementFromText(newStatement);
return statement.replaceWithStatement(newCall);
}
public static boolean seemsToBeQualifiedClassName(@Nullable GrExpression expr) {
if (expr == null) return false;
while (expr instanceof GrReferenceExpression) {
final PsiElement nameElement = ((GrReferenceExpression)expr).getReferenceNameElement();
if (((GrReferenceExpression)expr).getTypeArguments().length > 0) return false;
if (nameElement == null || nameElement.getNode().getElementType() != GroovyTokenTypes.mIDENT) return false;
IElementType dotType = ((GrReferenceExpression)expr).getDotTokenType();
if (dotType != null && dotType != GroovyTokenTypes.mDOT) return false;
expr = ((GrReferenceExpression)expr).getQualifierExpression();
}
return expr == null;
}
@Nullable
public static PsiType getQualifierType(@NotNull GrReferenceExpression ref) {
final GrExpression rtQualifier = getRuntimeQualifier(ref);
if (rtQualifier != null) {
return rtQualifier.getType();
}
PsiClass containingClass = null;
final GrMember member = PsiTreeUtil.getParentOfType(ref, GrMember.class);
if (member == null) {
final PsiFile file = ref.getContainingFile();
if (file instanceof GroovyFileBase && ((GroovyFileBase)file).isScript()) {
containingClass = ((GroovyFileBase)file).getScriptClass();
}
else {
return null;
}
}
else if (member instanceof GrMethod) {
if (!member.hasModifierProperty(PsiModifier.STATIC)) {
containingClass = member.getContainingClass();
}
}
if (containingClass != null) {
final PsiClassType categoryType = GdkMethodUtil.getCategoryType(containingClass);
if (categoryType != null) {
return categoryType;
}
return JavaPsiFacade.getElementFactory(ref.getProject()).createType(containingClass);
}
return null;
}
@NotNull
public static GroovyResolveResult reflectedToBase(GroovyResolveResult result, GrMethod baseMethod, GrReflectedMethod reflectedMethod) {
PsiSubstitutor substitutor = PsiSubstitutor.EMPTY;
PsiTypeParameter[] reflectedParameters = reflectedMethod.getTypeParameters();
PsiTypeParameter[] baseParameters = baseMethod.getTypeParameters();
assert baseParameters.length == reflectedParameters.length;
for (int i = 0; i < baseParameters.length; i++) {
substitutor = substitutor.put(baseParameters[i], result.getSubstitutor().substitute(reflectedParameters[i]));
}
return new GroovyResolveResultImpl(baseMethod, result.getCurrentFileResolveContext(), result.getSpreadState(),
substitutor, result.isAccessible(), result.isStaticsOK(),
result.isInvokedOnProperty(), result.isValidResult());
}
}
|
resolve groovy method references to non-reflected methods (IDEA-138048 partial)
preserve class-level substitutions
|
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/PsiImplUtil.java
|
resolve groovy method references to non-reflected methods (IDEA-138048 partial)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.